Tag Archive for 'openvpn'

一个Python脚本,让OpenVPN使用postfix邮箱帐号进行身份认证

这几天配置OpenVPN,使用了用户名密码的身份认证方式,借助已有的postfix邮箱帐号,省去了再为每个人设置用户名密码的麻烦。

原理很简单,OpenVPN服务器配置里有这样一句:

auth-user-pass-verify /etc/openvpn/auth-postfix-mailbox.py via-env

就是说要用/etc/openvpn/auth-postfix-mailbox.py这个脚本来验证用户名和密码。用户名和密码如何传递给它呢?via-env,环境变量。

脚本如下:

  1. #!/usr/bin/env python
  2.  
  3. import os
  4. import sys
  5. from MySQLdb import *
  6. import md5crypt
  7.  
  8. def auth(username, password):
  9.   conn = connect (host = 'localhost',
  10.                   user = 'dbuser',
  11.                   passwd = 'dbpasswd',
  12.                   db = 'postfix')
  13.   cursor = conn.cursor()
  14.   cursor.execute("""
  15.       select password from mailbox
  16.       where username=%s
  17.       and active=1
  18.     """, (username))
  19.   row = cursor.fetchone()
  20.   if row == None:
  21.     return 1
  22.   crypt = md5crypt.md5crypt(password, row[0])
  23.   cursor.execute("""
  24.       select * from mailbox
  25.       where username=%s
  26.       and password=%s
  27.       and active=1
  28.    """, (username,crypt))
  29.   row = cursor.fetchone()
  30.   cursor.close()
  31.   conn.close()
  32.   if row == None:
  33.     return 1
  34.   return 0
  35.  
  36. def main():
  37.   status = 0
  38.   try:
  39.     username = os.environ['username']
  40.     password = os.environ['password']
  41.     status = auth(username, password)
  42.   except:
  43.     sys.exit(1)
  44.  
  45.   sys.exit(status)
  46.  
  47. if __name__ == "__main__":
  48.   main()

由于postfix使用md5认证,所以需要用md5crypt这个模块,从这里可以下载到。

Related posts




This work by wolfg is licensed under a Attribution-Noncommercial-Share Alike 2.5 China Mainland.