OTcerts.py 16 KB

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