Debian Codegraph @

hgext/gpg.py

raw
1 # Copyright 2005, 2006 Benoit Boissinot <[email protected]>
2 #
3 # This software may be used and distributed according to the terms of the
4 # GNU General Public License version 2 or any later version.
5
6 '''commands to sign and verify changesets'''
7
8 from __future__ import annotations
9
10 import binascii
11 import os
12
13 from mercurial.i18n import _
14 from mercurial.node import (
15 bin,
16 hex,
17 short,
18 )
19 from mercurial import (
20 cmdutil,
21 error,
22 help,
23 match,
24 pycompat,
25 registrar,
26 )
27 from mercurial.utils import (
28 dateutil,
29 procutil,
30 )
31
32 cmdtable = {}
33 command = registrar.command(cmdtable)
34 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
35 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
36 # be specifying the version(s) of Mercurial they are tested with, or
37 # leave the attribute unspecified.
38 testedwith = b'ships-with-hg-core'
39
40 configtable = {}
41 configitem = registrar.configitem(configtable)
42
43 configitem(
44 b'gpg',
45 b'cmd',
46 default=b'gpg',
47 )
48 configitem(
49 b'gpg',
50 b'key',
51 default=None,
52 )
53 configitem(
54 b'gpg',
55 b'.*',
56 default=None,
57 generic=True,
58 )
59
60 # Custom help category
61 _HELP_CATEGORY = b'gpg'
62 help.CATEGORY_ORDER.insert(
63 help.CATEGORY_ORDER.index(registrar.command.CATEGORY_HELP), _HELP_CATEGORY
64 )
65 help.CATEGORY_NAMES[_HELP_CATEGORY] = b'Signing changes (GPG)'
66
67
68 class gpg:
69 def __init__(self, path, key=None):
70 self.path = path
71 self.key = (key and b" --local-user \"%s\"" % key) or b""
72
73 def sign(self, data):
74 gpgcmd = b"%s --sign --detach-sign%s" % (self.path, self.key)
75 return procutil.filter(data, gpgcmd)
76
77 def verify(self, data, sig):
78 """returns of the good and bad signatures"""
79 sigfile = datafile = None
80 try:
81 # create temporary files
82 fd, sigfile = pycompat.mkstemp(prefix=b"hg-gpg-", suffix=b".sig")
83 fp = os.fdopen(fd, 'wb')
84 fp.write(sig)
85 fp.close()
86 fd, datafile = pycompat.mkstemp(prefix=b"hg-gpg-", suffix=b".txt")
87 fp = os.fdopen(fd, 'wb')
88 fp.write(data)
89 fp.close()
90 gpgcmd = (
91 b"%s --logger-fd 1 --status-fd 1 --verify \"%s\" \"%s\""
92 % (
93 self.path,
94 sigfile,
95 datafile,
96 )
97 )
98 ret = procutil.filter(b"", gpgcmd)
99 finally:
100 for f in (sigfile, datafile):
101 try:
102 if f:
103 os.unlink(f)
104 except OSError:
105 pass
106 keys = []
107 key, fingerprint = None, None
108 for l in ret.splitlines():
109 # see DETAILS in the gnupg documentation
110 # filter the logger output
111 if not l.startswith(b"[GNUPG:]"):
112 continue
113 l = l[9:]
114 if l.startswith(b"VALIDSIG"):
115 # fingerprint of the primary key
116 fingerprint = l.split()[10]
117 elif l.startswith(b"ERRSIG"):
118 key = l.split(b" ", 3)[:2]
119 key.append(b"")
120 fingerprint = None
121 elif (
122 l.startswith(b"GOODSIG")
123 or l.startswith(b"EXPSIG")
124 or l.startswith(b"EXPKEYSIG")
125 or l.startswith(b"BADSIG")
126 ):
127 if key is not None:
128 keys.append(key + [fingerprint])
129 key = l.split(b" ", 2)
130 fingerprint = None
131 if key is not None:
132 keys.append(key + [fingerprint])
133 return keys
134
135
136 def newgpg(ui, **opts):
137 """create a new gpg instance"""
138 gpgpath = ui.config(b"gpg", b"cmd")
139 gpgkey = opts.get('key')
140 if not gpgkey:
141 gpgkey = ui.config(b"gpg", b"key")
142 return gpg(gpgpath, gpgkey)
143
144
145 def sigwalk(repo):
146 """
147 walk over every sigs, yields a couple
148 ((node, version, sig), (filename, linenumber))
149 """
150
151 def parsefile(fileiter, context):
152 ln = 1
153 for l in fileiter:
154 if not l:
155 continue
156 yield (l.split(b" ", 2), (context, ln))
157 ln += 1
158
159 # read the heads
160 fl = repo.file(b".hgsigs")
161 for r in reversed(fl.heads()):
162 fn = b".hgsigs|%s" % short(r)
163 yield from parsefile(fl.read(r).splitlines(), fn)
164 try:
165 # read local signatures
166 fn = b"localsigs"
167 yield from parsefile(repo.vfs(fn), fn)
168 except OSError:
169 pass
170
171
172 def getkeys(ui, repo, mygpg, sigdata, context):
173 """get the keys who signed a data"""
174 fn, ln = context
175 node, version, sig = sigdata
176 prefix = b"%s:%d" % (fn, ln)
177 node = bin(node)
178
179 data = node2txt(repo, node, version)
180 sig = binascii.a2b_base64(sig)
181 keys = mygpg.verify(data, sig)
182
183 validkeys = []
184 # warn for expired key and/or sigs
185 for key in keys:
186 if key[0] == b"ERRSIG":
187 ui.write(_(b"%s Unknown key ID \"%s\"\n") % (prefix, key[1]))
188 continue
189 if key[0] == b"BADSIG":
190 ui.write(_(b"%s Bad signature from \"%s\"\n") % (prefix, key[2]))
191 continue
192 if key[0] == b"EXPSIG":
193 ui.write(
194 _(b"%s Note: Signature has expired (signed by: \"%s\")\n")
195 % (prefix, key[2])
196 )
197 elif key[0] == b"EXPKEYSIG":
198 ui.write(
199 _(b"%s Note: This key has expired (signed by: \"%s\")\n")
200 % (prefix, key[2])
201 )
202 validkeys.append((key[1], key[2], key[3]))
203 return validkeys
204
205
206 @command(b"sigs", [], _(b'hg sigs'), helpcategory=_HELP_CATEGORY)
207 def sigs(ui, repo):
208 """list signed changesets"""
209 mygpg = newgpg(ui)
210 revs = {}
211
212 for data, context in sigwalk(repo):
213 node, version, sig = data
214 fn, ln = context
215 try:
216 n = repo.lookup(node)
217 except KeyError:
218 ui.warn(_(b"%s:%d node does not exist\n") % (fn, ln))
219 continue
220 r = repo.changelog.rev(n)
221 keys = getkeys(ui, repo, mygpg, data, context)
222 if not keys:
223 continue
224 revs.setdefault(r, [])
225 revs[r].extend(keys)
226 for rev in sorted(revs, reverse=True):
227 for k in revs[rev]:
228 r = b"%5d:%s" % (rev, hex(repo.changelog.node(rev)))
229 ui.write(b"%-30s %s\n" % (keystr(ui, k), r))
230
231
232 @command(b"sigcheck", [], _(b'hg sigcheck REV'), helpcategory=_HELP_CATEGORY)
233 def sigcheck(ui, repo, rev):
234 """verify all the signatures there may be for a particular revision"""
235 mygpg = newgpg(ui)
236 rev = repo.lookup(rev)
237 hexrev = hex(rev)
238 keys = []
239
240 for data, context in sigwalk(repo):
241 node, version, sig = data
242 if node == hexrev:
243 k = getkeys(ui, repo, mygpg, data, context)
244 if k:
245 keys.extend(k)
246
247 if not keys:
248 ui.write(_(b"no valid signature for %s\n") % short(rev))
249 return
250
251 # print summary
252 ui.write(_(b"%s is signed by:\n") % short(rev))
253 for key in keys:
254 ui.write(b" %s\n" % keystr(ui, key))
255
256
257 def keystr(ui, key):
258 """associate a string to a key (username, comment)"""
259 keyid, user, fingerprint = key
260 comment = ui.config(b"gpg", fingerprint)
261 if comment:
262 return b"%s (%s)" % (user, comment)
263 else:
264 return user
265
266
267 @command(
268 b"sign",
269 [
270 (b'l', b'local', None, _(b'make the signature local')),
271 (b'f', b'force', None, _(b'sign even if the sigfile is modified')),
272 (
273 b'',
274 b'no-commit',
275 None,
276 _(b'do not commit the sigfile after signing'),
277 ),
278 (b'k', b'key', b'', _(b'the key id to sign with'), _(b'ID')),
279 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
280 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
281 ]
282 + cmdutil.commitopts2,
283 _(b'hg sign [OPTION]... [REV]...'),
284 helpcategory=_HELP_CATEGORY,
285 )
286 def sign(ui, repo, *revs, **opts):
287 """add a signature for the current or given revision
288
289 If no revision is given, the parent of the working directory is used,
290 or tip if no revision is checked out.
291
292 The ``gpg.cmd`` config setting can be used to specify the command
293 to run. A default key can be specified with ``gpg.key``.
294
295 See :hg:`help dates` for a list of formats valid for -d/--date.
296 """
297 with repo.wlock():
298 return _dosign(ui, repo, *revs, **opts)
299
300
301 def _dosign(ui, repo, *revs, **opts):
302 mygpg = newgpg(ui, **opts)
303
304 sigver = b"0"
305 sigmessage = b""
306
307 date = opts.get('date')
308 if date:
309 opts['date'] = dateutil.parsedate(date)
310
311 if revs:
312 nodes = [repo.lookup(n) for n in revs]
313 else:
314 nodes = [
315 node for node in repo.dirstate.parents() if node != repo.nullid
316 ]
317 if len(nodes) > 1:
318 raise error.Abort(
319 _(b'uncommitted merge - please provide a specific revision')
320 )
321 if not nodes:
322 nodes = [repo.changelog.tip()]
323
324 for n in nodes:
325 hexnode = hex(n)
326 ui.write(_(b"signing %d:%s\n") % (repo.changelog.rev(n), short(n)))
327 # build data
328 data = node2txt(repo, n, sigver)
329 sig = mygpg.sign(data)
330 if not sig:
331 raise error.Abort(_(b"error while signing"))
332 sig = binascii.b2a_base64(sig)
333 sig = sig.replace(b"\n", b"")
334 sigmessage += b"%s %s %s\n" % (hexnode, sigver, sig)
335
336 # write it
337 if opts['local']:
338 repo.vfs.append(b"localsigs", sigmessage)
339 return
340
341 msigs = match.exact([b'.hgsigs'])
342
343 if not opts["force"]:
344 if any(repo.status(match=msigs, unknown=True, ignored=True)):
345 raise error.Abort(
346 _(b"working copy of .hgsigs is changed "),
347 hint=_(b"please commit .hgsigs manually"),
348 )
349
350 with repo.wvfs(b".hgsigs", b"ab") as sigsfile:
351 sigsfile.write(sigmessage)
352
353 if b'.hgsigs' not in repo.dirstate:
354 with repo.dirstate.changing_files(repo):
355 repo[None].add([b".hgsigs"])
356
357 if opts["no_commit"]:
358 return
359
360 message = opts['message']
361 if not message:
362 # we don't translate commit messages
363 message = b"\n".join(
364 [b"Added signature for changeset %s" % short(n) for n in nodes]
365 )
366 try:
367 editor = cmdutil.getcommiteditor(editform=b'gpg.sign', **opts)
368 repo.commit(
369 message, opts['user'], opts['date'], match=msigs, editor=editor
370 )
371 except ValueError as inst:
372 raise error.Abort(pycompat.bytestr(inst))
373
374
375 def node2txt(repo, node, ver):
376 """map a manifest into some text"""
377 if ver == b"0":
378 return b"%s\n" % hex(node)
379 else:
380 raise error.Abort(_(b"unknown signature version"))
381
382
383 def extsetup(ui):
384 # Add our category before "Repository maintenance".
385 help.CATEGORY_ORDER.insert(
386 help.CATEGORY_ORDER.index(command.CATEGORY_MAINTENANCE), _HELP_CATEGORY
387 )
388 help.CATEGORY_NAMES[_HELP_CATEGORY] = b'GPG signing'