Ejemplo n.º 1
0
def initialize(uri,
               trace_level=0,
               trace_file=sys.stdout,
               trace_stack_limit=None,
               bytes_mode=None,
               raise_for_result=RAISE_ALL,
               **kwargs):
    """
  Return LDAPObject instance by opening LDAP connection to
  LDAP host specified by LDAP URL

  Parameters:
  uri
        LDAP URL containing at least connection scheme and hostport,
        e.g. ldap://localhost:389
  trace_level
        If non-zero a trace output of LDAP calls is generated.
  trace_file
        File object where to write the trace output to.
        Default is to use stdout.
  bytes_mode
        Whether to enable :ref:`bytes_mode` for backwards compatibility under Py2.

  Additional keyword arguments (such as ``bytes_strictness``) are
  passed to ``LDAPObject``.
  """
    return LDAPObject(uri, trace_level, trace_file, trace_stack_limit,
                      bytes_mode, raise_for_result, **kwargs)
Ejemplo n.º 2
0
 def setUp(self):
     self.ldap = LDAPObject(self.server.ldap_uri, bytes_mode=False)
     self.ldap.protocol_version = 3
     self.ldap.set_option(ldap.OPT_REFERRALS, 0)
     self.ldap.simple_bind_s(
         self.server.root_dn,
         self.server.root_pw
     )
 def _get_bytes_ldapobject(self, explicit=True):
     if explicit:
         kwargs = {'bytes_mode': True}
     else:
         kwargs = {}
     l = LDAPObject(server.get_url(), **kwargs)
     l.protocol_version = 3
     l.set_option(ldap.OPT_REFERRALS, 0)
     l.simple_bind_s(self.server.get_root_dn().encode('utf-8'),
                     self.server.get_root_password().encode('utf-8'))
     return l
Ejemplo n.º 4
0
    def setUp(self):
        global server
        if server is None:
            server = SlapdObject()
            server.start()
            base = server.suffix
            suffix_dc = base.split(',')[0][3:]

            # insert some Foo* objects via ldapadd
            server.ldapadd("\n".join([
                'dn: ' + server.suffix,
                'objectClass: dcObject',
                'objectClass: organization',
                'dc: ' + suffix_dc,
                'o: ' + suffix_dc,
                '',
                'dn: ' + server.root_dn,
                'objectClass: applicationProcess',
                'cn: ' + server.root_cn,
                '',
                "dn: cn=Foo1," + base,
                "objectClass: organizationalRole",
                "cn: Foo1",
                "",
                "dn: cn=Foo2," + base,
                "objectClass: organizationalRole",
                "cn: Foo2",
                "",
                "dn: cn=Foo3," + base,
                "objectClass: organizationalRole",
                "cn: Foo3",
                "",
                "dn: ou=Container," + base,
                "objectClass: organizationalUnit",
                "ou: Container",
                "",
                "dn: cn=Foo4,ou=Container," + base,
                "objectClass: organizationalRole",
                "cn: Foo4",
                "",
            ]) + "\n")

        l = LDAPObject(server.ldap_uri, bytes_mode=False)
        l.protocol_version = 3
        l.set_option(ldap.OPT_REFERRALS, 0)
        l.simple_bind_s(server.root_dn, server.root_pw)
        self.ldap = l
        self.server = server
Ejemplo n.º 5
0
def initialize(uri,trace_level=0,trace_file=sys.stdout,trace_stack_limit=None):
  """
  Return LDAPObject instance by opening LDAP connection to
  LDAP host specified by LDAP URL

  Parameters:
  uri
        LDAP URL containing at least connection scheme and hostport,
        e.g. ldap://localhost:389
  trace_level
        If non-zero a trace output of LDAP calls is generated.
  trace_file
        File object where to write the trace output to.
        Default is to use stdout.
  """
  return LDAPObject(uri,trace_level,trace_file,trace_stack_limit)
Ejemplo n.º 6
0
    def setUp(self):
        global server
        if server is None:
            server = slapd.Slapd()
            server.start()
            base = server.get_dn_suffix()

            # insert some Foo* objects via ldapadd
            server.ldapadd("\n".join([
                "dn: cn=Foo1,"+base,
                "objectClass: organizationalRole",
                "cn: Foo1",
                "",
                "dn: cn=Foo2,"+base,
                "objectClass: organizationalRole",
                "cn: Foo2",
                "",
                "dn: cn=Foo3,"+base,
                "objectClass: organizationalRole",
                "cn: Foo3",
                "",
                "dn: ou=Container,"+base,
                "objectClass: organizationalUnit",
                "ou: Container",
                "",
                "dn: cn=Foo4,ou=Container,"+base,
                "objectClass: organizationalRole",
                "cn: Foo4",
                "",
            ])+"\n")

        l = LDAPObject(server.get_url())
        l.protocol_version = 3
        l.set_option(ldap.OPT_REFERRALS,0)
        l.simple_bind_s(server.get_root_dn(), 
                server.get_root_password())
        self.ldap = l
        self.server = server
Ejemplo n.º 7
0
def initialize(uri,
               trace_level=0,
               trace_file=sys.stdout,
               trace_stack_limit=None,
               bytes_mode=None):
    """
  Return LDAPObject instance by opening LDAP connection to
  LDAP host specified by LDAP URL

  Parameters:
  uri
        LDAP URL containing at least connection scheme and hostport,
        e.g. ldap://localhost:389
  trace_level
        If non-zero a trace output of LDAP calls is generated.
  trace_file
        File object where to write the trace output to.
        Default is to use stdout.
  bytes_mode
        Whether to enable :ref:`bytes_mode` for backwards compatibility under Py2.
  """
    return LDAPObject(uri, trace_level, trace_file, trace_stack_limit,
                      bytes_mode)
Ejemplo n.º 8
0
import sys, os, time, ldap

from ldap.ldapobject import LDAPObject
from ldapurl import LDAPUrl

try:
    ldap_url = LDAPUrl(sys.argv[1])
    num_tests = int(sys.argv[2])
except IndexError:
    print 'Usage: pref_test.py <LDAP URL> <number of tests>'
    sys.exit(1)

iter = num_tests
start_time = time.time()

l = LDAPObject(ldap_url.initializeUrl(), trace_level=0)
l.protocol_version = 3
l.simple_bind_s(ldap_url.who or '', ldap_url.cred or '')

while iter:

    l.search_s(ldap_url.dn, ldap_url.scope or ldap.SCOPE_BASE,
               ldap_url.filterstr or '(objectClass=*)', ldap_url.attrs
               or ['*'])

    iter -= 1

end_time = time.time()
l.unbind_s()
del l
print 'Reusing connection:', end_time - start_time
Ejemplo n.º 9
0
def main():
    uri = os.environ["URI1"]

    managerdn = os.environ['MANAGERDN']
    passwd = os.environ['PASSWD']

    babsdn = os.environ['BABSDN']
    babspw = b"bjensen"

    bjornsdn = os.environ['BJORNSDN']
    bjornspw = b"bjorn"

    connection = LDAPObject(uri)

    start = time.time()
    connection.bind_s(managerdn, passwd)
    end = time.time()

    if end - start > 1:
        print(
            "It takes more than a second to connect and bind, "
            "skipping potentially unstable test",
            file=sys.stderr)
        raise SystemExit(0)

    dn, token_entry = get_token_for(connection, babsdn)

    paramsdn = token_entry['oathTOTPParams'][0].decode()
    result = connection.search_s(paramsdn, ldap.SCOPE_BASE)
    _, attrs = result[0]
    params = CIDict(attrs)

    secret = token_entry['oathSecret'][0]
    period = int(params['oathTOTPTimeStepPeriod'][0].decode())

    bind_conn = LDAPObject(uri)

    interval_no = get_interval(period)
    token = get_hotp_token(secret, interval_no - 3)

    print("Testing old tokens are not useable")
    bind_conn.bind_s(babsdn, babspw + token)
    try:
        bind_conn.bind_s(babsdn, babspw + token)
    except ldap.INVALID_CREDENTIALS:
        pass
    else:
        raise SystemExit("Bind with an old token should have failed")

    interval_no = get_interval(period)
    token = get_hotp_token(secret, interval_no)

    print("Testing token can only be used once")
    bind_conn.bind_s(babsdn, babspw + token)
    try:
        bind_conn.bind_s(babsdn, babspw + token)
    except ldap.INVALID_CREDENTIALS:
        pass
    else:
        raise SystemExit("Bind with a reused token should have failed")

    token = get_hotp_token(secret, interval_no + 1)
    try:
        bind_conn.bind_s(babsdn, babspw + token)
    except ldap.INVALID_CREDENTIALS:
        raise SystemExit("Bind should have succeeded")

    dn, token_entry = get_token_for(connection, babsdn)
    last = int(token_entry['oathTOTPLastTimeStep'][0].decode())
    if last != interval_no + 1:
        SystemExit("Unexpected counter value %d (expected %d)" %
                   (last, interval_no + 1))

    print("Resetting counter and testing secret sharing between accounts")
    connection.modify_s(dn, [(ldap.MOD_REPLACE, 'oathTOTPLastTimeStep', [])])

    interval_no = get_interval(period)
    token = get_hotp_token(secret, interval_no)

    try:
        bind_conn.bind_s(bjornsdn, bjornspw + token)
    except ldap.INVALID_CREDENTIALS:
        raise SystemExit("Bind should have succeeded")

    try:
        bind_conn.bind_s(babsdn, babspw + token)
    except ldap.INVALID_CREDENTIALS:
        pass
    else:
        raise SystemExit("Bind with a reused token should have failed")

    print("Testing token is retired even with a wrong password")
    connection.modify_s(dn, [(ldap.MOD_REPLACE, 'oathTOTPLastTimeStep', [])])

    interval_no = get_interval(period)
    token = get_hotp_token(secret, interval_no)

    try:
        bind_conn.bind_s(babsdn, b"not the password" + token)
    except ldap.INVALID_CREDENTIALS:
        pass
    else:
        raise SystemExit("Bind with an incorrect password should have failed")

    try:
        bind_conn.bind_s(babsdn, babspw + token)
    except ldap.INVALID_CREDENTIALS:
        pass
    else:
        raise SystemExit("Bind with a reused token should have failed")

    token = get_hotp_token(secret, interval_no + 1)
    try:
        bind_conn.bind_s(babsdn, babspw + token)
    except ldap.INVALID_CREDENTIALS:
        raise SystemExit("Bind should have succeeded")
Ejemplo n.º 10
0
 def _get_ldapobject(self, bytes_mode=None):
     l = LDAPObject(self.server.ldap_uri, bytes_mode=bytes_mode)
     l.protocol_version = 3
     l.set_option(ldap.OPT_REFERRALS,0)
     return l
Ejemplo n.º 11
0
def main():
    adhost = 'w2k8x8664.testdomain.com'
    adport = 389
    aduri = "ldap://%s:%d/" % (adhost, adport)
    suffix = "DC=testdomain,DC=com"
    name = sys.argv[1]
    pwd = sys.argv[2]
    #    adroot = "cn=Dirsync User,cn=users," + suffix
    #    adrootpw = "Secret123"
    adroot = "cn=%s,cn=users,%s" % (name, suffix)
    adrootpw = pwd
    verbose = False

    #    ldap.set_option(ldap.OPT_DEBUG_LEVEL, 15)
    ad = LDAPObject(aduri)
    ad.simple_bind_s(adroot, adrootpw)

    # do initial dirsync search to get entries and the initial dirsync
    # cookie
    scope = ldap.SCOPE_SUBTREE
    filt = '(objectclass=*)'
    attrlist = None
    dirsyncctrl = DirSyncCtrl()
    page_size = 1000
    lc = SimplePagedResultsControl(ldap.LDAP_CONTROL_PAGE_OID, True,
                                   (page_size, ''))
    serverctrls = [dirsyncctrl, lc]

    msgid = ad.search_ext(suffix, scope, filt, attrlist, 0, serverctrls)
    initiallist = {}
    # the dirsync control is returned with the LDAP_RES_SEARCH_RESULT
    #  def result3(self,msgid=_ldap.RES_ANY,all=1,timeout=None):
    while True:
        (rtype, rdata, rmsgid, decoded_serverctrls) = ad.result3(msgid)
        print "Search returned %d results" % len(rdata)
        for dn, ent in rdata:
            print "dn: ", dn
            if verbose:
                pprint.pprint(ent)
        if rtype == ldap.RES_SEARCH_RESULT:
            dirsyncctrl.update(decoded_serverctrls)
            break

    # now search again with the updated dirsync control
    # we should get back no results since nothing in AD
    # has changed
    msgid = ad.search_ext(suffix, scope, filt, attrlist, 0, serverctrls)
    while True:
        (rtype, rdata, rmsgid, decoded_serverctrls) = ad.result3(msgid)
        print "Search returned %d results" % len(rdata)
        if len(rdata) > 0:
            print "Nothing changed but something was returned????"
            pprint.pprint(rdata)
        if rtype == ldap.RES_SEARCH_RESULT:
            dirsyncctrl.update(decoded_serverctrls)
            break

    print "Change something on the AD side, and press Enter"
    sys.stdin.readline()
    print "Searching for changes . . ."
    msgid = ad.search_ext(suffix, scope, filt, attrlist, 0, serverctrls)
    while True:
        (rtype, rdata, rmsgid, decoded_serverctrls) = ad.result3(msgid)
        print "Search returned %d results" % len(rdata)
        for dn, ent in rdata:
            print "dn: ", dn
            pprint.pprint(ent)
        if rtype == ldap.RES_SEARCH_RESULT:
            dirsyncctrl.update(decoded_serverctrls)
            break