OTcerts.py 13 KB

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