xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/signature.c (revision c505c4429840c353a86d4eb53b5e2bfc0092264e)
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.29 2010/06/25 03:37:27 agc 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 __ops_create_sig_t {
94 	__ops_hash_t		 hash;
95 	__ops_sig_t		 sig;
96 	__ops_memory_t		*mem;
97 	__ops_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 __ops_create_sig_t
106    \return new __ops_create_sig_t
107    \note It is the caller's responsibility to call __ops_create_sig_delete()
108    \sa __ops_create_sig_delete()
109 */
110 __ops_create_sig_t *
111 __ops_create_sig_new(void)
112 {
113 	return calloc(1, sizeof(__ops_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 __ops_create_sig_new()
121 */
122 void
123 __ops_create_sig_delete(__ops_create_sig_t *sig)
124 {
125 	__ops_output_delete(sig->output);
126 	sig->output = NULL;
127 	free(sig);
128 }
129 
130 #if 0
131 void
132 __ops_dump_sig(__ops_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(__ops_hash_t *hash,
157 	const __ops_rsa_pubkey_t *pubrsa,
158 	const __ops_rsa_seckey_t *secrsa,
159 	__ops_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 = OPS_SHA1_HASH_SIZE + sizeof(prefix_sha1);
174 		prefix = prefix_sha1;
175 		prefixsize = sizeof(prefix_sha1);
176 		expected = OPS_SHA1_HASH_SIZE;
177 	} else {
178 		hashsize = OPS_SHA256_HASH_SIZE + sizeof(prefix_sha256);
179 		prefix = prefix_sha256;
180 		prefixsize = sizeof(prefix_sha256);
181 		expected = OPS_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 (__ops_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 	__ops_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 = __ops_rsa_private_encrypt(sigbuf, hashbuf, keysize, secrsa, pubrsa);
219 	bn = BN_bin2bn(sigbuf, (int)t, NULL);
220 	__ops_write_mpi(out, bn);
221 	BN_free(bn);
222 	return 1;
223 }
224 
225 static int
226 dsa_sign(__ops_hash_t *hash,
227 	 const __ops_dsa_pubkey_t *dsa,
228 	 const __ops_dsa_seckey_t *sdsa,
229 	 __ops_output_t *output)
230 {
231 	unsigned        hashsize;
232 	unsigned        t;
233 	uint8_t		hashbuf[NETPGP_BUFSIZ];
234 	DSA_SIG        *dsasig;
235 
236 	/* hashsize must be "equal in size to the number of bits of q,  */
237 	/* the group generated by the DSA key's generator value */
238 	/* 160/8 = 20 */
239 
240 	hashsize = 20;
241 
242 	/* finalise hash */
243 	t = hash->finish(hash, &hashbuf[0]);
244 	if (t != 20) {
245 		(void) fprintf(stderr, "dsa_sign: hashfinish not 20\n");
246 		return 0;
247 	}
248 
249 	__ops_write(output, &hashbuf[0], 2);
250 
251 	/* write signature to buf */
252 	dsasig = __ops_dsa_sign(hashbuf, hashsize, sdsa, dsa);
253 
254 	/* convert and write the sig out to memory */
255 	__ops_write_mpi(output, dsasig->r);
256 	__ops_write_mpi(output, dsasig->s);
257 	DSA_SIG_free(dsasig);
258 	return 1;
259 }
260 
261 static unsigned
262 rsa_verify(__ops_hash_alg_t type,
263 	   const uint8_t *hash,
264 	   size_t hash_length,
265 	   const __ops_rsa_sig_t *sig,
266 	   const __ops_rsa_pubkey_t *pubrsa)
267 {
268 	const uint8_t	*prefix;
269 	unsigned       	 n;
270 	unsigned       	 keysize;
271 	unsigned	 plen;
272 	unsigned	 debug_len_decrypted;
273 	uint8_t   	 sigbuf[NETPGP_BUFSIZ];
274 	uint8_t   	 hashbuf_from_sig[NETPGP_BUFSIZ];
275 
276 	plen = 0;
277 	prefix = (const uint8_t *) "";
278 	keysize = BN_num_bytes(pubrsa->n);
279 	/* RSA key can't be bigger than 65535 bits, so... */
280 	if (keysize > sizeof(hashbuf_from_sig)) {
281 		(void) fprintf(stderr, "rsa_verify: keysize too big\n");
282 		return 0;
283 	}
284 	if ((unsigned) BN_num_bits(sig->sig) > 8 * sizeof(sigbuf)) {
285 		(void) fprintf(stderr, "rsa_verify: BN_numbits too big\n");
286 		return 0;
287 	}
288 	BN_bn2bin(sig->sig, sigbuf);
289 
290 	n = __ops_rsa_public_decrypt(hashbuf_from_sig, sigbuf,
291 		(unsigned)(BN_num_bits(sig->sig) + 7) / 8, pubrsa);
292 	debug_len_decrypted = n;
293 
294 	if (n != keysize) {
295 		/* obviously, this includes error returns */
296 		return 0;
297 	}
298 
299 	/* XXX: why is there a leading 0? The first byte should be 1... */
300 	/* XXX: because the decrypt should use keysize and not sigsize? */
301 	if (hashbuf_from_sig[0] != 0 || hashbuf_from_sig[1] != 1) {
302 		return 0;
303 	}
304 
305 	switch (type) {
306 	case OPS_HASH_MD5:
307 		prefix = prefix_md5;
308 		plen = sizeof(prefix_md5);
309 		break;
310 	case OPS_HASH_SHA1:
311 		prefix = prefix_sha1;
312 		plen = sizeof(prefix_sha1);
313 		break;
314 	case OPS_HASH_SHA256:
315 		prefix = prefix_sha256;
316 		plen = sizeof(prefix_sha256);
317 		break;
318 	default:
319 		(void) fprintf(stderr, "Unknown hash algorithm: %d\n", type);
320 		return 0;
321 	}
322 
323 	if (keysize - plen - hash_length < 10) {
324 		return 0;
325 	}
326 
327 	for (n = 2; n < keysize - plen - hash_length - 1; ++n) {
328 		if (hashbuf_from_sig[n] != 0xff) {
329 			return 0;
330 		}
331 	}
332 
333 	if (hashbuf_from_sig[n++] != 0) {
334 		return 0;
335 	}
336 
337 	if (__ops_get_debug_level(__FILE__)) {
338 		hexdump(stderr, "sig hashbuf", hashbuf_from_sig, debug_len_decrypted);
339 		hexdump(stderr, "prefix", prefix, plen);
340 		hexdump(stderr, "sig hash", &hashbuf_from_sig[n + plen], hash_length);
341 		hexdump(stderr, "input hash", hash, hash_length);
342 	}
343 	return (memcmp(&hashbuf_from_sig[n], prefix, plen) == 0 &&
344 	        memcmp(&hashbuf_from_sig[n + plen], hash, hash_length) == 0);
345 }
346 
347 static void
348 hash_add_key(__ops_hash_t *hash, const __ops_pubkey_t *key)
349 {
350 	__ops_memory_t	*mem = __ops_memory_new();
351 	const unsigned 	 dontmakepacket = 0;
352 	size_t		 len;
353 
354 	__ops_build_pubkey(mem, key, dontmakepacket);
355 	len = __ops_mem_len(mem);
356 	__ops_hash_add_int(hash, 0x99, 1);
357 	__ops_hash_add_int(hash, len, 2);
358 	hash->add(hash, __ops_mem_data(mem), len);
359 	__ops_memory_free(mem);
360 }
361 
362 static void
363 initialise_hash(__ops_hash_t *hash, const __ops_sig_t *sig)
364 {
365 	__ops_hash_any(hash, sig->info.hash_alg);
366 	if (!hash->init(hash)) {
367 		(void) fprintf(stderr,
368 			"initialise_hash: bad hash init\n");
369 		/* just continue and die */
370 		/* XXX - agc - no way to return failure */
371 	}
372 }
373 
374 static void
375 init_key_sig(__ops_hash_t *hash, const __ops_sig_t *sig,
376 		   const __ops_pubkey_t *key)
377 {
378 	initialise_hash(hash, sig);
379 	hash_add_key(hash, key);
380 }
381 
382 static void
383 hash_add_trailer(__ops_hash_t *hash, const __ops_sig_t *sig,
384 		 const uint8_t *raw_packet)
385 {
386 	if (sig->info.version == OPS_V4) {
387 		if (raw_packet) {
388 			hash->add(hash, raw_packet + sig->v4_hashstart,
389 				  sig->info.v4_hashlen);
390 		}
391 		__ops_hash_add_int(hash, (unsigned)sig->info.version, 1);
392 		__ops_hash_add_int(hash, 0xff, 1);
393 		__ops_hash_add_int(hash, sig->info.v4_hashlen, 4);
394 	} else {
395 		__ops_hash_add_int(hash, (unsigned)sig->info.type, 1);
396 		__ops_hash_add_int(hash, (unsigned)sig->info.birthtime, 4);
397 	}
398 }
399 
400 /**
401    \ingroup Core_Signature
402    \brief Checks a signature
403    \param hash Signature Hash to be checked
404    \param length Signature Length
405    \param sig The Signature to be checked
406    \param signer The signer's public key
407    \return 1 if good; else 0
408 */
409 unsigned
410 __ops_check_sig(const uint8_t *hash, unsigned length,
411 		    const __ops_sig_t * sig,
412 		    const __ops_pubkey_t * signer)
413 {
414 	unsigned   ret;
415 
416 	if (__ops_get_debug_level(__FILE__)) {
417 		hexdump(stdout, "hash", hash, length);
418 	}
419 	ret = 0;
420 	switch (sig->info.key_alg) {
421 	case OPS_PKA_DSA:
422 		ret = __ops_dsa_verify(hash, length, &sig->info.sig.dsa,
423 				&signer->key.dsa);
424 		break;
425 
426 	case OPS_PKA_RSA:
427 		ret = rsa_verify(sig->info.hash_alg, hash, length,
428 				&sig->info.sig.rsa,
429 				&signer->key.rsa);
430 		break;
431 
432 	default:
433 		(void) fprintf(stderr, "__ops_check_sig: unusual alg\n");
434 		ret = 0;
435 	}
436 
437 	return ret;
438 }
439 
440 static unsigned
441 hash_and_check_sig(__ops_hash_t *hash,
442 			 const __ops_sig_t *sig,
443 			 const __ops_pubkey_t *signer)
444 {
445 	uint8_t   hashout[OPS_MAX_HASH_SIZE];
446 	unsigned	n;
447 
448 	n = hash->finish(hash, hashout);
449 	return __ops_check_sig(hashout, n, sig, signer);
450 }
451 
452 static unsigned
453 finalise_sig(__ops_hash_t *hash,
454 		   const __ops_sig_t *sig,
455 		   const __ops_pubkey_t *signer,
456 		   const uint8_t *raw_packet)
457 {
458 	hash_add_trailer(hash, sig, raw_packet);
459 	return hash_and_check_sig(hash, sig, signer);
460 }
461 
462 /**
463  * \ingroup Core_Signature
464  *
465  * \brief Verify a certification signature.
466  *
467  * \param key The public key that was signed.
468  * \param id The user ID that was signed
469  * \param sig The signature.
470  * \param signer The public key of the signer.
471  * \param raw_packet The raw signature packet.
472  * \return 1 if OK; else 0
473  */
474 unsigned
475 __ops_check_useridcert_sig(const __ops_pubkey_t *key,
476 			  const uint8_t *id,
477 			  const __ops_sig_t *sig,
478 			  const __ops_pubkey_t *signer,
479 			  const uint8_t *raw_packet)
480 {
481 	__ops_hash_t	hash;
482 	size_t          userid_len;
483 
484 	userid_len = strlen((const char *) id);
485 	init_key_sig(&hash, sig, key);
486 	if (sig->info.version == OPS_V4) {
487 		__ops_hash_add_int(&hash, 0xb4, 1);
488 		__ops_hash_add_int(&hash, userid_len, 4);
489 	}
490 	hash.add(&hash, id, userid_len);
491 	return finalise_sig(&hash, sig, signer, raw_packet);
492 }
493 
494 /**
495  * \ingroup Core_Signature
496  *
497  * Verify a certification signature.
498  *
499  * \param key The public key that was signed.
500  * \param attribute The user attribute that was signed
501  * \param sig The signature.
502  * \param signer The public key of the signer.
503  * \param raw_packet The raw signature packet.
504  * \return 1 if OK; else 0
505  */
506 unsigned
507 __ops_check_userattrcert_sig(const __ops_pubkey_t *key,
508 				const __ops_data_t *attribute,
509 				const __ops_sig_t *sig,
510 				const __ops_pubkey_t *signer,
511 				const uint8_t *raw_packet)
512 {
513 	__ops_hash_t      hash;
514 
515 	init_key_sig(&hash, sig, key);
516 	if (sig->info.version == OPS_V4) {
517 		__ops_hash_add_int(&hash, 0xd1, 1);
518 		__ops_hash_add_int(&hash, attribute->len, 4);
519 	}
520 	hash.add(&hash, attribute->contents, attribute->len);
521 	return finalise_sig(&hash, sig, signer, raw_packet);
522 }
523 
524 /**
525  * \ingroup Core_Signature
526  *
527  * Verify a subkey signature.
528  *
529  * \param key The public key whose subkey was signed.
530  * \param subkey The subkey of the public key that was signed.
531  * \param sig The signature.
532  * \param signer The public key of the signer.
533  * \param raw_packet The raw signature packet.
534  * \return 1 if OK; else 0
535  */
536 unsigned
537 __ops_check_subkey_sig(const __ops_pubkey_t *key,
538 			   const __ops_pubkey_t *subkey,
539 			   const __ops_sig_t *sig,
540 			   const __ops_pubkey_t *signer,
541 			   const uint8_t *raw_packet)
542 {
543 	__ops_hash_t	hash;
544 	unsigned	ret;
545 
546 	init_key_sig(&hash, sig, key);
547 	hash_add_key(&hash, subkey);
548 	ret = finalise_sig(&hash, sig, signer, raw_packet);
549 	return ret;
550 }
551 
552 /**
553  * \ingroup Core_Signature
554  *
555  * Verify a direct signature.
556  *
557  * \param key The public key which was signed.
558  * \param sig The signature.
559  * \param signer The public key of the signer.
560  * \param raw_packet The raw signature packet.
561  * \return 1 if OK; else 0
562  */
563 unsigned
564 __ops_check_direct_sig(const __ops_pubkey_t *key,
565 			   const __ops_sig_t *sig,
566 			   const __ops_pubkey_t *signer,
567 			   const uint8_t *raw_packet)
568 {
569 	__ops_hash_t	hash;
570 	unsigned	ret;
571 
572 	init_key_sig(&hash, sig, key);
573 	ret = finalise_sig(&hash, sig, signer, raw_packet);
574 	return ret;
575 }
576 
577 /**
578  * \ingroup Core_Signature
579  *
580  * Verify a signature on a hash (the hash will have already been fed
581  * the material that was being signed, for example signed cleartext).
582  *
583  * \param hash A hash structure of appropriate type that has been fed
584  * the material to be signed. This MUST NOT have been finalised.
585  * \param sig The signature to be verified.
586  * \param signer The public key of the signer.
587  * \return 1 if OK; else 0
588  */
589 unsigned
590 __ops_check_hash_sig(__ops_hash_t *hash,
591 			 const __ops_sig_t *sig,
592 			 const __ops_pubkey_t *signer)
593 {
594 	return (sig->info.hash_alg == hash->alg) ?
595 		finalise_sig(hash, sig, signer, NULL) :
596 		0;
597 }
598 
599 static void
600 start_sig_in_mem(__ops_create_sig_t *sig)
601 {
602 	/* since this has subpackets and stuff, we have to buffer the whole */
603 	/* thing to get counts before writing. */
604 	sig->mem = __ops_memory_new();
605 	__ops_memory_init(sig->mem, 100);
606 	__ops_writer_set_memory(sig->output, sig->mem);
607 
608 	/* write nearly up to the first subpacket */
609 	__ops_write_scalar(sig->output, (unsigned)sig->sig.info.version, 1);
610 	__ops_write_scalar(sig->output, (unsigned)sig->sig.info.type, 1);
611 	__ops_write_scalar(sig->output, (unsigned)sig->sig.info.key_alg, 1);
612 	__ops_write_scalar(sig->output, (unsigned)sig->sig.info.hash_alg, 1);
613 
614 	/* dummy hashed subpacket count */
615 	sig->hashoff = __ops_mem_len(sig->mem);
616 	__ops_write_scalar(sig->output, 0, 2);
617 }
618 
619 /**
620  * \ingroup Core_Signature
621  *
622  * __ops_sig_start() creates a V4 public key signature with a SHA1 hash.
623  *
624  * \param sig The signature structure to initialise
625  * \param key The public key to be signed
626  * \param id The user ID being bound to the key
627  * \param type Signature type
628  */
629 void
630 __ops_sig_start_key_sig(__ops_create_sig_t *sig,
631 				  const __ops_pubkey_t *key,
632 				  const uint8_t *id,
633 				  __ops_sig_type_t type)
634 {
635 	sig->output = __ops_output_new();
636 
637 	/* XXX:  refactor with check (in several ways - check should
638 	 * probably use the buffered writer to construct packets
639 	 * (done), and also should share code for hash calculation) */
640 	sig->sig.info.version = OPS_V4;
641 	sig->sig.info.hash_alg = OPS_HASH_SHA1;
642 	sig->sig.info.key_alg = key->alg;
643 	sig->sig.info.type = type;
644 	sig->hashlen = (unsigned)-1;
645 	init_key_sig(&sig->hash, &sig->sig, key);
646 	__ops_hash_add_int(&sig->hash, 0xb4, 1);
647 	__ops_hash_add_int(&sig->hash, strlen((const char *) id), 4);
648 	sig->hash.add(&sig->hash, id, strlen((const char *) id));
649 	start_sig_in_mem(sig);
650 }
651 
652 /**
653  * \ingroup Core_Signature
654  *
655  * Create a V4 public key signature over some cleartext.
656  *
657  * \param sig The signature structure to initialise
658  * \param id
659  * \param type
660  * \todo Expand description. Allow other hashes.
661  */
662 
663 void
664 __ops_start_sig(__ops_create_sig_t *sig,
665 	      const __ops_seckey_t *key,
666 	      const __ops_hash_alg_t hash,
667 	      const __ops_sig_type_t type)
668 {
669 	sig->output = __ops_output_new();
670 
671 	/* XXX:  refactor with check (in several ways - check should
672 	 * probably use the buffered writer to construct packets
673 	 * (done), and also should share code for hash calculation) */
674 	sig->sig.info.version = OPS_V4;
675 	sig->sig.info.key_alg = key->pubkey.alg;
676 	sig->sig.info.hash_alg = hash;
677 	sig->sig.info.type = type;
678 
679 	sig->hashlen = (unsigned)-1;
680 
681 	if (__ops_get_debug_level(__FILE__)) {
682 		fprintf(stderr, "initialising hash for sig in mem\n");
683 	}
684 	initialise_hash(&sig->hash, &sig->sig);
685 	start_sig_in_mem(sig);
686 }
687 
688 /**
689  * \ingroup Core_Signature
690  *
691  * Add plaintext data to a signature-to-be.
692  *
693  * \param sig The signature-to-be.
694  * \param buf The plaintext data.
695  * \param length The amount of plaintext data.
696  */
697 void
698 __ops_sig_add_data(__ops_create_sig_t *sig, const void *buf, size_t length)
699 {
700 	sig->hash.add(&sig->hash, buf, length);
701 }
702 
703 /**
704  * \ingroup Core_Signature
705  *
706  * Mark the end of the hashed subpackets in the signature
707  *
708  * \param sig
709  */
710 
711 unsigned
712 __ops_end_hashed_subpkts(__ops_create_sig_t *sig)
713 {
714 	sig->hashlen = __ops_mem_len(sig->mem) - sig->hashoff - 2;
715 	__ops_memory_place_int(sig->mem, sig->hashoff, sig->hashlen, 2);
716 	/* dummy unhashed subpacket count */
717 	sig->unhashoff = __ops_mem_len(sig->mem);
718 	return __ops_write_scalar(sig->output, 0, 2);
719 }
720 
721 /**
722  * \ingroup Core_Signature
723  *
724  * Write out a signature
725  *
726  * \param sig
727  * \param key
728  * \param seckey
729  * \param info
730  *
731  */
732 
733 unsigned
734 __ops_write_sig(__ops_output_t *output,
735 			__ops_create_sig_t *sig,
736 			const __ops_pubkey_t *key,
737 			const __ops_seckey_t *seckey)
738 {
739 	unsigned	ret = 0;
740 	size_t		len = __ops_mem_len(sig->mem);
741 
742 	/* check key not decrypted */
743 	switch (seckey->pubkey.alg) {
744 	case OPS_PKA_RSA:
745 	case OPS_PKA_RSA_ENCRYPT_ONLY:
746 	case OPS_PKA_RSA_SIGN_ONLY:
747 		if (seckey->key.rsa.d == NULL) {
748 			(void) fprintf(stderr, "__ops_write_sig: null rsa.d\n");
749 			return 0;
750 		}
751 		break;
752 
753 	case OPS_PKA_DSA:
754 		if (seckey->key.dsa.x == NULL) {
755 			(void) fprintf(stderr, "__ops_write_sig: null dsa.x\n");
756 			return 0;
757 		}
758 		break;
759 
760 	default:
761 		(void) fprintf(stderr, "Unsupported algorithm %d\n",
762 				seckey->pubkey.alg);
763 		return 0;
764 	}
765 
766 	if (sig->hashlen == (unsigned) -1) {
767 		(void) fprintf(stderr,
768 				"ops_write_sig: bad hashed data len\n");
769 		return 0;
770 	}
771 
772 	__ops_memory_place_int(sig->mem, sig->unhashoff,
773 			     len - sig->unhashoff - 2, 2);
774 
775 	/* add the packet from version number to end of hashed subpackets */
776 	if (__ops_get_debug_level(__FILE__)) {
777 		(void) fprintf(stderr, "ops_write_sig: hashed packet info\n");
778 	}
779 	sig->hash.add(&sig->hash, __ops_mem_data(sig->mem), sig->unhashoff);
780 
781 	/* add final trailer */
782 	__ops_hash_add_int(&sig->hash, (unsigned)sig->sig.info.version, 1);
783 	__ops_hash_add_int(&sig->hash, 0xff, 1);
784 	/* +6 for version, type, pk alg, hash alg, hashed subpacket length */
785 	__ops_hash_add_int(&sig->hash, sig->hashlen + 6, 4);
786 
787 	if (__ops_get_debug_level(__FILE__)) {
788 		(void) fprintf(stderr, "ops_write_sig: done writing hashed\n");
789 	}
790 	/* XXX: technically, we could figure out how big the signature is */
791 	/* and write it directly to the output instead of via memory. */
792 	switch (seckey->pubkey.alg) {
793 	case OPS_PKA_RSA:
794 	case OPS_PKA_RSA_ENCRYPT_ONLY:
795 	case OPS_PKA_RSA_SIGN_ONLY:
796 		if (!rsa_sign(&sig->hash, &key->key.rsa, &seckey->key.rsa,
797 				sig->output)) {
798 			(void) fprintf(stderr,
799 				"__ops_write_sig: rsa_sign failure\n");
800 			return 0;
801 		}
802 		break;
803 
804 	case OPS_PKA_DSA:
805 		if (!dsa_sign(&sig->hash, &key->key.dsa, &seckey->key.dsa,
806 				sig->output)) {
807 			(void) fprintf(stderr,
808 				"__ops_write_sig: dsa_sign failure\n");
809 			return 0;
810 		}
811 		break;
812 
813 	default:
814 		(void) fprintf(stderr, "Unsupported algorithm %d\n",
815 					seckey->pubkey.alg);
816 		return 0;
817 	}
818 
819 	ret = __ops_write_ptag(output, OPS_PTAG_CT_SIGNATURE);
820 	if (ret) {
821 		len = __ops_mem_len(sig->mem);
822 		ret = __ops_write_length(output, len) &&
823 			__ops_write(output, __ops_mem_data(sig->mem), len);
824 	}
825 	__ops_memory_free(sig->mem);
826 
827 	if (ret == 0) {
828 		OPS_ERROR(&output->errors, OPS_E_W, "Cannot write signature");
829 	}
830 	return ret;
831 }
832 
833 /**
834  * \ingroup Core_Signature
835  *
836  * __ops_add_birthtime() adds a creation time to the signature.
837  *
838  * \param sig
839  * \param when
840  */
841 unsigned
842 __ops_add_birthtime(__ops_create_sig_t *sig, time_t when)
843 {
844 	return __ops_write_ss_header(sig->output, 5,
845 					OPS_PTAG_SS_CREATION_TIME) &&
846 		__ops_write_scalar(sig->output, (unsigned)when, 4);
847 }
848 
849 /**
850  * __ops_add_expiry() adds an expiration amount (duration) to the signature.
851  *
852  */
853 unsigned
854 __ops_add_expiration(__ops_create_sig_t *sig, time_t duration)
855 {
856 	uint32_t	d;
857 
858 	d = (uint32_t)duration;
859 	return __ops_write_ss_header(sig->output, 5,
860 					OPS_PTAG_SS_EXPIRATION_TIME) &&
861 		__ops_write_scalar(sig->output, (unsigned)d, 4);
862 }
863 
864 /**
865  * \ingroup Core_Signature
866  *
867  * Adds issuer's key ID to the signature
868  *
869  * \param sig
870  * \param keyid
871  */
872 
873 unsigned
874 __ops_add_issuer_keyid(__ops_create_sig_t *sig,
875 				const uint8_t keyid[OPS_KEY_ID_SIZE])
876 {
877 	return __ops_write_ss_header(sig->output, OPS_KEY_ID_SIZE + 1,
878 				OPS_PTAG_SS_ISSUER_KEY_ID) &&
879 		__ops_write(sig->output, keyid, OPS_KEY_ID_SIZE);
880 }
881 
882 /**
883  * \ingroup Core_Signature
884  *
885  * Adds primary user ID to the signature
886  *
887  * \param sig
888  * \param primary
889  */
890 void
891 __ops_add_primary_userid(__ops_create_sig_t *sig, unsigned primary)
892 {
893 	__ops_write_ss_header(sig->output, 2, OPS_PTAG_SS_PRIMARY_USER_ID);
894 	__ops_write_scalar(sig->output, primary, 1);
895 }
896 
897 /**
898  * \ingroup Core_Signature
899  *
900  * Get the hash structure in use for the signature.
901  *
902  * \param sig The signature structure.
903  * \return The hash structure.
904  */
905 __ops_hash_t     *
906 __ops_sig_get_hash(__ops_create_sig_t *sig)
907 {
908 	return &sig->hash;
909 }
910 
911 /* open up an output file */
912 static int
913 open_output_file(__ops_output_t **output,
914 			const char *inname,
915 			const char *outname,
916 			const char *suffix,
917 			const unsigned overwrite)
918 {
919 	int             fd;
920 
921 	/* setup output file */
922 	if (outname) {
923 		fd = __ops_setup_file_write(output, outname, overwrite);
924 	} else {
925 		unsigned        flen = strlen(inname) + 4 + 1;
926 		char           *f = NULL;
927 
928 		if ((f = calloc(1, flen)) == NULL) {
929 			(void) fprintf(stderr, "open_output_file: bad alloc\n");
930 			fd = -1;
931 		} else {
932 			(void) snprintf(f, flen, "%s.%s", inname, suffix);
933 			fd = __ops_setup_file_write(output, f, overwrite);
934 			free(f);
935 		}
936 	}
937 	return fd;
938 }
939 
940 /**
941 \ingroup HighLevel_Sign
942 \brief Sign a file
943 \param inname Input filename
944 \param outname Output filename. If NULL, a name is constructed from the input filename.
945 \param seckey Secret Key to use for signing
946 \param armored Write armoured text, if set.
947 \param overwrite May overwrite existing file, if set.
948 \return 1 if OK; else 0;
949 
950 */
951 unsigned
952 __ops_sign_file(__ops_io_t *io,
953 		const char *inname,
954 		const char *outname,
955 		const __ops_seckey_t *seckey,
956 		const char *hashname,
957 		const int64_t from,
958 		const uint64_t duration,
959 		const unsigned armored,
960 		const unsigned cleartext,
961 		const unsigned overwrite)
962 {
963 	__ops_create_sig_t	*sig;
964 	__ops_sig_type_t	 sig_type;
965 	__ops_hash_alg_t	 hash_alg;
966 	__ops_memory_t		*infile;
967 	__ops_output_t		*output;
968 	__ops_hash_t		*hash;
969 	unsigned		 ret;
970 	uint8_t			 keyid[OPS_KEY_ID_SIZE];
971 	int			 fd_out;
972 
973 	sig = NULL;
974 	sig_type = OPS_SIG_BINARY;
975 	infile = NULL;
976 	output = NULL;
977 	hash = NULL;
978 	fd_out = 0;
979 
980 	/* find the hash algorithm */
981 	hash_alg = __ops_str_to_hash_alg(hashname);
982 	if (hash_alg == OPS_HASH_UNKNOWN) {
983 		(void) fprintf(io->errs,
984 			"__ops_sign_file: unknown hash algorithm: \"%s\"\n",
985 			hashname);
986 		return 0;
987 	}
988 
989 	/* read input file into buf */
990 	infile = __ops_memory_new();
991 	if (!__ops_mem_readfile(infile, inname)) {
992 		return 0;
993 	}
994 
995 	/* setup output file */
996 	fd_out = open_output_file(&output, inname, outname,
997 				(armored) ? "asc" : "gpg", overwrite);
998 	if (fd_out < 0) {
999 		__ops_memory_free(infile);
1000 		return 0;
1001 	}
1002 
1003 	/* set up signature */
1004 	sig = __ops_create_sig_new();
1005 	if (!sig) {
1006 		__ops_memory_free(infile);
1007 		__ops_teardown_file_write(output, fd_out);
1008 		return 0;
1009 	}
1010 
1011 	__ops_start_sig(sig, seckey, hash_alg, sig_type);
1012 
1013 	if (cleartext) {
1014 		if (__ops_writer_push_clearsigned(output, sig) != 1) {
1015 			return 0;
1016 		}
1017 
1018 		/* Do the signing */
1019 		__ops_write(output, __ops_mem_data(infile), __ops_mem_len(infile));
1020 		__ops_memory_free(infile);
1021 
1022 		/* add signature with subpackets: */
1023 		/* - creation time */
1024 		/* - key id */
1025 		ret = __ops_writer_use_armored_sig(output) &&
1026 				__ops_add_birthtime(sig, (long long)from) &&
1027 				__ops_add_expiration(sig, (long long)duration);
1028 		if (ret == 0) {
1029 			__ops_teardown_file_write(output, fd_out);
1030 			return 0;
1031 		}
1032 
1033 		__ops_keyid(keyid, OPS_KEY_ID_SIZE, &seckey->pubkey, hash_alg);
1034 		ret = __ops_add_issuer_keyid(sig, keyid) &&
1035 			__ops_end_hashed_subpkts(sig) &&
1036 			__ops_write_sig(output, sig, &seckey->pubkey, seckey);
1037 
1038 		__ops_teardown_file_write(output, fd_out);
1039 
1040 		if (ret == 0) {
1041 			OPS_ERROR(&output->errors, OPS_E_W,
1042 					"Cannot sign file as cleartext");
1043 		}
1044 	} else {
1045 		/* set armoured/not armoured here */
1046 		if (armored) {
1047 			__ops_writer_push_armor_msg(output);
1048 		}
1049 
1050 		/* write one_pass_sig */
1051 		__ops_write_one_pass_sig(output, seckey, hash_alg, sig_type);
1052 
1053 		/* hash file contents */
1054 		hash = __ops_sig_get_hash(sig);
1055 		hash->add(hash, __ops_mem_data(infile), __ops_mem_len(infile));
1056 
1057 #if 1
1058 		/* output file contents as Literal Data packet */
1059 		__ops_write_litdata(output, __ops_mem_data(infile),
1060 			(const int)__ops_mem_len(infile),
1061 			OPS_LDT_BINARY);
1062 #else
1063 		/* XXX - agc - sync with writer.c 1094 for ops_writez */
1064 		__ops_setup_memory_write(&litoutput, &litmem, bufsz);
1065 		__ops_setup_memory_write(&zoutput, &zmem, bufsz);
1066 		__ops_write_litdata(litoutput,
1067 			__ops_mem_data(__ops_mem_data(infile),
1068 			(const int)__ops_mem_len(infile), OPS_LDT_BINARY);
1069 		__ops_writez(zoutput, __ops_mem_data(litmem), __ops_mem_len(litmem));
1070 #endif
1071 
1072 		/* add creation time to signature */
1073 		__ops_add_birthtime(sig, (long long)from);
1074 		__ops_add_expiration(sig, (long long)duration);
1075 		/* add key id to signature */
1076 		__ops_keyid(keyid, OPS_KEY_ID_SIZE, &seckey->pubkey, hash_alg);
1077 		__ops_add_issuer_keyid(sig, keyid);
1078 		__ops_end_hashed_subpkts(sig);
1079 		__ops_write_sig(output, sig, &seckey->pubkey, seckey);
1080 
1081 		/* tidy up */
1082 		__ops_teardown_file_write(output, fd_out);
1083 
1084 		__ops_create_sig_delete(sig);
1085 		__ops_memory_free(infile);
1086 
1087 		ret = 1;
1088 	}
1089 
1090 	return ret;
1091 }
1092 
1093 /**
1094 \ingroup HighLevel_Sign
1095 \brief Signs a buffer
1096 \param input Input text to be signed
1097 \param input_len Length of input text
1098 \param sig_type Signature type
1099 \param seckey Secret Key
1100 \param armored Write armoured text, if set
1101 \return New __ops_memory_t struct containing signed text
1102 \note It is the caller's responsibility to call __ops_memory_free(me)
1103 
1104 */
1105 __ops_memory_t *
1106 __ops_sign_buf(__ops_io_t *io,
1107 		const void *input,
1108 		const size_t insize,
1109 		const __ops_seckey_t *seckey,
1110 		const int64_t from,
1111 		const uint64_t duration,
1112 		const char *hashname,
1113 		const unsigned armored,
1114 		const unsigned cleartext)
1115 {
1116 	__ops_litdata_enum	 ld_type;
1117 	__ops_create_sig_t	*sig;
1118 	__ops_sig_type_t	 sig_type;
1119 	__ops_hash_alg_t	 hash_alg;
1120 	__ops_output_t		*output;
1121 	__ops_memory_t		*mem;
1122 	uint8_t			 keyid[OPS_KEY_ID_SIZE];
1123 	__ops_hash_t		*hash;
1124 	unsigned		 ret;
1125 
1126 	sig = NULL;
1127 	sig_type = OPS_SIG_BINARY;
1128 	output = NULL;
1129 	mem = __ops_memory_new();
1130 	hash = NULL;
1131 	ret = 0;
1132 
1133 	hash_alg = __ops_str_to_hash_alg(hashname);
1134 	if (hash_alg == OPS_HASH_UNKNOWN) {
1135 		(void) fprintf(io->errs,
1136 			"__ops_sign_buf: unknown hash algorithm: \"%s\"\n",
1137 			hashname);
1138 		return NULL;
1139 	}
1140 
1141 	/* setup literal data packet type */
1142 	ld_type = (cleartext) ? OPS_LDT_TEXT : OPS_LDT_BINARY;
1143 
1144 	if (input == NULL) {
1145 		(void) fprintf(io->errs,
1146 			"__ops_sign_buf: null input\n");
1147 		return NULL;
1148 	}
1149 
1150 	/* set up signature */
1151 	if ((sig = __ops_create_sig_new()) == NULL) {
1152 		return NULL;
1153 	}
1154 	__ops_start_sig(sig, seckey, hash_alg, sig_type);
1155 
1156 	/* setup writer */
1157 	__ops_setup_memory_write(&output, &mem, insize);
1158 
1159 	if (cleartext) {
1160 		/* Do the signing */
1161 		/* add signature with subpackets: */
1162 		/* - creation time */
1163 		/* - key id */
1164 		ret = __ops_writer_push_clearsigned(output, sig) &&
1165 			__ops_write(output, input, insize) &&
1166 			__ops_writer_use_armored_sig(output) &&
1167 			__ops_add_birthtime(sig, from) &&
1168 			__ops_add_expiration(sig, (long long)duration);
1169 		if (ret == 0) {
1170 			return NULL;
1171 		}
1172 		__ops_output_delete(output);
1173 	} else {
1174 		/* set armoured/not armoured here */
1175 		if (armored) {
1176 			__ops_writer_push_armor_msg(output);
1177 		}
1178 		if (__ops_get_debug_level(__FILE__)) {
1179 			fprintf(io->errs, "** Writing out one pass sig\n");
1180 		}
1181 		/* write one_pass_sig */
1182 		__ops_write_one_pass_sig(output, seckey, hash_alg, sig_type);
1183 
1184 		/* hash memory */
1185 		hash = __ops_sig_get_hash(sig);
1186 		hash->add(hash, input, insize);
1187 
1188 		/* output file contents as Literal Data packet */
1189 		if (__ops_get_debug_level(__FILE__)) {
1190 			(void) fprintf(stderr, "** Writing out data now\n");
1191 		}
1192 		__ops_write_litdata(output, input, (const int)insize, ld_type);
1193 		if (__ops_get_debug_level(__FILE__)) {
1194 			fprintf(stderr, "** After Writing out data now\n");
1195 		}
1196 
1197 		/* add creation time to signature */
1198 		__ops_add_birthtime(sig, from);
1199 		__ops_add_expiration(sig, (long long)duration);
1200 		/* add key id to signature */
1201 		__ops_keyid(keyid, OPS_KEY_ID_SIZE, &seckey->pubkey, hash_alg);
1202 		__ops_add_issuer_keyid(sig, keyid);
1203 		__ops_end_hashed_subpkts(sig);
1204 
1205 		/* write out sig */
1206 		__ops_write_sig(output, sig, &seckey->pubkey, seckey);
1207 
1208 		/* tidy up */
1209 		__ops_writer_close(output);
1210 		__ops_create_sig_delete(sig);
1211 	}
1212 	return mem;
1213 }
1214 
1215 /* sign a file, and put the signature in a separate file */
1216 int
1217 __ops_sign_detached(__ops_io_t *io,
1218 			const char *f,
1219 			char *sigfile,
1220 			__ops_seckey_t *seckey,
1221 			const char *hash,
1222 			const int64_t from,
1223 			const uint64_t duration,
1224 			const unsigned armored, const unsigned overwrite)
1225 {
1226 	__ops_create_sig_t	*sig;
1227 	__ops_hash_alg_t	 hash_alg;
1228 	__ops_output_t		*output;
1229 	__ops_memory_t		*mem;
1230 	uint8_t	 	 	 keyid[OPS_KEY_ID_SIZE];
1231 	int			 fd;
1232 
1233 	/* find out which hash algorithm to use */
1234 	hash_alg = __ops_str_to_hash_alg(hash);
1235 	if (hash_alg == OPS_HASH_UNKNOWN) {
1236 		(void) fprintf(io->errs,"Unknown hash algorithm: %s\n", hash);
1237 		return 0;
1238 	}
1239 
1240 	/* setup output file */
1241 	fd = open_output_file(&output, f, sigfile,
1242 				(armored) ? "asc" : "sig", overwrite);
1243 	if (fd < 0) {
1244 		(void) fprintf(io->errs,"Can't open output file: %s\n", f);
1245 		return 0;
1246 	}
1247 
1248 	/* create a new signature */
1249 	sig = __ops_create_sig_new();
1250 	__ops_start_sig(sig, seckey, hash_alg, OPS_SIG_BINARY);
1251 
1252 	/* read the contents of 'f', and add that to the signature */
1253 	mem = __ops_memory_new();
1254 	if (!__ops_mem_readfile(mem, f)) {
1255 		__ops_teardown_file_write(output, fd);
1256 		return 0;
1257 	}
1258 	/* set armoured/not armoured here */
1259 	if (armored) {
1260 		__ops_writer_push_armor_msg(output);
1261 	}
1262 	__ops_sig_add_data(sig, __ops_mem_data(mem), __ops_mem_len(mem));
1263 	__ops_memory_free(mem);
1264 
1265 	/* calculate the signature */
1266 	__ops_add_birthtime(sig, from);
1267 	__ops_add_expiration(sig, (long long)duration);
1268 	__ops_keyid(keyid, sizeof(keyid), &seckey->pubkey, hash_alg);
1269 	__ops_add_issuer_keyid(sig, keyid);
1270 	__ops_end_hashed_subpkts(sig);
1271 	__ops_write_sig(output, sig, &seckey->pubkey, seckey);
1272 	__ops_teardown_file_write(output, fd);
1273 	__ops_seckey_free(seckey);
1274 
1275 	return 1;
1276 }
1277