xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/signature.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
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.32 2010/08/15 16:36:24 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, (unsigned)len, 2);
358 	hash->add(hash, __ops_mem_data(mem), (unsigned)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 				  (unsigned)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, (unsigned)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, (unsigned)userid_len, 4);
489 	}
490 	hash.add(&hash, id, (unsigned)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, (unsigned)attribute->len, 4);
519 	}
520 	hash.add(&hash, attribute->contents, (unsigned)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 = (unsigned)__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, (unsigned)strlen((const char *) id), 4);
648 	sig->hash.add(&sig->hash, id, (unsigned)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, (unsigned)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 = (unsigned)(__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 = (unsigned)__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 			     (unsigned)(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, (unsigned)len) &&
823 			__ops_write(output, __ops_mem_data(sig->mem), (unsigned)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 /* add a time stamp to the output */
834 unsigned
835 __ops_add_time(__ops_create_sig_t *sig, int64_t when, const char *type)
836 {
837 	__ops_content_enum	tag;
838 
839 	tag = (strcmp(type, "birth") == 0) ?
840 		OPS_PTAG_SS_CREATION_TIME : OPS_PTAG_SS_EXPIRATION_TIME;
841 	/* just do 32-bit timestamps for just now - it's in the protocol */
842 	return __ops_write_ss_header(sig->output, 5, tag) &&
843 		__ops_write_scalar(sig->output, (uint32_t)when, (unsigned)sizeof(uint32_t));
844 }
845 
846 /**
847  * \ingroup Core_Signature
848  *
849  * Adds issuer's key ID to the signature
850  *
851  * \param sig
852  * \param keyid
853  */
854 
855 unsigned
856 __ops_add_issuer_keyid(__ops_create_sig_t *sig,
857 				const uint8_t keyid[OPS_KEY_ID_SIZE])
858 {
859 	return __ops_write_ss_header(sig->output, OPS_KEY_ID_SIZE + 1,
860 				OPS_PTAG_SS_ISSUER_KEY_ID) &&
861 		__ops_write(sig->output, keyid, OPS_KEY_ID_SIZE);
862 }
863 
864 /**
865  * \ingroup Core_Signature
866  *
867  * Adds primary user ID to the signature
868  *
869  * \param sig
870  * \param primary
871  */
872 void
873 __ops_add_primary_userid(__ops_create_sig_t *sig, unsigned primary)
874 {
875 	__ops_write_ss_header(sig->output, 2, OPS_PTAG_SS_PRIMARY_USER_ID);
876 	__ops_write_scalar(sig->output, primary, 1);
877 }
878 
879 /**
880  * \ingroup Core_Signature
881  *
882  * Get the hash structure in use for the signature.
883  *
884  * \param sig The signature structure.
885  * \return The hash structure.
886  */
887 __ops_hash_t     *
888 __ops_sig_get_hash(__ops_create_sig_t *sig)
889 {
890 	return &sig->hash;
891 }
892 
893 /* open up an output file */
894 static int
895 open_output_file(__ops_output_t **output,
896 			const char *inname,
897 			const char *outname,
898 			const char *suffix,
899 			const unsigned overwrite)
900 {
901 	int             fd;
902 
903 	/* setup output file */
904 	if (outname) {
905 		fd = __ops_setup_file_write(output, outname, overwrite);
906 	} else {
907 		unsigned        flen = (unsigned)(strlen(inname) + 4 + 1);
908 		char           *f = NULL;
909 
910 		if ((f = calloc(1, flen)) == NULL) {
911 			(void) fprintf(stderr, "open_output_file: bad alloc\n");
912 			fd = -1;
913 		} else {
914 			(void) snprintf(f, flen, "%s.%s", inname, suffix);
915 			fd = __ops_setup_file_write(output, f, overwrite);
916 			free(f);
917 		}
918 	}
919 	return fd;
920 }
921 
922 /**
923 \ingroup HighLevel_Sign
924 \brief Sign a file
925 \param inname Input filename
926 \param outname Output filename. If NULL, a name is constructed from the input filename.
927 \param seckey Secret Key to use for signing
928 \param armored Write armoured text, if set.
929 \param overwrite May overwrite existing file, if set.
930 \return 1 if OK; else 0;
931 
932 */
933 unsigned
934 __ops_sign_file(__ops_io_t *io,
935 		const char *inname,
936 		const char *outname,
937 		const __ops_seckey_t *seckey,
938 		const char *hashname,
939 		const int64_t from,
940 		const uint64_t duration,
941 		const unsigned armored,
942 		const unsigned cleartext,
943 		const unsigned overwrite)
944 {
945 	__ops_create_sig_t	*sig;
946 	__ops_sig_type_t	 sig_type;
947 	__ops_hash_alg_t	 hash_alg;
948 	__ops_memory_t		*infile;
949 	__ops_output_t		*output;
950 	__ops_hash_t		*hash;
951 	unsigned		 ret;
952 	uint8_t			 keyid[OPS_KEY_ID_SIZE];
953 	int			 fd_out;
954 
955 	sig = NULL;
956 	sig_type = OPS_SIG_BINARY;
957 	infile = NULL;
958 	output = NULL;
959 	hash = NULL;
960 	fd_out = 0;
961 
962 	/* find the hash algorithm */
963 	hash_alg = __ops_str_to_hash_alg(hashname);
964 	if (hash_alg == OPS_HASH_UNKNOWN) {
965 		(void) fprintf(io->errs,
966 			"__ops_sign_file: unknown hash algorithm: \"%s\"\n",
967 			hashname);
968 		return 0;
969 	}
970 
971 	/* read input file into buf */
972 	infile = __ops_memory_new();
973 	if (!__ops_mem_readfile(infile, inname)) {
974 		return 0;
975 	}
976 
977 	/* setup output file */
978 	fd_out = open_output_file(&output, inname, outname,
979 				(armored) ? "asc" : "gpg", overwrite);
980 	if (fd_out < 0) {
981 		__ops_memory_free(infile);
982 		return 0;
983 	}
984 
985 	/* set up signature */
986 	sig = __ops_create_sig_new();
987 	if (!sig) {
988 		__ops_memory_free(infile);
989 		__ops_teardown_file_write(output, fd_out);
990 		return 0;
991 	}
992 
993 	__ops_start_sig(sig, seckey, hash_alg, sig_type);
994 
995 	if (cleartext) {
996 		if (__ops_writer_push_clearsigned(output, sig) != 1) {
997 			return 0;
998 		}
999 
1000 		/* Do the signing */
1001 		__ops_write(output, __ops_mem_data(infile), (unsigned)__ops_mem_len(infile));
1002 		__ops_memory_free(infile);
1003 
1004 		/* add signature with subpackets: */
1005 		/* - creation time */
1006 		/* - key id */
1007 		ret = __ops_writer_use_armored_sig(output) &&
1008 				__ops_add_time(sig, (int64_t)from, "birth") &&
1009 				__ops_add_time(sig, (int64_t)duration, "expiration");
1010 		if (ret == 0) {
1011 			__ops_teardown_file_write(output, fd_out);
1012 			return 0;
1013 		}
1014 
1015 		__ops_keyid(keyid, OPS_KEY_ID_SIZE, &seckey->pubkey, hash_alg);
1016 		ret = __ops_add_issuer_keyid(sig, keyid) &&
1017 			__ops_end_hashed_subpkts(sig) &&
1018 			__ops_write_sig(output, sig, &seckey->pubkey, seckey);
1019 
1020 		__ops_teardown_file_write(output, fd_out);
1021 
1022 		if (ret == 0) {
1023 			OPS_ERROR(&output->errors, OPS_E_W,
1024 					"Cannot sign file as cleartext");
1025 		}
1026 	} else {
1027 		/* set armoured/not armoured here */
1028 		if (armored) {
1029 			__ops_writer_push_armor_msg(output);
1030 		}
1031 
1032 		/* write one_pass_sig */
1033 		__ops_write_one_pass_sig(output, seckey, hash_alg, sig_type);
1034 
1035 		/* hash file contents */
1036 		hash = __ops_sig_get_hash(sig);
1037 		hash->add(hash, __ops_mem_data(infile), (unsigned)__ops_mem_len(infile));
1038 
1039 #if 1
1040 		/* output file contents as Literal Data packet */
1041 		__ops_write_litdata(output, __ops_mem_data(infile),
1042 			(const int)__ops_mem_len(infile),
1043 			OPS_LDT_BINARY);
1044 #else
1045 		/* XXX - agc - sync with writer.c 1094 for ops_writez */
1046 		__ops_setup_memory_write(&litoutput, &litmem, bufsz);
1047 		__ops_setup_memory_write(&zoutput, &zmem, bufsz);
1048 		__ops_write_litdata(litoutput,
1049 			__ops_mem_data(__ops_mem_data(infile),
1050 			(const int)__ops_mem_len(infile), OPS_LDT_BINARY);
1051 		__ops_writez(zoutput, __ops_mem_data(litmem), __ops_mem_len(litmem));
1052 #endif
1053 
1054 		/* add creation time to signature */
1055 		__ops_add_time(sig, (int64_t)from, "birth");
1056 		__ops_add_time(sig, (int64_t)duration, "expiration");
1057 		/* add key id to signature */
1058 		__ops_keyid(keyid, OPS_KEY_ID_SIZE, &seckey->pubkey, hash_alg);
1059 		__ops_add_issuer_keyid(sig, keyid);
1060 		__ops_end_hashed_subpkts(sig);
1061 		__ops_write_sig(output, sig, &seckey->pubkey, seckey);
1062 
1063 		/* tidy up */
1064 		__ops_teardown_file_write(output, fd_out);
1065 
1066 		__ops_create_sig_delete(sig);
1067 		__ops_memory_free(infile);
1068 
1069 		ret = 1;
1070 	}
1071 
1072 	return ret;
1073 }
1074 
1075 /**
1076 \ingroup HighLevel_Sign
1077 \brief Signs a buffer
1078 \param input Input text to be signed
1079 \param input_len Length of input text
1080 \param sig_type Signature type
1081 \param seckey Secret Key
1082 \param armored Write armoured text, if set
1083 \return New __ops_memory_t struct containing signed text
1084 \note It is the caller's responsibility to call __ops_memory_free(me)
1085 
1086 */
1087 __ops_memory_t *
1088 __ops_sign_buf(__ops_io_t *io,
1089 		const void *input,
1090 		const size_t insize,
1091 		const __ops_seckey_t *seckey,
1092 		const int64_t from,
1093 		const uint64_t duration,
1094 		const char *hashname,
1095 		const unsigned armored,
1096 		const unsigned cleartext)
1097 {
1098 	__ops_litdata_enum	 ld_type;
1099 	__ops_create_sig_t	*sig;
1100 	__ops_sig_type_t	 sig_type;
1101 	__ops_hash_alg_t	 hash_alg;
1102 	__ops_output_t		*output;
1103 	__ops_memory_t		*mem;
1104 	uint8_t			 keyid[OPS_KEY_ID_SIZE];
1105 	__ops_hash_t		*hash;
1106 	unsigned		 ret;
1107 
1108 	sig = NULL;
1109 	sig_type = OPS_SIG_BINARY;
1110 	output = NULL;
1111 	mem = __ops_memory_new();
1112 	hash = NULL;
1113 	ret = 0;
1114 
1115 	hash_alg = __ops_str_to_hash_alg(hashname);
1116 	if (hash_alg == OPS_HASH_UNKNOWN) {
1117 		(void) fprintf(io->errs,
1118 			"__ops_sign_buf: unknown hash algorithm: \"%s\"\n",
1119 			hashname);
1120 		return NULL;
1121 	}
1122 
1123 	/* setup literal data packet type */
1124 	ld_type = (cleartext) ? OPS_LDT_TEXT : OPS_LDT_BINARY;
1125 
1126 	if (input == NULL) {
1127 		(void) fprintf(io->errs,
1128 			"__ops_sign_buf: null input\n");
1129 		return NULL;
1130 	}
1131 
1132 	/* set up signature */
1133 	if ((sig = __ops_create_sig_new()) == NULL) {
1134 		return NULL;
1135 	}
1136 	__ops_start_sig(sig, seckey, hash_alg, sig_type);
1137 
1138 	/* setup writer */
1139 	__ops_setup_memory_write(&output, &mem, insize);
1140 
1141 	if (cleartext) {
1142 		/* Do the signing */
1143 		/* add signature with subpackets: */
1144 		/* - creation time */
1145 		/* - key id */
1146 		ret = __ops_writer_push_clearsigned(output, sig) &&
1147 			__ops_write(output, input, (unsigned)insize) &&
1148 			__ops_writer_use_armored_sig(output) &&
1149 			__ops_add_time(sig, from, "birth") &&
1150 			__ops_add_time(sig, (int64_t)duration, "expiration");
1151 		if (ret == 0) {
1152 			return NULL;
1153 		}
1154 		__ops_output_delete(output);
1155 	} else {
1156 		/* set armoured/not armoured here */
1157 		if (armored) {
1158 			__ops_writer_push_armor_msg(output);
1159 		}
1160 		if (__ops_get_debug_level(__FILE__)) {
1161 			fprintf(io->errs, "** Writing out one pass sig\n");
1162 		}
1163 		/* write one_pass_sig */
1164 		__ops_write_one_pass_sig(output, seckey, hash_alg, sig_type);
1165 
1166 		/* hash memory */
1167 		hash = __ops_sig_get_hash(sig);
1168 		hash->add(hash, input, (unsigned)insize);
1169 
1170 		/* output file contents as Literal Data packet */
1171 		if (__ops_get_debug_level(__FILE__)) {
1172 			(void) fprintf(stderr, "** Writing out data now\n");
1173 		}
1174 		__ops_write_litdata(output, input, (const int)insize, ld_type);
1175 		if (__ops_get_debug_level(__FILE__)) {
1176 			fprintf(stderr, "** After Writing out data now\n");
1177 		}
1178 
1179 		/* add creation time to signature */
1180 		__ops_add_time(sig, from, "birth");
1181 		__ops_add_time(sig, (int64_t)duration, "expiration");
1182 		/* add key id to signature */
1183 		__ops_keyid(keyid, OPS_KEY_ID_SIZE, &seckey->pubkey, hash_alg);
1184 		__ops_add_issuer_keyid(sig, keyid);
1185 		__ops_end_hashed_subpkts(sig);
1186 
1187 		/* write out sig */
1188 		__ops_write_sig(output, sig, &seckey->pubkey, seckey);
1189 
1190 		/* tidy up */
1191 		__ops_writer_close(output);
1192 		__ops_create_sig_delete(sig);
1193 	}
1194 	return mem;
1195 }
1196 
1197 /* sign a file, and put the signature in a separate file */
1198 int
1199 __ops_sign_detached(__ops_io_t *io,
1200 			const char *f,
1201 			char *sigfile,
1202 			__ops_seckey_t *seckey,
1203 			const char *hash,
1204 			const int64_t from,
1205 			const uint64_t duration,
1206 			const unsigned armored, const unsigned overwrite)
1207 {
1208 	__ops_create_sig_t	*sig;
1209 	__ops_hash_alg_t	 hash_alg;
1210 	__ops_output_t		*output;
1211 	__ops_memory_t		*mem;
1212 	uint8_t	 	 	 keyid[OPS_KEY_ID_SIZE];
1213 	int			 fd;
1214 
1215 	/* find out which hash algorithm to use */
1216 	hash_alg = __ops_str_to_hash_alg(hash);
1217 	if (hash_alg == OPS_HASH_UNKNOWN) {
1218 		(void) fprintf(io->errs,"Unknown hash algorithm: %s\n", hash);
1219 		return 0;
1220 	}
1221 
1222 	/* setup output file */
1223 	fd = open_output_file(&output, f, sigfile,
1224 				(armored) ? "asc" : "sig", overwrite);
1225 	if (fd < 0) {
1226 		(void) fprintf(io->errs,"Can't open output file: %s\n", f);
1227 		return 0;
1228 	}
1229 
1230 	/* create a new signature */
1231 	sig = __ops_create_sig_new();
1232 	__ops_start_sig(sig, seckey, hash_alg, OPS_SIG_BINARY);
1233 
1234 	/* read the contents of 'f', and add that to the signature */
1235 	mem = __ops_memory_new();
1236 	if (!__ops_mem_readfile(mem, f)) {
1237 		__ops_teardown_file_write(output, fd);
1238 		return 0;
1239 	}
1240 	/* set armoured/not armoured here */
1241 	if (armored) {
1242 		__ops_writer_push_armor_msg(output);
1243 	}
1244 	__ops_sig_add_data(sig, __ops_mem_data(mem), __ops_mem_len(mem));
1245 	__ops_memory_free(mem);
1246 
1247 	/* calculate the signature */
1248 	__ops_add_time(sig, from, "birth");
1249 	__ops_add_time(sig, (int64_t)duration, "expiration");
1250 	__ops_keyid(keyid, sizeof(keyid), &seckey->pubkey, hash_alg);
1251 	__ops_add_issuer_keyid(sig, keyid);
1252 	__ops_end_hashed_subpkts(sig);
1253 	__ops_write_sig(output, sig, &seckey->pubkey, seckey);
1254 	__ops_teardown_file_write(output, fd);
1255 	__ops_seckey_free(seckey);
1256 
1257 	return 1;
1258 }
1259