xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/signature.c (revision 53d1339bf7f9c7367b35a9e1ebe693f9b047a47b)
1 /*-
2  * Copyright (c) 2009 The NetBSD Foundation, Inc.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to The NetBSD Foundation
6  * by Alistair Crooks (agc@NetBSD.org)
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 /*
30  * Copyright (c) 2005-2008 Nominet UK (www.nic.uk)
31  * All rights reserved.
32  * Contributors: Ben Laurie, Rachel Willmer. The Contributors have asserted
33  * their moral rights under the UK Copyright Design and Patents Act 1988 to
34  * be recorded as the authors of this copyright work.
35  *
36  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
37  * use this file except in compliance with the License.
38  *
39  * You may obtain a copy of the License at
40  *     http://www.apache.org/licenses/LICENSE-2.0
41  *
42  * Unless required by applicable law or agreed to in writing, software
43  * distributed under the License is distributed on an "AS IS" BASIS,
44  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
45  *
46  * See the License for the specific language governing permissions and
47  * limitations under the License.
48  */
49 
50 /** \file
51  */
52 #include "config.h"
53 
54 #ifdef HAVE_SYS_CDEFS_H
55 #include <sys/cdefs.h>
56 #endif
57 
58 #if defined(__NetBSD__)
59 __COPYRIGHT("@(#) Copyright (c) 2009 The NetBSD Foundation, Inc. All rights reserved.");
60 __RCSID("$NetBSD: signature.c,v 1.38 2018/02/05 23:56:01 christos Exp $");
61 #endif
62 
63 #include <sys/types.h>
64 #include <sys/param.h>
65 
66 #ifdef HAVE_FCNTL_H
67 #include <fcntl.h>
68 #endif
69 
70 #include <string.h>
71 
72 #ifdef HAVE_UNISTD_H
73 #include <unistd.h>
74 #endif
75 
76 #ifdef HAVE_OPENSSL_DSA_H
77 #include <openssl/dsa.h>
78 #endif
79 
80 #include "signature.h"
81 #include "crypto.h"
82 #include "create.h"
83 #include "netpgpsdk.h"
84 #include "readerwriter.h"
85 #include "validate.h"
86 #include "netpgpdefs.h"
87 #include "netpgpdigest.h"
88 
89 
90 /** \ingroup Core_Create
91  * needed for signature creation
92  */
93 struct pgp_create_sig_t {
94 	pgp_hash_t		 hash;
95 	pgp_sig_t		 sig;
96 	pgp_memory_t		*mem;
97 	pgp_output_t		*output;	/* how to do the writing */
98 	unsigned		 hashoff;	/* hashed count offset */
99 	unsigned		 hashlen;
100 	unsigned 		 unhashoff;
101 };
102 
103 /**
104    \ingroup Core_Signature
105    Creates new pgp_create_sig_t
106    \return new pgp_create_sig_t
107    \note It is the caller's responsibility to call pgp_create_sig_delete()
108    \sa pgp_create_sig_delete()
109 */
110 pgp_create_sig_t *
111 pgp_create_sig_new(void)
112 {
113 	return calloc(1, sizeof(pgp_create_sig_t));
114 }
115 
116 /**
117    \ingroup Core_Signature
118    Free signature and memory associated with it
119    \param sig struct to free
120    \sa pgp_create_sig_new()
121 */
122 void
123 pgp_create_sig_delete(pgp_create_sig_t *sig)
124 {
125 	pgp_output_delete(sig->output);
126 	sig->output = NULL;
127 	free(sig);
128 }
129 
130 #if 0
131 void
132 pgp_dump_sig(pgp_sig_t *sig)
133 {
134 }
135 #endif
136 
137 static uint8_t prefix_md5[] = {
138 	0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86,
139 	0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10
140 };
141 
142 static uint8_t prefix_sha1[] = {
143 	0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0E, 0x03, 0x02,
144 	0x1A, 0x05, 0x00, 0x04, 0x14
145 };
146 
147 static uint8_t prefix_sha256[] = {
148 	0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
149 	0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20
150 };
151 
152 
153 /* XXX: both this and verify would be clearer if the signature were */
154 /* treated as an MPI. */
155 static int
156 rsa_sign(pgp_hash_t *hash,
157 	const pgp_rsa_pubkey_t *pubrsa,
158 	const pgp_rsa_seckey_t *secrsa,
159 	pgp_output_t *out)
160 {
161 	unsigned        prefixsize;
162 	unsigned        expected;
163 	unsigned        hashsize;
164 	unsigned        keysize;
165 	unsigned        n;
166 	unsigned        t;
167 	uint8_t		hashbuf[NETPGP_BUFSIZ];
168 	uint8_t		sigbuf[NETPGP_BUFSIZ];
169 	uint8_t		*prefix;
170 	BIGNUM         *bn;
171 
172 	if (strcmp(hash->name, "SHA1") == 0) {
173 		hashsize = PGP_SHA1_HASH_SIZE + sizeof(prefix_sha1);
174 		prefix = prefix_sha1;
175 		prefixsize = sizeof(prefix_sha1);
176 		expected = PGP_SHA1_HASH_SIZE;
177 	} else {
178 		hashsize = PGP_SHA256_HASH_SIZE + sizeof(prefix_sha256);
179 		prefix = prefix_sha256;
180 		prefixsize = sizeof(prefix_sha256);
181 		expected = PGP_SHA256_HASH_SIZE;
182 	}
183 	keysize = (BN_num_bits(pubrsa->n) + 7) / 8;
184 	if (keysize > sizeof(hashbuf)) {
185 		(void) fprintf(stderr, "rsa_sign: keysize too big\n");
186 		return 0;
187 	}
188 	if (10 + hashsize > keysize) {
189 		(void) fprintf(stderr, "rsa_sign: hashsize too big\n");
190 		return 0;
191 	}
192 
193 	hashbuf[0] = 0;
194 	hashbuf[1] = 1;
195 	if (pgp_get_debug_level(__FILE__)) {
196 		printf("rsa_sign: PS is %d\n", keysize - hashsize - 1 - 2);
197 	}
198 	for (n = 2; n < keysize - hashsize - 1; ++n) {
199 		hashbuf[n] = 0xff;
200 	}
201 	hashbuf[n++] = 0;
202 
203 	(void) memcpy(&hashbuf[n], prefix, prefixsize);
204 	n += prefixsize;
205 	if ((t = hash->finish(hash, &hashbuf[n])) != expected) {
206 		(void) fprintf(stderr, "rsa_sign: short %s hash\n", hash->name);
207 		return 0;
208 	}
209 
210 	pgp_write(out, &hashbuf[n], 2);
211 
212 	n += t;
213 	if (n != keysize) {
214 		(void) fprintf(stderr, "rsa_sign: n != keysize\n");
215 		return 0;
216 	}
217 
218 	t = pgp_rsa_private_encrypt(sigbuf, hashbuf, keysize, secrsa, pubrsa);
219 	bn = BN_bin2bn(sigbuf, (int)t, NULL);
220 	pgp_write_mpi(out, bn);
221 	BN_free(bn);
222 	return 1;
223 }
224 
225 static int
226 dsa_sign(pgp_hash_t *hash,
227 	 const pgp_dsa_pubkey_t *dsa,
228 	 const pgp_dsa_seckey_t *sdsa,
229 	 pgp_output_t *output)
230 {
231 	unsigned        hashsize;
232 	unsigned        t;
233 	uint8_t		hashbuf[NETPGP_BUFSIZ];
234 	DSA_SIG        *dsasig;
235 	const BIGNUM   *r, *s;
236 
237 	/* hashsize must be "equal in size to the number of bits of q,  */
238 	/* the group generated by the DSA key's generator value */
239 	/* 160/8 = 20 */
240 
241 	hashsize = 20;
242 
243 	/* finalise hash */
244 	t = hash->finish(hash, &hashbuf[0]);
245 	if (t != 20) {
246 		(void) fprintf(stderr, "dsa_sign: hashfinish not 20\n");
247 		return 0;
248 	}
249 
250 	pgp_write(output, &hashbuf[0], 2);
251 
252 	/* write signature to buf */
253 	dsasig = pgp_dsa_sign(hashbuf, hashsize, sdsa, dsa);
254 
255 	/* convert and write the sig out to memory */
256 #if OPENSSL_VERSION_NUMBER >= 0x10100000
257 	DSA_SIG_get0(dsasig, &r, &s);
258 #else
259 	r = dsasig->r;
260 	s = dsasig->s;
261 #endif
262 	pgp_write_mpi(output, r);
263 	pgp_write_mpi(output, s);
264 	DSA_SIG_free(dsasig);
265 	return 1;
266 }
267 
268 static unsigned
269 rsa_verify(pgp_hash_alg_t type,
270 	   const uint8_t *hash,
271 	   size_t hash_length,
272 	   const pgp_rsa_sig_t *sig,
273 	   const pgp_rsa_pubkey_t *pubrsa)
274 {
275 	const uint8_t	*prefix;
276 	unsigned       	 n;
277 	unsigned       	 keysize;
278 	unsigned	 plen;
279 	unsigned	 debug_len_decrypted;
280 	uint8_t   	 sigbuf[NETPGP_BUFSIZ];
281 	uint8_t   	 hashbuf_from_sig[NETPGP_BUFSIZ];
282 
283 	plen = 0;
284 	prefix = (const uint8_t *) "";
285 	keysize = BN_num_bytes(pubrsa->n);
286 	/* RSA key can't be bigger than 65535 bits, so... */
287 	if (keysize > sizeof(hashbuf_from_sig)) {
288 		(void) fprintf(stderr, "rsa_verify: keysize too big\n");
289 		return 0;
290 	}
291 	if ((unsigned) BN_num_bits(sig->sig) > 8 * sizeof(sigbuf)) {
292 		(void) fprintf(stderr, "rsa_verify: BN_numbits too big\n");
293 		return 0;
294 	}
295 	BN_bn2bin(sig->sig, sigbuf);
296 
297 	n = pgp_rsa_public_decrypt(hashbuf_from_sig, sigbuf,
298 		(unsigned)(BN_num_bits(sig->sig) + 7) / 8, pubrsa);
299 	debug_len_decrypted = n;
300 
301 	if (n != keysize) {
302 		/* obviously, this includes error returns */
303 		return 0;
304 	}
305 
306 	/* XXX: why is there a leading 0? The first byte should be 1... */
307 	/* XXX: because the decrypt should use keysize and not sigsize? */
308 	if (hashbuf_from_sig[0] != 0 || hashbuf_from_sig[1] != 1) {
309 		return 0;
310 	}
311 
312 	switch (type) {
313 	case PGP_HASH_MD5:
314 		prefix = prefix_md5;
315 		plen = sizeof(prefix_md5);
316 		break;
317 	case PGP_HASH_SHA1:
318 		prefix = prefix_sha1;
319 		plen = sizeof(prefix_sha1);
320 		break;
321 	case PGP_HASH_SHA256:
322 		prefix = prefix_sha256;
323 		plen = sizeof(prefix_sha256);
324 		break;
325 	default:
326 		(void) fprintf(stderr, "Unknown hash algorithm: %d\n", type);
327 		return 0;
328 	}
329 
330 	if (keysize - plen - hash_length < 10) {
331 		return 0;
332 	}
333 
334 	for (n = 2; n < keysize - plen - hash_length - 1; ++n) {
335 		if (hashbuf_from_sig[n] != 0xff) {
336 			return 0;
337 		}
338 	}
339 
340 	if (hashbuf_from_sig[n++] != 0) {
341 		return 0;
342 	}
343 
344 	if (pgp_get_debug_level(__FILE__)) {
345 		hexdump(stderr, "sig hashbuf", hashbuf_from_sig, debug_len_decrypted);
346 		hexdump(stderr, "prefix", prefix, plen);
347 		hexdump(stderr, "sig hash", &hashbuf_from_sig[n + plen], hash_length);
348 		hexdump(stderr, "input hash", hash, hash_length);
349 	}
350 	return (memcmp(&hashbuf_from_sig[n], prefix, plen) == 0 &&
351 	        memcmp(&hashbuf_from_sig[n + plen], hash, hash_length) == 0);
352 }
353 
354 static void
355 hash_add_key(pgp_hash_t *hash, const pgp_pubkey_t *key)
356 {
357 	pgp_memory_t	*mem = pgp_memory_new();
358 	const unsigned 	 dontmakepacket = 0;
359 	size_t		 len;
360 
361 	pgp_build_pubkey(mem, key, dontmakepacket);
362 	len = pgp_mem_len(mem);
363 	pgp_hash_add_int(hash, 0x99, 1);
364 	pgp_hash_add_int(hash, (unsigned)len, 2);
365 	hash->add(hash, pgp_mem_data(mem), (unsigned)len);
366 	pgp_memory_free(mem);
367 }
368 
369 static void
370 initialise_hash(pgp_hash_t *hash, const pgp_sig_t *sig)
371 {
372 	pgp_hash_any(hash, sig->info.hash_alg);
373 	if (!hash->init(hash)) {
374 		(void) fprintf(stderr,
375 			"initialise_hash: bad hash init\n");
376 		/* just continue and die */
377 		/* XXX - agc - no way to return failure */
378 	}
379 }
380 
381 static void
382 init_key_sig(pgp_hash_t *hash, const pgp_sig_t *sig,
383 		   const pgp_pubkey_t *key)
384 {
385 	initialise_hash(hash, sig);
386 	hash_add_key(hash, key);
387 }
388 
389 static void
390 hash_add_trailer(pgp_hash_t *hash, const pgp_sig_t *sig,
391 		 const uint8_t *raw_packet)
392 {
393 	if (sig->info.version == PGP_V4) {
394 		if (raw_packet) {
395 			hash->add(hash, raw_packet + sig->v4_hashstart,
396 				  (unsigned)sig->info.v4_hashlen);
397 		}
398 		pgp_hash_add_int(hash, (unsigned)sig->info.version, 1);
399 		pgp_hash_add_int(hash, 0xff, 1);
400 		pgp_hash_add_int(hash, (unsigned)sig->info.v4_hashlen, 4);
401 	} else {
402 		pgp_hash_add_int(hash, (unsigned)sig->info.type, 1);
403 		pgp_hash_add_int(hash, (unsigned)sig->info.birthtime, 4);
404 	}
405 }
406 
407 /**
408    \ingroup Core_Signature
409    \brief Checks a signature
410    \param hash Signature Hash to be checked
411    \param length Signature Length
412    \param sig The Signature to be checked
413    \param signer The signer's public key
414    \return 1 if good; else 0
415 */
416 unsigned
417 pgp_check_sig(const uint8_t *hash, unsigned length,
418 		    const pgp_sig_t * sig,
419 		    const pgp_pubkey_t * signer)
420 {
421 	unsigned   ret;
422 
423 	if (pgp_get_debug_level(__FILE__)) {
424 		hexdump(stdout, "hash", hash, length);
425 	}
426 	ret = 0;
427 	switch (sig->info.key_alg) {
428 	case PGP_PKA_DSA:
429 		ret = pgp_dsa_verify(hash, length, &sig->info.sig.dsa,
430 				&signer->key.dsa);
431 		break;
432 
433 	case PGP_PKA_RSA:
434 		ret = rsa_verify(sig->info.hash_alg, hash, length,
435 				&sig->info.sig.rsa,
436 				&signer->key.rsa);
437 		break;
438 
439 	default:
440 		(void) fprintf(stderr, "pgp_check_sig: unusual alg\n");
441 		ret = 0;
442 	}
443 
444 	return ret;
445 }
446 
447 static unsigned
448 hash_and_check_sig(pgp_hash_t *hash,
449 			 const pgp_sig_t *sig,
450 			 const pgp_pubkey_t *signer)
451 {
452 	uint8_t   hashout[PGP_MAX_HASH_SIZE];
453 	unsigned	n;
454 
455 	n = hash->finish(hash, hashout);
456 	return pgp_check_sig(hashout, n, sig, signer);
457 }
458 
459 static unsigned
460 finalise_sig(pgp_hash_t *hash,
461 		   const pgp_sig_t *sig,
462 		   const pgp_pubkey_t *signer,
463 		   const uint8_t *raw_packet)
464 {
465 	hash_add_trailer(hash, sig, raw_packet);
466 	return hash_and_check_sig(hash, sig, signer);
467 }
468 
469 /**
470  * \ingroup Core_Signature
471  *
472  * \brief Verify a certification signature.
473  *
474  * \param key The public key that was signed.
475  * \param id The user ID that was signed
476  * \param sig The signature.
477  * \param signer The public key of the signer.
478  * \param raw_packet The raw signature packet.
479  * \return 1 if OK; else 0
480  */
481 unsigned
482 pgp_check_useridcert_sig(const pgp_pubkey_t *key,
483 			  const uint8_t *id,
484 			  const pgp_sig_t *sig,
485 			  const pgp_pubkey_t *signer,
486 			  const uint8_t *raw_packet)
487 {
488 	pgp_hash_t	hash;
489 	size_t          userid_len;
490 
491 	userid_len = strlen((const char *) id);
492 	init_key_sig(&hash, sig, key);
493 	if (sig->info.version == PGP_V4) {
494 		pgp_hash_add_int(&hash, 0xb4, 1);
495 		pgp_hash_add_int(&hash, (unsigned)userid_len, 4);
496 	}
497 	hash.add(&hash, id, (unsigned)userid_len);
498 	return finalise_sig(&hash, sig, signer, raw_packet);
499 }
500 
501 /**
502  * \ingroup Core_Signature
503  *
504  * Verify a certification signature.
505  *
506  * \param key The public key that was signed.
507  * \param attribute The user attribute that was signed
508  * \param sig The signature.
509  * \param signer The public key of the signer.
510  * \param raw_packet The raw signature packet.
511  * \return 1 if OK; else 0
512  */
513 unsigned
514 pgp_check_userattrcert_sig(const pgp_pubkey_t *key,
515 				const pgp_data_t *attribute,
516 				const pgp_sig_t *sig,
517 				const pgp_pubkey_t *signer,
518 				const uint8_t *raw_packet)
519 {
520 	pgp_hash_t      hash;
521 
522 	init_key_sig(&hash, sig, key);
523 	if (sig->info.version == PGP_V4) {
524 		pgp_hash_add_int(&hash, 0xd1, 1);
525 		pgp_hash_add_int(&hash, (unsigned)attribute->len, 4);
526 	}
527 	hash.add(&hash, attribute->contents, (unsigned)attribute->len);
528 	return finalise_sig(&hash, sig, signer, raw_packet);
529 }
530 
531 /**
532  * \ingroup Core_Signature
533  *
534  * Verify a subkey signature.
535  *
536  * \param key The public key whose subkey was signed.
537  * \param subkey The subkey of the public key that was signed.
538  * \param sig The signature.
539  * \param signer The public key of the signer.
540  * \param raw_packet The raw signature packet.
541  * \return 1 if OK; else 0
542  */
543 unsigned
544 pgp_check_subkey_sig(const pgp_pubkey_t *key,
545 			   const pgp_pubkey_t *subkey,
546 			   const pgp_sig_t *sig,
547 			   const pgp_pubkey_t *signer,
548 			   const uint8_t *raw_packet)
549 {
550 	pgp_hash_t	hash;
551 	unsigned	ret;
552 
553 	init_key_sig(&hash, sig, key);
554 	hash_add_key(&hash, subkey);
555 	ret = finalise_sig(&hash, sig, signer, raw_packet);
556 	return ret;
557 }
558 
559 /**
560  * \ingroup Core_Signature
561  *
562  * Verify a direct signature.
563  *
564  * \param key The public key which was signed.
565  * \param sig The signature.
566  * \param signer The public key of the signer.
567  * \param raw_packet The raw signature packet.
568  * \return 1 if OK; else 0
569  */
570 unsigned
571 pgp_check_direct_sig(const pgp_pubkey_t *key,
572 			   const pgp_sig_t *sig,
573 			   const pgp_pubkey_t *signer,
574 			   const uint8_t *raw_packet)
575 {
576 	pgp_hash_t	hash;
577 	unsigned	ret;
578 
579 	init_key_sig(&hash, sig, key);
580 	ret = finalise_sig(&hash, sig, signer, raw_packet);
581 	return ret;
582 }
583 
584 /**
585  * \ingroup Core_Signature
586  *
587  * Verify a signature on a hash (the hash will have already been fed
588  * the material that was being signed, for example signed cleartext).
589  *
590  * \param hash A hash structure of appropriate type that has been fed
591  * the material to be signed. This MUST NOT have been finalised.
592  * \param sig The signature to be verified.
593  * \param signer The public key of the signer.
594  * \return 1 if OK; else 0
595  */
596 unsigned
597 pgp_check_hash_sig(pgp_hash_t *hash,
598 			 const pgp_sig_t *sig,
599 			 const pgp_pubkey_t *signer)
600 {
601 	return (sig->info.hash_alg == hash->alg) ?
602 		finalise_sig(hash, sig, signer, NULL) :
603 		0;
604 }
605 
606 static void
607 start_sig_in_mem(pgp_create_sig_t *sig)
608 {
609 	/* since this has subpackets and stuff, we have to buffer the whole */
610 	/* thing to get counts before writing. */
611 	sig->mem = pgp_memory_new();
612 	pgp_memory_init(sig->mem, 100);
613 	pgp_writer_set_memory(sig->output, sig->mem);
614 
615 	/* write nearly up to the first subpacket */
616 	pgp_write_scalar(sig->output, (unsigned)sig->sig.info.version, 1);
617 	pgp_write_scalar(sig->output, (unsigned)sig->sig.info.type, 1);
618 	pgp_write_scalar(sig->output, (unsigned)sig->sig.info.key_alg, 1);
619 	pgp_write_scalar(sig->output, (unsigned)sig->sig.info.hash_alg, 1);
620 
621 	/* dummy hashed subpacket count */
622 	sig->hashoff = (unsigned)pgp_mem_len(sig->mem);
623 	pgp_write_scalar(sig->output, 0, 2);
624 }
625 
626 /**
627  * \ingroup Core_Signature
628  *
629  * pgp_sig_start() creates a V4 public key signature with a SHA1 hash.
630  *
631  * \param sig The signature structure to initialise
632  * \param key The public key to be signed
633  * \param id The user ID being bound to the key
634  * \param type Signature type
635  */
636 void
637 pgp_sig_start_key_sig(pgp_create_sig_t *sig,
638 				  const pgp_pubkey_t *key,
639 				  const uint8_t *id,
640 				  pgp_sig_type_t type)
641 {
642 	sig->output = pgp_output_new();
643 
644 	/* XXX:  refactor with check (in several ways - check should
645 	 * probably use the buffered writer to construct packets
646 	 * (done), and also should share code for hash calculation) */
647 	sig->sig.info.version = PGP_V4;
648 	sig->sig.info.hash_alg = PGP_HASH_SHA1;
649 	sig->sig.info.key_alg = key->alg;
650 	sig->sig.info.type = type;
651 	sig->hashlen = (unsigned)-1;
652 	init_key_sig(&sig->hash, &sig->sig, key);
653 	pgp_hash_add_int(&sig->hash, 0xb4, 1);
654 	pgp_hash_add_int(&sig->hash, (unsigned)strlen((const char *) id), 4);
655 	sig->hash.add(&sig->hash, id, (unsigned)strlen((const char *) id));
656 	start_sig_in_mem(sig);
657 }
658 
659 /**
660  * \ingroup Core_Signature
661  *
662  * Create a V4 public key signature over some cleartext.
663  *
664  * \param sig The signature structure to initialise
665  * \param id
666  * \param type
667  * \todo Expand description. Allow other hashes.
668  */
669 
670 void
671 pgp_start_sig(pgp_create_sig_t *sig,
672 	      const pgp_seckey_t *key,
673 	      const pgp_hash_alg_t hash,
674 	      const pgp_sig_type_t type)
675 {
676 	sig->output = pgp_output_new();
677 
678 	/* XXX:  refactor with check (in several ways - check should
679 	 * probably use the buffered writer to construct packets
680 	 * (done), and also should share code for hash calculation) */
681 	sig->sig.info.version = PGP_V4;
682 	sig->sig.info.key_alg = key->pubkey.alg;
683 	sig->sig.info.hash_alg = hash;
684 	sig->sig.info.type = type;
685 
686 	sig->hashlen = (unsigned)-1;
687 
688 	if (pgp_get_debug_level(__FILE__)) {
689 		fprintf(stderr, "initialising hash for sig in mem\n");
690 	}
691 	initialise_hash(&sig->hash, &sig->sig);
692 	start_sig_in_mem(sig);
693 }
694 
695 /**
696  * \ingroup Core_Signature
697  *
698  * Add plaintext data to a signature-to-be.
699  *
700  * \param sig The signature-to-be.
701  * \param buf The plaintext data.
702  * \param length The amount of plaintext data.
703  */
704 void
705 pgp_sig_add_data(pgp_create_sig_t *sig, const void *buf, size_t length)
706 {
707 	sig->hash.add(&sig->hash, buf, (unsigned)length);
708 }
709 
710 /**
711  * \ingroup Core_Signature
712  *
713  * Mark the end of the hashed subpackets in the signature
714  *
715  * \param sig
716  */
717 
718 unsigned
719 pgp_end_hashed_subpkts(pgp_create_sig_t *sig)
720 {
721 	sig->hashlen = (unsigned)(pgp_mem_len(sig->mem) - sig->hashoff - 2);
722 	pgp_memory_place_int(sig->mem, sig->hashoff, sig->hashlen, 2);
723 	/* dummy unhashed subpacket count */
724 	sig->unhashoff = (unsigned)pgp_mem_len(sig->mem);
725 	return pgp_write_scalar(sig->output, 0, 2);
726 }
727 
728 /**
729  * \ingroup Core_Signature
730  *
731  * Write out a signature
732  *
733  * \param sig
734  * \param key
735  * \param seckey
736  * \param info
737  *
738  */
739 
740 unsigned
741 pgp_write_sig(pgp_output_t *output,
742 			pgp_create_sig_t *sig,
743 			const pgp_pubkey_t *key,
744 			const pgp_seckey_t *seckey)
745 {
746 	unsigned	ret = 0;
747 	size_t		len = pgp_mem_len(sig->mem);
748 
749 	/* check key not decrypted */
750 	switch (seckey->pubkey.alg) {
751 	case PGP_PKA_RSA:
752 	case PGP_PKA_RSA_ENCRYPT_ONLY:
753 	case PGP_PKA_RSA_SIGN_ONLY:
754 		if (seckey->key.rsa.d == NULL) {
755 			(void) fprintf(stderr, "pgp_write_sig: null rsa.d\n");
756 			return 0;
757 		}
758 		break;
759 
760 	case PGP_PKA_DSA:
761 		if (seckey->key.dsa.x == NULL) {
762 			(void) fprintf(stderr, "pgp_write_sig: null dsa.x\n");
763 			return 0;
764 		}
765 		break;
766 
767 	default:
768 		(void) fprintf(stderr, "Unsupported algorithm %d\n",
769 				seckey->pubkey.alg);
770 		return 0;
771 	}
772 
773 	if (sig->hashlen == (unsigned) -1) {
774 		(void) fprintf(stderr,
775 				"ops_write_sig: bad hashed data len\n");
776 		return 0;
777 	}
778 
779 	pgp_memory_place_int(sig->mem, sig->unhashoff,
780 			     (unsigned)(len - sig->unhashoff - 2), 2);
781 
782 	/* add the packet from version number to end of hashed subpackets */
783 	if (pgp_get_debug_level(__FILE__)) {
784 		(void) fprintf(stderr, "ops_write_sig: hashed packet info\n");
785 	}
786 	sig->hash.add(&sig->hash, pgp_mem_data(sig->mem), sig->unhashoff);
787 
788 	/* add final trailer */
789 	pgp_hash_add_int(&sig->hash, (unsigned)sig->sig.info.version, 1);
790 	pgp_hash_add_int(&sig->hash, 0xff, 1);
791 	/* +6 for version, type, pk alg, hash alg, hashed subpacket length */
792 	pgp_hash_add_int(&sig->hash, sig->hashlen + 6, 4);
793 
794 	if (pgp_get_debug_level(__FILE__)) {
795 		(void) fprintf(stderr, "ops_write_sig: done writing hashed\n");
796 	}
797 	/* XXX: technically, we could figure out how big the signature is */
798 	/* and write it directly to the output instead of via memory. */
799 	switch (seckey->pubkey.alg) {
800 	case PGP_PKA_RSA:
801 	case PGP_PKA_RSA_ENCRYPT_ONLY:
802 	case PGP_PKA_RSA_SIGN_ONLY:
803 		if (!rsa_sign(&sig->hash, &key->key.rsa, &seckey->key.rsa,
804 				sig->output)) {
805 			(void) fprintf(stderr,
806 				"pgp_write_sig: rsa_sign failure\n");
807 			return 0;
808 		}
809 		break;
810 
811 	case PGP_PKA_DSA:
812 		if (!dsa_sign(&sig->hash, &key->key.dsa, &seckey->key.dsa,
813 				sig->output)) {
814 			(void) fprintf(stderr,
815 				"pgp_write_sig: dsa_sign failure\n");
816 			return 0;
817 		}
818 		break;
819 
820 	default:
821 		(void) fprintf(stderr, "Unsupported algorithm %d\n",
822 					seckey->pubkey.alg);
823 		return 0;
824 	}
825 
826 	ret = pgp_write_ptag(output, PGP_PTAG_CT_SIGNATURE);
827 	if (ret) {
828 		len = pgp_mem_len(sig->mem);
829 		ret = pgp_write_length(output, (unsigned)len) &&
830 			pgp_write(output, pgp_mem_data(sig->mem), (unsigned)len);
831 	}
832 	pgp_memory_free(sig->mem);
833 
834 	if (ret == 0) {
835 		PGP_ERROR_1(&output->errors, PGP_E_W, "%s",
836 		    "Cannot write signature");
837 	}
838 	return ret;
839 }
840 
841 /* add a time stamp to the output */
842 unsigned
843 pgp_add_time(pgp_create_sig_t *sig, int64_t when, const char *type)
844 {
845 	pgp_content_enum	tag;
846 
847 	tag = (strcmp(type, "birth") == 0) ?
848 		PGP_PTAG_SS_CREATION_TIME : PGP_PTAG_SS_EXPIRATION_TIME;
849 	/* just do 32-bit timestamps for just now - it's in the protocol */
850 	return pgp_write_ss_header(sig->output, 5, tag) &&
851 		pgp_write_scalar(sig->output, (uint32_t)when, (unsigned)sizeof(uint32_t));
852 }
853 
854 /**
855  * \ingroup Core_Signature
856  *
857  * Adds issuer's key ID to the signature
858  *
859  * \param sig
860  * \param keyid
861  */
862 
863 unsigned
864 pgp_add_issuer_keyid(pgp_create_sig_t *sig,
865 				const uint8_t keyid[PGP_KEY_ID_SIZE])
866 {
867 	return pgp_write_ss_header(sig->output, PGP_KEY_ID_SIZE + 1,
868 				PGP_PTAG_SS_ISSUER_KEY_ID) &&
869 		pgp_write(sig->output, keyid, PGP_KEY_ID_SIZE);
870 }
871 
872 /**
873  * \ingroup Core_Signature
874  *
875  * Adds primary user ID to the signature
876  *
877  * \param sig
878  * \param primary
879  */
880 void
881 pgp_add_primary_userid(pgp_create_sig_t *sig, unsigned primary)
882 {
883 	pgp_write_ss_header(sig->output, 2, PGP_PTAG_SS_PRIMARY_USER_ID);
884 	pgp_write_scalar(sig->output, primary, 1);
885 }
886 
887 /**
888  * \ingroup Core_Signature
889  *
890  * Get the hash structure in use for the signature.
891  *
892  * \param sig The signature structure.
893  * \return The hash structure.
894  */
895 pgp_hash_t     *
896 pgp_sig_get_hash(pgp_create_sig_t *sig)
897 {
898 	return &sig->hash;
899 }
900 
901 /* open up an output file */
902 static int
903 open_output_file(pgp_output_t **output,
904 			const char *inname,
905 			const char *outname,
906 			const char *suffix,
907 			const unsigned overwrite)
908 {
909 	int             fd;
910 
911 	/* setup output file */
912 	if (outname) {
913 		if (strcmp(outname, "-") == 0) {
914 			fd = pgp_setup_file_write(output, NULL, overwrite);
915 		} else {
916 			fd = pgp_setup_file_write(output, outname, overwrite);
917 		}
918 	} else {
919 		size_t          flen = strlen(inname) + 1 + strlen(suffix) + 1;
920 		char           *f = NULL;
921 
922 		if ((f = calloc(1, flen)) == NULL) {
923 			(void) fprintf(stderr, "open_output_file: bad alloc\n");
924 			fd = -1;
925 		} else {
926 			(void) snprintf(f, flen, "%s.%s", inname, suffix);
927 			fd = pgp_setup_file_write(output, f, overwrite);
928 			free(f);
929 		}
930 	}
931 	return fd;
932 }
933 
934 /**
935 \ingroup HighLevel_Sign
936 \brief Sign a file
937 \param inname Input filename
938 \param outname Output filename. If NULL, a name is constructed from the input filename.
939 \param seckey Secret Key to use for signing
940 \param armored Write armoured text, if set.
941 \param overwrite May overwrite existing file, if set.
942 \return 1 if OK; else 0;
943 
944 */
945 unsigned
946 pgp_sign_file(pgp_io_t *io,
947 		const char *inname,
948 		const char *outname,
949 		const pgp_seckey_t *seckey,
950 		const char *hashname,
951 		const int64_t from,
952 		const uint64_t duration,
953 		const unsigned armored,
954 		const unsigned cleartext,
955 		const unsigned overwrite)
956 {
957 	pgp_create_sig_t	*sig;
958 	pgp_sig_type_t	 sig_type;
959 	pgp_hash_alg_t	 hash_alg;
960 	pgp_memory_t		*infile;
961 	pgp_output_t		*output;
962 	pgp_hash_t		*hash;
963 	unsigned		 ret;
964 	uint8_t			 keyid[PGP_KEY_ID_SIZE];
965 	int			 fd_out;
966 
967 	sig = NULL;
968 	sig_type = PGP_SIG_BINARY;
969 	infile = NULL;
970 	output = NULL;
971 	hash = NULL;
972 	fd_out = 0;
973 
974 	/* find the hash algorithm */
975 	hash_alg = pgp_str_to_hash_alg(hashname);
976 	if (hash_alg == PGP_HASH_UNKNOWN) {
977 		(void) fprintf(io->errs,
978 			"pgp_sign_file: unknown hash algorithm: \"%s\"\n",
979 			hashname);
980 		return 0;
981 	}
982 
983 	/* read input file into buf */
984 	infile = pgp_memory_new();
985 	if (!pgp_mem_readfile(infile, inname)) {
986 		return 0;
987 	}
988 
989 	/* setup output file */
990 	fd_out = open_output_file(&output, inname, outname,
991 				(armored) ? "asc" : "gpg", overwrite);
992 	if (fd_out < 0) {
993 		pgp_memory_free(infile);
994 		return 0;
995 	}
996 
997 	/* set up signature */
998 	sig = pgp_create_sig_new();
999 	if (!sig) {
1000 		pgp_memory_free(infile);
1001 		pgp_teardown_file_write(output, fd_out);
1002 		return 0;
1003 	}
1004 
1005 	pgp_start_sig(sig, seckey, hash_alg, sig_type);
1006 
1007 	if (cleartext) {
1008 		if (pgp_writer_push_clearsigned(output, sig) != 1) {
1009 			return 0;
1010 		}
1011 
1012 		/* Do the signing */
1013 		pgp_write(output, pgp_mem_data(infile), (unsigned)pgp_mem_len(infile));
1014 		pgp_memory_free(infile);
1015 
1016 		/* add signature with subpackets: */
1017 		/* - creation time */
1018 		/* - key id */
1019 		ret = pgp_writer_use_armored_sig(output) &&
1020 				pgp_add_time(sig, (int64_t)from, "birth") &&
1021 				pgp_add_time(sig, (int64_t)duration, "expiration");
1022 		if (ret == 0) {
1023 			pgp_teardown_file_write(output, fd_out);
1024 			return 0;
1025 		}
1026 
1027 		pgp_keyid(keyid, PGP_KEY_ID_SIZE, &seckey->pubkey, hash_alg);
1028 		ret = pgp_add_issuer_keyid(sig, keyid) &&
1029 			pgp_end_hashed_subpkts(sig) &&
1030 			pgp_write_sig(output, sig, &seckey->pubkey, seckey);
1031 
1032 		pgp_teardown_file_write(output, fd_out);
1033 
1034 		if (ret == 0) {
1035 			PGP_ERROR_1(&output->errors, PGP_E_W, "%s",
1036 			    "Cannot sign file as cleartext");
1037 		}
1038 	} else {
1039 		/* set armoured/not armoured here */
1040 		if (armored) {
1041 			pgp_writer_push_armor_msg(output);
1042 		}
1043 
1044 		/* write one_pass_sig */
1045 		pgp_write_one_pass_sig(output, seckey, hash_alg, sig_type);
1046 
1047 		/* hash file contents */
1048 		hash = pgp_sig_get_hash(sig);
1049 		hash->add(hash, pgp_mem_data(infile), (unsigned)pgp_mem_len(infile));
1050 
1051 #if 1
1052 		/* output file contents as Literal Data packet */
1053 		pgp_write_litdata(output, pgp_mem_data(infile),
1054 			(const int)pgp_mem_len(infile),
1055 			PGP_LDT_BINARY);
1056 #else
1057 		/* XXX - agc - sync with writer.c 1094 for ops_writez */
1058 		pgp_setup_memory_write(&litoutput, &litmem, bufsz);
1059 		pgp_setup_memory_write(&zoutput, &zmem, bufsz);
1060 		pgp_write_litdata(litoutput,
1061 			pgp_mem_data(pgp_mem_data(infile),
1062 			(const int)pgp_mem_len(infile), PGP_LDT_BINARY);
1063 		pgp_writez(zoutput, pgp_mem_data(litmem), pgp_mem_len(litmem));
1064 #endif
1065 
1066 		/* add creation time to signature */
1067 		pgp_add_time(sig, (int64_t)from, "birth");
1068 		pgp_add_time(sig, (int64_t)duration, "expiration");
1069 		/* add key id to signature */
1070 		pgp_keyid(keyid, PGP_KEY_ID_SIZE, &seckey->pubkey, hash_alg);
1071 		pgp_add_issuer_keyid(sig, keyid);
1072 		pgp_end_hashed_subpkts(sig);
1073 		pgp_write_sig(output, sig, &seckey->pubkey, seckey);
1074 
1075 		/* tidy up */
1076 		pgp_teardown_file_write(output, fd_out);
1077 
1078 		pgp_create_sig_delete(sig);
1079 		pgp_memory_free(infile);
1080 
1081 		ret = 1;
1082 	}
1083 
1084 	return ret;
1085 }
1086 
1087 /**
1088 \ingroup HighLevel_Sign
1089 \brief Signs a buffer
1090 \param input Input text to be signed
1091 \param input_len Length of input text
1092 \param sig_type Signature type
1093 \param seckey Secret Key
1094 \param armored Write armoured text, if set
1095 \return New pgp_memory_t struct containing signed text
1096 \note It is the caller's responsibility to call pgp_memory_free(me)
1097 
1098 */
1099 pgp_memory_t *
1100 pgp_sign_buf(pgp_io_t *io,
1101 		const void *input,
1102 		const size_t insize,
1103 		const pgp_seckey_t *seckey,
1104 		const int64_t from,
1105 		const uint64_t duration,
1106 		const char *hashname,
1107 		const unsigned armored,
1108 		const unsigned cleartext)
1109 {
1110 	pgp_litdata_enum	 ld_type;
1111 	pgp_create_sig_t	*sig;
1112 	pgp_sig_type_t	 sig_type;
1113 	pgp_hash_alg_t	 hash_alg;
1114 	pgp_output_t		*output;
1115 	pgp_memory_t		*mem;
1116 	uint8_t			 keyid[PGP_KEY_ID_SIZE];
1117 	pgp_hash_t		*hash;
1118 	unsigned		 ret;
1119 
1120 	sig = NULL;
1121 	sig_type = PGP_SIG_BINARY;
1122 	output = NULL;
1123 	mem = pgp_memory_new();
1124 	hash = NULL;
1125 	ret = 0;
1126 
1127 	hash_alg = pgp_str_to_hash_alg(hashname);
1128 	if (hash_alg == PGP_HASH_UNKNOWN) {
1129 		(void) fprintf(io->errs,
1130 			"pgp_sign_buf: unknown hash algorithm: \"%s\"\n",
1131 			hashname);
1132 		return NULL;
1133 	}
1134 
1135 	/* setup literal data packet type */
1136 	ld_type = (cleartext) ? PGP_LDT_TEXT : PGP_LDT_BINARY;
1137 
1138 	if (input == NULL) {
1139 		(void) fprintf(io->errs,
1140 			"pgp_sign_buf: null input\n");
1141 		return NULL;
1142 	}
1143 
1144 	/* set up signature */
1145 	if ((sig = pgp_create_sig_new()) == NULL) {
1146 		return NULL;
1147 	}
1148 	pgp_start_sig(sig, seckey, hash_alg, sig_type);
1149 
1150 	/* setup writer */
1151 	pgp_setup_memory_write(&output, &mem, insize);
1152 
1153 	if (cleartext) {
1154 		/* Do the signing */
1155 		/* add signature with subpackets: */
1156 		/* - creation time */
1157 		/* - key id */
1158 		ret = pgp_writer_push_clearsigned(output, sig) &&
1159 			pgp_write(output, input, (unsigned)insize) &&
1160 			pgp_writer_use_armored_sig(output) &&
1161 			pgp_add_time(sig, from, "birth") &&
1162 			pgp_add_time(sig, (int64_t)duration, "expiration");
1163 		if (ret == 0) {
1164 			return NULL;
1165 		}
1166 		pgp_output_delete(output);
1167 	} else {
1168 		/* set armoured/not armoured here */
1169 		if (armored) {
1170 			pgp_writer_push_armor_msg(output);
1171 		}
1172 		if (pgp_get_debug_level(__FILE__)) {
1173 			fprintf(io->errs, "** Writing out one pass sig\n");
1174 		}
1175 		/* write one_pass_sig */
1176 		pgp_write_one_pass_sig(output, seckey, hash_alg, sig_type);
1177 
1178 		/* hash memory */
1179 		hash = pgp_sig_get_hash(sig);
1180 		hash->add(hash, input, (unsigned)insize);
1181 
1182 		/* output file contents as Literal Data packet */
1183 		if (pgp_get_debug_level(__FILE__)) {
1184 			(void) fprintf(stderr, "** Writing out data now\n");
1185 		}
1186 		pgp_write_litdata(output, input, (const int)insize, ld_type);
1187 		if (pgp_get_debug_level(__FILE__)) {
1188 			fprintf(stderr, "** After Writing out data now\n");
1189 		}
1190 
1191 		/* add creation time to signature */
1192 		pgp_add_time(sig, from, "birth");
1193 		pgp_add_time(sig, (int64_t)duration, "expiration");
1194 		/* add key id to signature */
1195 		pgp_keyid(keyid, PGP_KEY_ID_SIZE, &seckey->pubkey, hash_alg);
1196 		pgp_add_issuer_keyid(sig, keyid);
1197 		pgp_end_hashed_subpkts(sig);
1198 
1199 		/* write out sig */
1200 		pgp_write_sig(output, sig, &seckey->pubkey, seckey);
1201 
1202 		/* tidy up */
1203 		pgp_writer_close(output);
1204 		pgp_create_sig_delete(sig);
1205 	}
1206 	return mem;
1207 }
1208 
1209 /* sign a file, and put the signature in a separate file */
1210 int
1211 pgp_sign_detached(pgp_io_t *io,
1212 			const char *f,
1213 			char *sigfile,
1214 			pgp_seckey_t *seckey,
1215 			const char *hash,
1216 			const int64_t from,
1217 			const uint64_t duration,
1218 			const unsigned armored, const unsigned overwrite)
1219 {
1220 	pgp_create_sig_t	*sig;
1221 	pgp_hash_alg_t	 hash_alg;
1222 	pgp_output_t		*output;
1223 	pgp_memory_t		*mem;
1224 	uint8_t	 	 	 keyid[PGP_KEY_ID_SIZE];
1225 	int			 fd;
1226 
1227 	/* find out which hash algorithm to use */
1228 	hash_alg = pgp_str_to_hash_alg(hash);
1229 	if (hash_alg == PGP_HASH_UNKNOWN) {
1230 		(void) fprintf(io->errs,"Unknown hash algorithm: %s\n", hash);
1231 		return 0;
1232 	}
1233 
1234 	/* setup output file */
1235 	fd = open_output_file(&output, f, sigfile,
1236 				(armored) ? "asc" : "sig", overwrite);
1237 	if (fd < 0) {
1238 		(void) fprintf(io->errs,"Can't open output file: %s\n", f);
1239 		return 0;
1240 	}
1241 
1242 	/* create a new signature */
1243 	sig = pgp_create_sig_new();
1244 	pgp_start_sig(sig, seckey, hash_alg, PGP_SIG_BINARY);
1245 
1246 	/* read the contents of 'f', and add that to the signature */
1247 	mem = pgp_memory_new();
1248 	if (!pgp_mem_readfile(mem, f)) {
1249 		pgp_teardown_file_write(output, fd);
1250 		return 0;
1251 	}
1252 	/* set armoured/not armoured here */
1253 	if (armored) {
1254 		pgp_writer_push_armor_msg(output);
1255 	}
1256 	pgp_sig_add_data(sig, pgp_mem_data(mem), pgp_mem_len(mem));
1257 	pgp_memory_free(mem);
1258 
1259 	/* calculate the signature */
1260 	pgp_add_time(sig, from, "birth");
1261 	pgp_add_time(sig, (int64_t)duration, "expiration");
1262 	pgp_keyid(keyid, sizeof(keyid), &seckey->pubkey, hash_alg);
1263 	pgp_add_issuer_keyid(sig, keyid);
1264 	pgp_end_hashed_subpkts(sig);
1265 	pgp_write_sig(output, sig, &seckey->pubkey, seckey);
1266 	pgp_teardown_file_write(output, fd);
1267 	pgp_seckey_free(seckey);
1268 
1269 	return 1;
1270 }
1271