openpgp: Store the issuer key id and fingerprint in <openpgp-signature>.
[jackhill/guix/guix.git] / guix / openpgp.scm
CommitLineData
43408e30
LC
1;; -*- mode: scheme; coding: utf-8 -*-
2;; Copyright © 2010, 2012 Göran Weinholt <goran@weinholt.se>
3;; Copyright © 2020 Ludovic Courtès <ludo@gnu.org>
4
5;; Permission is hereby granted, free of charge, to any person obtaining a
6;; copy of this software and associated documentation files (the "Software"),
7;; to deal in the Software without restriction, including without limitation
8;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
9;; and/or sell copies of the Software, and to permit persons to whom the
10;; Software is furnished to do so, subject to the following conditions:
11
12;; The above copyright notice and this permission notice shall be included in
13;; all copies or substantial portions of the Software.
14
15;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21;; DEALINGS IN THE SOFTWARE.
22
23;;; This code was originally written by Göran Weinholt for Industria and
24;;; released under the Expat license shown above. It was then modified by
25;;; Ludovic Courtès for use in GNU Guix: turned into a native Guile module,
26;;; ported to Guile-Gcrypt, and extended and simplified in other ways.
27
28(define-module (guix openpgp)
29 #:export (get-openpgp-detached-signature/ascii
30 (get-packet . get-openpgp-packet)
31 verify-openpgp-signature
32 port-ascii-armored?
33
34 openpgp-signature?
7b2b3a13 35 openpgp-signature-issuer-key-id
4459c785 36 openpgp-signature-issuer-fingerprint
43408e30
LC
37 openpgp-signature-public-key-algorithm
38 openpgp-signature-hash-algorithm
39 openpgp-signature-creation-time
40 openpgp-signature-expiration-time
41
42 openpgp-user-id?
43 openpgp-user-id-value
44 openpgp-user-attribute?
45
46 openpgp-public-key?
47 openpgp-public-key-subkey?
48 openpgp-public-key-value
49 openpgp-public-key-fingerprint openpgp-format-fingerprint
50 openpgp-public-key-id
51
52 openpgp-keyring?
53 %empty-keyring
54 lookup-key-by-id
55 get-openpgp-keyring
56
57 read-radix-64)
58 #:use-module (rnrs bytevectors)
59 #:use-module (rnrs io ports)
60 #:use-module (srfi srfi-1)
61 #:use-module (srfi srfi-9)
62 #:use-module (srfi srfi-11)
63 #:use-module (srfi srfi-19)
64 #:use-module (srfi srfi-26)
65 #:use-module (srfi srfi-34)
66 #:use-module (srfi srfi-35)
67 #:use-module (srfi srfi-60)
68 #:use-module (ice-9 match)
69 #:use-module ((ice-9 rdelim) #:select (read-line))
70 #:use-module (ice-9 vlist)
71 #:use-module (gcrypt hash)
72 #:use-module (gcrypt pk-crypto)
73 #:use-module (gcrypt base64)
74 #:use-module (gcrypt base16)
75 #:use-module ((guix build utils) #:select (dump-port)))
76
77;;; Commentary:
78;;;
79;;; This module contains code to read OpenPGP messages as described in
80;;; <https://tools.ietf.org/html/rfc4880>, with extensions from
81;;; <https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-06> (notably
82;;; EdDSA support and extra signature sub-packets).
83;;;
84;;; Currently this module does enough to verify detached signatures of binary
85;;; data. It does _not_ perform sanity checks on self-signatures, subkey
86;;; binding signatures, etc., among others. Use only in a context where this
87;;; limitations are acceptable!
88;;;
89;;; Code:
90
91(define-syntax print
92 (syntax-rules ()
93 ;; ((_ args ...) (pk 'openpgp args))
94 ((_ args ...) (values))))
95
96(define-syntax-rule (define-alias new old)
97 (define-syntax new (identifier-syntax old)))
98
99(define-alias fx+ +)
100(define-alias fx- -)
101(define-alias fx* *)
102(define-alias fx/ /)
103(define-alias fxdiv quotient)
104(define-alias fxand logand)
105(define-alias fxbit-set? bit-set?)
106(define-alias fxbit-field bit-field)
107(define-alias bitwise-bit-field bit-field)
108(define-alias fxarithmetic-shift-left ash)
109(define-inlinable (fxarithmetic-shift-right i n) (ash i (- n)))
110(define-inlinable (port-eof? port) (eof-object? (lookahead-u8 port)))
111
112(define (string-hex-pad str)
113 (if (odd? (string-length str))
114 (string-append "0" str)
115 str))
116
117(define (unixtime n)
118 (time-monotonic->date (make-time 'time-monotonic 0 n)))
119
120\f
121;;;
122;;; Bitwise I/O.
123;;;
124;;; TODO: Use Bytestructures instead.
125;;;
126
127(define-syntax-rule (integer-read size)
128 (lambda (port)
129 "Read from PORT a big-endian integer of SIZE bytes. Return the EOF object
130on end-of-file."
131 (let ((buf (make-bytevector size)))
132 (match (get-bytevector-n! port buf 0 size)
133 (size (bytevector-uint-ref buf 0 (endianness big) size))
134 (_ (eof-object))))))
135
136(define get-u16 (integer-read 2))
137(define get-u32 (integer-read 4))
138(define get-u64 (integer-read 8))
139
140(define-syntax get-integers
141 (syntax-rules ()
142 "Read from PORT integers of the given TYPE, in big endian encoding. Each
143TYPE must be one of u8, u16, u32, u64, or _, as in this example:
144
145 (get-integers port u8 _ _ _ u32 u16)
146
147In the case of _ (wildcard), one byte is read and discarded. Return as many
148values as there are TYPEs."
149 ((_ port type ...)
150 (letrec-syntax ((get-integer (syntax-rules (u8 u16 u32 u64)
151 ((x u8) (get-u8 port))
152 ((x u16) (get-u16 port))
153 ((x u32) (get-u32 port))
154 ((x u64) (get-u64 port))))
155 (values* (syntax-rules (_)
156 ((x (result (... ...)))
157 (values result (... ...)))
158 ((x (result (... ...)) _ rest (... ...))
159 (let ((x (get-u8 port)))
160 (values* (result (... ...))
161 rest (... ...))))
162 ((x (result (... ...)) t rest (... ...))
163 (let ((x (get-integer t)))
164 (values* (result (... ...) x)
165 rest (... ...)))))))
166 (values* () type ...)))))
167
168(define (bytevector->uint bv)
169 (bytevector-uint-ref bv 0 (endianness big)
170 (bytevector-length bv)))
171
172(define-syntax-rule (integer-write size)
173 (lambda (port integer)
174 "Write INTEGER to PORT as a SIZE-byte integer and as big endian."
175 (let ((bv (make-bytevector size)))
176 (bytevector-uint-set! bv 0 integer (endianness big) size)
177 (put-bytevector port bv))))
178
179(define put-u16 (integer-write 2))
180(define put-u32 (integer-write 4))
181(define put-u64 (integer-write 8))
182
183(define-syntax put-integers
184 (syntax-rules ()
185 "Write the given integers as big endian to PORT. For example:
186
187 (put-integers port u8 42 u32 #x7777)
188
189writes to PORT the value 42 as an 8-bit integer and the value #x7777 as a
19032-bit integer."
191 ((_ port)
192 #t)
193 ((_ port type value rest ...)
194 (let-syntax ((put (syntax-rules (u8 u16 u32 u64)
195 ((_ u8 port integer)
196 (put-u8 port integer))
197 ((_ u16 port integer)
198 (put-u16 port integer))
199 ((_ u32 port integer)
200 (put-u32 port integer))
201 ((_ u64 port integer)
202 (put-u64 port integer)))))
203 (begin
204 (put type port value)
205 (put-integers port rest ...))))))
206
207(define-syntax-rule (integers->bytevector type value rest ...)
208 "Return the the TYPE/VALUE integers representation as a bytevector."
209 (let-values (((port get) (open-bytevector-output-port)))
210 (put-integers port type value rest ...)
211 (force-output port)
212 (get)))
213
214\f
215(define (bytevector->bitnames bv names)
216 (define (bit-set? bv i)
217 (let ((idx (fxarithmetic-shift-right i 3))
218 (bit (fxand i #b111)))
219 (and (< idx (bytevector-length bv))
220 (fxbit-set? (bytevector-u8-ref bv idx) bit))))
221 (do ((names names (cdr names))
222 (i 0 (fx+ i 1))
223 (bits '()
224 (if (bit-set? bv i)
225 (cons (car names) bits)
226 bits)))
227 ((null? names) (reverse bits))))
228
229(define (openpgp-format-fingerprint bv)
230 "Return a string representing BV, a bytevector, in the conventional OpenPGP
231hexadecimal format for fingerprints."
232 (define (h i)
233 (string-pad (string-upcase
234 (number->string
235 (bytevector-u16-ref bv (* i 2) (endianness big))
236 16))
237 4 #\0))
238 (string-append (h 0) " " (h 1) " " (h 2) " " (h 3) " " (h 4)
239 " "
240 (h 5) " " (h 6) " " (h 7) " " (h 8) " " (h 9)))
241
242;;; Constants
243
244
245(define PACKET-SESSION-KEY 1)
246(define PACKET-SIGNATURE 2)
247(define PACKET-SYMMETRIC-SESSION-KEY 3)
248(define PACKET-ONE-PASS-SIGNATURE 4)
249(define PACKET-SECRET-KEY 5)
250(define PACKET-PUBLIC-KEY 6)
251(define PACKET-SECRET-SUBKEY 7)
252(define PACKET-COMPRESSED-DATA 8)
253(define PACKET-SYMMETRIC-ENCRYPTED-DATA 9)
254(define PACKET-MARKER 10)
255(define PACKET-LITERAL-DATA 11)
256(define PACKET-TRUST 12)
257(define PACKET-USER-ID 13)
258(define PACKET-PUBLIC-SUBKEY 14)
259(define PACKET-USER-ATTRIBUTE 17)
260(define PACKET-SYMMETRIC-ENCRYPTED/PROTECTED-DATA 18)
261(define PACKET-MDC 19)
262
263(define PUBLIC-KEY-RSA 1)
264(define PUBLIC-KEY-RSA-ENCRYPT-ONLY 2)
265(define PUBLIC-KEY-RSA-SIGN-ONLY 3)
266(define PUBLIC-KEY-ELGAMAL-ENCRYPT-ONLY 16)
267(define PUBLIC-KEY-DSA 17)
268(define PUBLIC-KEY-ECDH 18) ;RFC-6637
269(define PUBLIC-KEY-ECDSA 19) ;RFC-6639
270(define PUBLIC-KEY-ELGAMAL 20) ;encrypt + sign (legacy)
271(define PUBLIC-KEY-EDDSA 22) ;"not yet assigned" says GPG
272
273(define (public-key-algorithm id)
274 (cond ((= id PUBLIC-KEY-RSA) 'rsa)
275 ((= id PUBLIC-KEY-DSA) 'dsa)
276 ((= id PUBLIC-KEY-ELGAMAL-ENCRYPT-ONLY) 'elgamal)
277 ((= id PUBLIC-KEY-EDDSA) 'eddsa)
278 (else id)))
279
280(define SYMMETRIC-KEY-PLAINTEXT 0)
281(define SYMMETRIC-KEY-IDEA 1)
282(define SYMMETRIC-KEY-TRIPLE-DES 2)
283(define SYMMETRIC-KEY-CAST5-128 3)
284(define SYMMETRIC-KEY-BLOWFISH-128 4)
285(define SYMMETRIC-KEY-AES-128 7)
286(define SYMMETRIC-KEY-AES-192 8)
287(define SYMMETRIC-KEY-AES-256 9)
288(define SYMMETRIC-KEY-TWOFISH-256 10)
289(define SYMMETRIC-KEY-CAMELLIA-128 11) ;RFC-5581
290(define SYMMETRIC-KEY-CAMELLIA-192 12)
291(define SYMMETRIC-KEY-CAMELLIA-256 13)
292
293(define (symmetric-key-algorithm id)
294 (cond ((= id SYMMETRIC-KEY-PLAINTEXT) 'plaintext)
295 ((= id SYMMETRIC-KEY-IDEA) 'idea)
296 ((= id SYMMETRIC-KEY-TRIPLE-DES) 'tdea)
297 ((= id SYMMETRIC-KEY-CAST5-128) 'cast5-128)
298 ((= id SYMMETRIC-KEY-BLOWFISH-128) 'blowfish-128)
299 ((= id SYMMETRIC-KEY-AES-128) 'aes-128)
300 ((= id SYMMETRIC-KEY-AES-192) 'aes-192)
301 ((= id SYMMETRIC-KEY-AES-256) 'aes-256)
302 ((= id SYMMETRIC-KEY-TWOFISH-256) 'twofish-256)
303 (else id)))
304
305(define HASH-MD5 1)
306(define HASH-SHA-1 2)
307(define HASH-RIPE-MD160 3)
308(define HASH-SHA-256 8)
309(define HASH-SHA-384 9)
310(define HASH-SHA-512 10)
311(define HASH-SHA-224 11)
312
313(define (openpgp-hash-algorithm id)
314 (cond ((= id HASH-MD5) 'md5)
315 ((= id HASH-SHA-1) 'sha1)
316 ((= id HASH-RIPE-MD160) 'rmd160)
317 ((= id HASH-SHA-256) 'sha256)
318 ((= id HASH-SHA-384) 'sha384)
319 ((= id HASH-SHA-512) 'sha512)
320 ((= id HASH-SHA-224) 'sha224)
321 (else (error "unknown hash algorithm" id))))
322
323(define COMPRESSION-UNCOMPRESSED 0)
324(define COMPRESSION-ZIP 1) ;deflate
325
326(define COMPRESSION-ZLIB 2)
327(define COMPRESSION-BZIP2 3)
328
329(define (compression-algorithm id)
330 (cond ((= id COMPRESSION-UNCOMPRESSED) 'uncompressed)
331 ((= id COMPRESSION-ZIP) 'deflate)
332 ((= id COMPRESSION-ZLIB) 'zlib)
333 ((= id COMPRESSION-BZIP2) 'bzip2)
334 (else id)))
335
336(define SUBPACKET-SIGNATURE-CTIME 2)
337(define SUBPACKET-SIGNATURE-ETIME 3)
338 ;; 4 = Exportable Certification
339
340(define SUBPACKET-TRUST-SIGNATURE 5)
341 ;; 6 = Regular Expression
342
343(define SUBPACKET-REVOCABLE 7)
344(define SUBPACKET-KEY-ETIME 9)
345(define SUBPACKET-PREFERRED-SYMMETRIC-ALGORITHMS 11)
346 ;; 12 = Revocation Key
347
348(define SUBPACKET-ISSUER 16)
43408e30
LC
349(define SUBPACKET-NOTATION-DATA 20)
350(define SUBPACKET-PREFERRED-HASH-ALGORITHMS 21)
351(define SUBPACKET-PREFERRED-COMPRESSION-ALGORITHMS 22)
352(define SUBPACKET-KEY-SERVER-PREFERENCES 23)
353(define SUBPACKET-PREFERRED-KEY-SERVER 24)
354(define SUBPACKET-PRIMARY-USER-ID 25)
355(define SUBPACKET-POLICY-URI 26)
356(define SUBPACKET-KEY-FLAGS 27)
357(define SUBPACKET-SIGNER-USER-ID 28)
358(define SUBPACKET-REASON-FOR-REVOCATION 29)
359(define SUBPACKET-FEATURES 30)
360 ;; 31 = Signature Target
43408e30 361(define SUBPACKET-EMBEDDED-SIGNATURE 32)
4459c785 362(define SUBPACKET-ISSUER-FINGERPRINT 33) ;defined in RFC4880bis
43408e30
LC
363
364(define SIGNATURE-BINARY #x00)
365(define SIGNATURE-TEXT #x01)
366(define SIGNATURE-STANDALONE #x02)
367(define SIGNATURE-GENERIC-CERT #x10)
368(define SIGNATURE-PERSONA-CERT #x11)
369(define SIGNATURE-CASUAL-CERT #x12)
370(define SIGNATURE-POSITIVE-CERT #x13)
371(define SIGNATURE-SUBKEY-BINDING #x18)
372(define SIGNATURE-PRIMARY-KEY-BINDING #x19)
373(define SIGNATURE-DIRECT #x1f)
374(define SIGNATURE-KEY-REVOCATION #x20)
375(define SIGNATURE-SUBKEY-REVOCATION #x28)
376(define SIGNATURE-CERT-REVOCATION #x30)
377(define SIGNATURE-TIMESTAMP #x40)
378(define SIGNATURE-THIRD-PARTY #x50)
379
380;;; Parsing
381
382 ;; Look at the tag byte and see if it looks reasonable, if it does
383 ;; then the file is likely not armored. Does not move the port
384 ;; position.
385
386(define (port-ascii-armored? p)
387 (let ((tag (lookahead-u8 p)))
388 (cond ((eof-object? tag) #f)
389 ((not (fxbit-set? tag 7)) #t)
390 (else
391 (let ((type (if (fxbit-set? tag 6)
392 (fxbit-field tag 0 6)
393 (fxbit-field tag 2 6))))
394 (not (<= PACKET-SESSION-KEY type PACKET-MDC)))))))
395
396(define (get-mpi/bytevector p)
397 (let* ((bitlen (get-u16 p))
398 (bytelen (fxdiv (fx+ bitlen 7) 8)))
399 (get-bytevector-n p bytelen)))
400
401(define (get-mpi p)
402 (bytevector->uint (get-mpi/bytevector p)))
403
404(define (get-v4-length p)
405 ;; TODO: indeterminate length (only for data packets)
406 (let ((o1 (get-u8 p)))
407 (cond ((< o1 192) o1)
408 ((< o1 255)
409 (+ (fxarithmetic-shift-left (fx- o1 192) 8)
410 (get-u8 p)
411 192))
412 ((= o1 255)
413 (get-u32 p)))))
414
415(define (get-packet p)
416 (if (port-eof? p)
417 (eof-object)
418 (get-packet* p get-data)))
419
420(define (get-packet* p get-data)
421 (let ((tag (get-u8 p)))
422 ;; (unless (fxbit-set? tag 7) (error 'get-packet "Invalid tag" tag))
423 (cond ((fxbit-set? tag 6) ;New packet format
424 (let ((tag (fxbit-field tag 0 6))
425 (len (get-v4-length p)))
426 (get-data p tag len)))
427 (else ;Old packet format
428 (let ((tag (fxbit-field tag 2 6))
429 (len (case (fxbit-field tag 0 2)
430 ((0) (get-u8 p))
431 ((1) (get-u16 p))
432 ((2) (get-u32 p))
433 ((3) #f))))
434 (get-data p tag len))))))
435
436(define (get-data p tag len)
437 (let ((pp (if len
438 (open-bytevector-input-port (get-bytevector-n p len))
439 p))) ;indeterminate length
440 (cond
441 ((= tag PACKET-SIGNATURE)
442 (get-signature pp))
443 ((= tag PACKET-PUBLIC-KEY)
444 (get-public-key pp #f))
445 ((= tag PACKET-TRUST)
446 'openpgp-trust) ;XXX: non-standard format?
447 ((= tag PACKET-USER-ID)
448 (get-user-id pp len))
449 ((= tag PACKET-PUBLIC-SUBKEY)
450 (get-public-key pp #t))
451 ((= tag PACKET-USER-ATTRIBUTE)
452 (get-user-attribute pp len))
453 ((= tag PACKET-ONE-PASS-SIGNATURE)
454 'one-pass-signature) ;TODO: implement
455 (else
456 (error 'get-data "Unsupported packet type" tag)))))
457
458(define-record-type <openpgp-public-key>
459 (make-openpgp-public-key version subkey? time value fingerprint)
460 openpgp-public-key?
461 (version openpgp-public-key-version)
462 (subkey? openpgp-public-key-subkey?)
463 (time openpgp-public-key-time)
464 (value openpgp-public-key-value)
465 (fingerprint openpgp-public-key-fingerprint))
466
467;;; Signatures
468
469(define-record-type <openpgp-signature>
470 (make-openpgp-signature version type pk-algorithm hash-algorithm hashl16
471 append-data hashed-subpackets unhashed-subpackets
7b2b3a13 472 value issuer issuer-fingerprint)
43408e30
LC
473 openpgp-signature?
474 (version openpgp-signature-version)
475 (type openpgp-signature-type)
476 (pk-algorithm openpgp-signature-public-key-algorithm)
477 (hash-algorithm openpgp-signature-hash-algorithm)
478 (hashl16 openpgp-signature-hashl16) ;left 16 bits of signed hash
479 (append-data openpgp-signature-append-data) ;append to data when hashing
480 (hashed-subpackets openpgp-signature-hashed-subpackets)
481 (unhashed-subpackets openpgp-signature-unhashed-subpackets)
7b2b3a13
LC
482 (value openpgp-signature-value)
483 (issuer openpgp-signature-issuer-key-id) ;integer | #f
484 (issuer-fingerprint openpgp-signature-issuer-fingerprint)) ;bytevector | #f
4459c785 485
43408e30
LC
486(define (openpgp-signature-creation-time sig)
487 (cond ((assq 'signature-ctime (openpgp-signature-hashed-subpackets sig))
488 => (lambda (x) (unixtime (cdr x))))
489 ;; XXX: should be an error?
490 (else #f)))
491
492(define (openpgp-signature-expiration-time sig)
493 (cond ((assq 'signature-etime (openpgp-signature-hashed-subpackets sig))
494 => (lambda (x)
495 (unixtime (+ (cdr x)
496 (openpgp-signature-creation-time sig)))))
497 (else #f)))
498
499
500(define (get-openpgp-detached-signature/ascii port)
501 "Read from PORT an ASCII-armored detached signature. Return an
502<openpgp-signature> record or the end-of-file object. Raise an error if the
503data read from PORT does is invalid or does not correspond to a detached
504signature."
505 (let-values (((data type) (read-radix-64 port)))
506 (cond ((eof-object? data) data)
507 ((string=? type "PGP SIGNATURE")
508 (get-packet (open-bytevector-input-port data)))
509 (else
510 (error "expected PGP SIGNATURE" type)))))
511
512(define (hash-algorithm-name algorithm) ;XXX: should be in Guile-Gcrypt
513 "Return the name of ALGORITHM, a 'hash-algorithm' integer, as a symbol."
514 (letrec-syntax ((->name (syntax-rules ()
515 ((_) #f)
516 ((_ name rest ...)
517 (if (= algorithm (hash-algorithm name))
518 'name
519 (->name rest ...))))))
520 (->name sha1 sha256 sha384 sha512 sha224
521 sha3-224 sha3-256 sha3-384 sha3-512)))
522
523(define (verify-openpgp-signature sig keyring dataport)
524 "Verify that the data read from DATAPORT matches SIG, an
525<openpgp-signature>. Fetch the public key of the issuer of SIG from KEYRING,
526a keyring as returned by 'get-openpgp-keyring'. Return two values: a status
527symbol, such as 'bad-signature or 'missing-key, and additional info, such as
528the issuer's OpenPGP public key extracted from KEYRING."
529 (define (check key sig)
530 (let*-values (((hash-algorithm) (lookup-hash-algorithm
531 (openpgp-signature-hash-algorithm sig)))
532 ((port get-hash) (open-hash-port hash-algorithm)))
533 (dump-port dataport port)
534
535 ;; As per RFC4880 Section 5.2.4 ("Computing Signatures"), hash some of
536 ;; the fields from the signature packet.
537 (for-each (cut put-bytevector port <>)
538 (openpgp-signature-append-data sig))
539 (close-port port)
540
541 (let* ((signature (openpgp-signature-value sig))
542 (public-key (openpgp-public-key-value key))
543 (hash (get-hash))
544 (key-type (key-type public-key))
545 (data
546 ;; See "(gcrypt) Cryptographic Functions".
547 (sexp->canonical-sexp
548 (if (eq? key-type 'ecc)
549 `(data
550 (flags eddsa)
551 (hash-algo sha512)
552 (value ,hash))
553 `(data
554 (flags ,(match key-type
555 ('rsa 'pkcs1)
556 ('dsa 'rfc6979)))
557 (hash ,(hash-algorithm-name hash-algorithm)
558 ,hash))))))
559 (values (if (verify signature data public-key)
560 'good-signature
561 'bad-signature)
562 key))))
563
564 ;; TODO: Support SIGNATURE-TEXT.
565 (if (= (openpgp-signature-type sig) SIGNATURE-BINARY)
7b2b3a13 566 (let* ((issuer (openpgp-signature-issuer-key-id sig))
43408e30
LC
567 (key-data (lookup-key-by-id keyring issuer)))
568 ;; Find the primary key or subkey that made the signature.
569 (let ((key (find (lambda (k)
570 (and (openpgp-public-key? k)
571 (= (openpgp-public-key-id k) issuer)))
572 key-data)))
573 (if key
574 (check key sig)
575 (values 'missing-key issuer))))
576 (values 'unsupported-signature sig)))
577
4459c785
LC
578(define (key-id-matches-fingerprint? key-id fingerprint)
579 "Return true if KEY-ID, a number, corresponds to the low 8 bytes of
580FINGERPRINT, a bytevector."
581 (let* ((len (bytevector-length fingerprint))
582 (low (make-bytevector 8)))
583 (bytevector-copy! fingerprint (- len 8) low 0 8)
584 (= (bytevector->uint low) key-id)))
585
43408e30
LC
586(define (get-signature p)
587 (define (->hex n)
588 (string-hex-pad (number->string n 16)))
589
590 (define (get-sig p pkalg)
591 (cond ((= pkalg PUBLIC-KEY-RSA)
592 (print "RSA signature")
593 (string->canonical-sexp
594 (format #f "(sig-val (rsa (s #~a#)))"
595 (->hex (get-mpi p)))))
596 ((= pkalg PUBLIC-KEY-DSA)
597 (print "DSA signature")
598 (let ((r (get-mpi p)) (s (get-mpi p)))
599 (string->canonical-sexp
600 (format #f "(sig-val (dsa (r #~a#) (s #~a#)))"
601 (->hex r) (->hex s)))))
602 ((= pkalg PUBLIC-KEY-EDDSA)
603 (print "EdDSA signature")
604 (let ((r (get-mpi/bytevector p))
605 (s (get-mpi/bytevector p)))
606 ;; XXX: 'verify' fails down the road with GPG_ERR_INV_LENGTH if
607 ;; we provide a 31-byte R or S below, hence the second argument
608 ;; to '->hex' ensuring the MPIs are represented as two-byte
609 ;; multiples, with leading zeros.
610 (define (bytevector->hex bv)
611 (let ((str (bytevector->base16-string bv)))
612 (if (odd? (bytevector-length bv))
613 (string-append "00" str)
614 str)))
615
616 (string->canonical-sexp
617 (format #f "(sig-val (eddsa (r #~a#) (s #~a#)))"
618 (bytevector->hex r) (bytevector->hex s)))))
619 (else
620 (list 'unsupported-algorithm
621 (public-key-algorithm pkalg)
622 (get-bytevector-all p)))))
623 (let ((version (get-u8 p)))
624 (case version
625 ((3)
626 (let-values (((hmlen type ctime keyid pkalg halg hashl16)
627 (get-integers p u8 u8 u32 u64 u8 u8 u16)))
628 (unless (= hmlen 5)
629 (error "invalid signature packet"))
630 (print "Signature type: " type " creation time: " (unixtime ctime))
631 (print "Hash algorithm: " (openpgp-hash-algorithm halg))
632 (let ((value (get-sig p pkalg)))
633 (unless (port-eof? p)
634 (print "Trailing data in signature: " (get-bytevector-all p)))
635 (make-openpgp-signature version type
636 (public-key-algorithm pkalg)
637 (openpgp-hash-algorithm halg) hashl16
638 (list (integers->bytevector u8 type
639 u32 ctime))
640 ;; Emulate hashed subpackets
641 (list (cons 'signature-ctime ctime))
642 ;; Unhashed subpackets
643 (list (cons 'issuer keyid))
7b2b3a13
LC
644 value
645 keyid #f))))
43408e30
LC
646 ((4)
647 (let*-values (((type pkalg halg) (get-integers p u8 u8 u8))
648 ((hashed-subpackets)
649 (get-bytevector-n p (get-u16 p)))
650 ((unhashed-subpackets)
651 (get-bytevector-n p (get-u16 p)))
652 ((hashl16) (get-u16 p)))
653 (print "Signature type: " type)
654 (print "Hash algorithm: " (openpgp-hash-algorithm halg))
655 (let ((value (get-sig p pkalg)))
656 (unless (port-eof? p)
657 (print "Trailing data in signature: " (get-bytevector-all p)))
658 (let* ((subpacket-len (bytevector-length hashed-subpackets))
659 (append-data
660 (list
661 (integers->bytevector u8 version
662 u8 type
663 u8 pkalg
664 u8 halg
665 u16 subpacket-len)
666 hashed-subpackets
667 ;; http://www.rfc-editor.org/errata_search.php?rfc=4880
668 ;; Errata ID: 2214.
669 (integers->bytevector u8 #x04
670 u8 #xff
4459c785
LC
671 u32 (+ 6 subpacket-len))))
672 (unhashed-subpackets
673 (parse-subpackets unhashed-subpackets))
674 (hashed-subpackets (parse-subpackets hashed-subpackets))
675 (subpackets (append hashed-subpackets
676 unhashed-subpackets))
677 (issuer-key-id (assoc-ref subpackets 'issuer))
678 (issuer (assoc-ref subpackets
679 'issuer-fingerprint)))
680 (unless (or (not issuer) (not issuer-key-id)
681 (key-id-matches-fingerprint? issuer-key-id issuer))
682 (error "issuer key id does not match fingerprint" issuer))
683
43408e30
LC
684 (make-openpgp-signature version type
685 (public-key-algorithm pkalg)
686 (openpgp-hash-algorithm halg)
687 hashl16
688 append-data
4459c785
LC
689 hashed-subpackets
690 unhashed-subpackets
7b2b3a13
LC
691 value
692 issuer-key-id issuer)))))
43408e30
LC
693 (else
694 (print "Unsupported signature version: " version)
695 'unsupported-signature-version))))
696
697(define (parse-subpackets bv)
698 (define (parse tag data)
699 (let ((type (fxbit-field tag 0 7))
700 (critical? (fxbit-set? tag 7)))
701 (cond
702 ((= type SUBPACKET-SIGNATURE-CTIME)
703 (cons 'signature-ctime
704 (bytevector-u32-ref data 0 (endianness big))))
705 ((= type SUBPACKET-SIGNATURE-ETIME)
706 (cons 'signature-etime
707 (bytevector-u32-ref data 0 (endianness big))))
708 ((= type SUBPACKET-TRUST-SIGNATURE)
709 (cons 'trust-signature
710 (bytevector-u8-ref data 0)))
711 ((= type SUBPACKET-REVOCABLE)
712 (cons 'revocable
713 (= (bytevector-u8-ref data 0) 1)))
714 ((= type SUBPACKET-KEY-ETIME)
715 (cons 'key-etime
716 (bytevector-u32-ref data 0 (endianness big))))
717 ((= type SUBPACKET-PREFERRED-SYMMETRIC-ALGORITHMS)
718 (cons 'preferred-symmetric-algorithms
719 (map symmetric-key-algorithm (bytevector->u8-list data))))
720 ((= type SUBPACKET-ISSUER)
721 (cons 'issuer
722 (bytevector-u64-ref data 0 (endianness big))))
4459c785
LC
723 ((= type SUBPACKET-ISSUER-FINGERPRINT) ;v4+ only, RFC4880bis
724 (cons 'issuer-fingerprint
725 (let* ((version (bytevector-u8-ref data 0))
726 (len (match version (4 20) (5 32)) )
727 (fingerprint (make-bytevector len)))
728 (bytevector-copy! data 1 fingerprint 0 len)
729 fingerprint)))
43408e30
LC
730 ((= type SUBPACKET-NOTATION-DATA)
731 (let ((p (open-bytevector-input-port data)))
732 (let-values (((f1 nlen vlen)
733 (get-integers p u8 _ _ _ u16 u16)))
734 (let* ((name (get-bytevector-n p nlen))
735 (value (get-bytevector-n p vlen)))
736 (cons 'notation-data
737 (list (utf8->string name)
738 (if (fxbit-set? f1 7)
739 (utf8->string value)
740 value)))))))
741 ((= type SUBPACKET-PREFERRED-HASH-ALGORITHMS)
742 (cons 'preferred-hash-algorithms
743 (map openpgp-hash-algorithm (bytevector->u8-list data))))
744 ((= type SUBPACKET-PREFERRED-COMPRESSION-ALGORITHMS)
745 (cons 'preferred-compression-algorithms
746 (map compression-algorithm (bytevector->u8-list data))))
747 ((= type SUBPACKET-KEY-SERVER-PREFERENCES)
748 (cons 'key-server-preferences
749 (if (and (>= (bytevector-length data) 1)
750 (fxbit-set? (bytevector-u8-ref data 0) 7))
751 (list 'no-modify)
752 (list))))
753 ((= type SUBPACKET-PREFERRED-KEY-SERVER)
754 (cons 'preferred-key-server (utf8->string data)))
755 ((= type SUBPACKET-PRIMARY-USER-ID)
756 (cons 'primary-user-id (not (zero? (bytevector-u8-ref data 0)))))
757 ((= type SUBPACKET-POLICY-URI)
758 (cons 'policy-uri (utf8->string data)))
759 ((= type SUBPACKET-KEY-FLAGS)
760 (cons 'key-flags (bytevector->bitnames
761 data
762 '(certification sign-data
763 communications-encryption
764 storage-encryption
765 split-key authentication
766 group-key))))
767 ((= type SUBPACKET-SIGNER-USER-ID)
768 (cons 'signer-user-id (utf8->string data)))
769 ((= type SUBPACKET-REASON-FOR-REVOCATION)
770 (let* ((p (open-bytevector-input-port data))
771 (revocation-code (get-u8 p)))
772 (cons 'reason-for-revocation
773 (list revocation-code
774 (if (port-eof? p)
775 ""
776 (utf8->string (get-bytevector-all p)))))))
777 ((= type SUBPACKET-FEATURES)
778 (cons 'features (bytevector->bitnames
779 data '(modification-detection))))
780 ((= type SUBPACKET-EMBEDDED-SIGNATURE)
781 (cons 'embedded-signature
782 (get-signature (open-bytevector-input-port data))))
783 (else
784 ;; Unknown subpacket type. If it is critical, then the signature
785 ;; should be considered invalid.
786 (print "Unknown subpacket type: " type)
787 (if critical?
788 (error "unrecognized critical signature subpacket" type)
789 (list 'unsupported-subpacket type data))))))
790
791 (let ((p (open-bytevector-input-port bv)))
792 (let lp ((subpackets '()))
793 ;; In case of multiple subpackets of the same type, the last
794 ;; one should be used. Therefore the list is not reversed
795 ;; here.
796 (if (port-eof? p)
797 (reverse subpackets)
798 (let* ((len (- (get-v4-length p) 1))
799 (tag (get-u8 p))
800 (sp (parse tag (get-bytevector-n p len))))
801 (print "#;Subpacket " sp)
802 (lp (cons sp subpackets)))))))
803
804;;; Public keys
805
806
807(define (openpgp-public-key-id k)
808 (let ((bv (openpgp-public-key-fingerprint k)))
809 (bytevector-u64-ref bv
810 (- (bytevector-length bv) 8)
811 (endianness big))))
812
813(define (get-public-key p subkey?)
814 (define (fingerprint p)
815 (let ((len (port-position p)))
816 (set-port-position! p 0)
817 (let-values (((sha1-port get)
818 (open-hash-port (hash-algorithm sha1))))
819 (put-u8 sha1-port #x99)
820 (put-u16 sha1-port len)
821 (dump-port p sha1-port)
822 (close-port sha1-port)
823 (get))))
824 (define (get-key p alg)
825 (define (->hex n)
826 (string-hex-pad (number->string n 16)))
827
828 (cond ((= alg PUBLIC-KEY-RSA)
829 (print "Public RSA key")
830 (let* ((n (get-mpi p)) (e (get-mpi p)))
831 (string->canonical-sexp
832 (format #f "(public-key (rsa (n #~a#) (e #~a#)))"
833 (->hex n) (->hex e)))))
834 ((= alg PUBLIC-KEY-DSA)
835 (print "Public DSA key")
836 (let* ((p* (get-mpi p)) (q (get-mpi p))
837 (g (get-mpi p)) (y (get-mpi p)))
838 (string->canonical-sexp
839 (format #f "(public-key (dsa (p #~a#)(q #~a#)(g #~a#)(y #~a#)))"
840 (->hex p*) (->hex q) (->hex g) (->hex y)))))
841 #;
842 ((= alg PUBLIC-KEY-ELGAMAL-ENCRYPT-ONLY) ; ; ; ;
843 (print "Public El-Gamal Key") ; ; ; ;
844 (let* ((p* (get-mpi p)) (g (get-mpi p)) (y (get-mpi p))) ; ; ; ;
845 (make-public-elgamal-key p* g y)))
846 ((= alg PUBLIC-KEY-EDDSA)
847 ;; See
848 ;; <https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04>
849 ;; and openpgp-oid.c in GnuPG.
850 (print "Public EdDSA key")
851 (let* ((len (get-u8 p))
852 (oid (bytevector->uint (get-bytevector-n p len)))
853 (q (get-mpi p)))
854 (define curve
855 (match oid
856 (#x2b06010401da470f01 'Ed25519)
857 (#x2b060104019755010501 'Curve25519)))
858
859 (string->canonical-sexp
860 (format #f "(public-key (ecc (curve ~a)(flags ~a)(q #~a#)))"
861 curve
862 (if (eq? curve 'Curve25519) 'djb-tweak 'eddsa)
863 (->hex q)))))
864 (else
865 (list 'unsupported-algorithm ;FIXME: throw
866 (public-key-algorithm alg)
867 (get-bytevector-all p)))))
868 (let ((version (get-u8 p)))
869 (case version
870 ((4)
871 (let-values (((ctime alg) (get-integers p u32 u8)))
872 (print "Key creation time: " (unixtime ctime))
873 (let ((key (get-key p alg)))
874 (unless (port-eof? p)
875 ;; Probably an error? Gonna cause trouble anyway.
876 (print "Trailing data in public key: " (get-bytevector-all p)))
877 (let ((digest (fingerprint p)))
878 (make-openpgp-public-key version subkey? ctime key
879 digest)))))
880 (else
881 (print "Unsupported public key version: " version)
882 'unsupported-public-key-version))))
883
884(define (openpgp-public-key-primary? key)
885 (and (openpgp-public-key? key)
886 (not (openpgp-public-key-subkey? key))))
887
888;;; User IDs and User attributes
889
890
891(define-record-type <openpgp-user-id>
892 (make-openpgp-user-id value unparsed)
893 openpgp-user-id?
894 (value openpgp-user-id-value)
895 (unparsed openpgp-user-id-unparsed))
896
897(define (get-user-id p len)
898 (let ((unparsed (get-bytevector-n p len)))
899 (make-openpgp-user-id (utf8->string unparsed) unparsed)))
900
901(define-record-type <openpgp-user-attribute>
902 (make-openpgp-user-attribute unparsed)
903 openpgp-user-attribute?
904 (unparsed openpgp-user-attribute-unparsed))
905
906(define (get-user-attribute p len)
907 (let ((bv (get-bytevector-n p len)))
908 ;; TODO: bv contains subpackets. Type 1 is JFIF.
909 (make-openpgp-user-attribute bv)))
910
911\f
912;;; Keyring management
913
914(define-record-type <openpgp-keyring>
915 (openpgp-keyring table)
916 openpgp-keyring?
917 (table openpgp-keyring-table)) ;vhash mapping key id to packets
918
919(define (lookup-key-by-id keyring id)
920 "Return a list of packets for the key with ID in KEYRING, or #f if ID could
921not be found. ID must be the 64-bit key ID of the key, an integer."
922 (match (vhash-assv id (openpgp-keyring-table keyring))
923 ((_ . lst) lst)
924 (#f '())))
925
926;; Reads a keyring from the binary input port p. It must not be
927;; ASCII armored.
928
929(define %empty-keyring
930 ;; The empty keyring.
931 (openpgp-keyring vlist-null))
932
933(define* (get-openpgp-keyring port
934 #:optional (keyring %empty-keyring)
935 #:key (limit -1))
936 "Read from PORT an OpenPGP keyring in binary format; return a keyring based
937on all the OpenPGP primary keys that were read. The returned keyring
938complements KEYRING. LIMIT is the maximum number of keys to read, or -1 if
939there is no limit."
940 (let lp ((pkt (get-packet port))
941 (limit limit)
942 (keyring (openpgp-keyring-table keyring)))
943 (print "#;key " pkt)
944 (cond ((or (zero? limit) (eof-object? pkt))
945 (openpgp-keyring keyring))
946 ((openpgp-public-key-primary? pkt)
947 ;; Read signatures, user id's, subkeys
948 (let lp* ((pkt (get-packet port))
949 (pkts (list pkt))
950 (key-ids (list (openpgp-public-key-id pkt))))
951 (print "#;keydata " pkt)
952 (cond ((or (eof-object? pkt)
953 (eq? pkt 'unsupported-public-key-version)
954 (openpgp-public-key-primary? pkt))
955 ;; KEYRING is indexed by key-id. Key ids for both the
956 ;; primary key and subkeys all point to the list of
957 ;; packets.
958 (lp pkt
959 (- limit 1)
960 (fold (cute vhash-consv <> (reverse pkts) <>)
961 keyring key-ids)))
962 ((openpgp-public-key? pkt) ;subkey
963 (lp* (get-packet port) (cons pkt pkts)
964 (cons (openpgp-public-key-id pkt) key-ids)))
965 (else
966 (lp* (get-packet port) (cons pkt pkts) key-ids)))))
967 (else
968 ;; Skip until there's a primary key. Ignore errors...
969 (lp (get-packet port) limit keyring)))))
970
971\f
972;;;
973;;; Radix-64 (RFC4880).
974;;;
975
976(define (crc24 bv)
977 "Compute a CRC24 as described in RFC4880, Section 6.1."
978 (define poly #x1864cfb)
979
980 (let loop ((crc #xb704ce)
981 (index 0))
982 (if (= index (bytevector-length bv))
983 (logand crc #xffffff)
984 (let ((crc (logxor (ash (bytevector-u8-ref bv index) 16)
985 crc)))
986 (let inner ((i 0)
987 (crc crc))
988 (if (< i 8)
989 (let ((crc (ash crc 1)))
990 (inner (+ i 1)
991 (if (zero? (logand crc #x1000000))
992 crc
993 (logxor crc poly))))
994 (loop crc (+ index 1))))))))
995
996(define %begin-block-prefix "-----BEGIN ")
997(define %begin-block-suffix "-----")
998
999(define %end-block-prefix "-----END ")
1000(define %end-block-suffix "-----")
1001
1002(define (read-radix-64 port)
1003 "Read from PORT an ASCII-armored Radix-64 stream, decode it, and return the
1004result as a bytevector as well as the type, a string such as \"PGP MESSAGE\".
1005Return #f if PORT does not contain a valid Radix-64 stream, and the
1006end-of-file object if the Radix-64 sequence was truncated."
1007 ;; This is the same as 'get-delimited-base64', except that it implements the
1008 ;; CRC24 check.
1009 (define (skip-headers port)
1010 ;; Skip the Radix-64 "armor headers".
1011 (match (read-line port)
1012 ((? eof-object? eof) eof)
1013 ((= string-trim-both "") "")
1014 (_ (skip-headers port))))
1015
1016 (let ((line (string-trim-right (read-line port))))
1017 (if (and (string-prefix? %begin-block-prefix line)
1018 (string-suffix? %begin-block-suffix line))
1019 (let* ((kind (string-drop-right
1020 (string-drop line (string-length %begin-block-prefix))
1021 (string-length %begin-block-suffix)))
1022 (end (string-append %end-block-prefix kind
1023 %end-block-suffix)))
1024 (skip-headers port)
1025 (let loop ((lines '()))
1026 (let ((line (read-line port)))
1027 (match line
1028 ((? eof-object? eof)
1029 (values eof kind))
1030 ((= string-trim-both "")
1031 (loop lines))
1032 ((= string-trim-both str)
1033 (if (string=? str end)
1034 (match lines
1035 ((crc lines ...)
1036 ;; The last line should be the CRC, starting with an
1037 ;; "=" sign.
1038 (let ((crc (and (string-prefix? "=" crc)
1039 (base64-decode (string-drop crc 1))))
1040 (data (base64-decode
1041 (string-concatenate-reverse lines))))
1042 (if (and crc (= (bytevector->uint crc) (crc24 data)))
1043 (values data kind)
1044 (values #f kind))))
1045 (_
1046 (values #f kind)))
1047 (loop (cons str lines))))))))
1048 (values #f #f))))