OTcerts.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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_request(config, domain_name, acme_test='DNS-01', webroot=None, dryrun=False, domains_list=None):
  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 acme_test == 'DNS-01':
  134. args += " --manual certonly "
  135. args += "--preferred-challenges dns-01 "
  136. args += "--manual-auth-hook {} ".format(config['certbot']['auth_hook'])
  137. args += "--manual-cleanup-hook {} ".format(config['certbot']['cleanup_hook'])
  138. args += "-d {},*.{}".format(domain_name, domain_name)
  139. elif acme_test == 'HTTP-01':
  140. args += " --webroot certonly "
  141. args += "--preferred-challenges http-01 "
  142. if webroot is None:
  143. args += "-w {}/{}/htdocs ".format(config['apache']['webroot'], domain_name)
  144. else:
  145. args += "-w {} ".format(webroot)
  146. if domains_list is None:
  147. args += "-d {}".format(domain_name)
  148. else:
  149. args += "--expand --cert-name {} ".format(domain_name)
  150. args += "-d {}".format(",".join(domains_list))
  151. else:
  152. logger.error('acme test {} not supported'.format(acme_test))
  153. return False
  154. if dryrun:
  155. logging.info("{} {}".format(config['certbot']['bin'], args))
  156. else:
  157. os.system("{} {}".format(config['certbot']['bin'], args))
  158. return True
  159. def symlink_force(target, link_name):
  160. try:
  161. os.symlink(target, link_name)
  162. except Exception as e:
  163. if e.errno == errno.EEXIST:
  164. os.remove(link_name)
  165. os.symlink(target, link_name)
  166. else:
  167. raise e
  168. def link_cert(config, source, dest, dryrun=False):
  169. src_name = os.path.join(config['certbot']['live_certificates_dir'], source)
  170. link_name = os.path.join(config['apache']['certificates_root'], dest)
  171. if dryrun:
  172. logger.info('{} -> {}'.format(link_name,src_name))
  173. return
  174. else:
  175. symlink_force(src_name, link_name)
  176. if __name__ == '__main__':
  177. args, config = init_prog(sys.argv)
  178. dryrun=config['main'].getboolean('dryrun')
  179. service_reload = dict()
  180. ot_conn=connect_db(dict(config['ot_db']))
  181. dns_conn=connect_db(dict(config['dns_db']))
  182. if dryrun:
  183. print("DRYRUN, nessun certificato verra' richiesto, nessun link/file creato o modificato")
  184. # Caso speciale per le webmail
  185. if args.webmail:
  186. logging.info('Asking certificates for webmail')
  187. vhost_name = config['webmail']['vhost'].strip()
  188. webmails_list = ["webmail.{}".format(d.strip()) for d in config['webmail']['domains'].split(',') if len(d.strip())>0]
  189. logging.info('vhost {}, domains_list {}'.format(vhost_name, webmails_list))
  190. if acme_request(config, vhost_name, acme_test='HTTP-01', dryrun=dryrun, domains_list=webmails_list):
  191. link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
  192. service_reload['webmail'] = True
  193. else:
  194. logger.error('Error asking certificate for {}'.format(vhost_name))
  195. # Caso speciale per il server POP/IMAP
  196. if args.mbox:
  197. logging.info('Asking certificates for POP/IMAP server')
  198. vhost_name = config['mail']['mbox_vhost'].strip()
  199. server_addresses = [s.strip() for s in config['mail']['mbox_server_addresses'].split(',') if len(s.strip())>0]
  200. mbox_fmt = ','.join(['%s'] * len(server_addresses))
  201. mbox_query = mbox_list_stmt.format(mbox_fmt)
  202. alias_list = get_alias_list(config, dns_conn, mbox_query, server_addresses)
  203. # Per usi futuri, aggiungo l'alias 'mail.indivia.net'
  204. alias_list.append('mail.indivia.net')
  205. logging.info('vhost {}, domains_list {}'.format(vhost_name, alias_list))
  206. if acme_request(config, vhost_name, acme_test='HTTP-01', webroot=config['mail']['mbox_webroot'].strip(),
  207. dryrun=dryrun, domains_list=alias_list):
  208. # non e' richiesto il link, punto direttamente le configurazioni alle dir di letsencrypt
  209. # link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
  210. service_reload['mbox'] = True
  211. pass
  212. else:
  213. logger.error('Error asking certificate for {}'.format(vhost_name))
  214. # Caso speciale per il server SMTP
  215. if args.smtp:
  216. logging.info('Asking certificates for SMTP server')
  217. vhost_name = config['mail']['smtp_vhost'].strip()
  218. server_addresses = [s.strip() for s in config['mail']['smtp_server_addresses'].split(',') if len(s.strip())>0]
  219. smtp_fmt = ','.join(['%s'] * len(server_addresses))
  220. smtp_query = smtp_list_stmt.format(smtp_fmt)
  221. alias_list = get_alias_list(config, dns_conn, smtp_query, server_addresses)
  222. logging.info('vhost {}, domains_list {}'.format(vhost_name, alias_list))
  223. if acme_request(config, vhost_name, acme_test='HTTP-01', webroot=config['mail']['smtp_webroot'].strip(),
  224. dryrun=dryrun, domains_list=alias_list):
  225. # non e' richiesto il link, punto direttamente le configurazioni alle dir di letsencrypt
  226. # link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
  227. service_reload['smtp'] = True
  228. pass
  229. else:
  230. logger.error('Error asking certificate for {}'.format(vhost_name))
  231. # Caso speciale per l'hosting
  232. if args.hosting:
  233. logging.info('Asking certificates for hosted web domains')
  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. service_reload['hosting'] = True
  249. else:
  250. # Nel caso i nameserver NON siano gestiti, allora chiedi un certificato per ogni sottodominio
  251. # Crea il link per ogni subdomain
  252. for subdomain in domain_feat['subdomains']:
  253. logger.info('Get certificates for {}'.format(subdomain))
  254. if acme_request(config, subdomain, acme_test='HTTP-01', dryrun=dryrun):
  255. link_cert(config, subdomain, subdomain, dryrun=dryrun)
  256. service_reload['hosting'] = True
  257. ot_conn.close()
  258. dns_conn.close()
  259. # Genero il certificato per l'interfaccia di mailman
  260. if args.liste:
  261. logging.info('Asking certificates for liste.indivia.net')
  262. vhost_name = config['mailman']['vhost'].strip()
  263. liste_list = ["liste.{}".format(d.strip()) for d in config['mailman']['domains'].split(',') if len(d.strip())>0]
  264. if acme_request(config, vhost_name, acme_test='HTTP-01', dryrun=dryrun, domains_list=liste_list):
  265. link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
  266. service_reload['liste'] = True
  267. else:
  268. logger.error('Error asking certificate for {}'.format(vhost_name))
  269. if set(['webmail','hosting','liste']) & set(service_reload.keys()):
  270. # reload apache
  271. logger.info("Restarting apache")
  272. # ret = subprocess.run("systemctl reload apache2")
  273. ret = os.system("systemctl reload apache2")
  274. logger.info(ret)
  275. if set(['smtp',]) & set(service_reload.keys()):
  276. # reload postfix
  277. logger.info("Restarting postfix")
  278. # ret = subprocess.run("systemctl reload postfix")
  279. ret = os.system("systemctl reload postfix")
  280. logger.info(ret)
  281. if set(['mbox',]) & set(service_reload.keys()):
  282. # restart dovecot
  283. logger.info("Restarting dovecot")
  284. # ret = subprocess.run("systemctl restart dovecot")
  285. ret = os.system("systemctl restart dovecot")
  286. logger.info(ret)