OTcerts.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import os
  2. import sys
  3. import errno
  4. import argparse
  5. import configparser
  6. import logging
  7. import mysql.connector
  8. import subprocess
  9. # Query for IMAP/POP3 certificate
  10. mbox_list_stmt = "SELECT DISTINCT(name) FROM records WHERE content in ({}) and (name LIKE 'imap.%' or name LIKE 'pop3.%' or name LIKE 'mail.%')"
  11. # Query for SMTP certificate
  12. smtp_list_stmt = "SELECT DISTINCT(name) FROM records WHERE content in ({}) and (name LIKE 'smtp.%' or name LIKE 'mail.%')"
  13. # Get list of defined domains in vhosts configuration database
  14. domains_list_stmt = """SELECT DISTINCT(SUBSTRING_INDEX(urls.dns_name, '.', -2)) AS domain_names
  15. FROM urls INNER JOIN (hosts_urls, hosts, vhosts_features, vhosts)
  16. ON (urls.url_id = hosts_urls.url_id and urls.url_id = vhosts.url_id and vhosts.vhost_id = vhosts_features.vhost_id)
  17. WHERE (hosts_urls.http = 'Y' and hosts.hostname = %(webserver)s)
  18. """
  19. # Get domain_id if defined in nameserver database
  20. domain_id_stmt="SELECT domains.id as domain_id FROM domains WHERE domains.name=%(domain)s"
  21. subdomains_list_stmt = "SELECT DISTINCT(urls.dns_name) AS domain_names "\
  22. "FROM urls INNER JOIN (hosts_urls, hosts, vhosts_features, vhosts ) "\
  23. "ON (urls.url_id = hosts_urls.url_id and urls.url_id = vhosts.url_id and vhosts.vhost_id = vhosts_features.vhost_id) "\
  24. "WHERE (hosts_urls.http = 'Y' and hosts.hostname = %(webserver)s and "\
  25. "urls.dns_name LIKE %(domain)s)"
  26. default_conf_file="./etc/ot_certs.ini"
  27. logging.basicConfig(level=logging.INFO)
  28. logger = logging.getLogger()
  29. def init_prog(argv):
  30. """
  31. Parse command line args and config file
  32. """
  33. parser = argparse.ArgumentParser(
  34. description="Manage LetsEncrypt certificates")
  35. parser.add_argument("-c", "--config", type=open,
  36. required=False,
  37. default=default_conf_file,
  38. help="Specifity config file (default: {})".format(default_conf_file))
  39. parser.add_argument("--renew", default=False, action='store_true', required=False,
  40. help="Invoca solamente il renew per i certificati gia' presenti")
  41. service_group = parser.add_mutually_exclusive_group(required=True)
  42. service_group.add_argument("--liste", default=False, action='store_true', required=False,
  43. help="Richiedi i certificati per liste.indivia.net")
  44. service_group.add_argument("--hosting", default=False, action='store_true', required=False,
  45. help="Richiedi i certificati per i siti in hosting")
  46. service_group.add_argument("--webmail", default=False, action='store_true', required=False,
  47. help="Richiedi i certificati per le webmail")
  48. service_group.add_argument("--smtp", default=False, action='store_true', required=False,
  49. help="Richiedi i certificati per il server SMTP")
  50. service_group.add_argument("--mbox", default=False, action='store_true', required=False,
  51. help="Richiedi i certificati per il server POP/IMAP")
  52. args = parser.parse_args()
  53. try:
  54. config = configparser.ConfigParser()
  55. config.read_file(args.config)
  56. except Exception as e:
  57. logger.error("Error parsing configuration {}".format(e))
  58. exit(-1)
  59. return args, config
  60. def connect_db(conf_dict):
  61. try:
  62. cnx = mysql.connector.connect(**conf_dict)
  63. except mysql.connector.Error as err:
  64. if err.errno == mysql.connector.errorcode.ER_ACCESS_DENIED_ERROR:
  65. logger.error("Something is wrong with your user name or password")
  66. elif err.errno == mysql.connector.errorcode.ER_BAD_DB_ERROR:
  67. logger.error("Database does not exist")
  68. else:
  69. logger.error(err)
  70. return None
  71. return cnx
  72. def get_subdomain_list(config, domain, ot_conn, ex_subdomains=tuple()):
  73. """
  74. Return a Python list containing subdomain of domain paramer
  75. eg: ['app.arkiwi.org']
  76. """
  77. result_dict=dict()
  78. ot_cursor=ot_conn.cursor()
  79. ot_cursor.execute(subdomains_list_stmt, {'webserver':config['main']['webserver'].strip(" '\""),
  80. 'domain':"%{}%".format(domain)})
  81. subdomains_res = ot_cursor.fetchall()
  82. ot_cursor.close()
  83. subdomains_filtered = [s[0].decode('utf-8') for s in subdomains_res
  84. if not(s[0].decode('utf-8').startswith(ex_subdomains))]
  85. return subdomains_filtered
  86. def get_domain_list(config, ot_conn, dns_conn):
  87. """
  88. Return a dictionary of domains and properties
  89. eg:{'indivia.net': {manage_ns=True, domain_id=92},
  90. 'metalabs.org': {managed_ns=False}}
  91. """
  92. result_dict=dict()
  93. ot_cursor=ot_conn.cursor()
  94. ot_cursor.execute(domains_list_stmt, {'webserver':config['main']['webserver'].strip(" '\"")})
  95. dns_cursor=dns_conn.cursor()
  96. for domain_barr, in ot_cursor:
  97. domain_name = domain_barr.decode("utf-8")
  98. try:
  99. dns_cursor.execute(domain_id_stmt, {'domain':domain_name})
  100. except Exception as e:
  101. logger.error(e)
  102. exit(-1)
  103. dns_res = dns_cursor.fetchall()
  104. if dns_cursor.rowcount == 1 :
  105. result_dict.update({domain_name: {'managed_ns':True, 'domain_id':dns_res[0][0]}})
  106. elif dns_cursor.rowcount == 0:
  107. result_dict.update({domain_name: {'managed_ns':False, 'domain_id':None}})
  108. else:
  109. logger.error('Unexpected result for domain {}'.format(domain_name))
  110. dns_cursor.close()
  111. ot_cursor.close()
  112. return result_dict
  113. def get_alias_list(config, dns_conn, query, aliases):
  114. """
  115. Return a list of domains to get the certificate for
  116. """
  117. result_list = list()
  118. dns_cursor=dns_conn.cursor()
  119. try:
  120. dns_cursor.execute(query, aliases)
  121. except Exception as e:
  122. logger.error(e)
  123. exit(-1)
  124. dns_res = dns_cursor.fetchall()
  125. result_list = [name[0].decode('utf-8') for name in dns_res]
  126. dns_cursor.close()
  127. return result_list
  128. def acme_renew(config, pre_hook_cmd, post_hook_cmd, dryrun=False):
  129. args = config['certbot']['base_args']
  130. # args += " -m {} ".format(config['certbot']['email'])
  131. # args += "--server {} ".format(config['certbot']['server'])
  132. if dryrun:
  133. args += "--dry-run "
  134. if not pre_hook_cmd is None:
  135. args +=' --pre-hook "{}"'.format(pre_hook_cmd)
  136. if not post_hook_cmd is None:
  137. args +=' --post-hook "{}"'.format(post_hook_cmd)
  138. args += " renew"
  139. if dryrun:
  140. logging.info("{} {}".format(config['certbot']['bin'], args))
  141. else:
  142. os.system("{} {}".format(config['certbot']['bin'], args))
  143. return True
  144. def acme_request(config, domain_name, acme_test='DNS-01', webroot=None, dryrun=False, domains_list=None):
  145. args = config['certbot']['base_args']
  146. args += " -m {} ".format(config['certbot']['email'])
  147. args += "--server {} ".format(config['certbot']['server'])
  148. if dryrun:
  149. args += "--dry-run "
  150. if acme_test == 'DNS-01':
  151. args += " --manual certonly "
  152. args += "--preferred-challenges dns-01 "
  153. args += "--manual-auth-hook {} ".format(config['certbot']['auth_hook'])
  154. args += "--manual-cleanup-hook {} ".format(config['certbot']['cleanup_hook'])
  155. args += "-d {},*.{}".format(domain_name, domain_name)
  156. elif acme_test == 'HTTP-01':
  157. args += " --webroot certonly "
  158. args += "--preferred-challenges http-01 "
  159. if webroot is None:
  160. args += "-w {}/{}/htdocs ".format(config['apache']['webroot'], domain_name)
  161. else:
  162. args += "-w {} ".format(webroot)
  163. if domains_list is None:
  164. args += "-d {}".format(domain_name)
  165. else:
  166. args += "--expand --cert-name {} ".format(domain_name)
  167. args += "-d {}".format(",".join(domains_list))
  168. else:
  169. logger.error('acme test {} not supported'.format(acme_test))
  170. return False
  171. if dryrun:
  172. logging.info("{} {}".format(config['certbot']['bin'], args))
  173. else:
  174. os.system("{} {}".format(config['certbot']['bin'], args))
  175. return True
  176. def symlink_force(target, link_name):
  177. try:
  178. os.symlink(target, link_name)
  179. except Exception as e:
  180. if e.errno == errno.EEXIST:
  181. os.remove(link_name)
  182. os.symlink(target, link_name)
  183. else:
  184. raise e
  185. def link_cert(config, source, dest, dryrun=False):
  186. src_name = os.path.join(config['certbot']['live_certificates_dir'], source)
  187. link_name = os.path.join(config['apache']['certificates_root'], dest)
  188. if dryrun:
  189. logger.info('{} -> {}'.format(link_name,src_name))
  190. return
  191. else:
  192. symlink_force(src_name, link_name)
  193. if __name__ == '__main__':
  194. args, config = init_prog(sys.argv)
  195. dryrun=config['main'].getboolean('dryrun')
  196. service_reload = dict()
  197. if dryrun:
  198. print("DRYRUN, nessun certificato verra' richiesto, nessun link/file creato o modificato")
  199. if args.renew:
  200. pre_hook_cmd = None
  201. post_hook_cmd = None
  202. logging.info('Renewing certificates ')
  203. if args.webmail or args.hosting or args.liste:
  204. post_hook_cmd = "systemctl reload apache2"
  205. elif args.smtp:
  206. post_hook_cmd = "systemctl reload postfix"
  207. elif args.mbox:
  208. post_hook_cmd = "systemctl restart dovecot"
  209. logger.debug("post_hook_cmd: {}".format(post_hook_cmd))
  210. if acme_renew(config, pre_hook_cmd, post_hook_cmd, dryrun=dryrun):
  211. logger.info("Done renew")
  212. else:
  213. # Fai le nuove richieste per i certificati
  214. # Caso speciale per le webmail
  215. if args.webmail:
  216. logging.info('Asking certificates for webmail')
  217. vhost_name = config['webmail']['vhost'].strip()
  218. webmails_list = ["webmail.{}".format(d.strip()) for d in config['webmail']['domains'].split(',') if len(d.strip())>0]
  219. logging.info('vhost {}, domains_list {}'.format(vhost_name, webmails_list))
  220. if acme_request(config, vhost_name, acme_test='HTTP-01', dryrun=dryrun, domains_list=webmails_list):
  221. link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
  222. else:
  223. logger.error('Error asking certificate for {}'.format(vhost_name))
  224. # reload apache
  225. logger.info("Reloading apache")
  226. # ret = subprocess.run("systemctl reload apache2")
  227. ret = os.system("systemctl reload apache2")
  228. logger.info(ret)
  229. # Caso speciale per l'hosting
  230. if args.hosting:
  231. logging.info('Asking certificates for hosted web domains')
  232. ot_conn=connect_db(dict(config['ot_db']))
  233. dns_conn=connect_db(dict(config['dns_db']))
  234. # Subdomains da escludere
  235. ex_subdomains = tuple([s.strip() for s in config['main']['special_subdomains'].split(',') if len(s.strip())>0])
  236. domains_dict = get_domain_list(config, ot_conn, dns_conn)
  237. for domain_name, domain_feat in domains_dict.items():
  238. domain_feat['subdomains']=get_subdomain_list(config, domain_name, ot_conn, ex_subdomains=ex_subdomains)
  239. # Controlla se i nameserver sono gestiti da noi
  240. if domain_feat['managed_ns']:
  241. # Nel caso il nameserver sia gestito, chiedi certificati per il dominio e la wildcard
  242. logger.info('Get certificates for {}, *.{}'.format(domain_name, domain_name))
  243. if acme_request(config, domain_name, acme_test='DNS-01', dryrun=dryrun):
  244. link_cert(config, domain_name, domain_name, dryrun=dryrun)
  245. # Crea il link per ogni subdomain
  246. for subdomain in domain_feat['subdomains']:
  247. link_cert(config, domain_name, subdomain, dryrun=dryrun)
  248. else:
  249. # Nel caso i nameserver NON siano gestiti, allora chiedi un certificato per ogni sottodominio
  250. # Crea il link per ogni subdomain
  251. for subdomain in domain_feat['subdomains']:
  252. logger.info('Get certificates for {}'.format(subdomain))
  253. if acme_request(config, subdomain, acme_test='HTTP-01', dryrun=dryrun):
  254. link_cert(config, subdomain, subdomain, dryrun=dryrun)
  255. ot_conn.close()
  256. dns_conn.close()
  257. # reload apache
  258. logger.info("Reloading apache")
  259. # ret = subprocess.run("systemctl reload apache2")
  260. ret = os.system("systemctl reload apache2")
  261. logger.info(ret)
  262. # Caso speciale per l'interfaccia di mailman
  263. if args.liste:
  264. logging.info('Asking certificates for liste.indivia.net')
  265. vhost_name = config['mailman']['vhost'].strip()
  266. liste_list = ["liste.{}".format(d.strip()) for d in config['mailman']['domains'].split(',') if len(d.strip())>0]
  267. if acme_request(config, vhost_name, acme_test='HTTP-01', dryrun=dryrun, domains_list=liste_list):
  268. link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
  269. else:
  270. logger.error('Error asking certificate for {}'.format(vhost_name))
  271. # reload apache
  272. logger.info("Reloading apache")
  273. # ret = subprocess.run("systemctl reload apache2")
  274. ret = os.system("systemctl reload apache2")
  275. logger.info(ret)
  276. # Caso speciale per il server POP/IMAP
  277. if args.mbox:
  278. dns_conn=connect_db(dict(config['dns_db']))
  279. logging.info('Asking certificates for POP/IMAP server')
  280. vhost_name = config['mail']['mbox_vhost'].strip()
  281. server_addresses = [s.strip() for s in config['mail']['mbox_server_addresses'].split(',') if len(s.strip())>0]
  282. mbox_fmt = ','.join(['%s'] * len(server_addresses))
  283. mbox_query = mbox_list_stmt.format(mbox_fmt)
  284. alias_list = get_alias_list(config, dns_conn, mbox_query, server_addresses)
  285. # Per usi futuri, aggiungo l'alias 'mail.indivia.net'
  286. alias_list.append('mail.indivia.net')
  287. logging.info('vhost {}, domains_list {}'.format(vhost_name, alias_list))
  288. if acme_request(config, vhost_name, acme_test='HTTP-01', webroot=config['mail']['mbox_webroot'].strip(),
  289. dryrun=dryrun, domains_list=alias_list):
  290. # non e' richiesto il link, punto direttamente le configurazioni alle dir di letsencrypt
  291. # link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
  292. service_reload['mbox'] = True
  293. pass
  294. else:
  295. logger.error('Error asking certificate for {}'.format(vhost_name))
  296. dns_conn.close()
  297. # restart dovecot
  298. logger.info("Restarting dovecot")
  299. # ret = subprocess.run("systemctl restart dovecot")
  300. ret = os.system("systemctl restart dovecot")
  301. logger.info(ret)
  302. # Caso speciale per il server SMTP
  303. if args.smtp:
  304. logging.info('Asking certificates for SMTP server')
  305. dns_conn=connect_db(dict(config['dns_db']))
  306. vhost_name = config['mail']['smtp_vhost'].strip()
  307. server_addresses = [s.strip() for s in config['mail']['smtp_server_addresses'].split(',') if len(s.strip())>0]
  308. smtp_fmt = ','.join(['%s'] * len(server_addresses))
  309. smtp_query = smtp_list_stmt.format(smtp_fmt)
  310. alias_list = get_alias_list(config, dns_conn, smtp_query, server_addresses)
  311. logging.info('vhost {}, domains_list {}'.format(vhost_name, alias_list))
  312. if acme_request(config, vhost_name, acme_test='HTTP-01', webroot=config['mail']['smtp_webroot'].strip(),
  313. dryrun=dryrun, domains_list=alias_list):
  314. # non e' richiesto il link, punto direttamente le configurazioni alle dir di letsencrypt
  315. # link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
  316. service_reload['smtp'] = True
  317. pass
  318. else:
  319. logger.error('Error asking certificate for {}'.format(vhost_name))
  320. dns_conn.close()
  321. # reload postfix
  322. logger.info("Restarting postfix")
  323. # ret = subprocess.run("systemctl reload postfix")
  324. ret = os.system("systemctl reload postfix")
  325. logger.info(ret)