Debian Codegraph @

dkim/dknewkey.py

raw symbols SCIP
1 #!/usr/bin/python
2 # This software is provided 'as-is', without any express or implied
3 # warranty. In no event will the author be held liable for any damages
4 # arising from the use of this software.
5 #
6 # Permission is granted to anyone to use this software for any purpose,
7 # including commercial applications, and to alter it and redistribute it
8 # freely, subject to the following restrictions:
9 #
10 # 1. The origin of this software must not be misrepresented; you must not
11 # claim that you wrote the original software. If you use this software
12 # in a product, an acknowledgment in the product documentation would be
13 # appreciated but is not required.
14 # 2. Altered source versions must be plainly marked as such, and must not be
15 # misrepresented as being the original software.
16 # 3. This notice may not be removed or altered from any source distribution.
17 #
18 # Copyright (c) 2016 Google, Inc.
19 # Contact: Brandon Long <[email protected]>
20 # Modified by Scott Kitterman <[email protected]>
21 # Copyright (c) 2017,2018 Scott Kitterman
22
23 """Generates new domainkeys pairs.
24
25 """
26
27
28 from __future__ import print_function
29 import os
30 import subprocess
31 import sys
32 import tempfile
33 import argparse
34 import hashlib
35 import base64
36
37 # how strong are our keys?
38 BITS_REQUIRED = 2048
39
40 # what openssl binary do we use to do key manipulation?
41 OPENSSL_BINARY = '/usr/bin/openssl'
42
43 def eprint(*args, **kwargs):
44 print(*args, file=sys.stderr, **kwargs)
45
46 def GenRSAKeys(private_key_file, verbose=True):
47 """ Generates a suitable private key. Output is unprotected.
48 You should encrypt your keys.
49 """
50 if verbose:
51 eprint('generating ' + private_key_file)
52 subprocess.check_call([OPENSSL_BINARY, 'genrsa', '-out', private_key_file,
53 str(BITS_REQUIRED)],
54 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
55
56 def GenEd25519Keys(private_key_file, verbose=True):
57 """Generates a base64 encoded private key for ed25519 DKIM signing.
58 Output is unprotected. You should protect your keys.
59 """
60 import nacl.signing # Yes, pep-8, but let's not make everyone install nacl
61 import nacl.encoding
62 import os
63 skg = nacl.signing.SigningKey(seed=os.urandom(32))
64 if verbose:
65 eprint('generating ' + private_key_file)
66 priv_key = skg.generate()
67 if os.name == 'posix':
68 old_umask = os.umask(0o077)
69 with open(private_key_file, 'w') as pkf:
70 pkf.write(priv_key.encode(encoder=nacl.encoding.Base64Encoder).decode("utf-8"))
71 if os.name == 'posix':
72 os.umask(old_umask)
73 return(priv_key)
74
75 def ExtractRSADnsPublicKey(private_key_file, dns_file, verbose=True):
76 """ Given a key, extract the bit we should place in DNS.
77 """
78 if verbose:
79 eprint('extracting ' + private_key_file)
80 working_file = tempfile.NamedTemporaryFile(delete=False).name
81 subprocess.check_call([OPENSSL_BINARY, 'rsa', '-in', private_key_file,
82 '-out', working_file, '-pubout', '-outform', 'PEM'],
83 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
84 try:
85 with open(working_file) as wf:
86 y = ''
87 for line in wf.readlines():
88 if not line.startswith('---'):
89 y+= line
90 output = ''.join(y.split())
91 finally:
92 os.unlink(working_file)
93 with open(dns_file, 'w') as dns_fp:
94 if verbose:
95 eprint('writing ' + dns_file)
96 dns_fp.write("v=DKIM1; k=rsa; h=sha256; p={0}".format(output))
97
98 def ExtractEd25519PublicKey(dns_file, priv_key, verbose=True):
99 """ Given a ed25519 key, extract the bit we should place in DNS.
100 """
101 import nacl.encoding # Yes, pep-8, but let's not make everyone install nacl
102 pubkey = priv_key.verify_key
103 output = pubkey.encode(encoder=nacl.encoding.Base64Encoder).decode("utf-8")
104 with open(dns_file, 'w') as dns_fp:
105 if verbose:
106 eprint('writing ' + dns_file)
107 dns_fp.write("v=DKIM1; k=ed25519; p={0}".format(output))
108
109 def main():
110 parser = argparse.ArgumentParser(
111 description='Produce DKIM keys.',)
112 parser.add_argument('key_name', action="store")
113 parser.add_argument('--ktype', choices=['rsa', 'ed25519'],
114 default='rsa',
115 help='DKIM key type: Default is rsa')
116 args=parser.parse_args()
117
118 key_name = args.key_name
119 key_type = args.ktype
120 private_key_file = key_name + '.key'
121 dns_file = key_name + '.dns'
122
123 if key_type == 'rsa':
124 GenRSAKeys(private_key_file)
125 ExtractRSADnsPublicKey(private_key_file, dns_file)
126 elif key_type == 'ed25519':
127 priv_key = GenEd25519Keys(private_key_file)
128 ExtractEd25519PublicKey(dns_file, priv_key)
129 else:
130 eprint("Unknown key type - no key generated.")
131
132
133 if __name__ == '__main__':
134 main()