Fix debian bug#543530
[gnupg.git] / kbx / keybox-openpgp.c
blob0968cf8b33898882e04862426e745d72c48253ad
1 /* keybox-openpgp.c - OpenPGP key parsing
2 * Copyright (C) 2001, 2003 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 /* This is a simple OpenPGP parser suitable for all OpenPGP key
21 material. It just provides the functionality required to build and
22 parse an KBX OpenPGP key blob. Thus it is not a complete parser.
23 However it is self-contained and optimized for fast in-memory
24 parsing. Note that we don't support old ElGamal v3 keys
25 anymore. */
27 #include <config.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <assert.h>
34 #include "keybox-defs.h"
36 #include <gcrypt.h>
39 enum packet_types
41 PKT_NONE =0,
42 PKT_PUBKEY_ENC =1, /* public key encrypted packet */
43 PKT_SIGNATURE =2, /* secret key encrypted packet */
44 PKT_SYMKEY_ENC =3, /* session key packet (OpenPGP)*/
45 PKT_ONEPASS_SIG =4, /* one pass sig packet (OpenPGP)*/
46 PKT_SECRET_KEY =5, /* secret key */
47 PKT_PUBLIC_KEY =6, /* public key */
48 PKT_SECRET_SUBKEY =7, /* secret subkey (OpenPGP) */
49 PKT_COMPRESSED =8, /* compressed data packet */
50 PKT_ENCRYPTED =9, /* conventional encrypted data */
51 PKT_MARKER =10, /* marker packet (OpenPGP) */
52 PKT_PLAINTEXT =11, /* plaintext data with filename and mode */
53 PKT_RING_TRUST =12, /* keyring trust packet */
54 PKT_USER_ID =13, /* user id packet */
55 PKT_PUBLIC_SUBKEY =14, /* public subkey (OpenPGP) */
56 PKT_OLD_COMMENT =16, /* comment packet from an OpenPGP draft */
57 PKT_ATTRIBUTE =17, /* PGP's attribute packet */
58 PKT_ENCRYPTED_MDC =18, /* integrity protected encrypted data */
59 PKT_MDC =19, /* manipulation detection code packet */
60 PKT_COMMENT =61, /* new comment packet (private) */
61 PKT_GPG_CONTROL =63 /* internal control packet */
66 /* Assume a valid OpenPGP packet at the address pointed to by BUFBTR
67 which is of amaximum length as stored at BUFLEN. Return the header
68 information of that packet and advance the pointer stored at BUFPTR
69 to the next packet; also adjust the length stored at BUFLEN to
70 match the remaining bytes. If there are no more packets, store NULL
71 at BUFPTR. Return an non-zero error code on failure or the
72 follwing data on success:
74 R_DATAPKT = Pointer to the begin of the packet data.
75 R_DATALEN = Length of this data. This has already been checked to fit
76 into the buffer.
77 R_PKTTYPE = The packet type.
78 R_NTOTAL = The total number of bytes of this packet
80 Note that these values are only updated on success.
82 static gpg_error_t
83 next_packet (unsigned char const **bufptr, size_t *buflen,
84 unsigned char const **r_data, size_t *r_datalen, int *r_pkttype,
85 size_t *r_ntotal)
87 const unsigned char *buf = *bufptr;
88 size_t len = *buflen;
89 int c, ctb, pkttype;
90 unsigned long pktlen;
92 if (!len)
93 return gpg_error (GPG_ERR_NO_DATA);
95 ctb = *buf++; len--;
96 if ( !(ctb & 0x80) )
97 return gpg_error (GPG_ERR_INV_PACKET); /* Invalid CTB. */
99 pktlen = 0;
100 if ((ctb & 0x40)) /* New style (OpenPGP) CTB. */
102 pkttype = (ctb & 0x3f);
103 if (!len)
104 return gpg_error (GPG_ERR_INV_PACKET); /* No 1st length byte. */
105 c = *buf++; len--;
106 if (pkttype == PKT_COMPRESSED)
107 return gpg_error (GPG_ERR_UNEXPECTED); /* ... packet in a keyblock. */
108 if ( c < 192 )
109 pktlen = c;
110 else if ( c < 224 )
112 pktlen = (c - 192) * 256;
113 if (!len)
114 return gpg_error (GPG_ERR_INV_PACKET); /* No 2nd length byte. */
115 c = *buf++; len--;
116 pktlen += c + 192;
118 else if (c == 255)
120 if (len <4 )
121 return gpg_error (GPG_ERR_INV_PACKET); /* No length bytes. */
122 pktlen = (*buf++) << 24;
123 pktlen |= (*buf++) << 16;
124 pktlen |= (*buf++) << 8;
125 pktlen |= (*buf++);
126 len -= 4;
128 else /* Partial length encoding is not allowed for key packets. */
129 return gpg_error (GPG_ERR_UNEXPECTED);
131 else /* Old style CTB. */
133 int lenbytes;
135 pktlen = 0;
136 pkttype = (ctb>>2)&0xf;
137 lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3));
138 if (!lenbytes) /* Not allowed in key packets. */
139 return gpg_error (GPG_ERR_UNEXPECTED);
140 if (len < lenbytes)
141 return gpg_error (GPG_ERR_INV_PACKET); /* Not enough length bytes. */
142 for (; lenbytes; lenbytes--)
144 pktlen <<= 8;
145 pktlen |= *buf++; len--;
149 /* Do some basic sanity check. */
150 switch (pkttype)
152 case PKT_SIGNATURE:
153 case PKT_SECRET_KEY:
154 case PKT_PUBLIC_KEY:
155 case PKT_SECRET_SUBKEY:
156 case PKT_MARKER:
157 case PKT_RING_TRUST:
158 case PKT_USER_ID:
159 case PKT_PUBLIC_SUBKEY:
160 case PKT_OLD_COMMENT:
161 case PKT_ATTRIBUTE:
162 case PKT_COMMENT:
163 case PKT_GPG_CONTROL:
164 break; /* Okay these are allowed packets. */
165 default:
166 return gpg_error (GPG_ERR_UNEXPECTED);
169 if (pktlen == 0xffffffff)
170 return gpg_error (GPG_ERR_INV_PACKET);
172 if (pktlen > len)
173 return gpg_error (GPG_ERR_INV_PACKET); /* Packet length header too long. */
175 *r_data = buf;
176 *r_datalen = pktlen;
177 *r_pkttype = pkttype;
178 *r_ntotal = (buf - *bufptr) + pktlen;
180 *bufptr = buf + pktlen;
181 *buflen = len - pktlen;
182 if (!*buflen)
183 *bufptr = NULL;
185 return 0;
189 /* Parse a key packet and store the ionformation in KI. */
190 static gpg_error_t
191 parse_key (const unsigned char *data, size_t datalen,
192 struct _keybox_openpgp_key_info *ki)
194 gpg_error_t err;
195 const unsigned char *data_start = data;
196 int i, version, algorithm;
197 size_t n;
198 unsigned long timestamp, expiredate;
199 int npkey;
200 unsigned char hashbuffer[768];
201 const unsigned char *mpi_n = NULL;
202 size_t mpi_n_len = 0, mpi_e_len = 0;
203 gcry_md_hd_t md;
205 if (datalen < 5)
206 return gpg_error (GPG_ERR_INV_PACKET);
207 version = *data++; datalen--;
208 if (version < 2 || version > 4 )
209 return gpg_error (GPG_ERR_INV_PACKET); /* Invalid version. */
211 timestamp = ((data[0]<<24)|(data[1]<<16)|(data[2]<<8)|(data[3]));
212 data +=4; datalen -=4;
214 if (version < 4)
216 unsigned short ndays;
218 if (datalen < 2)
219 return gpg_error (GPG_ERR_INV_PACKET);
220 ndays = ((data[0]<<8)|(data[1]));
221 data +=2; datalen -= 2;
222 if (ndays)
223 expiredate = ndays? (timestamp + ndays * 86400L) : 0;
225 else
226 expiredate = 0; /* This is stored in the self-signature. */
228 if (!datalen)
229 return gpg_error (GPG_ERR_INV_PACKET);
230 algorithm = *data++; datalen--;
232 switch (algorithm)
234 case 1:
235 case 2:
236 case 3: /* RSA */
237 npkey = 2;
238 break;
239 case 16:
240 case 20: /* Elgamal */
241 npkey = 3;
242 break;
243 case 17: /* DSA */
244 npkey = 4;
245 break;
246 default: /* Unknown algorithm. */
247 return gpg_error (GPG_ERR_UNKNOWN_ALGORITHM);
250 for (i=0; i < npkey; i++ )
252 unsigned int nbits, nbytes;
254 if (datalen < 2)
255 return gpg_error (GPG_ERR_INV_PACKET);
256 nbits = ((data[0]<<8)|(data[1]));
257 data += 2; datalen -=2;
258 nbytes = (nbits+7) / 8;
259 if (datalen < nbytes)
260 return gpg_error (GPG_ERR_INV_PACKET);
261 /* For use by v3 fingerprint calculation we need to know the RSA
262 modulus and exponent. */
263 if (i==0)
265 mpi_n = data;
266 mpi_n_len = nbytes;
268 else if (i==1)
269 mpi_e_len = nbytes;
271 data += nbytes; datalen -= nbytes;
273 n = data - data_start;
275 if (version < 4)
277 /* We do not support any other algorithm than RSA in v3
278 packets. */
279 if (algorithm < 1 || algorithm > 3)
280 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
282 err = gcry_md_open (&md, GCRY_MD_MD5, 0);
283 if (err)
284 return err; /* Oops */
285 gcry_md_write (md, mpi_n, mpi_n_len);
286 gcry_md_write (md, mpi_n+mpi_n_len+2, mpi_e_len);
287 memcpy (ki->fpr, gcry_md_read (md, 0), 16);
288 gcry_md_close (md);
289 ki->fprlen = 16;
291 if (mpi_n_len < 8)
293 /* Moduli less than 64 bit are out of the specs scope. Zero
294 them out becuase this is what gpg does too. */
295 memset (ki->keyid, 0, 8);
297 else
298 memcpy (ki->keyid, mpi_n + mpi_n_len - 8, 8);
300 else
302 /* Its a pitty that we need to prefix the buffer with the tag
303 and a length header: We can't simply pass it to the fast
304 hashing fucntion for that reason. It might be a good idea to
305 have a scatter-gather enabled hash function. What we do here
306 is to use a static buffer if this one is large enough and
307 only use the regular hash fucntions if this buffer is not
308 large enough. */
309 if ( 3 + n < sizeof hashbuffer )
311 hashbuffer[0] = 0x99; /* CTB */
312 hashbuffer[1] = (n >> 8); /* 2 byte length header. */
313 hashbuffer[2] = n;
314 memcpy (hashbuffer + 3, data_start, n);
315 gcry_md_hash_buffer (GCRY_MD_SHA1, ki->fpr, hashbuffer, 3 + n);
317 else
319 err = gcry_md_open (&md, GCRY_MD_SHA1, 0);
320 if (err)
321 return err; /* Oops */
322 gcry_md_putc (md, 0x99 ); /* CTB */
323 gcry_md_putc (md, (n >> 8) ); /* 2 byte length header. */
324 gcry_md_putc (md, n );
325 gcry_md_write (md, data_start, n);
326 memcpy (ki->fpr, gcry_md_read (md, 0), 20);
327 gcry_md_close (md);
329 ki->fprlen = 20;
330 memcpy (ki->keyid, ki->fpr+12, 8);
333 return 0;
338 /* The caller must pass the address of an INFO structure which will
339 get filled on success with information pertaining to the OpenPGP
340 keyblock IMAGE of length IMAGELEN. Note that a caller does only
341 need to release this INFO structure when the function returns
342 success. If NPARSED is not NULL the actual number of bytes parsed
343 will be stored at this address. */
344 gpg_error_t
345 _keybox_parse_openpgp (const unsigned char *image, size_t imagelen,
346 size_t *nparsed,
347 keybox_openpgp_info_t info)
349 gpg_error_t err = 0;
350 const unsigned char *image_start, *data;
351 size_t n, datalen;
352 int pkttype;
353 int first = 1;
354 struct _keybox_openpgp_key_info *k, **ktail = NULL;
355 struct _keybox_openpgp_uid_info *u, **utail = NULL;
357 memset (info, 0, sizeof *info);
358 if (nparsed)
359 *nparsed = 0;
361 image_start = image;
362 while (image)
364 err = next_packet (&image, &imagelen, &data, &datalen, &pkttype, &n);
365 if (err)
366 break;
368 if (first)
370 if (pkttype == PKT_PUBLIC_KEY)
372 else if (pkttype == PKT_SECRET_KEY)
373 info->is_secret = 1;
374 else
376 err = gpg_error (GPG_ERR_UNEXPECTED);
377 break;
379 first = 0;
381 else if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY)
382 break; /* Next keyblock encountered - ready. */
384 if (nparsed)
385 *nparsed += n;
387 if (pkttype == PKT_SIGNATURE)
389 /* For now we only count the total number of signatures. */
390 info->nsigs++;
392 else if (pkttype == PKT_USER_ID)
394 info->nuids++;
395 if (info->nuids == 1)
397 info->uids.off = data - image_start;
398 info->uids.len = datalen;
399 utail = &info->uids.next;
401 else
403 u = xtrycalloc (1, sizeof *u);
404 if (!u)
406 err = gpg_error_from_syserror ();
407 break;
409 u->off = data - image_start;
410 u->len = datalen;
411 *utail = u;
412 utail = &u->next;
415 else if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY)
417 err = parse_key (data, datalen, &info->primary);
418 if (err)
419 break;
421 else if( pkttype == PKT_PUBLIC_SUBKEY && datalen && *data == '#' )
423 /* Early versions of GnuPG used old PGP comment packets;
424 * luckily all those comments are prefixed by a hash
425 * sign - ignore these packets. */
427 else if (pkttype == PKT_PUBLIC_SUBKEY || pkttype == PKT_SECRET_SUBKEY)
429 info->nsubkeys++;
430 if (info->nsubkeys == 1)
432 err = parse_key (data, datalen, &info->subkeys);
433 if (err)
435 info->nsubkeys--;
436 if (gpg_err_code (err) != GPG_ERR_UNKNOWN_ALGORITHM)
437 break;
438 /* We ignore subkeys with unknown algorithms. */
440 else
441 ktail = &info->subkeys.next;
443 else
445 k = xtrycalloc (1, sizeof *k);
446 if (!k)
448 err = gpg_error_from_syserror ();
449 break;
451 err = parse_key (data, datalen, k);
452 if (err)
454 xfree (k);
455 info->nsubkeys--;
456 if (gpg_err_code (err) != GPG_ERR_UNKNOWN_ALGORITHM)
457 break;
458 /* We ignore subkeys with unknown algorithms. */
460 else
462 *ktail = k;
463 ktail = &k->next;
469 if (err)
471 _keybox_destroy_openpgp_info (info);
472 if (!first
473 && (gpg_err_code (err) == GPG_ERR_UNSUPPORTED_ALGORITHM
474 || gpg_err_code (err) == GPG_ERR_UNKNOWN_ALGORITHM))
476 /* We are able to skip to the end of this keyblock. */
477 while (image)
479 if (next_packet (&image, &imagelen,
480 &data, &datalen, &pkttype, &n) )
481 break; /* Another error - stop here. */
483 if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY)
484 break; /* Next keyblock encountered - ready. */
486 if (nparsed)
487 *nparsed += n;
492 return err;
496 /* Release any malloced data in INFO but not INFO itself! */
497 void
498 _keybox_destroy_openpgp_info (keybox_openpgp_info_t info)
500 struct _keybox_openpgp_key_info *k, *k2;
501 struct _keybox_openpgp_uid_info *u, *u2;
503 assert (!info->primary.next);
504 for (k=info->subkeys.next; k; k = k2)
506 k2 = k->next;
507 xfree (k);
510 for (u=info->uids.next; u; u = u2)
512 u2 = u->next;
513 xfree (u);