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