Debian Codegraph @

openpgpkey

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/python3
2 #
3 # openpgpkey: create OPENPGPKEY DNS record from a key in your keychain.
4 #
5 # Copyright 2012 - 2015 Paul Wouters <[email protected]>
6 # Copyright 2015 Dirk Stoecker <[email protected]>
7 # Copyright 2015 Jan Vcelak <[email protected]>
8 # Copyright 2015 Carsten Strotmann <[email protected]>
9 # Copyright 2015 Ondrej Sury <[email protected]>
10 #
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License along
22 # with this program; if not, write to the Free Software Foundation, Inc.,
23 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
25 VERSION="3.5"
26 OPENPGPKEY=61
27
28 import sys
29 import os
30 import gnupg
31 import unbound
32 import hashlib
33 import tempfile
34 import shutil
35
36 global ctx
37
38 def asctohex(s):
39 empty = '' # I use this construct because I find ''.join() too dense
40 return empty.join(['%02x' % c for c in s]) # the %02 pads when needed
41
42 def createOPENPGPKEY(email, gpgdisk, keyid, output, debug):
43 ekey64 = "".join(gpgdisk.export_keys(keyid,minimal=True, secret=False, armor=True).split("\n")[2:-3])
44 user,domain = email.lower().split("@")
45 euser = sha256trunc(user)
46
47 if output == "rfc" or output == "both":
48 print("; keyid: %s" % keyid)
49 print("%s._openpgpkey.%s. IN OPENPGPKEY %s" % (euser, domain, ekey64))
50 if output == "generic" or output == "both":
51 if debug:
52 print("Length for generic record is %s" % len(ekey))
53 print("; keyid: %s" % keyid)
54 print(r"%s._openpgpkey.%s. IN TYPE61 \# %s %s" % (euser, domain, len(ekey), asctohex(ekey)))
55
56 def sha256trunc(data):
57 """Compute SHA2-256 hash truncated to 28 octets."""
58 return hashlib.sha256(data.encode(encoding="utf-8")).hexdigest()[:56]
59
60 def getOPENPGPKEY(email,insecure_ok):
61 """This function queries for an OPENPGPKEY DNS Resource Record and compares it with the local gnupg keyring"""
62
63 global ctx
64
65 try:
66 username, domainname = email.lower().split("@")
67 except:
68 sys.exit("Invalid email syntax")
69
70 keyname = "%s._openpgpkey.%s"%(sha256trunc(username), domainname)
71
72 status, result = ctx.resolve(keyname, OPENPGPKEY)
73 if status == 0 and result.havedata:
74 if not result.secure:
75 if not insecure_ok:
76 # The data is insecure and a secure lookup was requested
77 sys.exit("Error: query data is not secured by DNSSEC - use --insecure to override")
78 else:
79 print('Warning: query data was not secured by DNSSEC.', file=sys.stderr)
80 # If we are here the data was either secure or insecure data is accepted
81 return result.data.raw
82 else:
83 sys.exit('Unsuccesful lookup or no data returned for OPENPGPKEY (rrtype 61)')
84
85 if __name__ == '__main__':
86 import argparse
87 # create the parser
88 parser = argparse.ArgumentParser(description='Create and verify OPENPGPKEY records.', epilog='For bugs. see [email protected]')
89
90 parser.add_argument('--verify','-v', action='store_true', help='Verify an OPENPGPKEY record, exit 0 when all records are matched, exit 1 on error.')
91 parser.add_argument('--fetch','-f', action='store_true', help='Fetch an OPENPGPKEY record, and show it in ascii armor on stdout')
92
93 parser.add_argument('--create','-c', action='store_true', help='Create an OPENPGKEY record')
94 parser.add_argument('--version', action='version', version='openpgpkey version: %s'%VERSION, help='show version and exit')
95
96 parser.add_argument('--insecure', action='store_true', default=False, help='Allow use of non-dnssec secured answers')
97 parser.add_argument('--resolvconf', action='store', default='', help='Use a recursive resolver listed in a resolv.conf file (default: /etc/resolv.conf)')
98 parser.add_argument('--rootanchor', action='store', default='', help='Location of the unbound compatible DNSSEC root.anchor (default: /var/lib/unbound/root.anchor)')
99 parser.add_argument('email', metavar="email")
100
101 parser.add_argument('--uid', action='store', default='', help='override the uid (email address) within the key')
102 parser.add_argument('--keyid', action='store', default='', help='specify key by keyid')
103
104 parser.add_argument('--debug', '-d', action='store_true', help='Print details plus the result of the validation')
105 parser.add_argument('--quiet', '-q', action='store_true', help='Ignored for backwards compatibility')
106
107 # default for now to generic - when more tools support OPENPGPKEY, switch the default to rfc
108 parser.add_argument('--output', '-o', action='store', default='rfc', choices=['generic','rfc','both'], help='The type of output. Generic (RFC 3597, TYPE61), RFC (OPENPGPKEY) or both (default: %(default)s).')
109
110 args = parser.parse_args()
111
112 if args.verify and args.create:
113 sys.exit("openpgpkey: must specify --create or --verify")
114
115 if args.verify or args.fetch:
116 # unbound setup, only for verify
117 global ctx
118 ctx = unbound.ub_ctx()
119 resolvconf = "/etc/resolv.conf"
120 rootanchor = None
121 if args.rootanchor:
122 if os.path.isfile(args.rootanchor):
123 rootanchor = args.rootanchor
124 else:
125 print('openpgpkey: %s is not a file. Unable to use it as rootanchor' % args.rootanchor, file=sys.stdout)
126 sys.exit(1)
127 else:
128 cauldron = ( "/var/lib/unbound/root.anchor", "/var/lib/unbound/root.key", "/etc/unbound/root.key" )
129 for root in cauldron:
130 if os.path.isfile(root):
131 rootanchor=root
132 break
133 if rootanchor:
134 try:
135 ctx.add_ta_file(rootanchor)
136 except:
137 unbound.ub_ctx_trustedkeys(ctx,rootanchor)
138
139 if args.resolvconf:
140 if os.path.isfile(args.resolvconf):
141 resolvconf = args.resolvconf
142 else:
143 print('openpgpkey: %s is not a file. Unable to use it as resolv.conf' % args.resolvconf, file=sys.stdout)
144 sys.exit(1)
145 ctx.resolvconf(resolvconf)
146
147 openpgpkeys = getOPENPGPKEY(args.email, args.insecure)
148 if len(openpgpkeys) == 0:
149 print('openpgpkey: Received nothing?', file=sys.stderr)
150 sys.exit(1)
151 fdir = tempfile.mkdtemp(".gpg","openpgpkey-","/tmp/")
152 gpgnet = gnupg.GPG(gnupghome=fdir)
153 gpgnet.decode_errors = 'ignore'
154
155 for openpgpkey in openpgpkeys:
156 import_result = gpgnet.import_keys(openpgpkey)
157 if args.fetch:
158 if args.keyid:
159 pubkey = gpgnet.export_keys(args.keyid, minimal=True)
160 if not pubkey:
161 print('openpgpkey: Requested keyid not present in received OpenPGP data', file=sys.stderr)
162 sys.exit(1)
163 if args.uid:
164 pubkey = gpgnet.export_keys(args.uid, minimal=True)
165 if not pubkey:
166 print('openpgpkey: Requested uid not present in received OpenPGP data', file=sys.stderr)
167 for id in gpgnet.list_keys()[0]['uids']:
168 print("# %s"%id, file=sys.stderr)
169 sys.exit(1)
170 if not args.uid and not args.keyid:
171 pubkey = gpgnet.export_keys(args.email, minimal=True)
172 if not pubkey:
173 print('openpgpkey: Received OpenPGP data does not contain a key with keyid %s'%args.email, file=sys.stderr)
174 print('(add --uid <uid> to override with any of the below received uids)', file=sys.stderr)
175 for id in gpgnet.list_keys()[0]['uids']:
176 print("# %s"%id, file=sys.stderr)
177 sys.exit(1)
178
179 pubkey = pubkey.replace("Version:","Comment: %s key obtained from DNS\nVersion:"%args.email)
180 if args.insecure:
181 pubkey = pubkey.replace("Version:","Comment: NOT VALIDATED BY DNSSEC\nVersion:")
182 else:
183 pubkey = pubkey.replace("Version:","Comment: key transfer was protected by DNSSEC\nVersion:")
184 print(pubkey)
185
186 if args.fetch:
187 sys.exit(0)
188
189 received_keys = gpgnet.list_keys()
190 gpgdisk = gnupg.GPG()
191 gpgdisk.decode_errors = 'ignore'
192 disk_keys = gpgdisk.list_keys()
193 for pkey in received_keys:
194 if args.debug:
195 print("Received from DNS: Key-ID:%s Fingerprint:%s"%(pkey["keyid"], pkey["fingerprint"]), file=sys.stderr)
196 found = False
197 for dkey in disk_keys:
198 if args.debug:
199 print("Local disk: Key-ID:%s Fingerprint:%s"%(dkey["keyid"], dkey["fingerprint"]), file=sys.stderr)
200 if pkey["keyid"] == dkey["keyid"] and pkey["fingerprint"] == dkey["fingerprint"]:
201 found = True
202 if found == False:
203 shutil.rmtree(fdir)
204 sys.exit("Received key with keyid %s was not found"%pkey["keyid"])
205 else:
206 if args.debug:
207 print("Received key with keyid %s was found"%pkey["keyid"], file=sys.stderr)
208 print("All OPENPGPKEY records matched with content from the local keyring")
209 shutil.rmtree(fdir)
210 sys.exit(0)
211
212 else: # we want to create
213 gpgdisk = gnupg.GPG()
214 gpgdisk.decode_errors = 'ignore'
215 found = False
216 # if we have the keyid, use that
217 if args.keyid:
218 ekey = gpgdisk.export_keys(args.keyid,minimal=True, secret=False, armor=False)
219 if ekey:
220 found = True
221 createOPENPGPKEY(args.email, gpgdisk, args.keyid, args.output, args.debug)
222 # else find key
223 if not found:
224 disk_keys = gpgdisk.list_keys()
225 for pgpkey in disk_keys:
226 for uid in pgpkey["uids"]:
227 if "<%s>"%args.email in uid:
228 if args.debug:
229 print("Found matching KeyID: %s (%s) for %s"%(pgpkey["keyid"], pgpkey["fingerprint"], uid), file=sys.stderr)
230 ekey = gpgdisk.export_keys(pgpkey["keyid"],minimal=True, secret=False, armor=False)
231 createOPENPGPKEY(args.email, gpgdisk, pgpkey["keyid"], args.output, args.debug)
232 found = True
233 # give up
234 if not found:
235 errt = "No key found for "
236 if args.email:
237 errt += "email address %s "%args.email
238 if args.uid:
239 errt += "or uid %s "%args.uid
240 if args.keyid:
241 errt += "or keyid %s "%args.keyid
242 sys.exit(errt)