public
nobgit
read
NobMail
Based on mailcow: dockerized
Languages
Repository composition by tracked source files.
PHP
49%
JavaScript
35%
HTML
9%
CSS
4%
Shell
2%
Python
1%
Lua
0%
Perl
0%
Ruby
0%
SCSS
0%
Create file
Wiki Documentation
Clone
https://nobgit.com/orgs/nobgit/nobmail.git
ssh://[email protected]:2222/orgs/nobgit/nobmail.git
Trace
helper-scripts/generate_caa_record.py
Trace helps you understand code history line by line. See who changed each line, when it changed, and which commit introduced it.
Author
Date
Commit
Line
Code
1
#!/usr/bin/env python3
2
# Based on github.com/diafygi/acme-tiny, original copyright:
3
# Copyright Daniel Roesler, under MIT license, see LICENSE at github.com/diafygi/acme-tiny
4
import argparse, subprocess, json, os, sys, base64, binascii, time, hashlib, re, copy, textwrap, logging
5
try:
6
from urllib.request import urlopen, Request # Python 3
7
except ImportError: # pragma: no cover
8
from urllib2 import urlopen, Request # Python 2
10
DEFAULT_DIRECTORY_URL = "https://acme-v02.api.letsencrypt.org/directory"
12
LOGGER = logging.getLogger(__name__)
13
LOGGER.addHandler(logging.StreamHandler())
14
LOGGER.setLevel(logging.INFO)
16
def get_id(account_key, log=LOGGER, directory_url=DEFAULT_DIRECTORY_URL, contact=None):
17
directory, acct_headers, alg, jwk = None, None, None, None # global variables
19
# helper functions - base64 encode for jose spec
20
def _b64(b):
21
return base64.urlsafe_b64encode(b).decode('utf8').replace("=", "")
23
# helper function - run external commands
24
def _cmd(cmd_list, stdin=None, cmd_input=None, err_msg="Command Line Error"):
25
proc = subprocess.Popen(cmd_list, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
26
out, err = proc.communicate(cmd_input)
27
if proc.returncode != 0:
28
raise IOError("{0}\n{1}".format(err_msg, err))
29
return out
31
# helper function - make request and automatically parse json response
32
def _do_request(url, data=None, err_msg="Error", depth=0):
33
try:
34
resp = urlopen(Request(url, data=data, headers={"Content-Type": "application/jose+json", "User-Agent": "acme-tiny"}))
35
resp_data, code, headers = resp.read().decode("utf8"), resp.getcode(), resp.headers
36
except IOError as e:
37
resp_data = e.read().decode("utf8") if hasattr(e, "read") else str(e)
38
code, headers = getattr(e, "code", None), {}
39
try:
40
resp_data = json.loads(resp_data) # try to parse json results
41
except ValueError:
42
pass # ignore json parsing errors
43
if depth < 100 and code == 400 and resp_data['type'] == "urn:ietf:params:acme:error:badNonce":
44
raise IndexError(resp_data) # allow 100 retrys for bad nonces
45
if code not in [200, 201, 204]:
46
raise ValueError("{0}:\nUrl: {1}\nData: {2}\nResponse Code: {3}\nResponse: {4}".format(err_msg, url, data, code, resp_data))
47
return resp_data, code, headers
49
# helper function - make signed requests
50
def _send_signed_request(url, payload, err_msg, depth=0):
51
payload64 = "" if payload is None else _b64(json.dumps(payload).encode('utf8'))
52
new_nonce = _do_request(directory['newNonce'])[2]['Replay-Nonce']
53
protected = {"url": url, "alg": alg, "nonce": new_nonce}
54
protected.update({"jwk": jwk} if acct_headers is None else {"kid": acct_headers['Location']})
55
protected64 = _b64(json.dumps(protected).encode('utf8'))
56
protected_input = "{0}.{1}".format(protected64, payload64).encode('utf8')
57
out = _cmd(["openssl", "dgst", "-sha256", "-sign", account_key], stdin=subprocess.PIPE, cmd_input=protected_input, err_msg="OpenSSL Error")
58
data = json.dumps({"protected": protected64, "payload": payload64, "signature": _b64(out)})
59
try:
60
return _do_request(url, data=data.encode('utf8'), err_msg=err_msg, depth=depth)
61
except IndexError: # retry bad nonces (they raise IndexError)
62
return _send_signed_request(url, payload, err_msg, depth=(depth + 1))
64
# helper function - poll until complete
65
def _poll_until_not(url, pending_statuses, err_msg):
66
result, t0 = None, time.time()
67
while result is None or result['status'] in pending_statuses:
68
assert (time.time() - t0 < 3600), "Polling timeout" # 1 hour timeout
69
time.sleep(0 if result is None else 2)
70
result, _, _ = _send_signed_request(url, None, err_msg)
71
return result
73
# parse account key to get public key
74
log.info("Parsing account key...")
75
out = _cmd(["openssl", "rsa", "-in", account_key, "-noout", "-text"], err_msg="OpenSSL Error")
76
pub_pattern = r"modulus:[\s]+?00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)"
77
pub_hex, pub_exp = re.search(pub_pattern, out.decode('utf8'), re.MULTILINE|re.DOTALL).groups()
78
pub_exp = "{0:x}".format(int(pub_exp))
79
pub_exp = "0{0}".format(pub_exp) if len(pub_exp) % 2 else pub_exp
80
alg, jwk = "RS256", {
81
"e": _b64(binascii.unhexlify(pub_exp.encode("utf-8"))),
82
"kty": "RSA",
83
"n": _b64(binascii.unhexlify(re.sub(r"(\s|:)", "", pub_hex).encode("utf-8"))),
84
}
85
accountkey_json = json.dumps(jwk, sort_keys=True, separators=(',', ':'))
86
thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
88
# get the ACME directory of urls
89
log.info("Getting directory...")
90
directory, _, _ = _do_request(directory_url, err_msg="Error getting directory")
91
log.info("Directory found!")
93
# create account and get the global key identifier
94
log.info("Registering account...")
95
reg_payload = {"termsOfServiceAgreed": True} if contact is None else {"termsOfServiceAgreed": True, "contact": contact}
96
account, code, acct_headers = _send_signed_request(directory['newAccount'], reg_payload, "Error registering")
97
log.info("Registered!" if code == 201 else "Already registered!")
99
return acct_headers['Location']
101
def main(argv=None):
102
parser = argparse.ArgumentParser(
103
formatter_class=argparse.RawDescriptionHelpFormatter,
104
description=textwrap.dedent("""\
105
Generate a CAA record for Mailcow.
107
Example Usage: python mailcow_gencaa.py --account-key data/assets/ssl/acme/account.pem
108
""")
109
)
110
parser.add_argument("--account-key", required=True, help="path to your Let's Encrypt account private key")
111
parser.add_argument("--quiet", action="store_const", const=logging.ERROR, help="suppress output except for errors")
112
parser.add_argument("--directory-url", default=DEFAULT_DIRECTORY_URL, help="certificate authority directory url, default is Let's Encrypt")
113
parser.add_argument("--contact", metavar="CONTACT", default=None, nargs="*", help="Contact details (e.g. mailto:[email protected]) for your account-key")
115
args = parser.parse_args(argv)
116
LOGGER.setLevel(args.quiet or LOGGER.level)
117
id = get_id(args.account_key, log=LOGGER, directory_url=args.directory_url, contact=args.contact)
118
print("Use this as your CAA record:")
119
print('issue 128 "letsencrypt.org;accounturi={}"'.format(id))
121
if __name__ == "__main__": # pragma: no cover
122
main(sys.argv[1:])