Compare commits

...

4 commits

Author SHA1 Message Date
7871a3302c Mutually exclusive service flag 2020-02-26 02:01:37 +01:00
3c849560ac Refactor renew 2020-02-26 01:59:03 +01:00
b684ad330a Fixed )( and if/else 2020-02-25 18:30:20 +01:00
5d13a5c70c First try at reloading after renew 2020-02-25 18:20:01 +01:00

View file

@ -47,18 +47,21 @@ def init_prog(argv):
required=False, required=False,
default=default_conf_file, default=default_conf_file,
help="Specifity config file (default: {})".format(default_conf_file)) help="Specifity config file (default: {})".format(default_conf_file))
parser.add_argument("--liste", default=False, action='store_true', required=False,
help="Richiedi i certificati per liste.indivia.net")
parser.add_argument("--hosting", default=False, action='store_true', required=False,
help="Richiedi i certificati per i siti in hosting")
parser.add_argument("--webmail", default=False, action='store_true', required=False,
help="Richiedi i certificati per le webmail")
parser.add_argument("--smtp", default=False, action='store_true', required=False,
help="Richiedi i certificati per il server SMTP")
parser.add_argument("--mbox", default=False, action='store_true', required=False,
help="Richiedi i certificati per il server POP/IMAP")
parser.add_argument("--renew", default=False, action='store_true', required=False, parser.add_argument("--renew", default=False, action='store_true', required=False,
help="Invoca solamente il renew per i certificati gia' presenti") help="Invoca solamente il renew per i certificati gia' presenti")
service_group = parser.add_mutually_exclusive_group(required=True)
service_group.add_argument("--liste", default=False, action='store_true', required=False,
help="Richiedi i certificati per liste.indivia.net")
service_group.add_argument("--hosting", default=False, action='store_true', required=False,
help="Richiedi i certificati per i siti in hosting")
service_group.add_argument("--webmail", default=False, action='store_true', required=False,
help="Richiedi i certificati per le webmail")
service_group.add_argument("--smtp", default=False, action='store_true', required=False,
help="Richiedi i certificati per il server SMTP")
service_group.add_argument("--mbox", default=False, action='store_true', required=False,
help="Richiedi i certificati per il server POP/IMAP")
args = parser.parse_args() args = parser.parse_args()
try: try:
config = configparser.ConfigParser() config = configparser.ConfigParser()
@ -156,6 +159,33 @@ def get_alias_list(config, dns_conn, query, aliases):
return result_list return result_list
def acme_renew(config, pre_hook_cmd, post_hook_cmd, dryrun=False):
args = config['certbot']['base_args']
# args += " -m {} ".format(config['certbot']['email'])
# args += "--server {} ".format(config['certbot']['server'])
if dryrun:
args += "--dry-run "
if not pre_hook_cmd is None:
args +=' --pre-hook "{}"'.format(pre_hook_cmd)
if not post_hook_cmd is None:
args +=' --post-hook "{}"'.format(post_hook_cmd)
args += " renew"
if dryrun:
logging.info("{} {}".format(config['certbot']['bin'], args))
else:
os.system("{} {}".format(config['certbot']['bin'], args))
return True
def acme_request(config, domain_name, acme_test='DNS-01', webroot=None, dryrun=False, domains_list=None): def acme_request(config, domain_name, acme_test='DNS-01', webroot=None, dryrun=False, domains_list=None):
args = config['certbot']['base_args'] args = config['certbot']['base_args']
@ -219,121 +249,156 @@ if __name__ == '__main__':
dryrun=config['main'].getboolean('dryrun') dryrun=config['main'].getboolean('dryrun')
service_reload = dict() service_reload = dict()
ot_conn=connect_db(dict(config['ot_db']))
dns_conn=connect_db(dict(config['dns_db']))
if dryrun: if dryrun:
print("DRYRUN, nessun certificato verra' richiesto, nessun link/file creato o modificato") print("DRYRUN, nessun certificato verra' richiesto, nessun link/file creato o modificato")
if args.renew:
pre_hook_cmd = None
post_hook_cmd = None
logging.info('Renewing certificates ')
if args.webmail or args.hosting or args.liste:
post_hook_cmd = "systemctl reload apache2"
elif args.smtp:
post_hook_cmd = "systemctl reload postfix"
elif args.mbox:
post_hook_cmd = "systemctl restart dovecot"
# Caso speciale per le webmail logger.debug("post_hook_cmd: {}".format(post_hook_cmd))
if args.webmail:
logging.info('Asking certificates for webmail')
vhost_name = config['webmail']['vhost'].strip()
webmails_list = ["webmail.{}".format(d.strip()) for d in config['webmail']['domains'].split(',') if len(d.strip())>0]
logging.info('vhost {}, domains_list {}'.format(vhost_name, webmails_list))
if acme_request(config, vhost_name, acme_test='HTTP-01', dryrun=dryrun, domains_list=webmails_list):
link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
service_reload['webmail'] = True
else:
logger.error('Error asking certificate for {}'.format(vhost_name))
# Caso speciale per il server POP/IMAP if acme_renew(config, pre_hook_cmd, post_hook_cmd, dryrun=dryrun):
if args.mbox: logger.info("Done renew")
logging.info('Asking certificates for POP/IMAP server')
vhost_name = config['mail']['mbox_vhost'].strip() else:
server_addresses = [s.strip() for s in config['mail']['mbox_server_addresses'].split(',') if len(s.strip())>0] # Fai le nuove richieste per i certificati
mbox_fmt = ','.join(['%s'] * len(server_addresses))
mbox_query = mbox_list_stmt.format(mbox_fmt) # Caso speciale per le webmail
alias_list = get_alias_list(config, dns_conn, mbox_query, server_addresses) if args.webmail:
# Per usi futuri, aggiungo l'alias 'mail.indivia.net' logging.info('Asking certificates for webmail')
alias_list.append('mail.indivia.net') vhost_name = config['webmail']['vhost'].strip()
logging.info('vhost {}, domains_list {}'.format(vhost_name, alias_list)) webmails_list = ["webmail.{}".format(d.strip()) for d in config['webmail']['domains'].split(',') if len(d.strip())>0]
if acme_request(config, vhost_name, acme_test='HTTP-01', webroot=config['mail']['mbox_webroot'].strip(), logging.info('vhost {}, domains_list {}'.format(vhost_name, webmails_list))
dryrun=dryrun, domains_list=alias_list): if acme_request(config, vhost_name, acme_test='HTTP-01', dryrun=dryrun, domains_list=webmails_list):
# non e' richiesto il link, punto direttamente le configurazioni alle dir di letsencrypt link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
# link_cert(config, vhost_name, vhost_name, dryrun=dryrun) else:
service_reload['mbox'] = True logger.error('Error asking certificate for {}'.format(vhost_name))
pass
else: # reload apache
logger.error('Error asking certificate for {}'.format(vhost_name)) logger.info("Reloading apache")
# ret = subprocess.run("systemctl reload apache2")
ret = os.system("systemctl reload apache2")
logger.info(ret)
# Caso speciale per il server SMTP # Caso speciale per l'hosting
if args.smtp: if args.hosting:
logging.info('Asking certificates for SMTP server') logging.info('Asking certificates for hosted web domains')
vhost_name = config['mail']['smtp_vhost'].strip() ot_conn=connect_db(dict(config['ot_db']))
server_addresses = [s.strip() for s in config['mail']['smtp_server_addresses'].split(',') if len(s.strip())>0] dns_conn=connect_db(dict(config['dns_db']))
smtp_fmt = ','.join(['%s'] * len(server_addresses)) # Subdomains da escludere
smtp_query = smtp_list_stmt.format(smtp_fmt) ex_subdomains = tuple([s.strip() for s in config['main']['special_subdomains'].split(',') if len(s.strip())>0])
alias_list = get_alias_list(config, dns_conn, smtp_query, server_addresses) domains_dict = get_domain_list(config, ot_conn, dns_conn)
logging.info('vhost {}, domains_list {}'.format(vhost_name, alias_list))
if acme_request(config, vhost_name, acme_test='HTTP-01', webroot=config['mail']['smtp_webroot'].strip(),
dryrun=dryrun, domains_list=alias_list):
# non e' richiesto il link, punto direttamente le configurazioni alle dir di letsencrypt
# link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
service_reload['smtp'] = True
pass
else:
logger.error('Error asking certificate for {}'.format(vhost_name))
# Caso speciale per l'hosting for domain_name, domain_feat in domains_dict.items():
if args.hosting: domain_feat['subdomains']=get_subdomain_list(config, domain_name, ot_conn, ex_subdomains=ex_subdomains)
logging.info('Asking certificates for hosted web domains') # Controlla se i nameserver sono gestiti da noi
# Subdomains da escludere if domain_feat['managed_ns']:
ex_subdomains = tuple([s.strip() for s in config['main']['special_subdomains'].split(',') if len(s.strip())>0]) # Nel caso il nameserver sia gestito, chiedi certificati per il dominio e la wildcard
domains_dict = get_domain_list(config, ot_conn, dns_conn) logger.info('Get certificates for {}, *.{}'.format(domain_name, domain_name))
if acme_request(config, domain_name, acme_test='DNS-01', dryrun=dryrun):
link_cert(config, domain_name, domain_name, dryrun=dryrun)
# Crea il link per ogni subdomain
for subdomain in domain_feat['subdomains']:
link_cert(config, domain_name, subdomain, dryrun=dryrun)
for domain_name, domain_feat in domains_dict.items(): else:
domain_feat['subdomains']=get_subdomain_list(config, domain_name, ot_conn, ex_subdomains=ex_subdomains) # Nel caso i nameserver NON siano gestiti, allora chiedi un certificato per ogni sottodominio
# Controlla se i nameserver sono gestiti da noi
if domain_feat['managed_ns']:
# Nel caso il nameserver sia gestito, chiedi certificati per il dominio e la wildcard
logger.info('Get certificates for {}, *.{}'.format(domain_name, domain_name))
if acme_request(config, domain_name, acme_test='DNS-01', dryrun=dryrun):
link_cert(config, domain_name, domain_name, dryrun=dryrun)
# Crea il link per ogni subdomain # Crea il link per ogni subdomain
for subdomain in domain_feat['subdomains']: for subdomain in domain_feat['subdomains']:
link_cert(config, domain_name, subdomain, dryrun=dryrun) logger.info('Get certificates for {}'.format(subdomain))
service_reload['hosting'] = True if acme_request(config, subdomain, acme_test='HTTP-01', dryrun=dryrun):
link_cert(config, subdomain, subdomain, dryrun=dryrun)
ot_conn.close()
dns_conn.close()
# reload apache
logger.info("Reloading apache")
# ret = subprocess.run("systemctl reload apache2")
ret = os.system("systemctl reload apache2")
logger.info(ret)
# Caso speciale per l'interfaccia di mailman
if args.liste:
logging.info('Asking certificates for liste.indivia.net')
vhost_name = config['mailman']['vhost'].strip()
liste_list = ["liste.{}".format(d.strip()) for d in config['mailman']['domains'].split(',') if len(d.strip())>0]
if acme_request(config, vhost_name, acme_test='HTTP-01', dryrun=dryrun, domains_list=liste_list):
link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
else: else:
# Nel caso i nameserver NON siano gestiti, allora chiedi un certificato per ogni sottodominio logger.error('Error asking certificate for {}'.format(vhost_name))
# Crea il link per ogni subdomain
for subdomain in domain_feat['subdomains']: # reload apache
logger.info('Get certificates for {}'.format(subdomain)) logger.info("Reloading apache")
if acme_request(config, subdomain, acme_test='HTTP-01', dryrun=dryrun): # ret = subprocess.run("systemctl reload apache2")
link_cert(config, subdomain, subdomain, dryrun=dryrun) ret = os.system("systemctl reload apache2")
service_reload['hosting'] = True logger.info(ret)
ot_conn.close()
dns_conn.close()
# Genero il certificato per l'interfaccia di mailman
if args.liste: # Caso speciale per il server POP/IMAP
logging.info('Asking certificates for liste.indivia.net') if args.mbox:
vhost_name = config['mailman']['vhost'].strip() dns_conn=connect_db(dict(config['dns_db']))
liste_list = ["liste.{}".format(d.strip()) for d in config['mailman']['domains'].split(',') if len(d.strip())>0] logging.info('Asking certificates for POP/IMAP server')
if acme_request(config, vhost_name, acme_test='HTTP-01', dryrun=dryrun, domains_list=liste_list): vhost_name = config['mail']['mbox_vhost'].strip()
link_cert(config, vhost_name, vhost_name, dryrun=dryrun) server_addresses = [s.strip() for s in config['mail']['mbox_server_addresses'].split(',') if len(s.strip())>0]
service_reload['liste'] = True mbox_fmt = ','.join(['%s'] * len(server_addresses))
else: mbox_query = mbox_list_stmt.format(mbox_fmt)
logger.error('Error asking certificate for {}'.format(vhost_name)) alias_list = get_alias_list(config, dns_conn, mbox_query, server_addresses)
# Per usi futuri, aggiungo l'alias 'mail.indivia.net'
alias_list.append('mail.indivia.net')
logging.info('vhost {}, domains_list {}'.format(vhost_name, alias_list))
if acme_request(config, vhost_name, acme_test='HTTP-01', webroot=config['mail']['mbox_webroot'].strip(),
dryrun=dryrun, domains_list=alias_list):
# non e' richiesto il link, punto direttamente le configurazioni alle dir di letsencrypt
# link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
service_reload['mbox'] = True
pass
else:
logger.error('Error asking certificate for {}'.format(vhost_name))
dns_conn.close()
# restart dovecot
logger.info("Restarting dovecot")
# ret = subprocess.run("systemctl restart dovecot")
ret = os.system("systemctl restart dovecot")
logger.info(ret)
if set(['webmail','hosting','liste']) & set(service_reload.keys()): # Caso speciale per il server SMTP
# reload apache if args.smtp:
logger.info("Restarting apache") logging.info('Asking certificates for SMTP server')
# ret = subprocess.run("systemctl reload apache2") dns_conn=connect_db(dict(config['dns_db']))
ret = os.system("systemctl reload apache2") vhost_name = config['mail']['smtp_vhost'].strip()
logger.info(ret) server_addresses = [s.strip() for s in config['mail']['smtp_server_addresses'].split(',') if len(s.strip())>0]
if set(['smtp',]) & set(service_reload.keys()): smtp_fmt = ','.join(['%s'] * len(server_addresses))
# reload postfix smtp_query = smtp_list_stmt.format(smtp_fmt)
logger.info("Restarting postfix") alias_list = get_alias_list(config, dns_conn, smtp_query, server_addresses)
# ret = subprocess.run("systemctl reload postfix") logging.info('vhost {}, domains_list {}'.format(vhost_name, alias_list))
ret = os.system("systemctl reload postfix") if acme_request(config, vhost_name, acme_test='HTTP-01', webroot=config['mail']['smtp_webroot'].strip(),
logger.info(ret) dryrun=dryrun, domains_list=alias_list):
if set(['mbox',]) & set(service_reload.keys()): # non e' richiesto il link, punto direttamente le configurazioni alle dir di letsencrypt
# restart dovecot # link_cert(config, vhost_name, vhost_name, dryrun=dryrun)
logger.info("Restarting dovecot") service_reload['smtp'] = True
# ret = subprocess.run("systemctl restart dovecot") pass
ret = os.system("systemctl restart dovecot") else:
logger.info(ret) logger.error('Error asking certificate for {}'.format(vhost_name))
dns_conn.close()
# reload postfix
logger.info("Restarting postfix")
# ret = subprocess.run("systemctl reload postfix")
ret = os.system("systemctl reload postfix")
logger.info(ret)