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 <https://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 /* Write the new ISSUER_FPR subpacket. */
1006 fingerprint_from_pk (pksk, buf+1, &fprlen);
1009 buf[0] = pksk->version;
1010 build_sig_subpkt (sig, SIGSUBPKT_ISSUER_FPR, buf, 21);
1013 /* Write the timestamp. */
1015 buf[0] = (u >> 24) & 0xff;
1016 buf[1] = (u >> 16) & 0xff;
1017 buf[2] = (u >> 8) & 0xff;
1019 build_sig_subpkt( sig, SIGSUBPKT_SIG_CREATED, buf, 4 );
1023 if(sig->expiredate>sig->timestamp)
1024 u=sig->expiredate-sig->timestamp;
1026 u=1; /* A 1-second expiration time is the shortest one
1029 buf[0] = (u >> 24) & 0xff;
1030 buf[1] = (u >> 16) & 0xff;
1031 buf[2] = (u >> 8) & 0xff;
1034 /* Mark this CRITICAL, so if any implementation doesn't
1035 understand sigs that can expire, it'll just disregard this
1038 build_sig_subpkt( sig, SIGSUBPKT_SIG_EXPIRE | SIGSUBPKT_FLAG_CRITICAL,
1044 build_attribute_subpkt(PKT_user_id *uid,byte type,
1045 const void *buf,u32 buflen,
1046 const void *header,u32 headerlen)
1051 if(1+headerlen+buflen>8383)
1053 else if(1+headerlen+buflen>191)
1058 /* realloc uid->attrib_data to the right size */
1060 uid->attrib_data=xrealloc(uid->attrib_data,
1061 uid->attrib_len+idx+1+headerlen+buflen);
1063 attrib=&uid->attrib_data[uid->attrib_len];
1068 attrib[1]=(1+headerlen+buflen) >> 24;
1069 attrib[2]=(1+headerlen+buflen) >> 16;
1070 attrib[3]=(1+headerlen+buflen) >> 8;
1071 attrib[4]=1+headerlen+buflen;
1075 attrib[0]=(1+headerlen+buflen-192) / 256 + 192;
1076 attrib[1]=(1+headerlen+buflen-192) % 256;
1079 attrib[0]=1+headerlen+buflen; /* Good luck finding a JPEG this small! */
1083 /* Tack on our data at the end */
1086 memcpy(&attrib[idx],header,headerlen);
1087 memcpy(&attrib[idx+headerlen],buf,buflen);
1088 uid->attrib_len+=idx+headerlen+buflen;
1091 /* Returns a human-readable string corresponding to the notation.
1092 This ignores notation->value. The caller must free the result. */
1094 notation_value_to_human_readable_string (struct notation *notation)
1099 size_t len = notation->blen;
1103 for (i = 0; i < len && i < sizeof (preview) - 1; i ++)
1104 if (isprint (notation->bdat[i]))
1105 preview[i] = notation->bdat[i];
1110 return xasprintf (_("[ not human readable (%zu bytes: %s%s) ]"),
1111 len, preview, i < len ? "..." : "");
1114 /* The value is human-readable. */
1115 return xstrdup (notation->value);
1118 /* Turn the notation described by the string STRING into a notation.
1120 STRING has the form:
1122 - -name - Delete the notation.
1123 - name@domain.name=value - Normal notation
1124 - !name@domain.name=value - Notation with critical bit set.
1126 The caller must free the result using free_notation(). */
1128 string_to_notation(const char *string,int is_utf8)
1132 struct notation *notation;
1134 notation=xmalloc_clear(sizeof(*notation));
1138 notation->flags.ignore=1;
1144 notation->flags.critical=1;
1148 /* If and when the IETF assigns some official name tags, we'll have
1149 to add them here. */
1151 for( s=string ; *s != '='; s++ )
1156 /* -notationname is legal without an = sign */
1157 if(!*s && notation->flags.ignore)
1160 if( !*s || !isascii (*s) || (!isgraph(*s) && !isspace(*s)) )
1162 log_error(_("a notation name must have only printable characters"
1163 " or spaces, and end with an '='\n") );
1168 notation->name=xmalloc((s-string)+1);
1169 strncpy(notation->name,string,s-string);
1170 notation->name[s-string]='\0';
1172 if(!saw_at && !opt.expert)
1174 log_error(_("a user notation name must contain the '@' character\n"));
1180 log_error(_("a notation name must not contain more than"
1181 " one '@' character\n"));
1190 /* we only support printable text - therefore we enforce the use
1191 of only printable characters (an empty value is valid) */
1194 if ( !isascii (*s) )
1196 else if (iscntrl(*s))
1198 log_error(_("a notation value must not use any"
1199 " control characters\n"));
1204 if(!highbit || is_utf8)
1205 notation->value=xstrdup(i);
1207 notation->value=native_to_utf8(i);
1213 free_notation(notation);
1217 /* Like string_to_notation, but store opaque data rather than human
1220 blob_to_notation(const char *name, const char *data, size_t len)
1224 struct notation *notation;
1226 notation=xmalloc_clear(sizeof(*notation));
1230 notation->flags.ignore=1;
1236 notation->flags.critical=1;
1240 /* If and when the IETF assigns some official name tags, we'll have
1241 to add them here. */
1243 for( s=name ; *s; s++ )
1248 /* -notationname is legal without an = sign */
1249 if(!*s && notation->flags.ignore)
1254 log_error(_("a notation name may not contain an '=' character\n"));
1258 if (!isascii (*s) || (!isgraph(*s) && !isspace(*s)))
1260 log_error(_("a notation name must have only printable characters"
1266 notation->name=xstrdup (name);
1268 if(!saw_at && !opt.expert)
1270 log_error(_("a user notation name must contain the '@' character\n"));
1276 log_error(_("a notation name must not contain more than"
1277 " one '@' character\n"));
1281 notation->bdat = xmalloc (len);
1282 memcpy (notation->bdat, data, len);
1283 notation->blen = len;
1285 notation->value = notation_value_to_human_readable_string (notation);
1290 free_notation(notation);
1295 sig_to_notation(PKT_signature *sig)
1301 notation_t list = NULL;
1303 /* See RFC 4880, 5.2.3.16 for the format of notation data. In
1304 short, a notation has:
1307 - 2 byte name length (n1)
1308 - 2 byte value length (n2)
1309 - n1 bytes of name data
1310 - n2 bytes of value data
1312 while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION,&len,&seq,&crit)))
1315 struct notation *n=NULL;
1319 log_info(_("WARNING: invalid notation data found\n"));
1330 log_info(_("WARNING: invalid notation data found\n"));
1334 n=xmalloc_clear(sizeof(*n));
1335 n->name=xmalloc(n1+1);
1337 memcpy(n->name,&p[8],n1);
1341 /* The value is human-readable. */
1343 n->value=xmalloc(n2+1);
1344 memcpy(n->value,&p[8+n1],n2);
1351 n->bdat=xmalloc(n2);
1353 memcpy(n->bdat,&p[8+n1],n2);
1355 n->value = notation_value_to_human_readable_string (n);
1358 n->flags.critical=crit;
1367 /* Release the resources associated with the *list* of notations. To
1368 release a single notation, make sure that notation->next is
1371 free_notation(struct notation *notation)
1375 struct notation *n=notation;
1386 /* Serialize the signature packet (RFC 4880, Section 5.2) described by
1387 SIG and write it to OUT. */
1389 do_signature( IOBUF out, int ctb, PKT_signature *sig )
1393 IOBUF a = iobuf_temp();
1395 log_assert (ctb_pkttype (ctb) == PKT_SIGNATURE);
1397 if ( !sig->version || sig->version == 3)
1401 /* Version 3 packets don't support subpackets. */
1402 log_assert (! sig->hashed);
1403 log_assert (! sig->unhashed);
1406 iobuf_put( a, sig->version );
1407 if ( sig->version < 4 )
1408 iobuf_put (a, 5 ); /* Constant */
1409 iobuf_put (a, sig->sig_class );
1410 if ( sig->version < 4 )
1412 write_32(a, sig->timestamp );
1413 write_32(a, sig->keyid[0] );
1414 write_32(a, sig->keyid[1] );
1416 iobuf_put(a, sig->pubkey_algo );
1417 iobuf_put(a, sig->digest_algo );
1418 if ( sig->version >= 4 )
1421 /* Timestamp and keyid must have been packed into the subpackets
1422 prior to the call of this function, because these subpackets
1424 nn = sig->hashed? sig->hashed->len : 0;
1427 iobuf_write( a, sig->hashed->data, nn );
1428 nn = sig->unhashed? sig->unhashed->len : 0;
1431 iobuf_write( a, sig->unhashed->data, nn );
1433 iobuf_put(a, sig->digest_start[0] );
1434 iobuf_put(a, sig->digest_start[1] );
1435 n = pubkey_get_nsig( sig->pubkey_algo );
1437 write_fake_data( a, sig->data[0] );
1438 for (i=0; i < n && !rc ; i++ )
1439 rc = gpg_mpi_write (a, sig->data[i] );
1443 if ( is_RSA(sig->pubkey_algo) && sig->version < 4 )
1444 write_sign_packet_header(out, ctb, iobuf_get_temp_length(a) );
1446 write_header(out, ctb, iobuf_get_temp_length(a) );
1447 rc = iobuf_write_temp( out, a );
1455 /* Serialize the one-pass signature packet (RFC 4880, Section 5.4)
1456 described by OPS and write it to OUT. */
1458 do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops )
1460 log_assert (ctb_pkttype (ctb) == PKT_ONEPASS_SIG);
1462 write_header(out, ctb, 4 + 8 + 1);
1464 iobuf_put (out, 3); /* Version. */
1465 iobuf_put(out, ops->sig_class );
1466 iobuf_put(out, ops->digest_algo );
1467 iobuf_put(out, ops->pubkey_algo );
1468 write_32(out, ops->keyid[0] );
1469 write_32(out, ops->keyid[1] );
1470 iobuf_put(out, ops->last );
1476 /* Write a 16-bit quantity to OUT in big endian order. */
1478 write_16(IOBUF out, u16 a)
1480 iobuf_put(out, a>>8);
1481 if( iobuf_put(out,a) )
1486 /* Write a 32-bit quantity to OUT in big endian order. */
1488 write_32(IOBUF out, u32 a)
1490 iobuf_put(out, a>> 24);
1491 iobuf_put(out, a>> 16);
1492 iobuf_put(out, a>> 8);
1493 return iobuf_put(out, a);
1498 * calculate the length of a header.
1500 * LEN is the length of the packet's body. NEW_CTB is whether we are
1501 * using a new or old format packet.
1503 * This function does not handle indeterminate lengths or partial body
1504 * lengths. (If you pass LEN as 0, then this function assumes you
1505 * really mean an empty body.)
1508 calc_header_length( u32 len, int new_ctb )
1527 * Write the CTB and the packet length
1530 write_header( IOBUF out, int ctb, u32 len )
1532 return write_header2( out, ctb, len, 0 );
1537 write_sign_packet_header (IOBUF out, int ctb, u32 len)
1541 /* Work around a bug in the pgp read function for signature packets,
1542 which are not correctly coded and silently assume at some point 2
1543 byte length headers.*/
1544 iobuf_put (out, 0x89 );
1545 iobuf_put (out, len >> 8 );
1546 return iobuf_put (out, len) == -1 ? -1:0;
1550 * Write a packet header to OUT.
1552 * CTB is the ctb. It determines whether a new or old format packet
1553 * header should be written. The length field is adjusted, but the
1554 * CTB is otherwise written out as is.
1556 * LEN is the length of the packet's body.
1558 * If HDRLEN is set, then we don't necessarily use the most efficient
1559 * encoding to store LEN, but the specified length. (If this is not
1560 * possible, this is a bug.) In this case, LEN=0 means a 0 length
1561 * packet. Note: setting HDRLEN is only supported for old format
1564 * If HDRLEN is not set, then the shortest encoding is used. In this
1565 * case, LEN=0 means the body has an indeterminate length and a
1566 * partial body length header (if a new format packet) or an
1567 * indeterminate length header (if an old format packet) is written
1568 * out. Further, if using partial body lengths, this enables partial
1569 * body length mode on OUT.
1572 write_header2( IOBUF out, int ctb, u32 len, int hdrlen )
1574 if (ctb_new_format_p (ctb))
1575 return write_new_header( out, ctb, len, hdrlen );
1577 /* An old format packet. Refer to RFC 4880, Section 4.2.1 to
1578 understand how lengths are encoded in this case. */
1580 /* The length encoding is stored in the two least significant bits.
1581 Make sure they are cleared. */
1582 log_assert ((ctb & 3) == 0);
1584 log_assert (hdrlen == 0 || hdrlen == 2 || hdrlen == 3 || hdrlen == 5);
1587 /* Header length is given. */
1589 if( hdrlen == 2 && len < 256 )
1590 /* 00 => 1 byte length. */
1592 else if( hdrlen == 3 && len < 65536 )
1593 /* 01 => 2 byte length. If len < 256, this is not the most
1594 compact encoding, but it is a correct encoding. */
1596 else if (hdrlen == 5)
1597 /* 10 => 4 byte length. If len < 65536, this is not the most
1598 compact encoding, but it is a correct encoding. */
1601 log_bug ("Can't encode length=%d in a %d byte header!\n",
1607 /* 11 => Indeterminate length. */
1609 else if( len < 256 )
1610 /* 00 => 1 byte length. */
1612 else if( len < 65536 )
1613 /* 01 => 2 byte length. */
1616 /* 10 => 4 byte length. */
1620 if( iobuf_put(out, ctb ) )
1627 if(iobuf_put(out, len >> 24 ))
1629 if(iobuf_put(out, len >> 16 ))
1634 if(iobuf_put(out, len >> 8 ))
1637 if( iobuf_put(out, len ) )
1645 /* Write a new format header to OUT.
1649 LEN is the length of the packet's body. If LEN is 0, then enables
1650 partial body length mode (i.e., the body is of an indeterminant
1651 length) on OUT. Note: this function cannot be used to generate a
1652 header for a zero length packet.
1654 HDRLEN is the length of the packet's header. If HDRLEN is 0, the
1655 shortest encoding is chosen based on the length of the packet's
1656 body. Currently, values other than 0 are not supported.
1658 Returns 0 on success. */
1660 write_new_header( IOBUF out, int ctb, u32 len, int hdrlen )
1663 log_bug("can't cope with hdrlen yet\n");
1665 if( iobuf_put(out, ctb ) )
1668 iobuf_set_partial_body_length_mode(out, 512 );
1672 if( iobuf_put(out, len ) )
1675 else if( len < 8384 ) {
1677 if( iobuf_put( out, (len / 256) + 192) )
1679 if( iobuf_put( out, (len % 256) ) )
1683 if( iobuf_put( out, 0xff ) )
1685 if( iobuf_put( out, (len >> 24)&0xff ) )
1687 if( iobuf_put( out, (len >> 16)&0xff ) )
1689 if( iobuf_put( out, (len >> 8)&0xff ) )
1691 if( iobuf_put( out, len & 0xff ) )