Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import time
- import ldap
- import re
- import smtplib
- from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
- from email.MIMEText import MIMEText
- from email.Header import Header
- from email.Utils import parseaddr, formataddr
- #gestion LDAP
- ldap_type = u"ldap" # Can be ldap or ldaps
- ldap_server = u"<YOUR LDAP SERVER HERE>"
- ldap_server_port = u"389"
- ldap_basedn = u"dc=example,dc=com"
- ldap_userbind = u"<YOUR LDAP BIND DN ACCOUNT HERE"
- ldap_passbind = u"<YOUR LDAP BIND ACCOUNT PASSWORD HERE>"
- #gestion du mail
- mailsubject = "<MAIL SUBJECT HERE>"
- mailsender = "<MAIL SENDER HERE>"
- mailserver = "<SMTP SERVER HERE>"
- def send_mail(sender, recipient, user, ip, mac):
- #Body construction (yes, that may not be the nicest python code you'll see ...)
- body = u"Bonjour "+ user + u", \r\n \r\n"
- body = body + u"Une connexion au VPN a été etablie avec votre compte le " + time.strftime("%d/%m/%Y") + u" à " + time.strftime("%H:%M:%S") + u".\r\n"
- body = body + u"Si vous n'êtes pas à l'origine de cette connexion, merci de prévenir le service informatique au plus vite.\r\n\r\n"
- body = body + u"IP source : " + ip + u"\r\n"
- body = body + u"Mac source : " + mac + u"\r\n \r\n"
- body = body + u"Bien cordialement,\r\n"
- body = body + u"Le serveur VPN."
- # Header class is smart enough to try US-ASCII, then the charset we
- # provide, then fall back to UTF-8.
- header_charset = 'ISO-8859-1'
- # We must choose the body charset manually
- for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
- try:
- body.encode(body_charset)
- except UnicodeError:
- pass
- else:
- break
- # Split real name (which is optional) and email address parts
- sender_name, sender_addr = parseaddr(sender)
- recipient_name, recipient_addr = parseaddr(recipient)
- # We must always pass Unicode strings to Header, otherwise it will
- # use RFC 2047 encoding even on plain ASCII strings.
- sender_name = str(Header(unicode(sender_name), header_charset))
- recipient_name = str(Header(unicode(recipient_name), header_charset))
- # Make sure email addresses do not contain non-ASCII characters
- sender_addr = sender_addr.encode('ascii')
- recipient_addr = recipient_addr.encode('ascii')
- # Create the message ('plain' stands for Content-Type: text/plain)
- msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
- msg['From'] = formataddr((sender_name, sender_addr))
- msg['To'] = formataddr((recipient_name, recipient_addr))
- msg['Subject'] = Header(unicode(mailsubject), header_charset)
- # Send the message via SMTP
- smtp = SMTP(mailserver)
- smtp.sendmail(sender, recipient, msg.as_string())
- smtp.quit()
- def getldapinfo(sAMAccountName):
- import ldap
- try:
- print "Post_Auth_Script_LDAP : Trying to initialize ..."
- l = ldap.initialize(ldap_type + '://' + ldap_server + ':' + ldap_server_port)
- l.protocol_version = ldap.VERSION3
- except ldap.LDAPError, e:
- print "Post_Auth_Script_LDAP : Initializing failed ..."
- print e
- try:
- print "Post_Auth_Script_LDAP : Initialize OK"
- print "Post_Auth_Script_LDAP : Trying to bind with " + ldap_userbind + ":[redacted]"
- l.simple_bind_s(ldap_userbind, ldap_passbind)
- print "Post_Auth_Script_LDAP : Bind Ok"
- #time.sleep(1)
- except ldap.LDAPError, e:
- print "Post_Auth_Script_LDAP : Bind Failed ..."
- print e
- try:
- givenname = ""
- mail = ""
- print "Post_Auth_Script_LDAP : Beginning LDAP search ..."
- try :
- r = l.search_ext(ldap_basedn,ldap.SCOPE_SUBTREE,'(sAMAccountName=' + sAMAccountName + ')', ['mail', 'givenname'])
- result_set = []
- result_set = l.result(r,0)
- print "Post_Auth_Script_LDAP : Checking if " + sAMAccountName + " has an email address ..."
- if 'mail' in result_set[1][0][1]:
- mail = ''.join(result_set[1][0][1]['mail'])
- print "Post_Auth_Script_LDAP : Yep, using " + mail + " :)"
- else:
- print "Post_Auth_Script_LDAP : Nop, returning empty email value :("
- print "Post_Auth_Script_LDAP : Checking if " + sAMAccountName + " has a givenName ..."
- if 'givenName' in result_set[1][0][1]:
- givenname = ''.join(result_set[1][0][1]['givenName'])
- print "Post_Auth_Script_LDAP : Yep, using " + givenname + " :)"
- else:
- print "Post_Auth_Script_LDAP : Nop, returning empty givenName value :("
- except ldap.LDAPError, e:
- print "Post_Auth_Script_LDAP : LDAP search Failed ..."
- l.unbind_s()
- except ldap.LDAPError, e:
- print e
- l.unbind_s()
- mail = ""
- return mail, givenname
- def post_auth(authcred, attributes, authret, info):
- print "**********************************************"
- print "****AUTHCRED", authcred
- print "ATTRIBUTES", attributes
- print "AUTHRET", authret
- print "INFO", info
- if info.get('auth_method') == 'session' or (info.get('auth_method') == 'challenge_response' and authcred.get('client_ip_addr') != '127.0.0.1'):
- if authcred.get('username'):
- username = authcred.get('username')
- else:
- username = ''
- if authcred.get('client_ip_addr'):
- userpubip = authcred.get('client_ip_addr')
- else:
- userpubip = 'Aucune'
- if authcred.get('client_hw_addr'):
- usermac = authcred.get('client_hw_addr')
- else:
- usermac = 'Aucune'
- useremail, givenname = getldapinfo(username)
- if str(useremail) != '':
- try:
- send_mail(mailsender, useremail, givenname, userpubip, usermac)
- print u"Post_Auth_Script_Email : Email de connexion envoyé à " + useremail + u"."
- except Exception, exc:
- print "Post_Auth_Script_Email : Erreur lors de l'envoie de l'Email : ", str(exc)
- else:
- print u"Post_Auth_Script_Email : L'utilisateur " + username + u" n'a pas d'adresse Email connue.\nEchec de l'envoie de mail."
- else:
- print u"Post_Auth_Script : Attente de la connexion type 'session' ou 'challenge_response' avec une IP cliente valable, annulation du script post-auth."
- print "**********************************************"
- return authret
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement