dataset/seed/letsencrypt/funcs/letsencrypt.py

81 lines
2.9 KiB
Python
Raw Normal View History

2022-03-15 12:12:56 +01:00
import __main__
from subprocess import run as _run
from os.path import dirname as _dirname, abspath as _abspath, join as _join, isfile as _isfile, isdir as _isdir
from datetime import datetime as _datetime
from shutil import copyfile as _copyfile
from os import makedirs as _makedirs
_HERE = _dirname(_abspath(__main__.__file__))
2022-10-01 19:23:14 +02:00
_HERE = '/home/gnunux/git/risotto/risotto'
2022-03-15 12:12:56 +01:00
_LE_DIR = _join(_HERE, 'pki', 'letsencrypt')
_X509_DIR = _join(_HERE, 'pki', 'x509')
def letsencrypt_certif(domain: str,
authority_cn: str,
plugin_name: str,
credential_filename: str,
email: str,
2022-06-24 19:00:16 +02:00
hide_secret: bool,
2022-03-15 12:12:56 +01:00
) -> None:
2022-06-24 19:00:16 +02:00
if hide_secret:
return
2022-03-20 21:15:45 +01:00
if None in (domain, authority_cn, plugin_name, credential_filename, email):
2022-03-15 12:12:56 +01:00
return
2022-03-20 21:15:45 +01:00
authority_name = 'External'
2022-03-15 12:12:56 +01:00
date_file = _join(_LE_DIR, f'{domain}.date')
date = _datetime.now()
today = str(date.date())
if not _isfile(date_file):
letsencrypt_date = '0'
else:
with open(date_file, 'r') as fh:
letsencrypt_date = fh.read().strip()
if letsencrypt_date != today:
2022-10-01 19:23:14 +02:00
# print(f"Obtain or renew Let's Encrypt certificate for {domain}...")
2022-03-15 12:12:56 +01:00
cli_args = ['certbot',
'certonly',
f'--dns-{plugin_name}',
f'--dns-{plugin_name}-credentials',
credential_filename,
'-d',
domain,
'--quiet',
'--config-dir',
f'{_LE_DIR}/{domain}/config',
'--work-dir',
f'{_LE_DIR}/{domain}/work',
'--logs-dir',
f'{_LE_DIR}/{domain}/logs',
'--agree-tos',
'-m',
email,
'--dns-ovh-propagation-seconds',
'360',
]
ret = _run(cli_args, capture_output=True)
if ret.returncode != 0:
2022-08-18 10:19:43 +02:00
print("FIXME")
#raise ValueError(ret.stderr.decode())
2022-10-01 19:23:14 +02:00
# print("Done")
2022-03-15 12:12:56 +01:00
with open(date_file, 'w') as fh:
fh.write(today)
rootdir = _join(_X509_DIR, f'{authority_name}+{authority_cn}')
chaindir = _join(rootdir, 'ca')
certdir = _join(rootdir, 'certificats', domain, 'server')
week_number = date.isocalendar().week
for dirname in (chaindir, certdir):
if not _isdir(dirname):
_makedirs(dirname)
_copyfile(_join(_LE_DIR, domain, 'config/live', domain, 'chain.pem'),
_join(chaindir, f'certificate_{week_number}.crt'),
)
_copyfile(_join(_LE_DIR, domain, 'config/live', domain, 'privkey.pem'),
_join(certdir, 'private.key'),
)
_copyfile(_join(_LE_DIR, domain, 'config/live', domain, 'fullchain.pem'),
_join(certdir, f'certificate_{week_number}.crt'),
)