SHARE
TWEET

OpenVPN Access Server - Post Auth Script

a guest May 23rd, 2014 756 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import sys
  2. import time
  3. import ldap
  4. import re
  5. import smtplib
  6.  
  7. from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)
  8. from email.MIMEText import MIMEText
  9. from email.Header import Header
  10. from email.Utils import parseaddr, formataddr
  11.  
  12.  
  13. #gestion LDAP
  14. ldap_type = u"ldap" # Can be ldap or ldaps
  15. ldap_server = u"<YOUR LDAP SERVER HERE>"
  16. ldap_server_port = u"389"
  17. ldap_basedn = u"dc=example,dc=com"
  18. ldap_userbind = u"<YOUR LDAP BIND DN ACCOUNT HERE"
  19. ldap_passbind = u"<YOUR LDAP BIND ACCOUNT PASSWORD HERE>"
  20.  
  21. #gestion du mail
  22. mailsubject = "<MAIL SUBJECT HERE>"
  23. mailsender = "<MAIL SENDER HERE>"
  24. mailserver = "<SMTP SERVER HERE>"
  25.  
  26.  
  27. def send_mail(sender, recipient, user, ip, mac):
  28.  
  29.     #Body construction (yes, that may not be the nicest python code you'll see ...)
  30.     body = u"Bonjour "+ user + u", \r\n \r\n"
  31.     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"
  32.     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"
  33.     body = body + u"IP source : " + ip + u"\r\n"
  34.     body = body + u"Mac source : " + mac + u"\r\n \r\n"
  35.     body = body + u"Bien cordialement,\r\n"
  36.     body = body + u"Le serveur VPN."
  37.    
  38.     # Header class is smart enough to try US-ASCII, then the charset we
  39.     # provide, then fall back to UTF-8.
  40.     header_charset = 'ISO-8859-1'
  41.  
  42.     # We must choose the body charset manually
  43.     for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
  44.         try:
  45.             body.encode(body_charset)
  46.         except UnicodeError:
  47.             pass
  48.         else:
  49.             break
  50.  
  51.     # Split real name (which is optional) and email address parts
  52.     sender_name, sender_addr = parseaddr(sender)
  53.     recipient_name, recipient_addr = parseaddr(recipient)
  54.  
  55.     # We must always pass Unicode strings to Header, otherwise it will
  56.     # use RFC 2047 encoding even on plain ASCII strings.
  57.     sender_name = str(Header(unicode(sender_name), header_charset))
  58.     recipient_name = str(Header(unicode(recipient_name), header_charset))
  59.  
  60.     # Make sure email addresses do not contain non-ASCII characters
  61.     sender_addr = sender_addr.encode('ascii')
  62.     recipient_addr = recipient_addr.encode('ascii')
  63.  
  64.     # Create the message ('plain' stands for Content-Type: text/plain)
  65.     msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
  66.     msg['From'] = formataddr((sender_name, sender_addr))
  67.     msg['To'] = formataddr((recipient_name, recipient_addr))
  68.     msg['Subject'] = Header(unicode(mailsubject), header_charset)
  69.  
  70.     # Send the message via SMTP
  71.     smtp = SMTP(mailserver)
  72.     smtp.sendmail(sender, recipient, msg.as_string())
  73.     smtp.quit()
  74.  
  75.  
  76. def getldapinfo(sAMAccountName):
  77.     import ldap
  78.  
  79.  
  80.     try:
  81.         print "Post_Auth_Script_LDAP : Trying to initialize ..."
  82.         l = ldap.initialize(ldap_type + '://' + ldap_server + ':' + ldap_server_port)
  83.         l.protocol_version = ldap.VERSION3
  84.     except ldap.LDAPError, e:
  85.         print "Post_Auth_Script_LDAP : Initializing failed ..."
  86.         print e
  87.     try:    
  88.         print "Post_Auth_Script_LDAP : Initialize OK"
  89.         print "Post_Auth_Script_LDAP : Trying to bind  with " + ldap_userbind + ":[redacted]"
  90.         l.simple_bind_s(ldap_userbind, ldap_passbind)
  91.         print "Post_Auth_Script_LDAP : Bind Ok"
  92.         #time.sleep(1)
  93.     except ldap.LDAPError, e:
  94.         print "Post_Auth_Script_LDAP : Bind Failed ..."
  95.         print e
  96.  
  97.     try:
  98.         givenname = ""
  99.         mail = ""
  100.         print "Post_Auth_Script_LDAP : Beginning LDAP search ..."
  101.         try :
  102.             r = l.search_ext(ldap_basedn,ldap.SCOPE_SUBTREE,'(sAMAccountName=' + sAMAccountName + ')', ['mail', 'givenname'])
  103.             result_set = []
  104.             result_set = l.result(r,0)
  105.             print "Post_Auth_Script_LDAP : Checking if " + sAMAccountName + " has an email address ..."
  106.             if 'mail' in result_set[1][0][1]:
  107.                 mail = ''.join(result_set[1][0][1]['mail'])
  108.                 print "Post_Auth_Script_LDAP : Yep, using " + mail + " :)"
  109.             else:
  110.                 print "Post_Auth_Script_LDAP : Nop, returning empty email value :("
  111.             print "Post_Auth_Script_LDAP : Checking if " + sAMAccountName + " has a givenName ..."
  112.             if 'givenName' in result_set[1][0][1]:
  113.                 givenname = ''.join(result_set[1][0][1]['givenName'])
  114.                 print "Post_Auth_Script_LDAP : Yep, using " + givenname + " :)"
  115.             else:
  116.                 print "Post_Auth_Script_LDAP : Nop, returning empty givenName value :("
  117.         except ldap.LDAPError, e:
  118.             print "Post_Auth_Script_LDAP : LDAP search Failed ..."
  119.        
  120.        
  121.         l.unbind_s()
  122.     except ldap.LDAPError, e:
  123.         print e      
  124.         l.unbind_s()
  125.         mail = ""
  126.     return mail, givenname
  127.  
  128.  
  129.  
  130. def post_auth(authcred, attributes, authret, info):
  131.  
  132.     print "**********************************************"
  133.     print "****AUTHCRED", authcred
  134.     print "ATTRIBUTES", attributes
  135.     print "AUTHRET", authret
  136.     print "INFO", info
  137.    
  138.  
  139.     if info.get('auth_method') == 'session' or (info.get('auth_method') == 'challenge_response' and authcred.get('client_ip_addr') != '127.0.0.1'):
  140.        
  141.         if authcred.get('username'):
  142.             username = authcred.get('username')
  143.         else:
  144.             username = ''
  145.         if authcred.get('client_ip_addr'):
  146.             userpubip = authcred.get('client_ip_addr')
  147.         else:
  148.             userpubip = 'Aucune'
  149.         if authcred.get('client_hw_addr'):
  150.             usermac = authcred.get('client_hw_addr')
  151.         else:
  152.             usermac = 'Aucune'
  153.         useremail, givenname = getldapinfo(username)
  154.         if str(useremail) != '':
  155.             try:
  156.                 send_mail(mailsender, useremail, givenname, userpubip, usermac)
  157.                 print u"Post_Auth_Script_Email : Email de connexion envoyé à " + useremail + u"."
  158.             except Exception, exc:
  159.                 print "Post_Auth_Script_Email : Erreur lors de l'envoie de l'Email : ", str(exc)
  160.         else:
  161.             print u"Post_Auth_Script_Email : L'utilisateur " + username + u" n'a pas d'adresse Email connue.\nEchec de l'envoie de mail."
  162.     else:
  163.         print u"Post_Auth_Script : Attente de la connexion type 'session' ou 'challenge_response' avec une IP cliente valable, annulation du script post-auth."
  164.    
  165.     print "**********************************************"
  166.     return authret
RAW Paste Data
Top