230 lines
13 KiB
Python
Executable File
230 lines
13 KiB
Python
Executable File
#!/usr/bin/python3
|
|
"""Manage the server's PKI, which the server's directory holds, from the command line, with linuxmanager_pki.
|
|
|
|
status shows the root, the issuing CAs and the warnings; list the certificates the server issued. issue signs a CSR,
|
|
or makes a key and writes a PFX file whose password is read from the first line of standard input. ca csr prints the
|
|
CSR of an issuing CA that waits for the offline root, with the openssl extensions to sign it with, and ca import takes
|
|
the signed certificate, and, named root, the certificate of the offline root. root import-crl takes a CRL of the
|
|
offline root, and root setup-code exchanges a setup code of a Simple CA token, read from the first line of standard
|
|
input, for the token. https status shows the server's HTTPS certificate, https csr prints a new CSR for
|
|
wan.local_fqdn, to be signed by another CA, https import takes the certificate signed for it, and https import-pfx a
|
|
PKCS#12 file whose password is read from the first line of standard input. maintain signs the stale CRLs again, or
|
|
fetches those of Simple CA; linux-manager-pki.service runs it daily. A change that needs linux-manager-setup requests a run of it without waiting.
|
|
|
|
The answer is text for people on standard output, and a failure is a message on standard error. With --json the answer
|
|
is JSON on standard output, and a failure is {"error": ...} there too. The exit status says what failed: 2 the request
|
|
is invalid, 3 something it names does not exist, 4 the state does not allow it, 1 anything else. -h or --help shows the
|
|
commands and their options.
|
|
|
|
linux-manager-ca [--json] status
|
|
linux-manager-ca [--json] list [--ca NAME]
|
|
linux-manager-ca [--json] issue --ca NAME --template NAME --csr FILE
|
|
linux-manager-ca [--json] issue --ca NAME --template NAME --subject NAME [--san NAME ...] --pfx FILE (password on stdin)
|
|
linux-manager-ca [--json] revoke SERIAL [--reason REASON]
|
|
linux-manager-ca [--json] maintain
|
|
linux-manager-ca [--json] ca csr NAME
|
|
linux-manager-ca [--json] ca import NAME|root FILE
|
|
linux-manager-ca [--json] root import-crl FILE
|
|
linux-manager-ca [--json] root setup-code (setup code on stdin)
|
|
linux-manager-ca [--json] https status|csr
|
|
linux-manager-ca [--json] https import FILE
|
|
linux-manager-ca [--json] https import-pfx FILE (password on stdin)
|
|
"""
|
|
|
|
import argparse
|
|
import base64
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
|
|
sys.path.insert(0, '/usr/lib/linux-manager')
|
|
|
|
import ldap
|
|
|
|
import linuxmanager
|
|
import linuxmanager_pki
|
|
from linuxmanager_pki import Failure
|
|
|
|
|
|
class Parser(argparse.ArgumentParser):
|
|
"""An argument parser whose errors end with status 2."""
|
|
|
|
def error(self, message):
|
|
print(f'{self.prog}: {message}; see {self.prog} --help', file=sys.stderr)
|
|
sys.exit(2)
|
|
|
|
|
|
def secret():
|
|
"""The first line of standard input."""
|
|
return sys.stdin.readline().rstrip('\r\n')
|
|
|
|
|
|
def show_status(document):
|
|
root = document['root']
|
|
source = {'local': 'created by the server', 'offline': 'offline',
|
|
'simple-ca': f'Simple CA {root["simple_ca_url"]}'}[root['source']]
|
|
if root['state'] == 'pending':
|
|
print(f'Root CA: {source}, waits for its certificate')
|
|
else:
|
|
print(f'Root CA: {root["subject"]}, {source}, expires {root["expires"]}, '
|
|
f'CRL until {root["crl_next_update"] or "none"}')
|
|
if root['upstream']:
|
|
upstream = root['upstream']
|
|
print(f'Simple CA issuing CA {upstream["name"]}: {upstream["subject"]}, expires {upstream["expires"]}, '
|
|
f'CRL until {upstream["crl_next_update"] or "none"}')
|
|
if root['source'] == 'simple-ca':
|
|
print(f'Simple CA token: {"valid until " + root["token_expires"] if root["token_expires"] else "none"}')
|
|
for authority in document['authorities']:
|
|
line = f'Issuing CA {authority["name"]}: {authority["common_name"]}, {authority["state"]}'
|
|
if authority['expires']:
|
|
line += f', expires {authority["expires"]}, CRL until {authority["crl_next_update"] or "none"}'
|
|
line += f', templates {", ".join(authority["templates"])}'
|
|
if authority['acme_url']:
|
|
line += f', ACME {authority["acme_url"]}'
|
|
print(line)
|
|
for retired in document['retired']:
|
|
print(f'Retired CA {retired["name"]}: {retired["retired"]}')
|
|
for warning in document['warnings']:
|
|
print(f'Warning: {warning}')
|
|
|
|
|
|
def run(options):
|
|
"""Do the command of the options; the answer as a document, and a text for people."""
|
|
cfg = linuxmanager.load_config()
|
|
if options.command == 'status':
|
|
document = linuxmanager_pki.status(cfg)
|
|
return document, None
|
|
if options.command == 'https' and options.action == 'status':
|
|
document = linuxmanager_pki.https_status(cfg)
|
|
return document, (f'Source: {document["source"]}, served: {document["served"] or "none"}\n'
|
|
f'Subject: {document["subject"] or "-"}, issuer: {document["issuer"] or "-"}, '
|
|
f'expires {document["expires"] or "-"}\n'
|
|
f'Names: {", ".join(document["sans"]) or "-"}' + ('\nA CSR waits for its certificate.'
|
|
if document['pending'] else ''))
|
|
if options.command == 'list':
|
|
found = [entry for entry in linuxmanager_pki.certificates() if options.ca in (None, entry['ca'])]
|
|
text = '\n'.join(f'{entry["serial"]} {entry["ca"]} {entry["kind"]} {entry["subject"]} {entry["state"]} '
|
|
f'{entry["expires"]}' for entry in found)
|
|
return {'certificates': found}, text
|
|
with linuxmanager_pki.locked():
|
|
if options.command == 'issue':
|
|
if options.csr:
|
|
document = linuxmanager_pki.issue(cfg, options.ca, options.template,
|
|
csr=pathlib.Path(options.csr).read_text(encoding='ascii'))
|
|
return document, document['certificate'] + document['chain']
|
|
if not options.subject or not options.pfx:
|
|
raise Failure('give --csr, or --subject and --pfx', 2)
|
|
document = linuxmanager_pki.issue(cfg, options.ca, options.template, subject=options.subject,
|
|
sans=options.san or [], password=secret())
|
|
out = pathlib.Path(options.pfx)
|
|
with open(out, 'xb') as handle:
|
|
handle.write(base64.b64decode(document['pfx']))
|
|
return {'serial': document['serial'], 'pfx': str(out)}, f'Certificate {document["serial"]} written to {out}.'
|
|
if options.command == 'revoke':
|
|
document = linuxmanager_pki.revoke(cfg, options.serial, options.reason)
|
|
if document['reissue']:
|
|
linuxmanager.request_setup()
|
|
return document, f'Certificate {document["serial"]} revoked' + \
|
|
('; linux-manager-setup issues a new one.' if document['reissue'] else '.')
|
|
if options.command == 'maintain':
|
|
notices, due = linuxmanager_pki.maintain(cfg)
|
|
if due:
|
|
linuxmanager.request_setup()
|
|
return {'renewal': due, 'notices': notices}, '\n'.join(
|
|
['CRLs checked' + ('; linux-manager-setup renews the certificates.' if due else '.'),
|
|
*(f'Warning: {notice}' for notice in notices)])
|
|
if options.command == 'ca' and options.action == 'csr':
|
|
document = linuxmanager_pki.csr(cfg, options.name)
|
|
return document, document['csr'] + '\n' + document['extensions']
|
|
if options.command == 'ca':
|
|
document = linuxmanager_pki.import_ca(cfg, options.name, pathlib.Path(options.file).read_text(encoding='ascii'))
|
|
linuxmanager.request_setup()
|
|
what = 'The root' if options.name == 'root' else f'Issuing CA {options.name}'
|
|
return document, f'{what} has its certificate, which expires {document["expires"]}.'
|
|
if options.command == 'https' and options.action == 'csr':
|
|
document = linuxmanager_pki.https_csr(cfg)
|
|
return document, document['csr']
|
|
if options.command == 'https':
|
|
if options.action == 'import':
|
|
document = linuxmanager_pki.import_https_certificate(
|
|
cfg, pathlib.Path(options.file).read_text(encoding='ascii'))
|
|
else:
|
|
document = linuxmanager_pki.import_https_pfx(cfg, pathlib.Path(options.file).read_bytes(), secret())
|
|
linuxmanager.request_setup()
|
|
return document, f'The HTTPS certificate of {document["subject"]}, issued by {document["issuer"]}, ' \
|
|
f'expires {document["expires"]}.'
|
|
if options.action == 'setup-code':
|
|
document = linuxmanager_pki.exchange_code(cfg, secret())
|
|
linuxmanager.request_setup()
|
|
return document, (f'Simple CA token of issuing CA {document["upstream"]} taken'
|
|
+ (f', valid until {document["expires"]}.' if document['expires'] else '.'))
|
|
document = linuxmanager_pki.import_root_crl(cfg, pathlib.Path(options.file).read_bytes())
|
|
return document, f'Root CRL taken, valid until {document["next_update"]}.'
|
|
|
|
|
|
def main(argv):
|
|
parser = Parser(prog='linux-manager-ca', description="Manage the server's PKI.")
|
|
parser.add_argument('--json', action='store_true', help='answer in JSON')
|
|
commands = parser.add_subparsers(dest='command', required=True, parser_class=Parser)
|
|
commands.add_parser('status', help='show the root, the issuing CAs and the warnings')
|
|
lister = commands.add_parser('list', help='list the certificates the server issued')
|
|
lister.add_argument('--ca', help='only those of this issuing CA')
|
|
issuer = commands.add_parser('issue', help='issue a certificate from a CSR, or with a new key into a PFX file')
|
|
issuer.add_argument('--ca', required=True, help='the issuing CA')
|
|
issuer.add_argument('--template', required=True, help='the certificate template')
|
|
issuer.add_argument('--csr', help='the PEM CSR to sign')
|
|
issuer.add_argument('--subject', help='the common name, without --csr')
|
|
issuer.add_argument('--san', action='append', help='a subject alternative name, without --csr; repeat for more')
|
|
issuer.add_argument('--pfx', help='the PFX file to write, without --csr; the password is read from standard input')
|
|
revoker = commands.add_parser('revoke', help='revoke a certificate the server issued')
|
|
revoker.add_argument('serial', help='the serial number, hexadecimal')
|
|
revoker.add_argument('--reason', choices=linuxmanager_pki.REASONS, help='the reason, unspecified by default')
|
|
commands.add_parser('maintain', help='sign the stale CRLs again, or fetch those of Simple CA')
|
|
authority = commands.add_parser('ca', help='an issuing CA, or the root, that waits for the offline root')
|
|
actions = authority.add_subparsers(dest='action', required=True, parser_class=Parser)
|
|
actions.add_parser('csr', help='print its CSR and the openssl extensions').add_argument('name')
|
|
importer = actions.add_parser('import', help='take its certificate signed by the root, or the root certificate')
|
|
importer.add_argument('name', help='the issuing CA, or root')
|
|
importer.add_argument('file')
|
|
root = commands.add_parser('root', help='the root CA')
|
|
root_actions = root.add_subparsers(dest='action', required=True, parser_class=Parser)
|
|
root_actions.add_parser('import-crl', help='take a CRL of the offline root').add_argument('file')
|
|
root_actions.add_parser('setup-code', help='exchange a Simple CA setup code from stdin for the token')
|
|
host = commands.add_parser('https', help="the server's HTTPS certificate")
|
|
host_actions = host.add_subparsers(dest='action', required=True, parser_class=Parser)
|
|
host_actions.add_parser('status', help='show the certificate Caddy serves')
|
|
host_actions.add_parser('csr', help='print a new CSR for wan.local_fqdn, to be signed by another CA')
|
|
host_actions.add_parser('import', help='take the certificate signed for the CSR, PEM with its chain').add_argument('file')
|
|
host_actions.add_parser('import-pfx', help='take a PKCS#12 file; the password is read from stdin').add_argument('file')
|
|
options = parser.parse_args(argv)
|
|
os.umask(0o077)
|
|
|
|
try:
|
|
document, text = run(options)
|
|
except Failure as failure:
|
|
code, message = failure.status, str(failure)
|
|
except OSError as exc:
|
|
code, message = 1, str(exc)
|
|
except ldap.LDAPError as exc:
|
|
code, message = 1, f'the directory, which holds the PKI, failed: {exc}'
|
|
except SystemExit as exc:
|
|
code, message = 1, str(exc.code)
|
|
else:
|
|
if options.json:
|
|
print(json.dumps(document, indent=2))
|
|
elif text is None:
|
|
show_status(document)
|
|
elif text:
|
|
print(text.rstrip('\n'))
|
|
return 0
|
|
if options.json:
|
|
print(json.dumps({'error': message}, indent=2))
|
|
else:
|
|
print(f'linux-manager-ca: {message}', file=sys.stderr)
|
|
return code
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main(sys.argv[1:]))
|