openpgp: Decode the issuer-fingerprint signature subpacket.
[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?
35 openpgp-signature-issuer
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
472 value)
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)
482 (value openpgp-signature-value))
483
484(define (openpgp-signature-issuer sig)
485 (cond ((assq 'issuer (openpgp-signature-unhashed-subpackets sig)) => cdr)
486 ;; XXX: is the issuer always in the unhashed subpackets?
487 (else #f)))
488
4459c785
LC
489(define (openpgp-signature-issuer-fingerprint sig)
490 "When it's available, return the fingerprint, a bytevector, or the issuer of
491SIG. Otherwise, return #f."
492 (or (assoc-ref (openpgp-signature-hashed-subpackets sig) 'issuer-fingerprint)
493 (assoc-ref (openpgp-signature-unhashed-subpackets sig)
494 'issuer-fingerprint)))
495
43408e30
LC
496(define (openpgp-signature-creation-time sig)
497 (cond ((assq 'signature-ctime (openpgp-signature-hashed-subpackets sig))
498 => (lambda (x) (unixtime (cdr x))))
499 ;; XXX: should be an error?
500 (else #f)))
501
502(define (openpgp-signature-expiration-time sig)
503 (cond ((assq 'signature-etime (openpgp-signature-hashed-subpackets sig))
504 => (lambda (x)
505 (unixtime (+ (cdr x)
506 (openpgp-signature-creation-time sig)))))
507 (else #f)))
508
509
510(define (get-openpgp-detached-signature/ascii port)
511 "Read from PORT an ASCII-armored detached signature. Return an
512<openpgp-signature> record or the end-of-file object. Raise an error if the
513data read from PORT does is invalid or does not correspond to a detached
514signature."
515 (let-values (((data type) (read-radix-64 port)))
516 (cond ((eof-object? data) data)
517 ((string=? type "PGP SIGNATURE")
518 (get-packet (open-bytevector-input-port data)))
519 (else
520 (error "expected PGP SIGNATURE" type)))))
521
522(define (hash-algorithm-name algorithm) ;XXX: should be in Guile-Gcrypt
523 "Return the name of ALGORITHM, a 'hash-algorithm' integer, as a symbol."
524 (letrec-syntax ((->name (syntax-rules ()
525 ((_) #f)
526 ((_ name rest ...)
527 (if (= algorithm (hash-algorithm name))
528 'name
529 (->name rest ...))))))
530 (->name sha1 sha256 sha384 sha512 sha224
531 sha3-224 sha3-256 sha3-384 sha3-512)))
532
533(define (verify-openpgp-signature sig keyring dataport)
534 "Verify that the data read from DATAPORT matches SIG, an
535<openpgp-signature>. Fetch the public key of the issuer of SIG from KEYRING,
536a keyring as returned by 'get-openpgp-keyring'. Return two values: a status
537symbol, such as 'bad-signature or 'missing-key, and additional info, such as
538the issuer's OpenPGP public key extracted from KEYRING."
539 (define (check key sig)
540 (let*-values (((hash-algorithm) (lookup-hash-algorithm
541 (openpgp-signature-hash-algorithm sig)))
542 ((port get-hash) (open-hash-port hash-algorithm)))
543 (dump-port dataport port)
544
545 ;; As per RFC4880 Section 5.2.4 ("Computing Signatures"), hash some of
546 ;; the fields from the signature packet.
547 (for-each (cut put-bytevector port <>)
548 (openpgp-signature-append-data sig))
549 (close-port port)
550
551 (let* ((signature (openpgp-signature-value sig))
552 (public-key (openpgp-public-key-value key))
553 (hash (get-hash))
554 (key-type (key-type public-key))
555 (data
556 ;; See "(gcrypt) Cryptographic Functions".
557 (sexp->canonical-sexp
558 (if (eq? key-type 'ecc)
559 `(data
560 (flags eddsa)
561 (hash-algo sha512)
562 (value ,hash))
563 `(data
564 (flags ,(match key-type
565 ('rsa 'pkcs1)
566 ('dsa 'rfc6979)))
567 (hash ,(hash-algorithm-name hash-algorithm)
568 ,hash))))))
569 (values (if (verify signature data public-key)
570 'good-signature
571 'bad-signature)
572 key))))
573
574 ;; TODO: Support SIGNATURE-TEXT.
575 (if (= (openpgp-signature-type sig) SIGNATURE-BINARY)
576 (let* ((issuer (openpgp-signature-issuer sig))
577 (key-data (lookup-key-by-id keyring issuer)))
578 ;; Find the primary key or subkey that made the signature.
579 (let ((key (find (lambda (k)
580 (and (openpgp-public-key? k)
581 (= (openpgp-public-key-id k) issuer)))
582 key-data)))
583 (if key
584 (check key sig)
585 (values 'missing-key issuer))))
586 (values 'unsupported-signature sig)))
587
4459c785
LC
588(define (key-id-matches-fingerprint? key-id fingerprint)
589 "Return true if KEY-ID, a number, corresponds to the low 8 bytes of
590FINGERPRINT, a bytevector."
591 (let* ((len (bytevector-length fingerprint))
592 (low (make-bytevector 8)))
593 (bytevector-copy! fingerprint (- len 8) low 0 8)
594 (= (bytevector->uint low) key-id)))
595
43408e30
LC
596(define (get-signature p)
597 (define (->hex n)
598 (string-hex-pad (number->string n 16)))
599
600 (define (get-sig p pkalg)
601 (cond ((= pkalg PUBLIC-KEY-RSA)
602 (print "RSA signature")
603 (string->canonical-sexp
604 (format #f "(sig-val (rsa (s #~a#)))"
605 (->hex (get-mpi p)))))
606 ((= pkalg PUBLIC-KEY-DSA)
607 (print "DSA signature")
608 (let ((r (get-mpi p)) (s (get-mpi p)))
609 (string->canonical-sexp
610 (format #f "(sig-val (dsa (r #~a#) (s #~a#)))"
611 (->hex r) (->hex s)))))
612 ((= pkalg PUBLIC-KEY-EDDSA)
613 (print "EdDSA signature")
614 (let ((r (get-mpi/bytevector p))
615 (s (get-mpi/bytevector p)))
616 ;; XXX: 'verify' fails down the road with GPG_ERR_INV_LENGTH if
617 ;; we provide a 31-byte R or S below, hence the second argument
618 ;; to '->hex' ensuring the MPIs are represented as two-byte
619 ;; multiples, with leading zeros.
620 (define (bytevector->hex bv)
621 (let ((str (bytevector->base16-string bv)))
622 (if (odd? (bytevector-length bv))
623 (string-append "00" str)
624 str)))
625
626 (string->canonical-sexp
627 (format #f "(sig-val (eddsa (r #~a#) (s #~a#)))"
628 (bytevector->hex r) (bytevector->hex s)))))
629 (else
630 (list 'unsupported-algorithm
631 (public-key-algorithm pkalg)
632 (get-bytevector-all p)))))
633 (let ((version (get-u8 p)))
634 (case version
635 ((3)
636 (let-values (((hmlen type ctime keyid pkalg halg hashl16)
637 (get-integers p u8 u8 u32 u64 u8 u8 u16)))
638 (unless (= hmlen 5)
639 (error "invalid signature packet"))
640 (print "Signature type: " type " creation time: " (unixtime ctime))
641 (print "Hash algorithm: " (openpgp-hash-algorithm halg))
642 (let ((value (get-sig p pkalg)))
643 (unless (port-eof? p)
644 (print "Trailing data in signature: " (get-bytevector-all p)))
645 (make-openpgp-signature version type
646 (public-key-algorithm pkalg)
647 (openpgp-hash-algorithm halg) hashl16
648 (list (integers->bytevector u8 type
649 u32 ctime))
650 ;; Emulate hashed subpackets
651 (list (cons 'signature-ctime ctime))
652 ;; Unhashed subpackets
653 (list (cons 'issuer keyid))
654 value))))
655 ((4)
656 (let*-values (((type pkalg halg) (get-integers p u8 u8 u8))
657 ((hashed-subpackets)
658 (get-bytevector-n p (get-u16 p)))
659 ((unhashed-subpackets)
660 (get-bytevector-n p (get-u16 p)))
661 ((hashl16) (get-u16 p)))
662 (print "Signature type: " type)
663 (print "Hash algorithm: " (openpgp-hash-algorithm halg))
664 (let ((value (get-sig p pkalg)))
665 (unless (port-eof? p)
666 (print "Trailing data in signature: " (get-bytevector-all p)))
667 (let* ((subpacket-len (bytevector-length hashed-subpackets))
668 (append-data
669 (list
670 (integers->bytevector u8 version
671 u8 type
672 u8 pkalg
673 u8 halg
674 u16 subpacket-len)
675 hashed-subpackets
676 ;; http://www.rfc-editor.org/errata_search.php?rfc=4880
677 ;; Errata ID: 2214.
678 (integers->bytevector u8 #x04
679 u8 #xff
4459c785
LC
680 u32 (+ 6 subpacket-len))))
681 (unhashed-subpackets
682 (parse-subpackets unhashed-subpackets))
683 (hashed-subpackets (parse-subpackets hashed-subpackets))
684 (subpackets (append hashed-subpackets
685 unhashed-subpackets))
686 (issuer-key-id (assoc-ref subpackets 'issuer))
687 (issuer (assoc-ref subpackets
688 'issuer-fingerprint)))
689 (unless (or (not issuer) (not issuer-key-id)
690 (key-id-matches-fingerprint? issuer-key-id issuer))
691 (error "issuer key id does not match fingerprint" issuer))
692
43408e30
LC
693 (make-openpgp-signature version type
694 (public-key-algorithm pkalg)
695 (openpgp-hash-algorithm halg)
696 hashl16
697 append-data
4459c785
LC
698 hashed-subpackets
699 unhashed-subpackets
43408e30
LC
700 value)))))
701 (else
702 (print "Unsupported signature version: " version)
703 'unsupported-signature-version))))
704
705(define (parse-subpackets bv)
706 (define (parse tag data)
707 (let ((type (fxbit-field tag 0 7))
708 (critical? (fxbit-set? tag 7)))
709 (cond
710 ((= type SUBPACKET-SIGNATURE-CTIME)
711 (cons 'signature-ctime
712 (bytevector-u32-ref data 0 (endianness big))))
713 ((= type SUBPACKET-SIGNATURE-ETIME)
714 (cons 'signature-etime
715 (bytevector-u32-ref data 0 (endianness big))))
716 ((= type SUBPACKET-TRUST-SIGNATURE)
717 (cons 'trust-signature
718 (bytevector-u8-ref data 0)))
719 ((= type SUBPACKET-REVOCABLE)
720 (cons 'revocable
721 (= (bytevector-u8-ref data 0) 1)))
722 ((= type SUBPACKET-KEY-ETIME)
723 (cons 'key-etime
724 (bytevector-u32-ref data 0 (endianness big))))
725 ((= type SUBPACKET-PREFERRED-SYMMETRIC-ALGORITHMS)
726 (cons 'preferred-symmetric-algorithms
727 (map symmetric-key-algorithm (bytevector->u8-list data))))
728 ((= type SUBPACKET-ISSUER)
729 (cons 'issuer
730 (bytevector-u64-ref data 0 (endianness big))))
4459c785
LC
731 ((= type SUBPACKET-ISSUER-FINGERPRINT) ;v4+ only, RFC4880bis
732 (cons 'issuer-fingerprint
733 (let* ((version (bytevector-u8-ref data 0))
734 (len (match version (4 20) (5 32)) )
735 (fingerprint (make-bytevector len)))
736 (bytevector-copy! data 1 fingerprint 0 len)
737 fingerprint)))
43408e30
LC
738 ((= type SUBPACKET-NOTATION-DATA)
739 (let ((p (open-bytevector-input-port data)))
740 (let-values (((f1 nlen vlen)
741 (get-integers p u8 _ _ _ u16 u16)))
742 (let* ((name (get-bytevector-n p nlen))
743 (value (get-bytevector-n p vlen)))
744 (cons 'notation-data
745 (list (utf8->string name)
746 (if (fxbit-set? f1 7)
747 (utf8->string value)
748 value)))))))
749 ((= type SUBPACKET-PREFERRED-HASH-ALGORITHMS)
750 (cons 'preferred-hash-algorithms
751 (map openpgp-hash-algorithm (bytevector->u8-list data))))
752 ((= type SUBPACKET-PREFERRED-COMPRESSION-ALGORITHMS)
753 (cons 'preferred-compression-algorithms
754 (map compression-algorithm (bytevector->u8-list data))))
755 ((= type SUBPACKET-KEY-SERVER-PREFERENCES)
756 (cons 'key-server-preferences
757 (if (and (>= (bytevector-length data) 1)
758 (fxbit-set? (bytevector-u8-ref data 0) 7))
759 (list 'no-modify)
760 (list))))
761 ((= type SUBPACKET-PREFERRED-KEY-SERVER)
762 (cons 'preferred-key-server (utf8->string data)))
763 ((= type SUBPACKET-PRIMARY-USER-ID)
764 (cons 'primary-user-id (not (zero? (bytevector-u8-ref data 0)))))
765 ((= type SUBPACKET-POLICY-URI)
766 (cons 'policy-uri (utf8->string data)))
767 ((= type SUBPACKET-KEY-FLAGS)
768 (cons 'key-flags (bytevector->bitnames
769 data
770 '(certification sign-data
771 communications-encryption
772 storage-encryption
773 split-key authentication
774 group-key))))
775 ((= type SUBPACKET-SIGNER-USER-ID)
776 (cons 'signer-user-id (utf8->string data)))
777 ((= type SUBPACKET-REASON-FOR-REVOCATION)
778 (let* ((p (open-bytevector-input-port data))
779 (revocation-code (get-u8 p)))
780 (cons 'reason-for-revocation
781 (list revocation-code
782 (if (port-eof? p)
783 ""
784 (utf8->string (get-bytevector-all p)))))))
785 ((= type SUBPACKET-FEATURES)
786 (cons 'features (bytevector->bitnames
787 data '(modification-detection))))
788 ((= type SUBPACKET-EMBEDDED-SIGNATURE)
789 (cons 'embedded-signature
790 (get-signature (open-bytevector-input-port data))))
791 (else
792 ;; Unknown subpacket type. If it is critical, then the signature
793 ;; should be considered invalid.
794 (print "Unknown subpacket type: " type)
795 (if critical?
796 (error "unrecognized critical signature subpacket" type)
797 (list 'unsupported-subpacket type data))))))
798
799 (let ((p (open-bytevector-input-port bv)))
800 (let lp ((subpackets '()))
801 ;; In case of multiple subpackets of the same type, the last
802 ;; one should be used. Therefore the list is not reversed
803 ;; here.
804 (if (port-eof? p)
805 (reverse subpackets)
806 (let* ((len (- (get-v4-length p) 1))
807 (tag (get-u8 p))
808 (sp (parse tag (get-bytevector-n p len))))
809 (print "#;Subpacket " sp)
810 (lp (cons sp subpackets)))))))
811
812;;; Public keys
813
814
815(define (openpgp-public-key-id k)
816 (let ((bv (openpgp-public-key-fingerprint k)))
817 (bytevector-u64-ref bv
818 (- (bytevector-length bv) 8)
819 (endianness big))))
820
821(define (get-public-key p subkey?)
822 (define (fingerprint p)
823 (let ((len (port-position p)))
824 (set-port-position! p 0)
825 (let-values (((sha1-port get)
826 (open-hash-port (hash-algorithm sha1))))
827 (put-u8 sha1-port #x99)
828 (put-u16 sha1-port len)
829 (dump-port p sha1-port)
830 (close-port sha1-port)
831 (get))))
832 (define (get-key p alg)
833 (define (->hex n)
834 (string-hex-pad (number->string n 16)))
835
836 (cond ((= alg PUBLIC-KEY-RSA)
837 (print "Public RSA key")
838 (let* ((n (get-mpi p)) (e (get-mpi p)))
839 (string->canonical-sexp
840 (format #f "(public-key (rsa (n #~a#) (e #~a#)))"
841 (->hex n) (->hex e)))))
842 ((= alg PUBLIC-KEY-DSA)
843 (print "Public DSA key")
844 (let* ((p* (get-mpi p)) (q (get-mpi p))
845 (g (get-mpi p)) (y (get-mpi p)))
846 (string->canonical-sexp
847 (format #f "(public-key (dsa (p #~a#)(q #~a#)(g #~a#)(y #~a#)))"
848 (->hex p*) (->hex q) (->hex g) (->hex y)))))
849 #;
850 ((= alg PUBLIC-KEY-ELGAMAL-ENCRYPT-ONLY) ; ; ; ;
851 (print "Public El-Gamal Key") ; ; ; ;
852 (let* ((p* (get-mpi p)) (g (get-mpi p)) (y (get-mpi p))) ; ; ; ;
853 (make-public-elgamal-key p* g y)))
854 ((= alg PUBLIC-KEY-EDDSA)
855 ;; See
856 ;; <https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04>
857 ;; and openpgp-oid.c in GnuPG.
858 (print "Public EdDSA key")
859 (let* ((len (get-u8 p))
860 (oid (bytevector->uint (get-bytevector-n p len)))
861 (q (get-mpi p)))
862 (define curve
863 (match oid
864 (#x2b06010401da470f01 'Ed25519)
865 (#x2b060104019755010501 'Curve25519)))
866
867 (string->canonical-sexp
868 (format #f "(public-key (ecc (curve ~a)(flags ~a)(q #~a#)))"
869 curve
870 (if (eq? curve 'Curve25519) 'djb-tweak 'eddsa)
871 (->hex q)))))
872 (else
873 (list 'unsupported-algorithm ;FIXME: throw
874 (public-key-algorithm alg)
875 (get-bytevector-all p)))))
876 (let ((version (get-u8 p)))
877 (case version
878 ((4)
879 (let-values (((ctime alg) (get-integers p u32 u8)))
880 (print "Key creation time: " (unixtime ctime))
881 (let ((key (get-key p alg)))
882 (unless (port-eof? p)
883 ;; Probably an error? Gonna cause trouble anyway.
884 (print "Trailing data in public key: " (get-bytevector-all p)))
885 (let ((digest (fingerprint p)))
886 (make-openpgp-public-key version subkey? ctime key
887 digest)))))
888 (else
889 (print "Unsupported public key version: " version)
890 'unsupported-public-key-version))))
891
892(define (openpgp-public-key-primary? key)
893 (and (openpgp-public-key? key)
894 (not (openpgp-public-key-subkey? key))))
895
896;;; User IDs and User attributes
897
898
899(define-record-type <openpgp-user-id>
900 (make-openpgp-user-id value unparsed)
901 openpgp-user-id?
902 (value openpgp-user-id-value)
903 (unparsed openpgp-user-id-unparsed))
904
905(define (get-user-id p len)
906 (let ((unparsed (get-bytevector-n p len)))
907 (make-openpgp-user-id (utf8->string unparsed) unparsed)))
908
909(define-record-type <openpgp-user-attribute>
910 (make-openpgp-user-attribute unparsed)
911 openpgp-user-attribute?
912 (unparsed openpgp-user-attribute-unparsed))
913
914(define (get-user-attribute p len)
915 (let ((bv (get-bytevector-n p len)))
916 ;; TODO: bv contains subpackets. Type 1 is JFIF.
917 (make-openpgp-user-attribute bv)))
918
919\f
920;;; Keyring management
921
922(define-record-type <openpgp-keyring>
923 (openpgp-keyring table)
924 openpgp-keyring?
925 (table openpgp-keyring-table)) ;vhash mapping key id to packets
926
927(define (lookup-key-by-id keyring id)
928 "Return a list of packets for the key with ID in KEYRING, or #f if ID could
929not be found. ID must be the 64-bit key ID of the key, an integer."
930 (match (vhash-assv id (openpgp-keyring-table keyring))
931 ((_ . lst) lst)
932 (#f '())))
933
934;; Reads a keyring from the binary input port p. It must not be
935;; ASCII armored.
936
937(define %empty-keyring
938 ;; The empty keyring.
939 (openpgp-keyring vlist-null))
940
941(define* (get-openpgp-keyring port
942 #:optional (keyring %empty-keyring)
943 #:key (limit -1))
944 "Read from PORT an OpenPGP keyring in binary format; return a keyring based
945on all the OpenPGP primary keys that were read. The returned keyring
946complements KEYRING. LIMIT is the maximum number of keys to read, or -1 if
947there is no limit."
948 (let lp ((pkt (get-packet port))
949 (limit limit)
950 (keyring (openpgp-keyring-table keyring)))
951 (print "#;key " pkt)
952 (cond ((or (zero? limit) (eof-object? pkt))
953 (openpgp-keyring keyring))
954 ((openpgp-public-key-primary? pkt)
955 ;; Read signatures, user id's, subkeys
956 (let lp* ((pkt (get-packet port))
957 (pkts (list pkt))
958 (key-ids (list (openpgp-public-key-id pkt))))
959 (print "#;keydata " pkt)
960 (cond ((or (eof-object? pkt)
961 (eq? pkt 'unsupported-public-key-version)
962 (openpgp-public-key-primary? pkt))
963 ;; KEYRING is indexed by key-id. Key ids for both the
964 ;; primary key and subkeys all point to the list of
965 ;; packets.
966 (lp pkt
967 (- limit 1)
968 (fold (cute vhash-consv <> (reverse pkts) <>)
969 keyring key-ids)))
970 ((openpgp-public-key? pkt) ;subkey
971 (lp* (get-packet port) (cons pkt pkts)
972 (cons (openpgp-public-key-id pkt) key-ids)))
973 (else
974 (lp* (get-packet port) (cons pkt pkts) key-ids)))))
975 (else
976 ;; Skip until there's a primary key. Ignore errors...
977 (lp (get-packet port) limit keyring)))))
978
979\f
980;;;
981;;; Radix-64 (RFC4880).
982;;;
983
984(define (crc24 bv)
985 "Compute a CRC24 as described in RFC4880, Section 6.1."
986 (define poly #x1864cfb)
987
988 (let loop ((crc #xb704ce)
989 (index 0))
990 (if (= index (bytevector-length bv))
991 (logand crc #xffffff)
992 (let ((crc (logxor (ash (bytevector-u8-ref bv index) 16)
993 crc)))
994 (let inner ((i 0)
995 (crc crc))
996 (if (< i 8)
997 (let ((crc (ash crc 1)))
998 (inner (+ i 1)
999 (if (zero? (logand crc #x1000000))
1000 crc
1001 (logxor crc poly))))
1002 (loop crc (+ index 1))))))))
1003
1004(define %begin-block-prefix "-----BEGIN ")
1005(define %begin-block-suffix "-----")
1006
1007(define %end-block-prefix "-----END ")
1008(define %end-block-suffix "-----")
1009
1010(define (read-radix-64 port)
1011 "Read from PORT an ASCII-armored Radix-64 stream, decode it, and return the
1012result as a bytevector as well as the type, a string such as \"PGP MESSAGE\".
1013Return #f if PORT does not contain a valid Radix-64 stream, and the
1014end-of-file object if the Radix-64 sequence was truncated."
1015 ;; This is the same as 'get-delimited-base64', except that it implements the
1016 ;; CRC24 check.
1017 (define (skip-headers port)
1018 ;; Skip the Radix-64 "armor headers".
1019 (match (read-line port)
1020 ((? eof-object? eof) eof)
1021 ((= string-trim-both "") "")
1022 (_ (skip-headers port))))
1023
1024 (let ((line (string-trim-right (read-line port))))
1025 (if (and (string-prefix? %begin-block-prefix line)
1026 (string-suffix? %begin-block-suffix line))
1027 (let* ((kind (string-drop-right
1028 (string-drop line (string-length %begin-block-prefix))
1029 (string-length %begin-block-suffix)))
1030 (end (string-append %end-block-prefix kind
1031 %end-block-suffix)))
1032 (skip-headers port)
1033 (let loop ((lines '()))
1034 (let ((line (read-line port)))
1035 (match line
1036 ((? eof-object? eof)
1037 (values eof kind))
1038 ((= string-trim-both "")
1039 (loop lines))
1040 ((= string-trim-both str)
1041 (if (string=? str end)
1042 (match lines
1043 ((crc lines ...)
1044 ;; The last line should be the CRC, starting with an
1045 ;; "=" sign.
1046 (let ((crc (and (string-prefix? "=" crc)
1047 (base64-decode (string-drop crc 1))))
1048 (data (base64-decode
1049 (string-concatenate-reverse lines))))
1050 (if (and crc (= (bytevector->uint crc) (crc24 data)))
1051 (values data kind)
1052 (values #f kind))))
1053 (_
1054 (values #f kind)))
1055 (loop (cons str lines))))))))
1056 (values #f #f))))