""" A lightweight authentication module that checks if username + password was ok against given LDAP server. The script takes its input from stdin and prints output to stdout. This script was developed in May 2010 for Verso project. Author: Heikki Salo heikki.ao.salo@iki.fi """ import ldap import sys import logging import logging.handlers from ldap_settings import server, base, log_filename, log_level logger = logging.getLogger('ldap_authenticate') if log_filename is not None: # Writes log only if filename is specified. if log_level: logger.setLevel(log_level) else: logger.setLevel(logging.DEBUG) handler = logging.handlers.RotatingFileHandler( \ log_filename, maxBytes=20000000, backupCount=5) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) def main(): """ Reads username\npassword from stdin and uses authenticate method to determine successful authentication. The specification is that on and only on successful authentication "1" is printed, in all other cases "0". This should be the only things this program prints to stdout. Some logging is also saved for timing the LDAP server and for latter debugging purposes. """ try: logger.debug("Parsing input.") line = sys.stdin.read() username, password = line.split("\n") logger.info("Authenticating %s begins." % username) result = authenticate(username, password) if result: print "1" logger.info("Authenticating %s is over: success." % username) return else: logger.info("Authenticating %s is over: failed." % username) except ValueError: logger.error("Malformed input, got ValueError.") except: logger.fatal("Caught '%s'." % sys.exc_info()[0]) print "0" def authenticate(username, password): """ Authenticates user with defined LDAP server. This method simply takes username and password, then returns if the pair was correct. Documentation for Python LDAP can be found here: http://www.python-ldap.org/doc/html/ldap.html """ conn = ldap.initialize(server) dn = "cn=%s,%s" % (username, base) try: conn.bind(dn, password) result = conn.result() return result[0] == ldap.RES_BIND except ldap.INVALID_CREDENTIALS: return False except: logger.fatal("Caught '%s' while authenticating %s." % (sys.exc_info()[0], username)) return False if __name__ == "__main__": main()