nixawk / pentest-wiki

PENTEST-WIKI is a free online security knowledge library for pentesters / researchers. If you have a good idea, please share it with others.
MIT License
3.37k stars 915 forks source link

[bruteforce] LDAP Login #27

Open nixawk opened 6 years ago

nixawk commented 6 years ago
#!/usr/bin/python
# -*- coding: utf-8 -*-

# $ pip install --user python-ldap

import ldap
import ldapurl
import logging
import getpass

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__file__)

def ldap_login(username, password, host, port=389, urlscheme='ldap'):

    #    SSL : ldaps://example.com:636/
    #  NOSSL : ldap://example.com:389/

    status = False

    try:
        u = ldapurl.LDAPUrl(
            urlscheme=urlscheme,
            hostport='%s:%d' % (host, int(port))
        )

        l = ldap.initialize(u.unparse())

        # perform a synchronous bind
        l.set_option(ldap.OPT_REFERRALS, 0)

        # you should  set this to ldap.VERSION2 if you're using a v2 directory
        l.protocol_version = ldap.VERSION3  
        # Pass in a valid username and password to get 
        # privileged directory access.
        # If you leave them as empty strings or pass an invalid value
        # you will still bind to the server but with limited privileges.

        # Any errors will throw an ldap.LDAPError exception 
        # or related exception so you can ignore the result

        l.simple_bind_s(username, password)
        l.unbind()

        # Return True if ldap allows anonymous binds.

        status = True  # If no exceptions, login status is succeful.

    # except ldap.LDAPError as e:
    except Exception as e:
        log.exception(e)
        # handle error however you like

    if status:
        log.info("%s:%d / %s:%s - Login ldap successfully" % (
            host, int(port), username, password
        ))
    else:
        log.info("%s:%d / %s:%s - Login ldap failed" % (
            host, int(port), username, password
        ))

    return status

if __name__ == '__main__':

    username = input('Username: ')
    password = getpass.getpass()

    ldaphost = "8.8.8.8"    # Ldap Server IP

    ldap_login(username, password, ldaphost)

## References

# https://www.python-ldap.org/en/latest/
# http://www.grotan.com/ldap/python-ldap-samples.html