Synch with the semi-1_14 branch.
[elisp/semi.git] / pgg-parse.el
1 ;;; pgg-parse.el --- OpenPGP packet parsing
2
3 ;; Copyright (C) 1999 Daiki Ueno
4
5 ;; Author: Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
6 ;; Created: 1999/10/28
7 ;; Keywords: PGP, OpenPGP, GnuPG
8
9 ;; This file is part of SEMI (Secure Emacs MIME Interface).
10
11 ;; This program is free software; you can redistribute it and/or
12 ;; modify it under the terms of the GNU General Public License as
13 ;; published by the Free Software Foundation; either version 2, or (at
14 ;; your option) any later version.
15
16 ;; This program is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;;    This module is based on
29
30 ;;      [OpenPGP] RFC 2440: "OpenPGP Message Format"
31 ;;          by John W. Noerenberg, II <jwn2@qualcomm.com>,
32 ;;          Jon Callas <jon@pgp.com>, Lutz Donnerhacke <lutz@iks-jena.de>,
33 ;;          Hal Finney <hal@pgp.com> and Rodney Thayer <rodney@unitran.com>
34 ;;          (1998/11)
35
36 ;;; Code:
37
38 (eval-when-compile (require 'cl))
39
40 (eval-when-compile (require 'static))
41
42 (require 'poem)
43 (require 'pccl)
44 (require 'pcustom)
45 (require 'mel)
46
47 (defgroup pgg-parse ()
48   "OpenPGP packet parsing"
49   :group 'pgg)
50
51 (defcustom pgg-parse-public-key-algorithm-alist
52   '((1 . RSA) (2 . RSA-E) (3 . RSA-S) (16 . ELG-E) (17 . DSA) (20 . ELG))
53   "Alist of the assigned number to the public key algorithm."
54   :group 'pgg-parse
55   :type 'alist)
56
57 (defcustom pgg-parse-symmetric-key-algorithm-alist
58   '((1 . IDEA) (2 . 3DES) (4 . CAST5) (5 . SAFER-SK128))
59   "Alist of the assigned number to the simmetric key algorithm."
60   :group 'pgg-parse
61   :type 'alist)
62
63 (defcustom pgg-parse-hash-algorithm-alist
64   '((1 . MD5) (2 . SHA1) (3 . RIPEMD160) (5 . MD2))
65   "Alist of the assigned number to the cryptographic hash algorithm."
66   :group 'pgg-parse
67   :type 'alist)
68
69 (defcustom pgg-parse-compression-algorithm-alist
70   '((0 . nil); Uncompressed
71     (1 . ZIP)
72     (2 . ZLIB))
73   "Alist of the assigned number to the compression algorithm."
74   :group 'pgg-parse
75   :type 'alist)
76
77 (defcustom pgg-parse-signature-type-alist
78   '((0 . "Signature of a binary document")
79     (1 . "Signature of a canonical text document")
80     (2 . "Standalone signature")
81     (16 . "Generic certification of a User ID and Public Key packet")
82     (17 . "Persona certification of a User ID and Public Key packet")
83     (18 . "Casual certification of a User ID and Public Key packet")
84     (19 . "Positive certification of a User ID and Public Key packet")
85     (24 . "Subkey Binding Signature")
86     (31 . "Signature directly on a key")
87     (32 . "Key revocation signature")
88     (40 . "Subkey revocation signature")
89     (48 . "Certification revocation signature")
90     (64 . "Timestamp signature."))
91   "Alist of the assigned number to the signature type."
92   :group 'pgg-parse
93   :type 'alist)
94
95 (defcustom pgg-ignore-packet-checksum t; XXX
96   "If non-nil checksum of each ascii armored packet will be ignored."
97   :group 'pgg-parse
98   :type 'boolean)
99
100 (defvar pgg-armor-header-lines
101   '("^-----BEGIN PGP MESSAGE\\(, PART [0-9]+\\(/[0-9]+\\)?\\)?-----\r?$"
102     "^-----BEGIN PGP PUBLIC KEY BLOCK-----\r?$"
103     "^-----BEGIN PGP PRIVATE KEY BLOCK-----\r?$"
104     "^-----BEGIN PGP SIGNATURE-----\r?$")
105   "Armor headers.")
106
107 (defmacro pgg-format-key-identifier (string)
108   `(upcase (apply #'format "%02x%02x%02x%02x%02x%02x%02x%02x"
109                   (string-to-int-list ,string))))
110
111 (defmacro pgg-parse-time-field (bytes)
112   `(list (logior (lsh (car ,bytes) 8)
113                  (nth 1 ,bytes))
114          (logior (lsh (nth 2 ,bytes) 8)
115                  (nth 3 ,bytes))
116          0))
117
118 (defmacro pgg-byte-after (&optional pos)
119   `(char-int (char-after ,(or pos `(point)))))
120
121 (defmacro pgg-read-byte ()
122   `(char-int (char-after (prog1 (point) (forward-char)))))
123
124 (defmacro pgg-read-bytes-string (nbytes)
125   `(buffer-substring
126     (point) (prog1 (+ ,nbytes (point))
127               (forward-char ,nbytes))))
128
129 (defmacro pgg-read-bytes (nbytes)
130   `(string-to-int-list (pgg-read-bytes-string ,nbytes)))
131
132 (defmacro pgg-read-body-string (ptag)
133   `(if (nth 1 ,ptag)
134        (pgg-read-bytes-string (nth 1 ,ptag))
135      (pgg-read-bytes-string (- (point-max) (point)))))
136
137 (defmacro pgg-read-body (ptag)
138   `(string-to-int-list (pgg-read-body-string ,ptag)))
139
140 (defalias 'pgg-skip-bytes 'forward-char)
141
142 (defmacro pgg-skip-header (ptag)
143   `(pgg-skip-bytes (nth 2 ,ptag)))
144
145 (defmacro pgg-skip-body (ptag)
146   `(pgg-skip-bytes (nth 1 ,ptag)))
147
148 (defmacro pgg-set-alist (alist key value)
149   `(setq ,alist (nconc ,alist (list (cons ,key ,value)))))
150
151 (unless-broken ccl-usable
152   (define-ccl-program pgg-parse-crc24
153     '(1
154       ((loop
155         (read r0) (r1 ^= r0) (r2 ^= 0)
156         (r5 = 0)
157         (loop
158          (r1 <<= 1)
159          (r1 += ((r2 >> 15) & 1))
160          (r2 <<= 1)
161          (if (r1 & 256)
162              ((r1 ^= 390) (r2 ^= 19707)))
163          (if (r5 < 7)
164              ((r5 += 1)
165               (repeat))))
166         (repeat)))))
167
168   (defun pgg-parse-crc24-string (string)
169     (let ((h (vector nil 183 1230 nil nil nil nil nil nil)))
170       (ccl-execute-on-string pgg-parse-crc24 h string)
171       (format "%c%c%c"
172               (logand (aref h 1) 255)
173               (logand (lsh (aref h 2) -8) 255)
174               (logand (aref h 2) 255)))))
175
176 (defmacro pgg-parse-length-type (c)
177   `(cond
178     ((< ,c 192) (cons ,c 1))
179     ((< ,c 224)
180      (cons (+ (lsh (- ,c 192) 8)
181               (pgg-byte-after (+ 2 (point)))
182               192)
183            2))
184     ((= ,c 255)
185      (cons (cons (logior (lsh (pgg-byte-after (+ 2 (point))) 8)
186                          (pgg-byte-after (+ 3 (point))))
187                  (logior (lsh (pgg-byte-after (+ 4 (point))) 8)
188                          (pgg-byte-after (+ 5 (point)))))
189            5))
190     (t;partial body length
191      '(0 . 0))))
192
193 (defun pgg-parse-packet-header ()
194   (let ((ptag (pgg-byte-after))
195         length-type content-tag packet-bytes header-bytes)
196     (if (zerop (logand 64 ptag));Old format
197         (progn
198           (setq length-type (logand ptag 3)
199                 length-type (if (= 3 length-type) 0 (lsh 1 length-type))
200                 content-tag (logand 15 (lsh ptag -2))
201                 packet-bytes 0
202                 header-bytes (1+ length-type))
203           (dotimes (i length-type)
204             (setq packet-bytes
205                   (logior (lsh packet-bytes 8)
206                           (pgg-byte-after (+ 1 i (point)))))))
207       (setq content-tag (logand 63 ptag)
208             length-type (pgg-parse-length-type
209                          (pgg-byte-after (1+ (point))))
210             packet-bytes (car length-type)
211             header-bytes (1+ (cdr length-type))))
212     (list content-tag packet-bytes header-bytes)))
213
214 (defun pgg-parse-packet (ptag)
215   (case (car ptag)
216     (1 ;Public-Key Encrypted Session Key Packet
217      (pgg-parse-public-key-encrypted-session-key-packet ptag))
218     (2 ;Signature Packet
219      (pgg-parse-signature-packet ptag))
220     (3 ;Symmetric-Key Encrypted Session Key Packet
221      (pgg-parse-symmetric-key-encrypted-session-key-packet ptag))
222     ;; 4        -- One-Pass Signature Packet
223     ;; 5        -- Secret Key Packet
224     (6 ;Public Key Packet
225      (pgg-parse-public-key-packet ptag))
226     ;; 7        -- Secret Subkey Packet
227     ;; 8        -- Compressed Data Packet
228     (9 ;Symmetrically Encrypted Data Packet
229      (pgg-read-body-string ptag))
230     (10 ;Marker Packet
231      (pgg-read-body-string ptag))
232     (11 ;Literal Data Packet
233      (pgg-read-body-string ptag))
234     ;; 12       -- Trust Packet
235     (13 ;User ID Packet
236      (pgg-read-body-string ptag))
237     ;; 14       -- Public Subkey Packet
238     ;; 60 .. 63 -- Private or Experimental Values
239     ))
240
241 (defun pgg-parse-packets (&optional header-parser body-parser)
242   (let ((header-parser
243          (or header-parser
244              (function pgg-parse-packet-header)))
245         (body-parser
246          (or body-parser
247              (function pgg-parse-packet)))
248         result ptag)
249     (while (> (point-max) (1+ (point)))
250       (setq ptag (funcall header-parser))
251       (pgg-skip-header ptag)
252       (push (cons (car ptag)
253                   (save-excursion
254                     (funcall body-parser ptag)))
255             result)
256       (if (zerop (nth 1 ptag))
257           (goto-char (point-max))
258         (forward-char (nth 1 ptag))))
259     result))
260
261 (defun pgg-parse-signature-subpacket-header ()
262   (let ((length-type (pgg-parse-length-type (pgg-byte-after))))
263     (list (pgg-byte-after (+ (cdr length-type) (point)))
264           (1- (car length-type))
265           (1+ (cdr length-type)))))
266         
267 (defun pgg-parse-signature-subpacket (ptag)
268   (case (car ptag)
269     (2 ;signature creation time
270      (cons 'creation-time
271            (let ((bytes (pgg-read-bytes 4)))
272              (pgg-parse-time-field bytes))))
273     (3 ;signature expiration time
274      (cons 'signature-expiry
275            (let ((bytes (pgg-read-bytes 4)))
276              (pgg-parse-time-field bytes))))
277     (4 ;exportable certification
278      (cons 'exportability (pgg-read-byte)))
279     (5 ;trust signature
280      (cons 'trust-level (pgg-read-byte)))
281     (6 ;regular expression
282      (cons 'regular-expression
283            (pgg-read-body-string ptag)))
284     (7 ;revocable
285      (cons 'revocability (pgg-read-byte)))
286     (9 ;key expiration time
287      (cons 'key-expiry
288            (let ((bytes (pgg-read-bytes 4)))
289              (pgg-parse-time-field bytes))))
290     ;; 10 = placeholder for backward compatibility
291     (11 ;preferred symmetric algorithms
292      (cons 'preferred-symmetric-key-algorithm
293            (cdr (assq (pgg-read-byte)
294                       pgg-parse-symmetric-key-algorithm-alist))))
295     (12 ;revocation key
296      )
297     (16 ;issuer key ID
298      (cons 'key-identifier
299            (pgg-format-key-identifier (pgg-read-body-string ptag))))
300     (20 ;notation data
301      (pgg-skip-bytes 4)
302      (cons 'notation
303            (let ((name-bytes (pgg-read-bytes 2))
304                  (value-bytes (pgg-read-bytes 2)))
305              (cons (pgg-read-bytes-string
306                     (logior (lsh (car name-bytes) 8)
307                             (nth 1 name-bytes)))
308                    (pgg-read-bytes-string
309                     (logior (lsh (car value-bytes) 8)
310                             (nth 1 value-bytes)))))))
311     (21 ;preferred hash algorithms
312      (cons 'preferred-hash-algorithm
313            (cdr (assq (pgg-read-byte)
314                       pgg-parse-hash-algorithm-alist))))
315     (22 ;preferred compression algorithms
316      (cons 'preferred-compression-algorithm
317            (cdr (assq (pgg-read-byte)
318                       pgg-parse-compression-algorithm-alist))))
319     (23 ;key server preferences
320      (cons 'key-server-preferences
321            (pgg-read-body ptag)))
322     (24 ;preferred key server
323      (cons 'preferred-key-server
324            (pgg-read-body-string ptag)))
325     ;; 25 = primary user id
326     (26 ;policy URL
327      (cons 'policy-url (pgg-read-body-string ptag)))
328     ;; 27 = key flags
329     ;; 28 = signer's user id
330     ;; 29 = reason for revocation
331     ;; 100 to 110 = internal or user-defined
332     ))
333
334 (defun pgg-parse-signature-packet (ptag)
335   (let* ((signature-version (pgg-byte-after))
336          (result (list (cons 'version signature-version)))
337          hashed-material field n)
338     (cond
339      ((= signature-version 3)
340       (pgg-skip-bytes 2)
341       (setq hashed-material (pgg-read-bytes 5))
342       (pgg-set-alist result
343                      'signature-type
344                      (cdr (assq (pop hashed-material)
345                                 pgg-parse-signature-type-alist)))
346       (pgg-set-alist result
347                      'creation-time
348                      (pgg-parse-time-field hashed-material))
349       (pgg-set-alist result
350                      'key-identifier
351                      (pgg-format-key-identifier
352                       (pgg-read-bytes-string 8)))
353       (pgg-set-alist result
354                      'public-key-algorithm (pgg-read-byte))
355       (pgg-set-alist result
356                      'hash-algorithm (pgg-read-byte)))
357      ((= signature-version 4)
358       (pgg-skip-bytes 1)
359       (pgg-set-alist result
360                      'signature-type
361                      (cdr (assq (pgg-read-byte)
362                                 pgg-parse-signature-type-alist)))
363       (pgg-set-alist result
364                      'public-key-algorithm
365                      (pgg-read-byte))
366       (pgg-set-alist result
367                      'hash-algorithm (pgg-read-byte))
368       (when (>= 10000 (setq n (pgg-read-bytes 2)
369                             n (logior (lsh (car n) 8)
370                                       (nth 1 n))))
371         (save-restriction
372           (narrow-to-region (point)(+ n (point)))
373           (nconc result
374                  (mapcar (function cdr) ;remove packet types
375                          (pgg-parse-packets
376                           #'pgg-parse-signature-subpacket-header
377                           #'pgg-parse-signature-subpacket)))
378           (goto-char (point-max))))
379       (when (>= 10000 (setq n (pgg-read-bytes 2)
380                             n (logior (lsh (car n) 8)
381                                       (nth 1 n))))
382         (save-restriction
383           (narrow-to-region (point)(+ n (point)))
384           (nconc result
385                  (mapcar (function cdr) ;remove packet types
386                          (pgg-parse-packets
387                           #'pgg-parse-signature-subpacket-header
388                           #'pgg-parse-signature-subpacket)))))))
389
390     (setcdr (setq field (assq 'public-key-algorithm
391                               result))
392             (cdr (assq (cdr field)
393                        pgg-parse-public-key-algorithm-alist)))
394     (setcdr (setq field (assq 'hash-algorithm
395                               result))
396             (cdr (assq (cdr field)
397                        pgg-parse-hash-algorithm-alist)))
398     result))
399
400 (defun pgg-parse-public-key-encrypted-session-key-packet (ptag)
401   (let (result)
402     (pgg-set-alist result
403                    'version (pgg-read-byte))
404     (pgg-set-alist result
405                    'key-identifier
406                    (pgg-format-key-identifier
407                     (pgg-read-bytes-string 8)))
408     (pgg-set-alist result
409                    'public-key-algorithm
410                    (cdr (assq (pgg-read-byte)
411                               pgg-parse-public-key-algorithm-alist)))
412     result))
413
414 (defun pgg-parse-symmetric-key-encrypted-session-key-packet (ptag)
415   (let (result)
416     (pgg-set-alist result
417                    'version
418                    (pgg-read-byte))
419     (pgg-set-alist result
420                    'symmetric-key-algorithm
421                    (cdr (assq (pgg-read-byte)
422                               pgg-parse-symmetric-key-algorithm-alist)))
423     result))
424
425 (defun pgg-parse-public-key-packet (ptag)
426   (let* ((key-version (pgg-read-byte))
427          (result (list (cons 'version key-version)))
428          field)
429     (cond
430      ((= 3 key-version)
431       (pgg-set-alist result
432                      'creation-time
433                      (let ((bytes (pgg-read-bytes 4)))
434                        (pgg-parse-time-field bytes)))
435       (pgg-set-alist result
436                      'key-expiry (pgg-read-bytes 2))
437       (pgg-set-alist result
438                      'public-key-algorithm (pgg-read-byte)))
439      ((= 4 key-version)
440       (pgg-set-alist result
441                      'creation-time
442                      (let ((bytes (pgg-read-bytes 4)))
443                        (pgg-parse-time-field bytes)))
444       (pgg-set-alist result
445                      'public-key-algorithm (pgg-read-byte))))
446
447     (setcdr (setq field (assq 'public-key-algorithm
448                               result))
449             (cdr (assq (cdr field)
450                        pgg-parse-public-key-algorithm-alist)))
451     result))
452      
453 (defun pgg-decode-packets ()
454   (let* ((marker
455           (set-marker (make-marker)
456                       (and (re-search-forward "^=")
457                            (match-beginning 0))))
458          (checksum (buffer-substring (point) (+ 4 (point)))))
459     (delete-region marker (point-max))
460     (mime-decode-region (point-min) marker "base64")
461     (static-when (fboundp 'pgg-parse-crc24-string )
462       (or pgg-ignore-packet-checksum
463           (string-equal
464            (funcall (mel-find-function 'mime-encode-string "base64")
465                     (pgg-parse-crc24-string
466                      (buffer-substring (point-min)(point-max))))
467            checksum)
468           (error "PGP packet checksum does not match")))))
469
470 (defun pgg-decode-armor-region (start end)
471   (save-restriction
472     (narrow-to-region start end)
473     (goto-char (point-min))
474     (re-search-forward "^-+BEGIN PGP" nil t)
475     (delete-region (point-min)
476                    (and (search-forward "\n\n")
477                         (match-end 0)))
478     (pgg-decode-packets)
479     (goto-char (point-min))
480     (pgg-parse-packets)))
481
482 (defun pgg-parse-armor (string)
483   (with-temp-buffer
484     (buffer-disable-undo)
485     (set-buffer-multibyte nil)
486     (insert string)
487     (pgg-decode-armor-region (point-min)(point))))
488
489 (defun pgg-parse-armor-region (start end)
490   (pgg-parse-armor (string-as-unibyte (buffer-substring start end))))
491
492 (provide 'pgg-parse)
493
494 ;;; pgg-parse.el ends here