1 /* build-packet.c - assemble packets and write them
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2010, 2011 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
36 static int do_user_id( IOBUF out, int ctb, PKT_user_id *uid );
37 static int do_key (iobuf_t out, int ctb, PKT_public_key *pk);
38 static int do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc );
39 static int do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc );
40 static u32 calc_plaintext( PKT_plaintext *pt );
41 static int do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt );
42 static int do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed );
43 static int do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed );
44 static int do_compressed( IOBUF out, int ctb, PKT_compressed *cd );
45 static int do_signature( IOBUF out, int ctb, PKT_signature *sig );
46 static int do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops );
48 static int calc_header_length( u32 len, int new_ctb );
49 static int write_16(IOBUF inp, u16 a);
50 static int write_32(IOBUF inp, u32 a);
51 static int write_header( IOBUF out, int ctb, u32 len );
52 static int write_sign_packet_header( IOBUF out, int ctb, u32 len );
53 static int write_header2( IOBUF out, int ctb, u32 len, int hdrlen );
54 static int write_new_header( IOBUF out, int ctb, u32 len, int hdrlen );
56 /* Returns 1 if CTB is a new format ctb and 0 if CTB is an old format
59 ctb_new_format_p (int ctb)
61 /* Bit 7 must always be set. */
62 log_assert ((ctb & (1 << 7)));
63 /* Bit 6 indicates whether the packet is a new format packet. */
64 return (ctb & (1 << 6));
67 /* Extract the packet type from a CTB. */
71 if (ctb_new_format_p (ctb))
72 /* Bits 0 through 5 are the packet type. */
73 return (ctb & ((1 << 6) - 1));
75 /* Bits 2 through 5 are the packet type. */
76 return (ctb & ((1 << 6) - 1)) >> 2;
80 * Build a packet and write it to INP
83 * Note: Caller must free the packet
86 build_packet( IOBUF out, PACKET *pkt )
88 int new_ctb=0, rc=0, ctb;
92 log_debug("build_packet() type=%d\n", pkt->pkttype );
93 log_assert( pkt->pkt.generic );
95 switch ((pkttype = pkt->pkttype))
98 if (pkt->pkt.public_key->seckey_info)
99 pkttype = PKT_SECRET_KEY;
101 case PKT_PUBLIC_SUBKEY:
102 if (pkt->pkt.public_key->seckey_info)
103 pkttype = PKT_SECRET_SUBKEY;
105 case PKT_PLAINTEXT: new_ctb = pkt->pkt.plaintext->new_ctb; break;
107 case PKT_ENCRYPTED_MDC: new_ctb = pkt->pkt.encrypted->new_ctb; break;
108 case PKT_COMPRESSED:new_ctb = pkt->pkt.compressed->new_ctb; break;
110 if( pkt->pkt.user_id->attrib_data )
111 pkttype = PKT_ATTRIBUTE;
116 if( new_ctb || pkttype > 15 ) /* new format */
117 ctb = 0xc0 | (pkttype & 0x3f);
119 ctb = 0x80 | ((pkttype & 15)<<2);
124 rc = do_user_id( out, ctb, pkt->pkt.user_id );
126 case PKT_OLD_COMMENT:
129 Ignore these. Theoretically, this will never be called as
130 we have no way to output comment packets any longer, but
131 just in case there is some code path that would end up
132 outputting a comment that was written before comments were
133 dropped (in the public key?) this is a no-op.
136 case PKT_PUBLIC_SUBKEY:
138 case PKT_SECRET_SUBKEY:
140 rc = do_key (out, ctb, pkt->pkt.public_key);
143 rc = do_symkey_enc( out, ctb, pkt->pkt.symkey_enc );
146 rc = do_pubkey_enc( out, ctb, pkt->pkt.pubkey_enc );
149 rc = do_plaintext( out, ctb, pkt->pkt.plaintext );
152 rc = do_encrypted( out, ctb, pkt->pkt.encrypted );
154 case PKT_ENCRYPTED_MDC:
155 rc = do_encrypted_mdc( out, ctb, pkt->pkt.encrypted );
158 rc = do_compressed( out, ctb, pkt->pkt.compressed );
161 rc = do_signature( out, ctb, pkt->pkt.signature );
163 case PKT_ONEPASS_SIG:
164 rc = do_onepass_sig( out, ctb, pkt->pkt.onepass_sig );
167 break; /* ignore it (keyring.c does write it directly)*/
168 case PKT_MDC: /* we write it directly, so we should never see it here. */
170 log_bug("invalid packet type in build_packet()\n");
179 * Write the mpi A to OUT.
182 gpg_mpi_write (iobuf_t out, gcry_mpi_t a)
186 if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
189 const unsigned char *p;
190 unsigned char lenhdr[2];
192 /* gcry_log_debugmpi ("a", a); */
193 p = gcry_mpi_get_opaque (a, &nbits);
196 /* Strip leading zero bits. */
197 for (; nbits >= 8 && !*p; p++, nbits -= 8)
199 if (nbits >= 8 && !(*p & 0x80))
200 if (--nbits >= 7 && !(*p & 0x40))
201 if (--nbits >= 6 && !(*p & 0x20))
202 if (--nbits >= 5 && !(*p & 0x10))
203 if (--nbits >= 4 && !(*p & 0x08))
204 if (--nbits >= 3 && !(*p & 0x04))
205 if (--nbits >= 2 && !(*p & 0x02))
206 if (--nbits >= 1 && !(*p & 0x01))
209 /* gcry_log_debug (" [%u bit]\n", nbits); */
210 /* gcry_log_debughex (" ", p, (nbits+7)/8); */
211 lenhdr[0] = nbits >> 8;
213 rc = iobuf_write (out, lenhdr, 2);
215 rc = iobuf_write (out, p, (nbits+7)/8);
219 char buffer[(MAX_EXTERN_MPI_BITS+7)/8+2]; /* 2 is for the mpi length. */
222 nbytes = DIM(buffer);
223 rc = gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, &nbytes, a );
225 rc = iobuf_write( out, buffer, nbytes );
226 else if (gpg_err_code(rc) == GPG_ERR_TOO_SHORT )
228 log_info ("mpi too large (%u bits)\n", gcry_mpi_get_nbits (a));
229 /* The buffer was too small. We better tell the user about the MPI. */
230 rc = gpg_error (GPG_ERR_TOO_LARGE);
239 * Write an opaque MPI to the output stream without length info.
242 gpg_mpi_write_nohdr (iobuf_t out, gcry_mpi_t a)
246 if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
251 p = gcry_mpi_get_opaque (a, &nbits);
252 rc = p ? iobuf_write (out, p, (nbits+7)/8) : 0;
255 rc = gpg_error (GPG_ERR_BAD_MPI);
261 /* Calculate the length of a packet described by PKT. */
263 calc_packet_length( PACKET *pkt )
268 log_assert (pkt->pkt.generic);
269 switch( pkt->pkttype ) {
271 n = calc_plaintext( pkt->pkt.plaintext );
272 new_ctb = pkt->pkt.plaintext->new_ctb;
283 case PKT_ONEPASS_SIG:
287 log_bug("invalid packet type in calc_packet_length()");
291 n += calc_header_length(n, new_ctb);
297 write_fake_data (IOBUF out, gcry_mpi_t a)
304 if (!gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
305 return 0; /* e.g. due to generating a key with wrong usage. */
306 p = gcry_mpi_get_opaque ( a, &n);
308 return 0; /* For example due to a read error in
309 parse-packet.c:read_rest. */
310 return iobuf_write (out, p, (n+7)/8 );
314 /* Serialize the user id (RFC 4880, Section 5.11) or the user
315 attribute UID (Section 5.12) and write it to OUT.
317 CTB is the serialization's CTB. It specifies the header format and
318 the packet's type. The header length must not be set. */
320 do_user_id( IOBUF out, int ctb, PKT_user_id *uid )
324 log_assert (ctb_pkttype (ctb) == PKT_USER_ID
325 || ctb_pkttype (ctb) == PKT_ATTRIBUTE);
327 if (uid->attrib_data)
329 write_header(out, ctb, uid->attrib_len);
330 rc = iobuf_write( out, uid->attrib_data, uid->attrib_len );
334 write_header2( out, ctb, uid->len, 0 );
335 rc = iobuf_write( out, uid->name, uid->len );
341 /* Serialize the key (RFC 4880, Section 5.5) described by PK and write
344 This function serializes both primary keys and subkeys with or
345 without a secret part.
347 CTB is the serialization's CTB. It specifies the header format and
348 the packet's type. The header length must not be set.
350 PK->VERSION specifies the serialization format. A value of 0 means
351 to use the default version. Currently, only version 4 packets are
355 do_key (iobuf_t out, int ctb, PKT_public_key *pk)
358 /* The length of the body is stored in the packet's header, which
359 occurs before the body. Unfortunately, we don't know the length
360 of the packet's body until we've written all of the data! To
361 work around this, we first write the data into this temporary
362 buffer, then generate the header, and finally copy the contents
363 of this buffer to OUT. */
364 iobuf_t a = iobuf_temp();
367 log_assert (pk->version == 0 || pk->version == 4);
368 log_assert (ctb_pkttype (ctb) == PKT_PUBLIC_KEY
369 || ctb_pkttype (ctb) == PKT_PUBLIC_SUBKEY
370 || ctb_pkttype (ctb) == PKT_SECRET_KEY
371 || ctb_pkttype (ctb) == PKT_SECRET_SUBKEY);
373 /* Write the version number - if none is specified, use 4 */
377 iobuf_put ( a, pk->version );
378 write_32 (a, pk->timestamp );
380 iobuf_put (a, pk->pubkey_algo );
382 /* Get number of secret and public parameters. They are held in one
383 array: the public ones followed by the secret ones. */
384 nskey = pubkey_get_nskey (pk->pubkey_algo);
385 npkey = pubkey_get_npkey (pk->pubkey_algo);
387 /* If we don't have any public parameters - which is for example the
388 case if we don't know the algorithm used - the parameters are
389 stored as one blob in a faked (opaque) MPI. */
392 write_fake_data (a, pk->pkey[0]);
395 log_assert (npkey < nskey);
397 for (i=0; i < npkey; i++ )
399 if ( (pk->pubkey_algo == PUBKEY_ALGO_ECDSA && (i == 0))
400 || (pk->pubkey_algo == PUBKEY_ALGO_EDDSA && (i == 0))
401 || (pk->pubkey_algo == PUBKEY_ALGO_ECDH && (i == 0 || i == 2)))
402 err = gpg_mpi_write_nohdr (a, pk->pkey[i]);
404 err = gpg_mpi_write (a, pk->pkey[i]);
412 /* This is a secret key packet. */
413 struct seckey_info *ski = pk->seckey_info;
415 /* Build the header for protected (encrypted) secret parameters. */
416 if (ski->is_protected)
418 /* OpenPGP protection according to rfc2440. */
419 iobuf_put (a, ski->sha1chk? 0xfe : 0xff);
420 iobuf_put (a, ski->algo);
421 if (ski->s2k.mode >= 1000)
423 /* These modes are not possible in OpenPGP, we use them
424 to implement our extensions, 101 can be viewed as a
425 private/experimental extension (this is not specified
426 in rfc2440 but the same scheme is used for all other
427 algorithm identifiers). */
429 iobuf_put (a, ski->s2k.hash_algo);
430 iobuf_write (a, "GNU", 3 );
431 iobuf_put (a, ski->s2k.mode - 1000);
435 iobuf_put (a, ski->s2k.mode);
436 iobuf_put (a, ski->s2k.hash_algo);
439 if (ski->s2k.mode == 1 || ski->s2k.mode == 3)
440 iobuf_write (a, ski->s2k.salt, 8);
442 if (ski->s2k.mode == 3)
443 iobuf_put (a, ski->s2k.count);
445 /* For our special modes 1001, 1002 we do not need an IV. */
446 if (ski->s2k.mode != 1001 && ski->s2k.mode != 1002)
447 iobuf_write (a, ski->iv, ski->ivlen);
450 else /* Not protected. */
453 if (ski->s2k.mode == 1001)
454 ; /* GnuPG extension - don't write a secret key at all. */
455 else if (ski->s2k.mode == 1002)
457 /* GnuPG extension - divert to OpenPGP smartcard. */
458 /* Length of the serial number or 0 for no serial number. */
459 iobuf_put (a, ski->ivlen );
460 /* The serial number gets stored in the IV field. */
461 iobuf_write (a, ski->iv, ski->ivlen);
463 else if (ski->is_protected)
465 /* The secret key is protected - write it out as it is. */
467 unsigned int ndatabits;
469 log_assert (gcry_mpi_get_flag (pk->pkey[npkey], GCRYMPI_FLAG_OPAQUE));
470 p = gcry_mpi_get_opaque (pk->pkey[npkey], &ndatabits);
472 iobuf_write (a, p, (ndatabits+7)/8 );
476 /* Non-protected key. */
477 for ( ; i < nskey; i++ )
478 if ( (err = gpg_mpi_write (a, pk->pkey[i])))
480 write_16 (a, ski->csum );
487 /* Build the header of the packet - which we must do after
488 writing all the other stuff, so that we know the length of
490 write_header2 (out, ctb, iobuf_get_temp_length(a), 0);
491 /* And finally write it out to the real stream. */
492 err = iobuf_write_temp (out, a);
495 iobuf_close (a); /* Close the temporary buffer */
499 /* Serialize the symmetric-key encrypted session key packet (RFC 4880,
500 5.3) described by ENC and write it to OUT.
502 CTB is the serialization's CTB. It specifies the header format and
503 the packet's type. The header length must not be set. */
505 do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc )
508 IOBUF a = iobuf_temp();
510 log_assert (ctb_pkttype (ctb) == PKT_SYMKEY_ENC);
512 /* The only acceptable version. */
513 log_assert( enc->version == 4 );
515 /* RFC 4880, Section 3.7. */
516 switch( enc->s2k.mode )
522 /* Iterated and salted S2K. */
524 /* Reasonable values. */
528 log_bug("do_symkey_enc: s2k=%d\n", enc->s2k.mode );
530 iobuf_put( a, enc->version );
531 iobuf_put( a, enc->cipher_algo );
532 iobuf_put( a, enc->s2k.mode );
533 iobuf_put( a, enc->s2k.hash_algo );
534 if( enc->s2k.mode == 1 || enc->s2k.mode == 3 ) {
535 iobuf_write(a, enc->s2k.salt, 8 );
536 if( enc->s2k.mode == 3 )
537 iobuf_put(a, enc->s2k.count);
540 iobuf_write(a, enc->seskey, enc->seskeylen );
542 write_header(out, ctb, iobuf_get_temp_length(a) );
543 rc = iobuf_write_temp( out, a );
550 /* Serialize the public-key encrypted session key packet (RFC 4880,
551 5.1) described by ENC and write it to OUT.
553 CTB is the serialization's CTB. It specifies the header format and
554 the packet's type. The header length must not be set. */
556 do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc )
560 IOBUF a = iobuf_temp();
562 log_assert (ctb_pkttype (ctb) == PKT_PUBKEY_ENC);
564 iobuf_put (a, 3); /* Version. */
566 if ( enc->throw_keyid )
568 write_32(a, 0 ); /* Don't tell Eve who can decrypt the message. */
573 write_32(a, enc->keyid[0] );
574 write_32(a, enc->keyid[1] );
576 iobuf_put(a,enc->pubkey_algo );
577 n = pubkey_get_nenc( enc->pubkey_algo );
579 write_fake_data( a, enc->data[0] );
581 for (i=0; i < n && !rc ; i++ )
583 if (enc->pubkey_algo == PUBKEY_ALGO_ECDH && i == 1)
584 rc = gpg_mpi_write_nohdr (a, enc->data[i]);
586 rc = gpg_mpi_write (a, enc->data[i]);
591 write_header (out, ctb, iobuf_get_temp_length(a) );
592 rc = iobuf_write_temp (out, a);
599 /* Calculate the length of the serialized plaintext packet PT (RFC
600 4480, Section 5.9). */
602 calc_plaintext( PKT_plaintext *pt )
604 /* Truncate namelen to the maximum 255 characters. Note this means
605 that a function that calls build_packet with an illegal literal
606 packet will get it back legalized. */
611 return pt->len? (1 + 1 + pt->namelen + 4 + pt->len) : 0;
614 /* Serialize the plaintext packet (RFC 4880, 5.9) described by PT and
617 The body of the message is stored in PT->BUF. The amount of data
618 to write is PT->LEN. (PT->BUF should be configured to return EOF
619 after this much data has been read.) If PT->LEN is 0 and CTB
620 indicates that this is a new format packet, then partial block mode
621 is assumed to have been enabled on OUT. On success, partial block
624 If PT->BUF is NULL, the the caller must write out the data. In
625 this case, if PT->LEN was 0, then partial body length mode was
626 enabled and the caller must disable it by calling
627 iobuf_set_partial_body_length_mode (out, 0). */
629 do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt )
634 log_assert (ctb_pkttype (ctb) == PKT_PLAINTEXT);
636 write_header(out, ctb, calc_plaintext( pt ) );
637 log_assert (pt->mode == 'b' || pt->mode == 't' || pt->mode == 'u'
639 || pt->mode == 'l' || pt->mode == '1');
640 iobuf_put(out, pt->mode );
641 iobuf_put(out, pt->namelen );
642 iobuf_write (out, pt->name, pt->namelen);
643 rc = write_32(out, pt->timestamp );
649 nbytes = iobuf_copy (out, pt->buf);
650 if(ctb_new_format_p (ctb) && !pt->len)
651 /* Turn off partial body length mode. */
652 iobuf_set_partial_body_length_mode (out, 0);
653 if( pt->len && nbytes != pt->len )
654 log_error("do_plaintext(): wrote %lu bytes but expected %lu bytes\n",
655 (ulong)nbytes, (ulong)pt->len );
663 /* Serialize the symmetrically encrypted data packet (RFC 4880,
664 Section 5.7) described by ED and write it to OUT.
666 Note: this only writes the packets header! The call must then
667 follow up and write the initial random data and the body to OUT.
668 (If you use the encryption iobuf filter (cipher_filter), then this
669 is done automatically.) */
671 do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed )
676 log_assert (! ed->mdc_method);
677 log_assert (ctb_pkttype (ctb) == PKT_ENCRYPTED);
679 n = ed->len ? (ed->len + ed->extralen) : 0;
680 write_header(out, ctb, n );
682 /* This is all. The caller has to write the real data */
687 /* Serialize the symmetrically encrypted integrity protected data
688 packet (RFC 4880, Section 5.13) described by ED and write it to
691 Note: this only writes the packet's header! The caller must then
692 follow up and write the initial random data, the body and the MDC
693 packet to OUT. (If you use the encryption iobuf filter
694 (cipher_filter), then this is done automatically.) */
696 do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed )
701 log_assert (ed->mdc_method);
702 log_assert (ctb_pkttype (ctb) == PKT_ENCRYPTED_MDC);
704 /* Take version number and the following MDC packet in account. */
705 n = ed->len ? (ed->len + ed->extralen + 1 + 22) : 0;
706 write_header(out, ctb, n );
707 iobuf_put(out, 1 ); /* version */
709 /* This is all. The caller has to write the real data */
715 /* Serialize the compressed packet (RFC 4880, Section 5.6) described
716 by CD and write it to OUT.
718 Note: this only writes the packet's header! The caller must then
719 follow up and write the body to OUT. */
721 do_compressed( IOBUF out, int ctb, PKT_compressed *cd )
725 log_assert (ctb_pkttype (ctb) == PKT_COMPRESSED);
727 /* We must use the old convention and don't use blockmode for the
728 sake of PGP 2 compatibility. However if the new_ctb flag was
729 set, CTB is already formatted as new style and write_header2
730 does create a partial length encoding using new the new
732 write_header2(out, ctb, 0, 0);
733 iobuf_put(out, cd->algorithm );
735 /* This is all. The caller has to write the real data */
742 * Delete all subpackets of type REQTYPE and return a bool whether a packet
746 delete_sig_subpkt (subpktarea_t *area, sigsubpkttype_t reqtype )
749 sigsubpkttype_t type;
750 byte *buffer, *bufstart;
765 n = *buffer++; buflen--;
769 n = buf32_to_size_t (buffer);
773 else if( n >= 192 ) {
776 n = (( n - 192 ) << 8) + *buffer + 192;
783 type = *buffer & 0x7f;
784 if( type == reqtype ) {
790 buffer += n; /* point to next subpkt */
792 memmove (bufstart, buffer, buflen); /* shift */
793 unused += buffer - bufstart;
797 buffer += n; buflen -=n;
802 log_error ("delete_subpkt: buffer shorter than subpacket\n");
803 log_assert (unused <= area->len);
810 * Create or update a signature subpacket for SIG of TYPE. This
811 * functions knows where to put the data (hashed or unhashed). The
812 * function may move data from the unhashed part to the hashed one.
813 * Note: All pointers into sig->[un]hashed (e.g. returned by
814 * parse_sig_subpkt) are not valid after a call to this function. The
815 * data to put into the subpaket should be in a buffer with a length
819 build_sig_subpkt (PKT_signature *sig, sigsubpkttype_t type,
820 const byte *buffer, size_t buflen )
823 int critical, hashed;
824 subpktarea_t *oldarea, *newarea;
827 critical = (type & SIGSUBPKT_FLAG_CRITICAL);
828 type &= ~SIGSUBPKT_FLAG_CRITICAL;
830 /* Sanity check buffer sizes */
831 if(parse_one_sig_subpkt(buffer,buflen,type)<0)
836 case SIGSUBPKT_NOTATION:
837 case SIGSUBPKT_POLICY:
838 case SIGSUBPKT_REV_KEY:
839 case SIGSUBPKT_SIGNATURE:
840 /* we do allow multiple subpackets */
844 /* we don't allow multiple subpackets */
845 delete_sig_subpkt(sig->hashed,type);
846 delete_sig_subpkt(sig->unhashed,type);
850 /* Any special magic that needs to be done for this type so the
851 packet doesn't need to be reparsed? */
854 case SIGSUBPKT_NOTATION:
855 sig->flags.notation=1;
858 case SIGSUBPKT_POLICY:
859 sig->flags.policy_url=1;
862 case SIGSUBPKT_PREF_KS:
863 sig->flags.pref_ks=1;
866 case SIGSUBPKT_EXPORTABLE:
868 sig->flags.exportable=1;
870 sig->flags.exportable=0;
873 case SIGSUBPKT_REVOCABLE:
875 sig->flags.revocable=1;
877 sig->flags.revocable=0;
880 case SIGSUBPKT_TRUST:
881 sig->trust_depth=buffer[0];
882 sig->trust_value=buffer[1];
885 case SIGSUBPKT_REGEXP:
886 sig->trust_regexp=buffer;
889 /* This should never happen since we don't currently allow
890 creating such a subpacket, but just in case... */
891 case SIGSUBPKT_SIG_EXPIRE:
892 if(buf32_to_u32(buffer)+sig->timestamp<=make_timestamp())
893 sig->flags.expired=1;
895 sig->flags.expired=0;
902 if( (buflen+1) >= 8384 )
903 nlen = 5; /* write 5 byte length header */
904 else if( (buflen+1) >= 192 )
905 nlen = 2; /* write 2 byte length header */
907 nlen = 1; /* just a 1 byte length header */
911 /* The issuer being unhashed is a historical oddity. It
912 should work equally as well hashed. Of course, if even an
913 unhashed issuer is tampered with, it makes it awfully hard
914 to verify the sig... */
915 case SIGSUBPKT_ISSUER:
916 case SIGSUBPKT_SIGNATURE:
925 type |= SIGSUBPKT_FLAG_CRITICAL;
927 oldarea = hashed? sig->hashed : sig->unhashed;
929 /* Calculate new size of the area and allocate */
930 n0 = oldarea? oldarea->len : 0;
931 n = n0 + nlen + 1 + buflen; /* length, type, buffer */
932 if (oldarea && n <= oldarea->size) { /* fits into the unused space */
934 /*log_debug ("updating area for type %d\n", type );*/
937 newarea = xrealloc (oldarea, sizeof (*newarea) + n - 1);
939 /*log_debug ("reallocating area for type %d\n", type );*/
942 newarea = xmalloc (sizeof (*newarea) + n - 1);
944 /*log_debug ("allocating area for type %d\n", type );*/
948 p = newarea->data + n0;
951 *p++ = (buflen+1) >> 24;
952 *p++ = (buflen+1) >> 16;
953 *p++ = (buflen+1) >> 8;
956 memcpy (p, buffer, buflen);
958 else if (nlen == 2) {
959 *p++ = (buflen+1-192) / 256 + 192;
960 *p++ = (buflen+1-192) % 256;
962 memcpy (p, buffer, buflen);
967 memcpy (p, buffer, buflen);
971 sig->hashed = newarea;
973 sig->unhashed = newarea;
977 * Put all the required stuff from SIG into subpackets of sig.
978 * PKSK is the signing key.
979 * Hmmm, should we delete those subpackets which are in a wrong area?
982 build_sig_subpkt_from_sig (PKT_signature *sig, PKT_public_key *pksk)
985 byte buf[1+MAX_FINGERPRINT_LEN];
988 /* For v4 keys we need to write the ISSUER subpacket. We do not
989 * want that for a future v5 format. */
990 if (pksk->version < 5)
993 buf[0] = (u >> 24) & 0xff;
994 buf[1] = (u >> 16) & 0xff;
995 buf[2] = (u >> 8) & 0xff;
998 buf[4] = (u >> 24) & 0xff;
999 buf[5] = (u >> 16) & 0xff;
1000 buf[6] = (u >> 8) & 0xff;
1002 build_sig_subpkt (sig, SIGSUBPKT_ISSUER, buf, 8);
1005 /* For a future v5 keys we write the ISSUER_FPR subpacket. We
1006 * also write that for a v4 key is experimental support for
1007 * RFC4880bis is requested. */
1008 if (pksk->version > 4 || opt.flags.rfc4880bis)
1010 fingerprint_from_pk (pksk, buf+1, &fprlen);
1013 buf[0] = pksk->version;
1014 build_sig_subpkt (sig, SIGSUBPKT_ISSUER_FPR, buf, 21);
1018 /* Write the timestamp. */
1020 buf[0] = (u >> 24) & 0xff;
1021 buf[1] = (u >> 16) & 0xff;
1022 buf[2] = (u >> 8) & 0xff;
1024 build_sig_subpkt( sig, SIGSUBPKT_SIG_CREATED, buf, 4 );
1028 if(sig->expiredate>sig->timestamp)
1029 u=sig->expiredate-sig->timestamp;
1031 u=1; /* A 1-second expiration time is the shortest one
1034 buf[0] = (u >> 24) & 0xff;
1035 buf[1] = (u >> 16) & 0xff;
1036 buf[2] = (u >> 8) & 0xff;
1039 /* Mark this CRITICAL, so if any implementation doesn't
1040 understand sigs that can expire, it'll just disregard this
1043 build_sig_subpkt( sig, SIGSUBPKT_SIG_EXPIRE | SIGSUBPKT_FLAG_CRITICAL,
1049 build_attribute_subpkt(PKT_user_id *uid,byte type,
1050 const void *buf,u32 buflen,
1051 const void *header,u32 headerlen)
1056 if(1+headerlen+buflen>8383)
1058 else if(1+headerlen+buflen>191)
1063 /* realloc uid->attrib_data to the right size */
1065 uid->attrib_data=xrealloc(uid->attrib_data,
1066 uid->attrib_len+idx+1+headerlen+buflen);
1068 attrib=&uid->attrib_data[uid->attrib_len];
1073 attrib[1]=(1+headerlen+buflen) >> 24;
1074 attrib[2]=(1+headerlen+buflen) >> 16;
1075 attrib[3]=(1+headerlen+buflen) >> 8;
1076 attrib[4]=1+headerlen+buflen;
1080 attrib[0]=(1+headerlen+buflen-192) / 256 + 192;
1081 attrib[1]=(1+headerlen+buflen-192) % 256;
1084 attrib[0]=1+headerlen+buflen; /* Good luck finding a JPEG this small! */
1088 /* Tack on our data at the end */
1091 memcpy(&attrib[idx],header,headerlen);
1092 memcpy(&attrib[idx+headerlen],buf,buflen);
1093 uid->attrib_len+=idx+headerlen+buflen;
1096 /* Returns a human-readable string corresponding to the notation.
1097 This ignores notation->value. The caller must free the result. */
1099 notation_value_to_human_readable_string (struct notation *notation)
1104 size_t len = notation->blen;
1108 for (i = 0; i < len && i < sizeof (preview) - 1; i ++)
1109 if (isprint (notation->bdat[i]))
1110 preview[i] = notation->bdat[i];
1115 return xasprintf (_("[ not human readable (%zu bytes: %s%s) ]"),
1116 len, preview, i < len ? "..." : "");
1119 /* The value is human-readable. */
1120 return xstrdup (notation->value);
1123 /* Turn the notation described by the string STRING into a notation.
1125 STRING has the form:
1127 - -name - Delete the notation.
1128 - name@domain.name=value - Normal notation
1129 - !name@domain.name=value - Notation with critical bit set.
1131 The caller must free the result using free_notation(). */
1133 string_to_notation(const char *string,int is_utf8)
1137 struct notation *notation;
1139 notation=xmalloc_clear(sizeof(*notation));
1143 notation->flags.ignore=1;
1149 notation->flags.critical=1;
1153 /* If and when the IETF assigns some official name tags, we'll have
1154 to add them here. */
1156 for( s=string ; *s != '='; s++ )
1161 /* -notationname is legal without an = sign */
1162 if(!*s && notation->flags.ignore)
1165 if( !*s || !isascii (*s) || (!isgraph(*s) && !isspace(*s)) )
1167 log_error(_("a notation name must have only printable characters"
1168 " or spaces, and end with an '='\n") );
1173 notation->name=xmalloc((s-string)+1);
1174 strncpy(notation->name,string,s-string);
1175 notation->name[s-string]='\0';
1177 if(!saw_at && !opt.expert)
1179 log_error(_("a user notation name must contain the '@' character\n"));
1185 log_error(_("a notation name must not contain more than"
1186 " one '@' character\n"));
1195 /* we only support printable text - therefore we enforce the use
1196 of only printable characters (an empty value is valid) */
1199 if ( !isascii (*s) )
1201 else if (iscntrl(*s))
1203 log_error(_("a notation value must not use any"
1204 " control characters\n"));
1209 if(!highbit || is_utf8)
1210 notation->value=xstrdup(i);
1212 notation->value=native_to_utf8(i);
1218 free_notation(notation);
1222 /* Like string_to_notation, but store opaque data rather than human
1225 blob_to_notation(const char *name, const char *data, size_t len)
1229 struct notation *notation;
1231 notation=xmalloc_clear(sizeof(*notation));
1235 notation->flags.ignore=1;
1241 notation->flags.critical=1;
1245 /* If and when the IETF assigns some official name tags, we'll have
1246 to add them here. */
1248 for( s=name ; *s; s++ )
1253 /* -notationname is legal without an = sign */
1254 if(!*s && notation->flags.ignore)
1259 log_error(_("a notation name may not contain an '=' character\n"));
1263 if (!isascii (*s) || (!isgraph(*s) && !isspace(*s)))
1265 log_error(_("a notation name must have only printable characters"
1271 notation->name=xstrdup (name);
1273 if(!saw_at && !opt.expert)
1275 log_error(_("a user notation name must contain the '@' character\n"));
1281 log_error(_("a notation name must not contain more than"
1282 " one '@' character\n"));
1286 notation->bdat = xmalloc (len);
1287 memcpy (notation->bdat, data, len);
1288 notation->blen = len;
1290 notation->value = notation_value_to_human_readable_string (notation);
1295 free_notation(notation);
1300 sig_to_notation(PKT_signature *sig)
1306 notation_t list = NULL;
1308 /* See RFC 4880, 5.2.3.16 for the format of notation data. In
1309 short, a notation has:
1312 - 2 byte name length (n1)
1313 - 2 byte value length (n2)
1314 - n1 bytes of name data
1315 - n2 bytes of value data
1317 while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION,&len,&seq,&crit)))
1320 struct notation *n=NULL;
1324 log_info(_("WARNING: invalid notation data found\n"));
1335 log_info(_("WARNING: invalid notation data found\n"));
1339 n=xmalloc_clear(sizeof(*n));
1340 n->name=xmalloc(n1+1);
1342 memcpy(n->name,&p[8],n1);
1346 /* The value is human-readable. */
1348 n->value=xmalloc(n2+1);
1349 memcpy(n->value,&p[8+n1],n2);
1356 n->bdat=xmalloc(n2);
1358 memcpy(n->bdat,&p[8+n1],n2);
1360 n->value = notation_value_to_human_readable_string (n);
1363 n->flags.critical=crit;
1372 /* Release the resources associated with the *list* of notations. To
1373 release a single notation, make sure that notation->next is
1376 free_notation(struct notation *notation)
1380 struct notation *n=notation;
1391 /* Serialize the signature packet (RFC 4880, Section 5.2) described by
1392 SIG and write it to OUT. */
1394 do_signature( IOBUF out, int ctb, PKT_signature *sig )
1398 IOBUF a = iobuf_temp();
1400 log_assert (ctb_pkttype (ctb) == PKT_SIGNATURE);
1402 if ( !sig->version || sig->version == 3)
1406 /* Version 3 packets don't support subpackets. */
1407 log_assert (! sig->hashed);
1408 log_assert (! sig->unhashed);
1411 iobuf_put( a, sig->version );
1412 if ( sig->version < 4 )
1413 iobuf_put (a, 5 ); /* Constant */
1414 iobuf_put (a, sig->sig_class );
1415 if ( sig->version < 4 )
1417 write_32(a, sig->timestamp );
1418 write_32(a, sig->keyid[0] );
1419 write_32(a, sig->keyid[1] );
1421 iobuf_put(a, sig->pubkey_algo );
1422 iobuf_put(a, sig->digest_algo );
1423 if ( sig->version >= 4 )
1426 /* Timestamp and keyid must have been packed into the subpackets
1427 prior to the call of this function, because these subpackets
1429 nn = sig->hashed? sig->hashed->len : 0;
1432 iobuf_write( a, sig->hashed->data, nn );
1433 nn = sig->unhashed? sig->unhashed->len : 0;
1436 iobuf_write( a, sig->unhashed->data, nn );
1438 iobuf_put(a, sig->digest_start[0] );
1439 iobuf_put(a, sig->digest_start[1] );
1440 n = pubkey_get_nsig( sig->pubkey_algo );
1442 write_fake_data( a, sig->data[0] );
1443 for (i=0; i < n && !rc ; i++ )
1444 rc = gpg_mpi_write (a, sig->data[i] );
1448 if ( is_RSA(sig->pubkey_algo) && sig->version < 4 )
1449 write_sign_packet_header(out, ctb, iobuf_get_temp_length(a) );
1451 write_header(out, ctb, iobuf_get_temp_length(a) );
1452 rc = iobuf_write_temp( out, a );
1460 /* Serialize the one-pass signature packet (RFC 4880, Section 5.4)
1461 described by OPS and write it to OUT. */
1463 do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops )
1465 log_assert (ctb_pkttype (ctb) == PKT_ONEPASS_SIG);
1467 write_header(out, ctb, 4 + 8 + 1);
1469 iobuf_put (out, 3); /* Version. */
1470 iobuf_put(out, ops->sig_class );
1471 iobuf_put(out, ops->digest_algo );
1472 iobuf_put(out, ops->pubkey_algo );
1473 write_32(out, ops->keyid[0] );
1474 write_32(out, ops->keyid[1] );
1475 iobuf_put(out, ops->last );
1481 /* Write a 16-bit quantity to OUT in big endian order. */
1483 write_16(IOBUF out, u16 a)
1485 iobuf_put(out, a>>8);
1486 if( iobuf_put(out,a) )
1491 /* Write a 32-bit quantity to OUT in big endian order. */
1493 write_32(IOBUF out, u32 a)
1495 iobuf_put(out, a>> 24);
1496 iobuf_put(out, a>> 16);
1497 iobuf_put(out, a>> 8);
1498 return iobuf_put(out, a);
1503 * calculate the length of a header.
1505 * LEN is the length of the packet's body. NEW_CTB is whether we are
1506 * using a new or old format packet.
1508 * This function does not handle indeterminate lengths or partial body
1509 * lengths. (If you pass LEN as 0, then this function assumes you
1510 * really mean an empty body.)
1513 calc_header_length( u32 len, int new_ctb )
1532 * Write the CTB and the packet length
1535 write_header( IOBUF out, int ctb, u32 len )
1537 return write_header2( out, ctb, len, 0 );
1542 write_sign_packet_header (IOBUF out, int ctb, u32 len)
1546 /* Work around a bug in the pgp read function for signature packets,
1547 which are not correctly coded and silently assume at some point 2
1548 byte length headers.*/
1549 iobuf_put (out, 0x89 );
1550 iobuf_put (out, len >> 8 );
1551 return iobuf_put (out, len) == -1 ? -1:0;
1555 * Write a packet header to OUT.
1557 * CTB is the ctb. It determines whether a new or old format packet
1558 * header should be written. The length field is adjusted, but the
1559 * CTB is otherwise written out as is.
1561 * LEN is the length of the packet's body.
1563 * If HDRLEN is set, then we don't necessarily use the most efficient
1564 * encoding to store LEN, but the specified length. (If this is not
1565 * possible, this is a bug.) In this case, LEN=0 means a 0 length
1566 * packet. Note: setting HDRLEN is only supported for old format
1569 * If HDRLEN is not set, then the shortest encoding is used. In this
1570 * case, LEN=0 means the body has an indeterminate length and a
1571 * partial body length header (if a new format packet) or an
1572 * indeterminate length header (if an old format packet) is written
1573 * out. Further, if using partial body lengths, this enables partial
1574 * body length mode on OUT.
1577 write_header2( IOBUF out, int ctb, u32 len, int hdrlen )
1579 if (ctb_new_format_p (ctb))
1580 return write_new_header( out, ctb, len, hdrlen );
1582 /* An old format packet. Refer to RFC 4880, Section 4.2.1 to
1583 understand how lengths are encoded in this case. */
1585 /* The length encoding is stored in the two least significant bits.
1586 Make sure they are cleared. */
1587 log_assert ((ctb & 3) == 0);
1589 log_assert (hdrlen == 0 || hdrlen == 2 || hdrlen == 3 || hdrlen == 5);
1592 /* Header length is given. */
1594 if( hdrlen == 2 && len < 256 )
1595 /* 00 => 1 byte length. */
1597 else if( hdrlen == 3 && len < 65536 )
1598 /* 01 => 2 byte length. If len < 256, this is not the most
1599 compact encoding, but it is a correct encoding. */
1601 else if (hdrlen == 5)
1602 /* 10 => 4 byte length. If len < 65536, this is not the most
1603 compact encoding, but it is a correct encoding. */
1606 log_bug ("Can't encode length=%d in a %d byte header!\n",
1612 /* 11 => Indeterminate length. */
1614 else if( len < 256 )
1615 /* 00 => 1 byte length. */
1617 else if( len < 65536 )
1618 /* 01 => 2 byte length. */
1621 /* 10 => 4 byte length. */
1625 if( iobuf_put(out, ctb ) )
1632 if(iobuf_put(out, len >> 24 ))
1634 if(iobuf_put(out, len >> 16 ))
1639 if(iobuf_put(out, len >> 8 ))
1642 if( iobuf_put(out, len ) )
1650 /* Write a new format header to OUT.
1654 LEN is the length of the packet's body. If LEN is 0, then enables
1655 partial body length mode (i.e., the body is of an indeterminant
1656 length) on OUT. Note: this function cannot be used to generate a
1657 header for a zero length packet.
1659 HDRLEN is the length of the packet's header. If HDRLEN is 0, the
1660 shortest encoding is chosen based on the length of the packet's
1661 body. Currently, values other than 0 are not supported.
1663 Returns 0 on success. */
1665 write_new_header( IOBUF out, int ctb, u32 len, int hdrlen )
1668 log_bug("can't cope with hdrlen yet\n");
1670 if( iobuf_put(out, ctb ) )
1673 iobuf_set_partial_body_length_mode(out, 512 );
1677 if( iobuf_put(out, len ) )
1680 else if( len < 8384 ) {
1682 if( iobuf_put( out, (len / 256) + 192) )
1684 if( iobuf_put( out, (len % 256) ) )
1688 if( iobuf_put( out, 0xff ) )
1690 if( iobuf_put( out, (len >> 24)&0xff ) )
1692 if( iobuf_put( out, (len >> 16)&0xff ) )
1694 if( iobuf_put( out, (len >> 8)&0xff ) )
1696 if( iobuf_put( out, len & 0xff ) )