From e0d19c7791b004cdaa605ddef1fda69fab043f7a Mon Sep 17 00:00:00 2001 From: Austin King Date: Thu, 21 Jul 2011 08:10:30 -0700 Subject: [PATCH] Escaping input to avoid LDAP injection. Finished search function. Added find_by_uniqueIdentifier --- apps/larper/models.py | 44 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/apps/larper/models.py b/apps/larper/models.py index ccf27eca..465d5229 100644 --- a/apps/larper/models.py +++ b/apps/larper/models.py @@ -1,4 +1,5 @@ import ldap +from ldap.filter import filter_format import logging @@ -18,19 +19,19 @@ class Person(object): self.request = request - def search(self, query): + def search(self, query): + people = [] uid = self.request.user.username dn = larper.dn(self.request, uid) password = larper.password(self.request) conn = ldap.initialize(settings.AUTH_LDAP_SERVER_URI, 2) - # TODO: cache dn in session too try: log.debug("Doing bind_s(%s, %s)" % (dn, password, )) try: o = conn.bind_s(dn, password) - search_filter = "(cn=*%s*)" % query + search_filter = filter_format("(cn=*%s*)", (query, )) attrs = None # All for now # TODO - optimize ['cn', 'mail'] rs = conn.search_s("ou=people,dc=mozillians,dc=org", ldap.SCOPE_SUBTREE, search_filter, attrs) @@ -38,11 +39,44 @@ class Person(object): log.error("Search has results!") for result in rs: dn, person = result - log.debug("Results for dn=%s" % dn) - log.debug(person) + people.append(person) else: log.debug('No one with cn=*david* was found') except ldap.INVALID_CREDENTIALS, ic: log.error(ic) finally: conn.unbind() + return people + + def find_by_uniqueIdentifier(self, query): + """ + Given a uniqueIdentifier, retrieve the one matching + person or None. + + TODO DRY - extract function + """ + person = {} + uid = self.request.user.username + dn = larper.dn(self.request, uid) + password = larper.password(self.request) + + conn = ldap.initialize(settings.AUTH_LDAP_SERVER_URI, 2) + + try: + o = conn.bind_s(dn, password) + search_filter = filter_format("(uniqueIdentifier=%s)", (query, )) + attrs = None + rs = conn.search_s("ou=people,dc=mozillians,dc=org", ldap.SCOPE_SUBTREE, search_filter, attrs) + if len(rs) > 0: + if len(rs) > 1: + log.warning("Searching for %s gave %d results... expected 0 or 1. Returning the first one.", (query, len(rs))) + log.error("Search has results!") + for result in rs: + dn, person = result + return person + else: + log.debug('No one with cn=*david* was found') + except ldap.INVALID_CREDENTIALS, ic: + log.error(ic) + finally: + conn.unbind()