2006-09-06 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / kbx / keybox-openpgp.c
blob8ac71397976998f11a53e0e7f7452a6dc7543154
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 2 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, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 * USA.
22 /* This is a simple OpenPGP parser suitable for all OpenPGP key
23 material. It just provides the functionality required to build and
24 parse an KBX OpenPGP key blob. Thus it is not a complete parser.
25 However it is self-contained and optimized for fast in-memory
26 parsing. Note that we don't support old ElGamal v3 keys
27 anymore. */
29 #include <config.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <assert.h>
36 #include "keybox-defs.h"
38 #include <gcrypt.h>
41 enum packet_types
43 PKT_NONE =0,
44 PKT_PUBKEY_ENC =1, /* public key encrypted packet */
45 PKT_SIGNATURE =2, /* secret key encrypted packet */
46 PKT_SYMKEY_ENC =3, /* session key packet (OpenPGP)*/
47 PKT_ONEPASS_SIG =4, /* one pass sig packet (OpenPGP)*/
48 PKT_SECRET_KEY =5, /* secret key */
49 PKT_PUBLIC_KEY =6, /* public key */
50 PKT_SECRET_SUBKEY =7, /* secret subkey (OpenPGP) */
51 PKT_COMPRESSED =8, /* compressed data packet */
52 PKT_ENCRYPTED =9, /* conventional encrypted data */
53 PKT_MARKER =10, /* marker packet (OpenPGP) */
54 PKT_PLAINTEXT =11, /* plaintext data with filename and mode */
55 PKT_RING_TRUST =12, /* keyring trust packet */
56 PKT_USER_ID =13, /* user id packet */
57 PKT_PUBLIC_SUBKEY =14, /* public subkey (OpenPGP) */
58 PKT_OLD_COMMENT =16, /* comment packet from an OpenPGP draft */
59 PKT_ATTRIBUTE =17, /* PGP's attribute packet */
60 PKT_ENCRYPTED_MDC =18, /* integrity protected encrypted data */
61 PKT_MDC =19, /* manipulation detection code packet */
62 PKT_COMMENT =61, /* new comment packet (private) */
63 PKT_GPG_CONTROL =63 /* internal control packet */
68 /* Assume a valid OpenPGP packet at the address pointed to by BUFBTR
69 which is of amaximum length as stored at BUFLEN. Return the header
70 information of that packet and advance the pointer stored at BUFPTR
71 to the next packet; also adjust the length stored at BUFLEN to
72 match the remaining bytes. If there are no more packets, store NULL
73 at BUFPTR. Return an non-zero error code on failure or the
74 follwing data on success:
76 R_DATAPKT = Pointer to the begin of the packet data.
77 R_DATALEN = Length of this data. This has already been checked to fit
78 into the buffer.
79 R_PKTTYPE = The packet type.
80 R_NTOTAL = The total number of bytes of this packet
82 Note that these values are only updated on success.
84 static gpg_error_t
85 next_packet (unsigned char const **bufptr, size_t *buflen,
86 unsigned char const **r_data, size_t *r_datalen, int *r_pkttype,
87 size_t *r_ntotal)
89 const unsigned char *buf = *bufptr;
90 size_t len = *buflen;
91 int c, ctb, pkttype;
92 unsigned long pktlen;
94 if (!len)
95 return gpg_error (GPG_ERR_NO_DATA);
97 ctb = *buf++; len--;
98 if ( !(ctb & 0x80) )
99 return gpg_error (GPG_ERR_INV_PACKET); /* Invalid CTB. */
101 pktlen = 0;
102 if ((ctb & 0x40)) /* New style (OpenPGP) CTB. */
104 pkttype = (ctb & 0x3f);
105 if (!len)
106 return gpg_error (GPG_ERR_INV_PACKET); /* No 1st length byte. */
107 c = *buf++; len--;
108 if (pkttype == PKT_COMPRESSED)
109 return gpg_error (GPG_ERR_UNEXPECTED); /* ... packet in a keyblock. */
110 if ( c < 192 )
111 pktlen = c;
112 else if ( c < 224 )
114 pktlen = (c - 192) * 256;
115 if (!len)
116 return gpg_error (GPG_ERR_INV_PACKET); /* No 2nd length byte. */
117 c = *buf++; len--;
118 pktlen += c + 192;
120 else if (c == 255)
122 if (len <4 )
123 return gpg_error (GPG_ERR_INV_PACKET); /* No length bytes. */
124 pktlen = (*buf++) << 24;
125 pktlen |= (*buf++) << 16;
126 pktlen |= (*buf++) << 8;
127 pktlen |= (*buf++);
128 len -= 4;
130 else /* Partial length encoding is not allowed for key packets. */
131 return gpg_error (GPG_ERR_UNEXPECTED);
133 else /* Old style CTB. */
135 int lenbytes;
137 pktlen = 0;
138 pkttype = (ctb>>2)&0xf;
139 lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3));
140 if (!lenbytes) /* Not allowed in key packets. */
141 return gpg_error (GPG_ERR_UNEXPECTED);
142 if (len < lenbytes)
143 return gpg_error (GPG_ERR_INV_PACKET); /* Not enough length bytes. */
144 for (; lenbytes; lenbytes--)
146 pktlen <<= 8;
147 pktlen |= *buf++; len--;
151 /* Do some basic sanity check. */
152 switch (pkttype)
154 case PKT_SIGNATURE:
155 case PKT_SECRET_KEY:
156 case PKT_PUBLIC_KEY:
157 case PKT_SECRET_SUBKEY:
158 case PKT_MARKER:
159 case PKT_RING_TRUST:
160 case PKT_USER_ID:
161 case PKT_PUBLIC_SUBKEY:
162 case PKT_OLD_COMMENT:
163 case PKT_ATTRIBUTE:
164 case PKT_COMMENT:
165 case PKT_GPG_CONTROL:
166 break; /* Okay these are allowed packets. */
167 default:
168 return gpg_error (GPG_ERR_UNEXPECTED);
171 if (pktlen == 0xffffffff)
172 return gpg_error (GPG_ERR_INV_PACKET);
174 if (pktlen > len)
175 return gpg_error (GPG_ERR_INV_PACKET); /* Packet length header too long. */
177 *r_data = buf;
178 *r_datalen = pktlen;
179 *r_pkttype = pkttype;
180 *r_ntotal = (buf - *bufptr) + pktlen;
182 *bufptr = buf + pktlen;
183 *buflen = len - pktlen;
184 if (!*buflen)
185 *bufptr = NULL;
187 return 0;
191 /* Parse a key packet and store the ionformation in KI. */
192 static gpg_error_t
193 parse_key (const unsigned char *data, size_t datalen,
194 struct _keybox_openpgp_key_info *ki)
196 gpg_error_t err;
197 const unsigned char *data_start = data;
198 int i, version, algorithm;
199 size_t n;
200 unsigned long timestamp, expiredate;
201 int npkey;
202 unsigned char hashbuffer[768];
203 const unsigned char *mpi_n = NULL;
204 size_t mpi_n_len = 0, mpi_e_len = 0;
205 gcry_md_hd_t md;
207 if (datalen < 5)
208 return gpg_error (GPG_ERR_INV_PACKET);
209 version = *data++; datalen--;
210 if (version < 2 || version > 4 )
211 return gpg_error (GPG_ERR_INV_PACKET); /* Invalid version. */
213 timestamp = ((data[0]<<24)|(data[1]<<16)|(data[2]<<8)|(data[3]));
214 data +=4; datalen -=4;
216 if (version < 4)
218 unsigned short ndays;
220 if (datalen < 2)
221 return gpg_error (GPG_ERR_INV_PACKET);
222 ndays = ((data[0]<<8)|(data[1]));
223 data +=2; datalen -= 2;
224 if (ndays)
225 expiredate = ndays? (timestamp + ndays * 86400L) : 0;
227 else
228 expiredate = 0; /* This is stored in the self-signature. */
230 if (!datalen)
231 return gpg_error (GPG_ERR_INV_PACKET);
232 algorithm = *data++; datalen--;
234 switch (algorithm)
236 case 1:
237 case 2:
238 case 3: /* RSA */
239 npkey = 2;
240 break;
241 case 16:
242 case 20: /* Elgamal */
243 npkey = 3;
244 break;
245 case 17: /* DSA */
246 npkey = 4;
247 break;
248 default: /* Unknown algorithm. */
249 return gpg_error (GPG_ERR_UNKNOWN_ALGORITHM);
252 for (i=0; i < npkey; i++ )
254 unsigned int nbits, nbytes;
256 if (datalen < 2)
257 return gpg_error (GPG_ERR_INV_PACKET);
258 nbits = ((data[0]<<8)|(data[1]));
259 data += 2; datalen -=2;
260 nbytes = (nbits+7) / 8;
261 if (datalen < nbytes)
262 return gpg_error (GPG_ERR_INV_PACKET);
263 /* For use by v3 fingerprint calculation we need to know the RSA
264 modulus and exponent. */
265 if (i==0)
267 mpi_n = data;
268 mpi_n_len = nbytes;
270 else if (i==1)
271 mpi_e_len = nbytes;
273 data += nbytes; datalen -= nbytes;
275 n = data - data_start;
277 if (version < 4)
279 /* We do not support any other algorithm than RSA in v3
280 packets. */
281 if (algorithm < 1 || algorithm > 3)
282 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
284 err = gcry_md_open (&md, GCRY_MD_MD5, 0);
285 if (err)
286 return err; /* Oops */
287 gcry_md_write (md, mpi_n, mpi_n_len);
288 gcry_md_write (md, mpi_n+mpi_n_len+2, mpi_e_len);
289 memcpy (ki->fpr, gcry_md_read (md, 0), 16);
290 gcry_md_close (md);
291 ki->fprlen = 16;
293 if (mpi_n_len < 8)
295 /* Moduli less than 64 bit are out of the specs scope. Zero
296 them out becuase this is what gpg does too. */
297 memset (ki->keyid, 0, 8);
299 else
300 memcpy (ki->keyid, mpi_n + mpi_n_len - 8, 8);
302 else
304 /* Its a pitty that we need to prefix the buffer with the tag
305 and a length header: We can't simply pass it to the fast
306 hashing fucntion for that reason. It might be a good idea to
307 have a scatter-gather enabled hash function. What we do here
308 is to use a static buffer if this one is large enough and
309 only use the regular hash fucntions if this buffer is not
310 large enough. */
311 if ( 3 + n < sizeof hashbuffer )
313 hashbuffer[0] = 0x99; /* CTB */
314 hashbuffer[1] = (n >> 8); /* 2 byte length header. */
315 hashbuffer[2] = n;
316 memcpy (hashbuffer + 3, data_start, n);
317 gcry_md_hash_buffer (GCRY_MD_SHA1, ki->fpr, hashbuffer, 3 + n);
319 else
321 err = gcry_md_open (&md, GCRY_MD_SHA1, 0);
322 if (err)
323 return err; /* Oops */
324 gcry_md_putc (md, 0x99 ); /* CTB */
325 gcry_md_putc (md, (n >> 8) ); /* 2 byte length header. */
326 gcry_md_putc (md, n );
327 gcry_md_write (md, data_start, n);
328 memcpy (ki->fpr, gcry_md_read (md, 0), 20);
329 gcry_md_close (md);
331 ki->fprlen = 20;
332 memcpy (ki->keyid, ki->fpr+12, 8);
335 return 0;
340 /* The caller must pass the address of an INFO structure which will
341 get filled on success with information pertaining to the OpenPGP
342 keyblock IMAGE of length IMAGELEN. Note that a caller does only
343 need to release this INFO structure when the function returns
344 success. If NPARSED is not NULL the actual number of bytes parsed
345 will be stored at this address. */
346 gpg_error_t
347 _keybox_parse_openpgp (const unsigned char *image, size_t imagelen,
348 size_t *nparsed,
349 keybox_openpgp_info_t info)
351 gpg_error_t err = 0;
352 const unsigned char *image_start, *data;
353 size_t n, datalen;
354 int pkttype;
355 int first = 1;
356 struct _keybox_openpgp_key_info *k, **ktail = NULL;
357 struct _keybox_openpgp_uid_info *u, **utail = NULL;
359 memset (info, 0, sizeof *info);
360 if (nparsed)
361 *nparsed = 0;
363 image_start = image;
364 while (image)
366 err = next_packet (&image, &imagelen, &data, &datalen, &pkttype, &n);
367 if (err)
368 break;
370 if (first)
372 if (pkttype == PKT_PUBLIC_KEY)
374 else if (pkttype == PKT_SECRET_KEY)
375 info->is_secret = 1;
376 else
378 err = gpg_error (GPG_ERR_UNEXPECTED);
379 break;
381 first = 0;
383 else if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY)
384 break; /* Next keyblock encountered - ready. */
386 if (nparsed)
387 *nparsed += n;
389 if (pkttype == PKT_SIGNATURE)
391 /* For now we only count the total number of signatures. */
392 info->nsigs++;
394 else if (pkttype == PKT_USER_ID)
396 info->nuids++;
397 if (info->nuids == 1)
399 info->uids.off = data - image_start;
400 info->uids.len = datalen;
401 utail = &info->uids.next;
403 else
405 u = xtrycalloc (1, sizeof *u);
406 if (!u)
408 err = gpg_error_from_errno (errno);
409 break;
411 u->off = data - image_start;
412 u->len = datalen;
413 *utail = u;
414 utail = &u->next;
417 else if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY)
419 err = parse_key (data, datalen, &info->primary);
420 if (err)
421 break;
423 else if( pkttype == PKT_PUBLIC_SUBKEY && datalen && *data == '#' )
425 /* Early versions of GnuPG used old PGP comment packets;
426 * luckily all those comments are prefixed by a hash
427 * sign - ignore these packets. */
429 else if (pkttype == PKT_PUBLIC_SUBKEY || pkttype == PKT_SECRET_SUBKEY)
431 info->nsubkeys++;
432 if (info->nsubkeys == 1)
434 err = parse_key (data, datalen, &info->subkeys);
435 if (err)
437 info->nsubkeys--;
438 if (gpg_err_code (err) != GPG_ERR_UNKNOWN_ALGORITHM)
439 break;
440 /* We ignore subkeys with unknown algorithms. */
442 else
443 ktail = &info->subkeys.next;
445 else
447 k = xtrycalloc (1, sizeof *k);
448 if (!k)
450 err = gpg_error_from_errno (errno);
451 break;
453 err = parse_key (data, datalen, k);
454 if (err)
456 xfree (k);
457 info->nsubkeys--;
458 if (gpg_err_code (err) != GPG_ERR_UNKNOWN_ALGORITHM)
459 break;
460 /* We ignore subkeys with unknown algorithms. */
462 else
464 *ktail = k;
465 ktail = &k->next;
471 if (err)
473 _keybox_destroy_openpgp_info (info);
474 if (!first
475 && (gpg_err_code (err) == GPG_ERR_UNSUPPORTED_ALGORITHM
476 || gpg_err_code (err) == GPG_ERR_UNKNOWN_ALGORITHM))
478 /* We are able to skip to the end of this keyblock. */
479 while (image)
481 if (next_packet (&image, &imagelen,
482 &data, &datalen, &pkttype, &n) )
483 break; /* Another error - stop here. */
485 if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY)
486 break; /* Next keyblock encountered - ready. */
488 if (nparsed)
489 *nparsed += n;
494 return err;
498 /* Release any malloced data in INFO but not INFO itself! */
499 void
500 _keybox_destroy_openpgp_info (keybox_openpgp_info_t info)
502 struct _keybox_openpgp_key_info *k, *k2;
503 struct _keybox_openpgp_uid_info *u, *u2;
505 assert (!info->primary.next);
506 for (k=info->subkeys.next; k; k = k2)
508 k2 = k->next;
509 xfree (k);
512 for (u=info->uids.next; u; u = u2)
514 u2 = u->next;
515 xfree (u);