You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vpngen.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import glob
  2. import json
  3. import os
  4. import os.path
  5. import re
  6. import shutil
  7. from enum import Enum
  8. from subprocess import call
  9. class VpnGenError(Enum):
  10. Success = 0,
  11. VpnAlreadyExists = 1,
  12. VpnDoesNotExists = 2,
  13. ClientAlreadyExists = 3,
  14. ClientDoesNotExists = 4
  15. class VpnGen:
  16. default_config_base_dir = ""
  17. default_config_file = ""
  18. default_client_config_file = ""
  19. ovpn_config_path = ""
  20. def __init__(self, default_config_path, ovpn_config_path):
  21. self.default_config_base_dir = os.path.abspath(default_config_path)
  22. self.default_config_file = "%s.conf" % self.default_config_base_dir
  23. self.default_client_config_file = "%s%sclients%sclient.conf" % (self.default_config_base_dir, os.sep, os.sep)
  24. self.ovpn_config_path = os.path.abspath(ovpn_config_path)
  25. def f7(self, seq):
  26. seen = set()
  27. seen_add = seen.add
  28. return [x for x in seq if not (x in seen or seen_add(x))]
  29. def get_vpn_vars(self):
  30. with open(self.default_config_file, "r") as f:
  31. default_config = f.read()
  32. variables = re.findall('\$\{([^}]+)}', default_config)
  33. variables += ["KEY_COUNTRY", "KEY_PROVINCE", "KEY_CITY", "KEY_ORG", "KEY_EMAIL"]
  34. variables = self.f7(variables)
  35. return variables
  36. def get_client_vars(self, vpn_name):
  37. default_client_config_path = self.get_client_default_config_path(vpn_name)
  38. if not os.path.exists(default_client_config_path):
  39. return None
  40. with open(default_client_config_path, "r") as f:
  41. default_config = f.read()
  42. variables = re.findall('\$\{([^}]+)}', default_config)
  43. variables = self.f7(variables)
  44. vpn_variables = self.get_vpn_vars()
  45. real_variables = []
  46. for var in variables:
  47. if var not in vpn_variables and var != "client":
  48. real_variables.append(var)
  49. return real_variables
  50. def get_base_dir(self, vpn_name):
  51. return "%s%s%s%s" % (self.ovpn_config_path, os.sep, vpn_name, os.sep)
  52. def get_config_path(self, vpn_name):
  53. return "%s%s%s.conf" % (self.ovpn_config_path, os.sep, vpn_name)
  54. def get_vpn_variables_path(self, vpn_name):
  55. base_dir = self.get_base_dir(vpn_name)
  56. return "%svpngen.json" % base_dir
  57. def get_easy_rsa_dir(self, vpn_name):
  58. base_dir = self.get_base_dir(vpn_name)
  59. return "%seasy-rsa%s" % (base_dir, os.sep)
  60. def get_easy_rsa_key_dir(self, vpn_name):
  61. easyrsadir = self.get_easy_rsa_dir(vpn_name)
  62. return "%skeys%s" % (easyrsadir, os.sep)
  63. def get_pkitool_path(self, vpn_name):
  64. easyrsadir = self.get_easy_rsa_dir(vpn_name)
  65. return "%spkitool" % easyrsadir
  66. def get_client_default_config_path(self, vpn_name):
  67. base_dir = self.get_base_dir(vpn_name)
  68. return "%s%sclients%sclient.conf" % (base_dir, os.sep, os.sep)
  69. def get_client_dir(self, vpn_name, client_name):
  70. base_dir = self.get_base_dir(vpn_name)
  71. return "%sclients%s%s-%s%s" % (base_dir, os.sep, client_name, vpn_name, os.sep)
  72. def get_client_config_path(self, vpn_name, client_name):
  73. client_dir = self.get_client_dir(vpn_name, client_name)
  74. return "%s%s-%s.conf" % (client_dir, client_name, vpn_name)
  75. def get_client_variables_path(self, vpn_name, client_name):
  76. client_dir = self.get_client_dir(vpn_name, client_name)
  77. return "%svpngen.json" % client_dir
  78. def get_client_generated_files_paths(self, vpn_name, client_name):
  79. keys_dir = self.get_easy_rsa_key_dir(vpn_name,)
  80. return [
  81. "%s%s.crt" % (keys_dir, client_name),
  82. "%s%s.key" % (keys_dir, client_name)
  83. ]
  84. def get_client_tarball_path(self, vpn_name, client_name):
  85. base_dir = self.get_base_dir(vpn_name)
  86. return "%sclients%s%s-%s.tar.bz2" % (base_dir, os.sep, client_name, vpn_name)
  87. def get_server_needed_files_paths(self, vpn_name):
  88. keys_dir = self.get_easy_rsa_key_dir(vpn_name)
  89. return [
  90. "%sca.crt" % keys_dir,
  91. "%sta.key" % keys_dir
  92. ]
  93. def get_client_misc_files_paths(self, vpn_name):
  94. base_dir = self.get_base_dir(vpn_name)
  95. return glob.glob("%smisc-files%s*" % (base_dir, os.sep))
  96. def get_all_needed_files_paths(self, vpn_name, client_name):
  97. return self.get_client_generated_files_paths(vpn_name, client_name) +\
  98. self.get_server_needed_files_paths(vpn_name) +\
  99. self.get_client_misc_files_paths(vpn_name)
  100. def get_server_variables(self, vpn_name):
  101. with open(self.get_vpn_variables_path(vpn_name), "r") as f:
  102. return json.load(f)['variables']
  103. def get_client_variables(self, vpn_name, client_name):
  104. with open(self.get_client_variables_path(vpn_name, client_name), "r") as f:
  105. return json.load(f)['variables']
  106. def get_client_list(self, vpn_name):
  107. base_dir = self.get_base_dir(vpn_name)
  108. files_paths = glob.glob("%sclients%s*" % (base_dir, os.sep))
  109. files_names = list(map(lambda file_path: os.path.basename(file_path), files_paths))
  110. clients = []
  111. for file_name in files_names:
  112. if file_name != 'client.conf' and not file_name.endswith(".tar.bz2"):
  113. clients.append(file_name[0:len(file_name) - len(vpn_name) - 1])
  114. return clients
  115. def setup_vars(self, vpn_name, variables):
  116. easyrsadir = self.get_easy_rsa_dir(vpn_name)
  117. os.environ["KEY_COUNTRY"] = variables['KEY_COUNTRY']
  118. os.environ["KEY_PROVINCE"] = variables['KEY_PROVINCE']
  119. os.environ["KEY_CITY"] = variables['KEY_CITY']
  120. os.environ["KEY_ORG"] = variables['KEY_ORG']
  121. os.environ["KEY_OU"] = variables['KEY_ORG']
  122. os.environ["KEY_CN"] = variables['KEY_ORG']
  123. os.environ["KEY_NAME"] = variables['KEY_ORG']
  124. os.environ["KEY_EMAIL"] = variables['KEY_EMAIL']
  125. os.environ["KEY_SIZE"] = variables['KEY_SIZE']
  126. os.environ["CA_EXPIRE"] = variables['CA_EXPIRE']
  127. os.environ["KEY_EXPIRE"] = variables['KEY_EXPIRE']
  128. os.environ["EASY_RSA"] = easyrsadir
  129. os.environ["OPENSSL"] = "openssl"
  130. os.environ["PKCS11TOOL"] = "pkcs11-tool"
  131. os.environ["GREP"] = "grep"
  132. os.environ["KEY_CONFIG"] = "%s%s" % (easyrsadir, "openssl.cnf")
  133. os.environ["KEY_DIR"] = "%s%s" % (easyrsadir, "keys")
  134. os.environ["PKCS11_MODULE_PATH"] = "dummy"
  135. os.environ["PKCS11_PIN"] = "dummy"
  136. def create_vpn(self, vpn_name, variables):
  137. base_dir = self.get_base_dir(vpn_name)
  138. conf_file = self.get_config_path(vpn_name)
  139. conf_vpngen_file = self.get_vpn_variables_path(vpn_name)
  140. if os.path.exists(base_dir) or os.path.exists(conf_file):
  141. return VpnGenError.VpnAlreadyExists
  142. with open(self.default_config_file, "r") as f:
  143. default_config = f.read()
  144. variables['name'] = vpn_name
  145. for variable in variables:
  146. default_config = default_config.replace("${%s}" % variable, variables[variable])
  147. os.makedirs(base_dir)
  148. with open(conf_file, "w") as f:
  149. f.write(default_config)
  150. os.rmdir(base_dir)
  151. shutil.copytree(self.default_config_base_dir, base_dir)
  152. curdir = os.curdir
  153. easyrsadir = self.get_easy_rsa_dir(vpn_name)
  154. pkitool = self.get_pkitool_path(vpn_name)
  155. os.chdir(easyrsadir)
  156. self.setup_vars(vpn_name, variables)
  157. call([".%sclean-all" % os.sep])
  158. call([pkitool, "--initca", "-batch"])
  159. call([pkitool, "--server", "server", "-batch"])
  160. call([".%sbuild-dh" % os.sep])
  161. call(["openssl", "ca", "-gencrl",
  162. "-keyfile", "keys%sca.key" % os.sep,
  163. "-cert", "keys%sca.crt" % os.sep,
  164. "-out", "keys%scrl.pem" % os.sep,
  165. "-config", "openssl.cnf"])
  166. del os.environ["KEY_OU"]
  167. del os.environ["KEY_CN"]
  168. del os.environ["KEY_NAME"]
  169. call(["openvpn", "--genkey", "--secret", "keys%sta.key" % os.sep])
  170. with open(conf_vpngen_file, "w") as f:
  171. json.dump({'variables': variables}, f, indent=4, separators=(',', ': '))
  172. os.chdir(curdir)
  173. return VpnGenError.Success
  174. def remove_vpn(self, vpn_name):
  175. base_dir = self.get_base_dir(vpn_name)
  176. conf_file = self.get_config_path(vpn_name)
  177. if not os.path.exists(base_dir) and not os.path.exists(conf_file):
  178. return VpnGenError.VpnDoesNotExists
  179. os.remove(conf_file)
  180. shutil.rmtree(base_dir)
  181. return VpnGenError.Success
  182. def create_client(self, vpn_name, client_name, variables):
  183. base_dir = self.get_base_dir(vpn_name)
  184. if not os.path.exists(base_dir):
  185. return VpnGenError.VpnDoesNotExists
  186. client_dir = self.get_client_dir(vpn_name, client_name)
  187. if os.path.exists(client_dir):
  188. return VpnGenError.ClientAlreadyExists
  189. curdir = os.curdir
  190. easyrsadir = self.get_easy_rsa_dir(vpn_name)
  191. pkitool = self.get_pkitool_path(vpn_name)
  192. os.chdir(easyrsadir)
  193. self.setup_vars(vpn_name, variables)
  194. os.environ["KEY_CN"] = client_name
  195. os.environ["KEY_NAME"] = client_name
  196. call([pkitool, client_name])
  197. os.chdir(curdir)
  198. os.makedirs(client_dir)
  199. return self.rebuild_client(vpn_name, client_name, variables)
  200. def remove_client(self, vpn_name, client_name):
  201. base_dir = self.get_base_dir(vpn_name)
  202. if not os.path.exists(base_dir):
  203. return VpnGenError.VpnDoesNotExists
  204. client_dir = self.get_client_dir(vpn_name, client_name)
  205. if not os.path.exists(client_dir):
  206. return VpnGenError.ClientDoesNotExists
  207. return VpnGenError.Success
  208. def rebuild_client(self, vpn_name, client_name, variables):
  209. client_dir = self.get_client_dir(vpn_name, client_name)
  210. client_conf_file = self.get_client_config_path(vpn_name, client_name)
  211. client_default_config_path = self.get_client_default_config_path(vpn_name)
  212. with open(client_default_config_path, "r") as f:
  213. client_default_config = f.read()
  214. for variable in variables:
  215. client_default_config = client_default_config.replace("${%s}" % variable, variables[variable])
  216. files_names = glob.glob("%s%s*" % (client_dir, os.sep))
  217. for file_name in files_names:
  218. os.remove(file_name)
  219. with open(client_conf_file, "w") as f:
  220. f.write(client_default_config)
  221. files_paths = self.get_all_needed_files_paths(vpn_name, client_name)
  222. for file_path in files_paths:
  223. split = os.path.splitext(file_path)
  224. dest = "%s%s-%s%s" % (client_dir, os.path.basename(split[0]), vpn_name, split[1])
  225. shutil.copy(file_path, dest)
  226. split = os.path.splitext(client_conf_file)
  227. client_ovpn_file = "%s.ovpn" % split[0]
  228. shutil.copy(client_conf_file, client_ovpn_file)
  229. files_names = glob.glob("%s%s*" % (client_dir, os.sep))
  230. files_names = list(map(lambda file_path: os.path.basename(file_path), files_names))
  231. call(["tar", "cfj", self.get_client_tarball_path(vpn_name, client_name),
  232. "-C", client_dir] + files_names)
  233. client_variables = {}
  234. for variable in self.get_client_vars(vpn_name):
  235. client_variables[variable] = variables[variable]
  236. with open(self.get_client_variables_path(vpn_name, client_name), "w") as f:
  237. json.dump({'variables': client_variables}, f, indent=4, separators=(',', ': '))
  238. return VpnGenError.Success