* pgg.el, pgg-gpg.el, pgg-pgp5.el, pgg-pgp.el:
[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 (featurep 'xemacs); 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 ,pos)))
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   (check-broken-facility ccl-cascading-read)
153
154   (define-ccl-program pgg-parse-crc24
155     '(1
156       ((r1 = 183) (r2 = 1230)
157        (loop
158         (read r0) (r1 ^= r0) (r2 ^= 0)
159         (r5 = 0)
160         (loop
161          (r1 <<= 1)
162          (r1 += ((r2 >> 15) & 1))
163          (r2 <<= 1)
164          (if (r1 & 256)
165              ((r1 ^= 390) (r2 ^= 19707)))
166          (if (r5 < 7)
167              ((r5 += 1)
168               (repeat))))
169         (repeat)))
170       ((r1 &= 255) 
171        (r3 = (r2 & 255))
172        (r2 = ((r2 >> 8) & 255))
173        (write r1 r2 r3))))
174
175   (make-ccl-coding-system 
176    'pgg-parse-crc24 ?C "CRC24 checker"
177    'pgg-parse-crc24 'pgg-parse-crc24)
178
179   (defun pgg-parse-crc24-string (string)
180     (encode-coding-string string 'pgg-parse-crc24))
181   )
182
183 (defmacro pgg-parse-length-type (c)
184   `(cond 
185     ((< ,c 192) (cons ,c 1))
186     ((< ,c 224)
187      (cons (+ (lsh (- ,c 192) 8) 
188               (pgg-byte-after (+ 2 (point)))
189               192)
190            2))
191     ((= ,c 255)
192      (cons (cons (logior (lsh (pgg-byte-after (+ 2 (point))) 8)
193                          (pgg-byte-after (+ 3 (point))))
194                  (logior (lsh (pgg-byte-after (+ 4 (point))) 8)
195                          (pgg-byte-after (+ 5 (point)))))
196            5))
197     (t;partial body length
198      '(0 . 0))))
199
200 (defun pgg-parse-packet-header ()
201   (let ((ptag (pgg-byte-after))
202         length-type content-tag packet-bytes header-bytes)
203     (if (zerop (logand 64 ptag));Old format
204         (progn
205           (setq length-type (logand ptag 3)
206                 length-type (if (= 3 length-type) 0 (lsh 1 length-type))
207                 content-tag (logand 15 (lsh ptag -2))
208                 packet-bytes 0
209                 header-bytes (1+ length-type))
210           (dotimes (i length-type)
211             (setq packet-bytes 
212                   (logior (lsh packet-bytes 8) 
213                           (pgg-byte-after (+ 1 i (point))))))
214           )
215       (setq content-tag (logand 63 ptag)
216             length-type (pgg-parse-length-type 
217                          (pgg-byte-after (1+ (point))))
218             packet-bytes (car length-type)
219             header-bytes (1+ (cdr length-type))))
220     (list content-tag packet-bytes header-bytes)))
221
222 (defun pgg-parse-packet (ptag)
223   (case (car ptag)
224     (1 ;Public-Key Encrypted Session Key Packet
225      (pgg-parse-public-key-encrypted-session-key-packet ptag))
226     (2 ;Signature Packet
227      (pgg-parse-signature-packet ptag))
228     (3 ;Symmetric-Key Encrypted Session Key Packet
229      (pgg-parse-symmetric-key-encrypted-session-key-packet ptag))
230     ;; 4        -- One-Pass Signature Packet
231     ;; 5        -- Secret Key Packet
232     (6 ;Public Key Packet
233      (pgg-parse-public-key-packet ptag))
234     ;; 7        -- Secret Subkey Packet
235     ;; 8        -- Compressed Data Packet
236     (9 ;Symmetrically Encrypted Data Packet
237      (pgg-read-body-string ptag))
238     (10 ;Marker Packet
239      (pgg-read-body-string ptag))
240     (11 ;Literal Data Packet
241      (pgg-read-body-string ptag))
242     ;; 12       -- Trust Packet
243     (13 ;User ID Packet
244      (pgg-read-body-string ptag))
245     ;; 14       -- Public Subkey Packet 
246     ;; 60 .. 63 -- Private or Experimental Values
247     ))
248
249 (defun pgg-parse-packets (&optional header-parser body-parser)
250   (let ((header-parser
251          (or header-parser 
252              (function pgg-parse-packet-header)))
253         (body-parser
254          (or body-parser 
255              (function pgg-parse-packet)))
256         result ptag)
257     (while (> (point-max) (1+ (point)))
258       (setq ptag (funcall header-parser))
259       (pgg-skip-header ptag)
260       (push (cons (car ptag) 
261                   (save-excursion 
262                     (funcall body-parser ptag)))
263             result)
264       (if (zerop (nth 1 ptag))
265           (goto-char (point-max))
266         (forward-char (nth 1 ptag))))
267     result))
268
269 (defun pgg-parse-signature-subpacket-header ()
270   (let ((length-type (pgg-parse-length-type (pgg-byte-after))))
271     (list (pgg-byte-after (+ (cdr length-type) (point)))
272           (1- (car length-type))
273           (1+ (cdr length-type)))))
274         
275 (defun pgg-parse-signature-subpacket (ptag)
276   (case (car ptag)
277     (2 ;signature creation time
278      (cons 'creation-time 
279            (let ((bytes (pgg-read-bytes 4)))
280              (pgg-parse-time-field bytes))))
281     (3 ;signature expiration time
282      (cons 'signature-expiry 
283            (let ((bytes (pgg-read-bytes 4)))
284              (pgg-parse-time-field bytes))))
285     (4 ;exportable certification
286      (cons 'exportability (pgg-read-byte)))
287     (5 ;trust signature
288      (cons 'trust-level (pgg-read-byte)))
289     (6 ;regular expression
290      (cons 'regular-expression 
291            (pgg-read-body-string ptag)))
292     (7 ;revocable
293      (cons 'revocability (pgg-read-byte)))
294     (9 ;key expiration time
295      (cons 'key-expiry 
296            (let ((bytes (pgg-read-bytes 4)))
297              (pgg-parse-time-field bytes))))
298     ;; 10 = placeholder for backward compatibility
299     (11 ;preferred symmetric algorithms
300      (cons 'preferred-symmetric-key-algorithm
301            (cdr (assq (pgg-read-byte)
302                       pgg-parse-symmetric-key-algorithm-alist))))
303     (12 ;revocation key
304      )
305     (16 ;issuer key ID
306      (cons 'key-identifier
307            (pgg-format-key-identifier (pgg-read-body-string ptag))))
308     (20 ;notation data
309      (pgg-skip-bytes 4)
310      (cons 'notation
311            (let ((name-bytes (pgg-read-bytes 2))
312                  (value-bytes (pgg-read-bytes 2)))
313              (cons (pgg-read-bytes-string 
314                     (logior (lsh (car name-bytes) 8)
315                             (nth 1 name-bytes)))
316                    (pgg-read-bytes-string 
317                     (logior (lsh (car value-bytes) 8)
318                             (nth 1 value-bytes))))))
319      )
320     (21 ;preferred hash algorithms
321      (cons 'preferred-hash-algorithm
322            (cdr (assq (pgg-read-byte)
323                       pgg-parse-hash-algorithm-alist))))
324     (22 ;preferred compression algorithms
325      (cons 'preferred-compression-algorithm
326            (cdr (assq (pgg-read-byte)
327                       pgg-parse-compression-algorithm-alist))))
328     (23 ;key server preferences
329      (cons 'key-server-preferences
330            (pgg-read-body ptag)))
331     (24 ;preferred key server
332      (cons 'preferred-key-server
333            (pgg-read-body-string ptag)))
334     ;; 25 = primary user id
335     (26 ;policy URL
336      (cons 'policy-url (pgg-read-body-string ptag)))
337     ;; 27 = key flags
338     ;; 28 = signer's user id
339     ;; 29 = reason for revocation
340     ;; 100 to 110 = internal or user-defined
341     ))
342
343 (defun pgg-parse-signature-packet (ptag)
344   (let* ((signature-version (pgg-byte-after))
345          (result (list (cons 'version signature-version)))
346          hashed-material field n)
347     (cond 
348      ((= signature-version 3)
349       (pgg-skip-bytes 2)
350       (setq hashed-material (pgg-read-bytes 5))
351       (pgg-set-alist result 
352                      'signature-type 
353                      (cdr (assq (pop hashed-material)
354                                 pgg-parse-signature-type-alist)))
355       (pgg-set-alist result
356                      'creation-time  
357                      (pgg-parse-time-field hashed-material))
358       (pgg-set-alist result
359                      'key-identifier
360                      (pgg-format-key-identifier
361                       (pgg-read-bytes-string 8)))
362       (pgg-set-alist result
363                      'public-key-algorithm (pgg-read-byte))
364       (pgg-set-alist result
365                      'hash-algorithm (pgg-read-byte))
366       )
367      ((= signature-version 4)
368       (pgg-skip-bytes 1)
369       (pgg-set-alist result
370                      'signature-type 
371                      (cdr (assq (pgg-read-byte)
372                                 pgg-parse-signature-type-alist)))
373       (pgg-set-alist result
374                      'public-key-algorithm 
375                      (pgg-read-byte))
376       (pgg-set-alist result
377                      'hash-algorithm (pgg-read-byte))
378       (when (>= 10000 (setq n (pgg-read-bytes 2)
379                             n (logior (lsh (car n) 8)
380                                       (nth 1 n))))
381         (save-restriction
382           (narrow-to-region (point)(+ n (point)))
383           (nconc result
384                  (mapcar (function cdr) ;remove packet types
385                          (pgg-parse-packets 
386                           #'pgg-parse-signature-subpacket-header
387                           #'pgg-parse-signature-subpacket)))
388           (goto-char (point-max)))
389         )
390       (when (>= 10000 (setq n (pgg-read-bytes 2)
391                             n (logior (lsh (car n) 8)
392                                       (nth 1 n))))
393         (save-restriction
394           (narrow-to-region (point)(+ n (point)))
395           (nconc result
396                  (mapcar (function cdr) ;remove packet types
397                          (pgg-parse-packets 
398                           #'pgg-parse-signature-subpacket-header
399                           #'pgg-parse-signature-subpacket)))
400           ))
401       ))
402
403     (setcdr (setq field (assq 'public-key-algorithm
404                               result))
405             (cdr (assq (cdr field)
406                        pgg-parse-public-key-algorithm-alist)))
407     (setcdr (setq field (assq 'hash-algorithm
408                               result))
409             (cdr (assq (cdr field)
410                        pgg-parse-hash-algorithm-alist)))
411     result))
412
413 (defun pgg-parse-public-key-encrypted-session-key-packet (ptag)
414   (let (result)
415     (pgg-set-alist result
416                    'version (pgg-read-byte))
417     (pgg-set-alist result
418                    'key-identifier
419                    (pgg-format-key-identifier 
420                     (pgg-read-bytes-string 8)))
421     (pgg-set-alist result
422                    'public-key-algorithm
423                    (cdr (assq (pgg-read-byte)
424                               pgg-parse-public-key-algorithm-alist)))
425     result))
426
427 (defun pgg-parse-symmetric-key-encrypted-session-key-packet (ptag)
428   (let (result)
429     (pgg-set-alist result
430                    'version
431                    (pgg-read-byte))
432     (pgg-set-alist result
433                    'symmetric-key-algorithm
434                    (cdr (assq (pgg-read-byte)
435                               pgg-parse-symmetric-key-algorithm-alist)))
436     result))
437
438 (defun pgg-parse-public-key-packet (ptag)
439   (let* ((key-version (pgg-read-byte))
440          (result (list (cons 'version key-version)))
441          field)
442     (cond
443      ((= 3 key-version)
444       (pgg-set-alist result
445                      'creation-time
446                      (let ((bytes (pgg-read-bytes 4)))
447                        (pgg-parse-time-field bytes)))
448       (pgg-set-alist result
449                      'key-expiry (pgg-read-bytes 2))
450       (pgg-set-alist result
451                      'public-key-algorithm (pgg-read-byte))
452       )
453      ((= 4 key-version)
454       (pgg-set-alist result
455                      'creation-time
456                      (let ((bytes (pgg-read-bytes 4)))
457                        (pgg-parse-time-field bytes)))
458       (pgg-set-alist result
459                      'public-key-algorithm (pgg-read-byte))
460       ))
461
462     (setcdr (setq field (assq 'public-key-algorithm
463                               result))
464             (cdr (assq (cdr field)
465                        pgg-parse-public-key-algorithm-alist)))
466     result))
467      
468 (defun pgg-decode-packets ()
469   (let* ((marker
470           (set-marker (make-marker)
471                       (and (re-search-forward "^=")
472                            (match-beginning 0))))
473          (checksum (buffer-substring (point) (+ 4 (point)))))
474     (delete-region marker (point-max))
475     (mime-decode-region (point-min) marker "base64")
476     (static-when (fboundp 'pgg-parse-crc24-string )
477       (or pgg-ignore-packet-checksum
478           (string-equal (mime-encode-string 
479                          (pgg-parse-crc24-string 
480                           (buffer-substring (point-min)(point-max)))
481                          "base64")
482                         checksum)
483           (error "PGP packet checksum does not match.")))))
484
485 (defun pgg-decode-armor-region (start end)
486   (save-restriction
487     (narrow-to-region start end)
488     (goto-char (point-min))
489     (re-search-forward "^-+BEGIN PGP" nil t)
490     (delete-region (point-min)
491                    (and (search-forward "\n\n")
492                         (match-end 0)))
493     (pgg-decode-packets)
494     (goto-char (point-min))
495     (pgg-parse-packets)))
496
497 (defun pgg-parse-armor (string)
498   (with-temp-buffer
499     (buffer-disable-undo)
500     (set-buffer-multibyte nil)
501     (insert string)
502     (pgg-decode-armor-region (point-min)(point))))
503
504 (defun pgg-parse-armor-region (start end)
505   (pgg-parse-armor (string-as-unibyte (buffer-substring start end))))
506
507 (provide 'pgg-parse)
508
509 ;;; pgg-parse.el ends here