diff --git a/refresh-certificate.py b/refresh-certificate.py index 956c406..c586795 100755 --- a/refresh-certificate.py +++ b/refresh-certificate.py @@ -41,6 +41,7 @@ from cryptography import x509 from cryptography.hazmat.primitives.serialization import Encoding from dateutil.parser import parse from typeguard import typechecked +from datetime import datetime, timedelta import requests import coloredlogs @@ -344,6 +345,40 @@ def install_certificate(hostname: str, verify: bool, username: str, password: st logger.info('Certificate successfully installed.') +@typechecked +def self_signed(hostname:str, verify:bool, username: str, password: str, bearer=None) -> None: + logger = logging.getLogger(__name__) + base_url = f'https://{hostname}' + + if bearer is None: + bearer = get_bearer(hostname, verify, username, password) + + + now = datetime.now() + end = now + timedelta(days=365) + end = end.strftime('%Y-%m-%dT%H:%M:%S.000Z') + url = base_url+'/cdm/certificate/v1/certificates/selfSignedCertificate' + certificate = {"version":"1.1.0","signatureAlgorithm":"sha256WithRsa", + "subjectAlternativeNameList":[hostname], "privateKeyExportable": False, + "links":[{"rel":"certificateConstraints", + "href":"/cdm/certificate/v1/certificates/selfSignedCertificate/constraints", + "hints":None}], + "certificateAttributes":{"commonName":hostname}, + "keyInfo":{"keyType":"rsa","keyStrength":"bits2048"}, + "validity":{"toDate":end},"state":"processing"} + + headers = { 'Authorization': f'Bearer {bearer}' } + + r = requests.patch(url, headers=headers, data=json.dumps(certificate), verify=verify, + timeout=10) + + if r.status_code != 204: + logger.error('Impossible to create a self-signed certificate. Error code: %d', + r.status_code) + sys.exit(-1) + + logger.info('Self-signed certificate created successfully.') + @typechecked def get_certificates(hostname:str, verify:bool, username: str, password: str, @@ -496,7 +531,9 @@ def main(): subparsers = parser.add_subparsers(dest='command', required=True, help='command help') - subparsers.add_parser('list', help='List certificates') + subparsers.add_parser('list', help='List certificates.') + + subparsers.add_parser('self', help='Create a self-signed certificate.') parser_delete = subparsers.add_parser('del', help='Delete a certificate') parser_delete.add_argument("-#", "--number", dest='certid', required=True, type=int, @@ -624,6 +661,9 @@ def main(): case 'pem': install_certificate(hostname=args.hostname, verify=args.verify, username=args.username, password=args.password, filename=args.input) + case 'self': + self_signed(hostname=args.hostname, verify=args.verify, username=args.username, + password=args.password) case _: logger.error('Unknown command: %s', args.command) sys.exit(-1)