xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/signature.c (revision 93bf6008f8b7982c1d1a9486e4a4a0e687fe36eb)
1 /*
2  * Copyright (c) 2005-2008 Nominet UK (www.nic.uk)
3  * All rights reserved.
4  * Contributors: Ben Laurie, Rachel Willmer. The Contributors have asserted
5  * their moral rights under the UK Copyright Design and Patents Act 1988 to
6  * be recorded as the authors of this copyright work.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9  * use this file except in compliance with the License.
10  *
11  * You may obtain a copy of the License at
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  */
21 
22 /** \file
23  */
24 #include "config.h"
25 
26 #include "signature.h"
27 #include "crypto.h"
28 #include "create.h"
29 #include "netpgpsdk.h"
30 
31 #include "readerwriter.h"
32 #include "loccreate.h"
33 #include "validate.h"
34 #include "netpgpdefs.h"
35 
36 #ifdef HAVE_ASSERT_H
37 #include <assert.h>
38 #endif
39 
40 #include <string.h>
41 #include <fcntl.h>
42 
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 
47 #ifdef HAVE_OPENSSL_DSA_H
48 #include <openssl/dsa.h>
49 #endif
50 
51 #define MAXBUF 1024		/* <! Standard buffer size to use */
52 
53 /** \ingroup Core_Create
54  * needed for signature creation
55  */
56 struct __ops_create_signature {
57 	__ops_hash_t      hash;
58 	__ops_signature_t sig;
59 	__ops_memory_t   *mem;
60 	__ops_create_info_t *info;/* !< how to do the writing */
61 	unsigned        hashed_count_offset;
62 	unsigned        hashed_data_length;
63 	unsigned        unhashed_count_offset;
64 };
65 
66 /**
67    \ingroup Core_Signature
68    Creates new __ops_create_signature_t
69    \return new __ops_create_signature_t
70    \note It is the caller's responsibility to call __ops_create_signature_delete()
71    \sa __ops_create_signature_delete()
72 */
73 __ops_create_signature_t *
74 __ops_create_signature_new()
75 {
76 	return calloc(1, sizeof(__ops_create_signature_t));
77 }
78 
79 /**
80    \ingroup Core_Signature
81    Free signature and memory associated with it
82    \param sig struct to free
83    \sa __ops_create_signature_new()
84 */
85 void
86 __ops_create_signature_delete(__ops_create_signature_t * sig)
87 {
88 	__ops_create_info_delete(sig->info);
89 	sig->info = NULL;
90 	free(sig);
91 }
92 
93 static unsigned char prefix_md5[] = {0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86,
94 	0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00,
95 0x04, 0x10};
96 
97 static unsigned char prefix_sha1[] = {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0E,
98 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14};
99 
100 static unsigned char prefix_sha256[] = {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
101 	0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
102 0x00, 0x04, 0x20};
103 
104 #if 0
105 /**
106    \ingroup Core_Create
107    implementation of EMSA-PKCS1-v1_5, as defined in OpenPGP RFC
108    \param M
109    \param mLen
110    \param hash_alg Hash algorithm to use
111    \param EM
112    \return true if OK; else false
113 */
114 static bool
115 encode_hash_buf(const unsigned char *M, size_t mLen,
116 		const __ops_hash_algorithm_t hash_alg,
117 		unsigned char *EM
118 )
119 {
120 	/* implementation of EMSA-PKCS1-v1_5, as defined in OpenPGP RFC */
121 
122 	unsigned        i;
123 
124 	int             n = 0;
125 	__ops_hash_t      hash;
126 	int             hash_sz = 0;
127 	int             encoded_hash_sz = 0;
128 	int             prefix_sz = 0;
129 	unsigned        padding_sz = 0;
130 	unsigned        encoded_msg_sz = 0;
131 	unsigned char  *prefix = NULL;
132 
133 	assert(hash_alg == OPS_HASH_SHA1);
134 
135 	/* 1. Apply hash function to M */
136 
137 	__ops_hash_any(&hash, hash_alg);
138 	hash.init(&hash);
139 	hash.add(&hash, M, mLen);
140 
141 	/* \todo combine with rsa_sign */
142 
143 	/* 2. Get hash prefix */
144 
145 	switch (hash_alg) {
146 	case OPS_HASH_SHA1:
147 		prefix = prefix_sha1;
148 		prefix_sz = sizeof(prefix_sha1);
149 		hash_sz = OPS_SHA1_HASH_SIZE;
150 		encoded_hash_sz = hash_sz + prefix_sz;
151 		/* \todo why is Ben using a PS size of 90 in rsa_sign? */
152 		/* (keysize-hashsize-1-2) */
153 		padding_sz = 90;
154 		break;
155 
156 	default:
157 		assert(0);
158 	}
159 
160 	/* \todo 3. Test for len being too short */
161 
162 	/* 4 and 5. Generate PS and EM */
163 
164 	EM[0] = 0x00;
165 	EM[1] = 0x01;
166 
167 	for (i = 0; i < padding_sz; i++)
168 		EM[2 + i] = 0xFF;
169 
170 	i += 2;
171 
172 	EM[i++] = 0x00;
173 
174 	(void) memcpy(&EM[i], prefix, prefix_sz);
175 	i += prefix_sz;
176 
177 	/* finally, write out hashed result */
178 
179 	n = hash.finish(&hash, &EM[i]);
180 
181 	encoded_msg_sz = i + hash_sz - 1;
182 
183 	/* \todo test n for OK response? */
184 
185 	if (__ops_get_debug_level(__FILE__)) {
186 		fprintf(stderr, "Encoded Message: \n");
187 		for (i = 0; i < encoded_msg_sz; i++)
188 			fprintf(stderr, "%2x ", EM[i]);
189 		fprintf(stderr, "\n");
190 	}
191 	return true;
192 }
193 #endif
194 
195 /* XXX: both this and verify would be clearer if the signature were */
196 /* treated as an MPI. */
197 static void
198 rsa_sign(__ops_hash_t * hash, const __ops_rsa_public_key_t * rsa,
199 	 const __ops_rsa_secret_key_t * srsa,
200 	 __ops_create_info_t * opt)
201 {
202 	unsigned char   hashbuf[NETPGP_BUFSIZ];
203 	unsigned char   sigbuf[NETPGP_BUFSIZ];
204 	unsigned        keysize;
205 	unsigned        hashsize;
206 	unsigned        n;
207 	unsigned        t;
208 	BIGNUM         *bn;
209 
210 	/* XXX: we assume hash is sha-1 for now */
211 	hashsize = 20 + sizeof(prefix_sha1);
212 
213 	keysize = (BN_num_bits(rsa->n) + 7) / 8;
214 	assert(keysize <= sizeof(hashbuf));
215 	assert(10 + hashsize <= keysize);
216 
217 	hashbuf[0] = 0;
218 	hashbuf[1] = 1;
219 	if (__ops_get_debug_level(__FILE__)) {
220 		printf("rsa_sign: PS is %d\n", keysize - hashsize - 1 - 2);
221 	}
222 	for (n = 2; n < keysize - hashsize - 1; ++n)
223 		hashbuf[n] = 0xff;
224 	hashbuf[n++] = 0;
225 
226 	(void) memcpy(&hashbuf[n], prefix_sha1, sizeof(prefix_sha1));
227 	n += sizeof(prefix_sha1);
228 
229 	t = hash->finish(hash, &hashbuf[n]);
230 	assert(t == 20);
231 
232 	__ops_write(&hashbuf[n], 2, opt);
233 
234 	n += t;
235 	assert(n == keysize);
236 
237 	t = __ops_rsa_private_encrypt(sigbuf, hashbuf, keysize, srsa, rsa);
238 	bn = BN_bin2bn(sigbuf, t, NULL);
239 	__ops_write_mpi(bn, opt);
240 	BN_free(bn);
241 }
242 
243 static void
244 dsa_sign(__ops_hash_t * hash,
245 	 const __ops_dsa_public_key_t * dsa,
246 	 const __ops_dsa_secret_key_t * sdsa,
247 	 __ops_create_info_t * cinfo)
248 {
249 	unsigned char   hashbuf[NETPGP_BUFSIZ];
250 	unsigned        hashsize;
251 	unsigned        t;
252 	DSA_SIG        *dsasig;
253 
254 	/* hashsize must be "equal in size to the number of bits of q,  */
255 	/* the group generated by the DSA key's generator value */
256 	/* 160/8 = 20 */
257 
258 	hashsize = 20;
259 
260 	/* finalise hash */
261 	t = hash->finish(hash, &hashbuf[0]);
262 	assert(t == 20);
263 
264 	__ops_write(&hashbuf[0], 2, cinfo);
265 
266 	/* write signature to buf */
267 	dsasig = __ops_dsa_sign(hashbuf, hashsize, sdsa, dsa);
268 
269 	/* convert and write the sig out to memory */
270 	__ops_write_mpi(dsasig->r, cinfo);
271 	__ops_write_mpi(dsasig->s, cinfo);
272 	DSA_SIG_free(dsasig);
273 }
274 
275 static bool
276 rsa_verify(__ops_hash_algorithm_t type,
277 	   const unsigned char *hash,
278 	   size_t hash_length,
279 	   const __ops_rsa_signature_t * sig,
280 	   const __ops_rsa_public_key_t * rsa)
281 {
282 	unsigned char   sigbuf[NETPGP_BUFSIZ];
283 	unsigned char   hashbuf_from_sig[NETPGP_BUFSIZ];
284 	unsigned        n;
285 	unsigned        keysize;
286 	const unsigned char *prefix;
287 	int             plen;
288 	int             debug_len_decrypted;
289 
290 	plen = 0;
291 	prefix = (const unsigned char *) "";
292 	keysize = BN_num_bytes(rsa->n);
293 	/* RSA key can't be bigger than 65535 bits, so... */
294 	assert(keysize <= sizeof(hashbuf_from_sig));
295 	assert((unsigned) BN_num_bits(sig->sig) <= 8 * sizeof(sigbuf));
296 	BN_bn2bin(sig->sig, sigbuf);
297 
298 	n = __ops_rsa_public_decrypt(hashbuf_from_sig, sigbuf, (BN_num_bits(sig->sig) + 7) / 8, rsa);
299 	debug_len_decrypted = n;
300 
301 	if (n != keysize)	/* obviously, this includes error returns */
302 		return false;
303 
304 	/* XXX: why is there a leading 0? The first byte should be 1... */
305 	/* XXX: because the decrypt should use keysize and not sigsize? */
306 	if (hashbuf_from_sig[0] != 0 || hashbuf_from_sig[1] != 1)
307 		return false;
308 
309 	switch (type) {
310 	case OPS_HASH_MD5:
311 		prefix = prefix_md5;
312 		plen = sizeof(prefix_md5);
313 		break;
314 	case OPS_HASH_SHA1:
315 		prefix = prefix_sha1;
316 		plen = sizeof(prefix_sha1);
317 		break;
318 	case OPS_HASH_SHA256:
319 		prefix = prefix_sha256;
320 		plen = sizeof(prefix_sha256);
321 		break;
322 	default:
323 		(void) fprintf(stderr, "Unknown hash algorithm: %d\n", type);
324 		return false;
325 	}
326 
327 	if (keysize - plen - hash_length < 10)
328 		return false;
329 
330 	for (n = 2; n < keysize - plen - hash_length - 1; ++n)
331 		if (hashbuf_from_sig[n] != 0xff)
332 			return false;
333 
334 	if (hashbuf_from_sig[n++] != 0)
335 		return false;
336 
337 	if (__ops_get_debug_level(__FILE__)) {
338 		int             zz;
339 		unsigned        uu;
340 
341 		printf("\n");
342 		printf("hashbuf_from_sig\n");
343 		for (zz = 0; zz < debug_len_decrypted; zz++) {
344 			printf("%02x ", hashbuf_from_sig[n + zz]);
345 		}
346 		printf("\n");
347 		printf("prefix\n");
348 		for (zz = 0; zz < plen; zz++) {
349 			printf("%02x ", prefix[zz]);
350 		}
351 		printf("\n");
352 
353 		printf("\n");
354 		printf("hash from sig\n");
355 		for (uu = 0; uu < hash_length; uu++) {
356 			printf("%02x ", hashbuf_from_sig[n + plen + uu]);
357 		}
358 		printf("\n");
359 		printf("hash passed in (should match hash from sig)\n");
360 		for (uu = 0; uu < hash_length; uu++) {
361 			printf("%02x ", hash[uu]);
362 		}
363 		printf("\n");
364 	}
365 	if (memcmp(&hashbuf_from_sig[n], prefix, plen) != 0
366 	    || memcmp(&hashbuf_from_sig[n + plen], hash, hash_length) != 0)
367 		return false;
368 
369 	return true;
370 }
371 
372 static void
373 hash_add_key(__ops_hash_t * hash, const __ops_public_key_t * key)
374 {
375 	__ops_memory_t   *mem = __ops_memory_new();
376 	size_t          l;
377 
378 	__ops_build_public_key(mem, key, false);
379 
380 	l = __ops_memory_get_length(mem);
381 	__ops_hash_add_int(hash, 0x99, 1);
382 	__ops_hash_add_int(hash, l, 2);
383 	hash->add(hash, __ops_memory_get_data(mem), l);
384 
385 	__ops_memory_free(mem);
386 }
387 
388 static void
389 initialise_hash(__ops_hash_t * hash, const __ops_signature_t * sig)
390 {
391 	__ops_hash_any(hash, sig->info.hash_algorithm);
392 	hash->init(hash);
393 }
394 
395 static void
396 init_key_signature(__ops_hash_t * hash, const __ops_signature_t * sig,
397 		   const __ops_public_key_t * key)
398 {
399 	initialise_hash(hash, sig);
400 	hash_add_key(hash, key);
401 }
402 
403 static void
404 hash_add_trailer(__ops_hash_t * hash, const __ops_signature_t * sig,
405 		 const unsigned char *raw_packet)
406 {
407 	if (sig->info.version == OPS_V4) {
408 		if (raw_packet)
409 			hash->add(hash, raw_packet + sig->v4_hashed_data_start,
410 				  sig->info.v4_hashed_data_length);
411 		__ops_hash_add_int(hash, sig->info.version, 1);
412 		__ops_hash_add_int(hash, 0xff, 1);
413 		__ops_hash_add_int(hash, sig->info.v4_hashed_data_length, 4);
414 	} else {
415 		__ops_hash_add_int(hash, sig->info.type, 1);
416 		__ops_hash_add_int(hash, sig->info.creation_time, 4);
417 	}
418 }
419 
420 /**
421    \ingroup Core_Signature
422    \brief Checks a signature
423    \param hash Signature Hash to be checked
424    \param length Signature Length
425    \param sig The Signature to be checked
426    \param signer The signer's public key
427    \return true if good; else false
428 */
429 bool
430 __ops_check_signature(const unsigned char *hash, unsigned length,
431 		    const __ops_signature_t * sig,
432 		    const __ops_public_key_t * signer)
433 {
434 	bool   ret;
435 
436 	if (__ops_get_debug_level(__FILE__)) {
437 		printf("__ops_check_signature: (length %d) hash=", length);
438 		/* hashout[0]=0; */
439 		hexdump(hash, length, "");
440 	}
441 	ret = 0;
442 	switch (sig->info.key_algorithm) {
443 	case OPS_PKA_DSA:
444 		ret = __ops_dsa_verify(hash, length, &sig->info.signature.dsa, &signer->key.dsa);
445 		break;
446 
447 	case OPS_PKA_RSA:
448 		ret = rsa_verify(sig->info.hash_algorithm, hash, length, &sig->info.signature.rsa,
449 				 &signer->key.rsa);
450 		break;
451 
452 	default:
453 		assert(0);
454 	}
455 
456 	return ret;
457 }
458 
459 static bool
460 hash_and_check_signature(__ops_hash_t * hash,
461 			 const __ops_signature_t * sig,
462 			 const __ops_public_key_t * signer)
463 {
464 	int             n;
465 	unsigned char   hashout[OPS_MAX_HASH_SIZE];
466 
467 	n = hash->finish(hash, hashout);
468 
469 	return __ops_check_signature(hashout, n, sig, signer);
470 }
471 
472 static bool
473 finalise_signature(__ops_hash_t * hash,
474 		   const __ops_signature_t * sig,
475 		   const __ops_public_key_t * signer,
476 		   const unsigned char *raw_packet)
477 {
478 	hash_add_trailer(hash, sig, raw_packet);
479 	return hash_and_check_signature(hash, sig, signer);
480 }
481 
482 /**
483  * \ingroup Core_Signature
484  *
485  * \brief Verify a certification signature.
486  *
487  * \param key The public key that was signed.
488  * \param id The user ID that was signed
489  * \param sig The signature.
490  * \param signer The public key of the signer.
491  * \param raw_packet The raw signature packet.
492  * \return true if OK; else false
493  */
494 bool
495 __ops_check_user_id_certification_signature(const __ops_public_key_t * key,
496 					  const __ops_user_id_t * id,
497 					  const __ops_signature_t * sig,
498 					  const __ops_public_key_t * signer,
499 					  const unsigned char *raw_packet)
500 {
501 	__ops_hash_t      hash;
502 	size_t          user_id_len = strlen((char *) id->user_id);
503 
504 	init_key_signature(&hash, sig, key);
505 
506 	if (sig->info.version == OPS_V4) {
507 		__ops_hash_add_int(&hash, 0xb4, 1);
508 		__ops_hash_add_int(&hash, user_id_len, 4);
509 	}
510 	hash.add(&hash, id->user_id, user_id_len);
511 
512 	return finalise_signature(&hash, sig, signer, raw_packet);
513 }
514 
515 /**
516  * \ingroup Core_Signature
517  *
518  * Verify a certification signature.
519  *
520  * \param key The public key that was signed.
521  * \param attribute The user attribute that was signed
522  * \param sig The signature.
523  * \param signer The public key of the signer.
524  * \param raw_packet The raw signature packet.
525  * \return true if OK; else false
526  */
527 bool
528 __ops_check_user_attribute_certification_signature(const __ops_public_key_t * key,
529 				     const __ops_user_attribute_t * attribute,
530 						 const __ops_signature_t * sig,
531 					    const __ops_public_key_t * signer,
532 					    const unsigned char *raw_packet)
533 {
534 	__ops_hash_t      hash;
535 
536 	init_key_signature(&hash, sig, key);
537 
538 	if (sig->info.version == OPS_V4) {
539 		__ops_hash_add_int(&hash, 0xd1, 1);
540 		__ops_hash_add_int(&hash, attribute->data.len, 4);
541 	}
542 	hash.add(&hash, attribute->data.contents, attribute->data.len);
543 
544 	return finalise_signature(&hash, sig, signer, raw_packet);
545 }
546 
547 /**
548  * \ingroup Core_Signature
549  *
550  * Verify a subkey signature.
551  *
552  * \param key The public key whose subkey was signed.
553  * \param subkey The subkey of the public key that was signed.
554  * \param sig The signature.
555  * \param signer The public key of the signer.
556  * \param raw_packet The raw signature packet.
557  * \return true if OK; else false
558  */
559 bool
560 __ops_check_subkey_signature(const __ops_public_key_t * key,
561 			   const __ops_public_key_t * subkey,
562 			   const __ops_signature_t * sig,
563 			   const __ops_public_key_t * signer,
564 			   const unsigned char *raw_packet)
565 {
566 	__ops_hash_t      hash;
567 
568 	init_key_signature(&hash, sig, key);
569 	hash_add_key(&hash, subkey);
570 
571 	return finalise_signature(&hash, sig, signer, raw_packet);
572 }
573 
574 /**
575  * \ingroup Core_Signature
576  *
577  * Verify a direct signature.
578  *
579  * \param key The public key which was signed.
580  * \param sig The signature.
581  * \param signer The public key of the signer.
582  * \param raw_packet The raw signature packet.
583  * \return true if OK; else false
584  */
585 bool
586 __ops_check_direct_signature(const __ops_public_key_t * key,
587 			   const __ops_signature_t * sig,
588 			   const __ops_public_key_t * signer,
589 			   const unsigned char *raw_packet)
590 {
591 	__ops_hash_t      hash;
592 
593 	init_key_signature(&hash, sig, key);
594 	return finalise_signature(&hash, sig, signer, raw_packet);
595 }
596 
597 /**
598  * \ingroup Core_Signature
599  *
600  * Verify a signature on a hash (the hash will have already been fed
601  * the material that was being signed, for example signed cleartext).
602  *
603  * \param hash A hash structure of appropriate type that has been fed
604  * the material to be signed. This MUST NOT have been finalised.
605  * \param sig The signature to be verified.
606  * \param signer The public key of the signer.
607  * \return true if OK; else false
608  */
609 bool
610 __ops_check_hash_signature(__ops_hash_t * hash,
611 			 const __ops_signature_t * sig,
612 			 const __ops_public_key_t * signer)
613 {
614 	if (sig->info.hash_algorithm != hash->algorithm)
615 		return false;
616 
617 	return finalise_signature(hash, sig, signer, NULL);
618 }
619 
620 static void
621 start_signature_in_mem(__ops_create_signature_t * sig)
622 {
623 	/* since this has subpackets and stuff, we have to buffer the whole */
624 	/* thing to get counts before writing. */
625 	sig->mem = __ops_memory_new();
626 	__ops_memory_init(sig->mem, 100);
627 	__ops_writer_set_memory(sig->info, sig->mem);
628 
629 	/* write nearly up to the first subpacket */
630 	__ops_write_scalar(sig->sig.info.version, 1, sig->info);
631 	__ops_write_scalar(sig->sig.info.type, 1, sig->info);
632 	__ops_write_scalar(sig->sig.info.key_algorithm, 1, sig->info);
633 	__ops_write_scalar(sig->sig.info.hash_algorithm, 1, sig->info);
634 
635 	/* dummy hashed subpacket count */
636 	sig->hashed_count_offset = __ops_memory_get_length(sig->mem);
637 	__ops_write_scalar(0, 2, sig->info);
638 }
639 
640 /**
641  * \ingroup Core_Signature
642  *
643  * __ops_signature_start() creates a V4 public key signature with a SHA1 hash.
644  *
645  * \param sig The signature structure to initialise
646  * \param key The public key to be signed
647  * \param id The user ID being bound to the key
648  * \param type Signature type
649  */
650 void
651 __ops_signature_start_key_signature(__ops_create_signature_t * sig,
652 				  const __ops_public_key_t * key,
653 				  const __ops_user_id_t * id,
654 				  __ops_sig_type_t type)
655 {
656 	sig->info = __ops_create_info_new();
657 
658 	/* XXX: refactor with check (in several ways - check should probably */
659 	/*
660 	 * use the buffered writer to construct packets (done), and also
661 	 * should
662 	 */
663 	/* share code for hash calculation) */
664 	sig->sig.info.version = OPS_V4;
665 	sig->sig.info.hash_algorithm = OPS_HASH_SHA1;
666 	sig->sig.info.key_algorithm = key->algorithm;
667 	sig->sig.info.type = type;
668 
669 	sig->hashed_data_length = -1;
670 
671 	init_key_signature(&sig->hash, &sig->sig, key);
672 
673 	__ops_hash_add_int(&sig->hash, 0xb4, 1);
674 	__ops_hash_add_int(&sig->hash, strlen((char *) id->user_id), 4);
675 	sig->hash.add(&sig->hash, id->user_id, strlen((char *) id->user_id));
676 
677 	start_signature_in_mem(sig);
678 }
679 
680 /**
681  * \ingroup Core_Signature
682  *
683  * Create a V4 public key signature over some cleartext.
684  *
685  * \param sig The signature structure to initialise
686  * \param id
687  * \param type
688  * \todo Expand description. Allow other hashes.
689  */
690 
691 static void
692 __ops_signature_start_signature(__ops_create_signature_t * sig,
693 			      const __ops_secret_key_t * key,
694 			      const __ops_hash_algorithm_t hash,
695 			      const __ops_sig_type_t type)
696 {
697 	sig->info = __ops_create_info_new();
698 
699 	/* XXX: refactor with check (in several ways - check should probably */
700 	/*
701 	 * use the buffered writer to construct packets (done), and also
702 	 * should
703 	 */
704 	/* share code for hash calculation) */
705 	sig->sig.info.version = OPS_V4;
706 	sig->sig.info.key_algorithm = key->public_key.algorithm;
707 	sig->sig.info.hash_algorithm = hash;
708 	sig->sig.info.type = type;
709 
710 	sig->hashed_data_length = -1;
711 
712 	if (__ops_get_debug_level(__FILE__)) {
713 		fprintf(stderr, "initialising hash for sig in mem\n");
714 	}
715 	initialise_hash(&sig->hash, &sig->sig);
716 	start_signature_in_mem(sig);
717 }
718 
719 /**
720  * \ingroup Core_Signature
721  * \brief Setup to start a cleartext's signature
722  */
723 void
724 __ops_signature_start_cleartext_signature(__ops_create_signature_t * sig,
725 					const __ops_secret_key_t * key,
726 					const __ops_hash_algorithm_t hash,
727 					const __ops_sig_type_t type)
728 {
729 	__ops_signature_start_signature(sig, key, hash, type);
730 }
731 
732 /**
733  * \ingroup Core_Signature
734  * \brief Setup to start a message's signature
735  */
736 void
737 __ops_signature_start_message_signature(__ops_create_signature_t * sig,
738 				      const __ops_secret_key_t * key,
739 				      const __ops_hash_algorithm_t hash,
740 				      const __ops_sig_type_t type)
741 {
742 	__ops_signature_start_signature(sig, key, hash, type);
743 }
744 
745 /**
746  * \ingroup Core_Signature
747  *
748  * Add plaintext data to a signature-to-be.
749  *
750  * \param sig The signature-to-be.
751  * \param buf The plaintext data.
752  * \param length The amount of plaintext data.
753  */
754 void
755 __ops_signature_add_data(__ops_create_signature_t * sig, const void *buf,
756 		       size_t length)
757 {
758 	if (__ops_get_debug_level(__FILE__)) {
759 		fprintf(stderr, "__ops_signature_add_data adds to hash\n");
760 	}
761 	sig->hash.add(&sig->hash, buf, length);
762 }
763 
764 /**
765  * \ingroup Core_Signature
766  *
767  * Mark the end of the hashed subpackets in the signature
768  *
769  * \param sig
770  */
771 
772 bool
773 __ops_signature_hashed_subpackets_end(__ops_create_signature_t * sig)
774 {
775 	sig->hashed_data_length = __ops_memory_get_length(sig->mem)
776 	- sig->hashed_count_offset - 2;
777 	__ops_memory_place_int(sig->mem, sig->hashed_count_offset,
778 			     sig->hashed_data_length, 2);
779 	/* dummy unhashed subpacket count */
780 	sig->unhashed_count_offset = __ops_memory_get_length(sig->mem);
781 	return __ops_write_scalar(0, 2, sig->info);
782 }
783 
784 /**
785  * \ingroup Core_Signature
786  *
787  * Write out a signature
788  *
789  * \param sig
790  * \param key
791  * \param skey
792  * \param info
793  *
794  */
795 
796 bool
797 __ops_write_signature(__ops_create_signature_t * sig, const __ops_public_key_t * key,
798 		    const __ops_secret_key_t * skey, __ops_create_info_t * info)
799 {
800 	bool   rtn = false;
801 	size_t          l = __ops_memory_get_length(sig->mem);
802 
803 	/* check key not decrypted */
804 	switch (skey->public_key.algorithm) {
805 	case OPS_PKA_RSA:
806 	case OPS_PKA_RSA_ENCRYPT_ONLY:
807 	case OPS_PKA_RSA_SIGN_ONLY:
808 		assert(skey->key.rsa.d);
809 		break;
810 
811 	case OPS_PKA_DSA:
812 		assert(skey->key.dsa.x);
813 		break;
814 
815 	default:
816 		fprintf(stderr, "Unsupported algorithm %d\n", skey->public_key.algorithm);
817 		assert(0);
818 	}
819 
820 	assert(sig->hashed_data_length != (unsigned) -1);
821 
822 	__ops_memory_place_int(sig->mem, sig->unhashed_count_offset,
823 			     l - sig->unhashed_count_offset - 2, 2);
824 
825 	/* add the packet from version number to end of hashed subpackets */
826 
827 	if (__ops_get_debug_level(__FILE__)) {
828 		fprintf(stderr, "--- Adding packet to hash from version number to hashed subpkts\n");
829 	}
830 	sig->hash.add(&sig->hash, __ops_memory_get_data(sig->mem),
831 		      sig->unhashed_count_offset);
832 
833 	/* add final trailer */
834 	__ops_hash_add_int(&sig->hash, sig->sig.info.version, 1);
835 	__ops_hash_add_int(&sig->hash, 0xff, 1);
836 	/* +6 for version, type, pk alg, hash alg, hashed subpacket length */
837 	__ops_hash_add_int(&sig->hash, sig->hashed_data_length + 6, 4);
838 
839 	if (__ops_get_debug_level(__FILE__)) {
840 		fprintf(stderr, "--- Finished adding packet to hash from version number to hashed subpkts\n");
841 	}
842 	/* XXX: technically, we could figure out how big the signature is */
843 	/* and write it directly to the output instead of via memory. */
844 	switch (skey->public_key.algorithm) {
845 	case OPS_PKA_RSA:
846 	case OPS_PKA_RSA_ENCRYPT_ONLY:
847 	case OPS_PKA_RSA_SIGN_ONLY:
848 		rsa_sign(&sig->hash, &key->key.rsa, &skey->key.rsa, sig->info);
849 		break;
850 
851 	case OPS_PKA_DSA:
852 		dsa_sign(&sig->hash, &key->key.dsa, &skey->key.dsa, sig->info);
853 		break;
854 
855 	default:
856 		fprintf(stderr, "Unsupported algorithm %d\n", skey->public_key.algorithm);
857 		assert(0);
858 	}
859 
860 
861 
862 	rtn = __ops_write_ptag(OPS_PTAG_CT_SIGNATURE, info);
863 	if (rtn != false) {
864 		l = __ops_memory_get_length(sig->mem);
865 		rtn = __ops_write_length(l, info)
866 			&& __ops_write(__ops_memory_get_data(sig->mem), l, info);
867 	}
868 	__ops_memory_free(sig->mem);
869 
870 	if (rtn == false) {
871 		OPS_ERROR(&info->errors, OPS_E_W, "Cannot write signature");
872 	}
873 	return rtn;
874 }
875 
876 /**
877  * \ingroup Core_Signature
878  *
879  * __ops_signature_add_creation_time() adds a creation time to the signature.
880  *
881  * \param sig
882  * \param when
883  */
884 bool
885 __ops_signature_add_creation_time(__ops_create_signature_t * sig, time_t when)
886 {
887 	return __ops_write_ss_header(5, OPS_PTAG_SS_CREATION_TIME, sig->info)
888 	&& __ops_write_scalar(when, 4, sig->info);
889 }
890 
891 /**
892  * \ingroup Core_Signature
893  *
894  * Adds issuer's key ID to the signature
895  *
896  * \param sig
897  * \param keyid
898  */
899 
900 bool
901 __ops_signature_add_issuer_key_id(__ops_create_signature_t * sig,
902 				const unsigned char keyid[OPS_KEY_ID_SIZE])
903 {
904 	return __ops_write_ss_header(OPS_KEY_ID_SIZE + 1, OPS_PTAG_SS_ISSUER_KEY_ID, sig->info)
905 	&& __ops_write(keyid, OPS_KEY_ID_SIZE, sig->info);
906 }
907 
908 /**
909  * \ingroup Core_Signature
910  *
911  * Adds primary user ID to the signature
912  *
913  * \param sig
914  * \param primary
915  */
916 void
917 __ops_signature_add_primary_user_id(__ops_create_signature_t * sig,
918 				  bool primary)
919 {
920 	__ops_write_ss_header(2, OPS_PTAG_SS_PRIMARY_USER_ID, sig->info);
921 	__ops_write_scalar(primary, 1, sig->info);
922 }
923 
924 /**
925  * \ingroup Core_Signature
926  *
927  * Get the hash structure in use for the signature.
928  *
929  * \param sig The signature structure.
930  * \return The hash structure.
931  */
932 __ops_hash_t     *
933 __ops_signature_get_hash(__ops_create_signature_t * sig)
934 {
935 	return &sig->hash;
936 }
937 
938 static int
939 open_output_file(__ops_create_info_t ** cinfo, const char *input_filename, const char *output_filename, const bool use_armour, const bool overwrite)
940 {
941 	int             fd_out;
942 
943 	/* setup output file */
944 
945 	if (output_filename) {
946 		fd_out = __ops_setup_file_write(cinfo, output_filename, overwrite);
947 	} else {
948 		char           *myfilename = NULL;
949 		unsigned        filenamelen = strlen(input_filename) + 4 + 1;
950 		myfilename = calloc(1, filenamelen);
951 		if (use_armour)
952 			snprintf(myfilename, filenamelen, "%s.asc", input_filename);
953 		else
954 			snprintf(myfilename, filenamelen, "%s.gpg", input_filename);
955 		fd_out = __ops_setup_file_write(cinfo, myfilename, overwrite);
956 		free(myfilename);
957 	}
958 
959 	return fd_out;
960 }
961 
962 /**
963    \ingroup HighLevel_Sign
964    \brief Sign a file with a Cleartext Signature
965    \param input_filename Name of file to be signed
966    \param output_filename Filename to be created. If NULL, filename will be constructed from the input_filename.
967    \param skey Secret Key to sign with
968    \param overwrite Allow output file to be overwritten, if set
969    \return true if OK, else false
970 
971    Example code:
972    \code
973    void example(const __ops_secret_key_t *skey, bool overwrite)
974    {
975    if (__ops_sign_file_as_cleartext("mytestfile.txt",NULL,skey,overwrite)==true)
976        printf("OK");
977    else
978        printf("ERR");
979    }
980    \endcode
981 */
982 bool
983 __ops_sign_file_as_cleartext(const char *input_filename, const char *output_filename, const __ops_secret_key_t * skey, const bool overwrite)
984 {
985 	/* \todo allow choice of hash algorithams */
986 	/* enforce use of SHA1 for now */
987 
988 	unsigned char   keyid[OPS_KEY_ID_SIZE];
989 	__ops_create_signature_t *sig = NULL;
990 
991 	int             fd_in = 0;
992 	int             fd_out = 0;
993 	__ops_create_info_t *cinfo = NULL;
994 	unsigned char   buf[MAXBUF];
995 	/* int flags=0; */
996 	bool   rtn = false;
997 	bool   use_armour = true;
998 
999 	/* open file to sign */
1000 #ifdef O_BINARY
1001 	fd_in = open(input_filename, O_RDONLY | O_BINARY);
1002 #else
1003 	fd_in = open(input_filename, O_RDONLY);
1004 #endif
1005 	if (fd_in < 0) {
1006 		return false;
1007 	}
1008 	/* set up output file */
1009 
1010 	fd_out = open_output_file(&cinfo, input_filename, output_filename, use_armour, overwrite);
1011 
1012 	if (fd_out < 0) {
1013 		close(fd_in);
1014 		return false;
1015 	}
1016 	/* set up signature */
1017 	sig = __ops_create_signature_new();
1018 	if (!sig) {
1019 		close(fd_in);
1020 		__ops_teardown_file_write(cinfo, fd_out);
1021 		return false;
1022 	}
1023 	/* \todo could add more error detection here */
1024 	__ops_signature_start_cleartext_signature(sig, skey, OPS_HASH_SHA1, OPS_SIG_BINARY);
1025 	if (__ops_writer_push_clearsigned(cinfo, sig) != true) {
1026 		return false;
1027 	}
1028 	/* Do the signing */
1029 
1030 	for (;;) {
1031 		int             n = 0;
1032 
1033 		n = read(fd_in, buf, sizeof(buf));
1034 		if (!n)
1035 			break;
1036 		assert(n >= 0);
1037 		__ops_write(buf, n, cinfo);
1038 	}
1039 	close(fd_in);
1040 
1041 	/* add signature with subpackets: */
1042 	/* - creation time */
1043 	/* - key id */
1044 	rtn = __ops_writer_switch_to_armoured_signature(cinfo)
1045 		&& __ops_signature_add_creation_time(sig, time(NULL));
1046 	if (rtn == false) {
1047 		__ops_teardown_file_write(cinfo, fd_out);
1048 		return false;
1049 	}
1050 	__ops_keyid(keyid, OPS_KEY_ID_SIZE, OPS_KEY_ID_SIZE, &skey->public_key);
1051 
1052 	rtn = __ops_signature_add_issuer_key_id(sig, keyid)
1053 		&& __ops_signature_hashed_subpackets_end(sig)
1054 		&& __ops_write_signature(sig, &skey->public_key, skey, cinfo);
1055 
1056 	__ops_teardown_file_write(cinfo, fd_out);
1057 
1058 	if (rtn == false) {
1059 		OPS_ERROR(&cinfo->errors, OPS_E_W, "Cannot sign file as cleartext");
1060 	}
1061 	return rtn;
1062 }
1063 
1064 
1065 /**
1066  * \ingroup HighLevel_Sign
1067  * \brief Sign a buffer with a Cleartext signature
1068  * \param cleartext Text to be signed
1069  * \param len Length of text
1070  * \param signed_cleartext __ops_memory_t struct in which to write the signed cleartext
1071  * \param skey Secret key with which to sign the cleartext
1072  * \return true if OK; else false
1073 
1074  * \note It is the calling function's responsibility to free signed_cleartext
1075  * \note signed_cleartext should be a NULL pointer when passed in
1076 
1077  Example code:
1078  \code
1079  void example(const __ops_secret_key_t *skey)
1080  {
1081    __ops_memory_t* mem=NULL;
1082    const char* buf="Some example text";
1083    size_t len=strlen(buf);
1084    if (__ops_sign_buf_as_cleartext(buf,len, &mem, skey)==true)
1085      printf("OK");
1086    else
1087      printf("ERR");
1088    // free signed cleartext after use
1089    __ops_memory_free(mem);
1090  }
1091  \endcode
1092  */
1093 bool
1094 __ops_sign_buf_as_cleartext(const char *cleartext, const size_t len, __ops_memory_t ** signed_cleartext, const __ops_secret_key_t * skey)
1095 {
1096 	bool   rtn = false;
1097 
1098 	/* \todo allow choice of hash algorithams */
1099 	/* enforce use of SHA1 for now */
1100 
1101 	unsigned char   keyid[OPS_KEY_ID_SIZE];
1102 	__ops_create_signature_t *sig = NULL;
1103 
1104 	__ops_create_info_t *cinfo = NULL;
1105 
1106 	assert(*signed_cleartext == NULL);
1107 
1108 	/* set up signature */
1109 	sig = __ops_create_signature_new();
1110 	if (!sig) {
1111 		return false;
1112 	}
1113 	/* \todo could add more error detection here */
1114 	__ops_signature_start_cleartext_signature(sig, skey, OPS_HASH_SHA1, OPS_SIG_BINARY);
1115 
1116 	/* set up output file */
1117 	__ops_setup_memory_write(&cinfo, signed_cleartext, len);
1118 
1119 	/* Do the signing */
1120 	/* add signature with subpackets: */
1121 	/* - creation time */
1122 	/* - key id */
1123 	rtn = __ops_writer_push_clearsigned(cinfo, sig)
1124 		&& __ops_write(cleartext, len, cinfo)
1125 		&& __ops_writer_switch_to_armoured_signature(cinfo)
1126 		&& __ops_signature_add_creation_time(sig, time(NULL));
1127 
1128 	if (rtn == false) {
1129 		return false;
1130 	}
1131 	__ops_keyid(keyid, OPS_KEY_ID_SIZE, OPS_KEY_ID_SIZE, &skey->public_key);
1132 
1133 	rtn = __ops_signature_add_issuer_key_id(sig, keyid)
1134 		&& __ops_signature_hashed_subpackets_end(sig)
1135 		&& __ops_write_signature(sig, &skey->public_key, skey, cinfo)
1136 		&& __ops_writer_close(cinfo);
1137 
1138 	/* Note: the calling function must free signed_cleartext */
1139 	__ops_create_info_delete(cinfo);
1140 
1141 	return rtn;
1142 }
1143 
1144 /**
1145 \ingroup HighLevel_Sign
1146 \brief Sign a file
1147 \param input_filename Input filename
1148 \param output_filename Output filename. If NULL, a name is constructed from the input filename.
1149 \param skey Secret Key to use for signing
1150 \param use_armour Write armoured text, if set.
1151 \param overwrite May overwrite existing file, if set.
1152 \return true if OK; else false;
1153 
1154 Example code:
1155 \code
1156 void example(const __ops_secret_key_t *skey)
1157 {
1158   const char* filename="mytestfile";
1159   const bool use_armour=false;
1160   const bool overwrite=false;
1161   if (__ops_sign_file(filename, NULL, skey, use_armour, overwrite)==true)
1162     printf("OK");
1163   else
1164     printf("ERR");
1165 }
1166 \endcode
1167 */
1168 bool
1169 __ops_sign_file(const char *input_filename, const char *output_filename, const __ops_secret_key_t * skey, const bool use_armour, const bool overwrite)
1170 {
1171 	/* \todo allow choice of hash algorithams */
1172 	/* enforce use of SHA1 for now */
1173 
1174 	unsigned char   keyid[OPS_KEY_ID_SIZE];
1175 	__ops_create_signature_t *sig = NULL;
1176 
1177 	int             fd_out = 0;
1178 	__ops_create_info_t *cinfo = NULL;
1179 
1180 	__ops_hash_algorithm_t hash_alg = OPS_HASH_SHA1;
1181 	__ops_sig_type_t  sig_type = OPS_SIG_BINARY;
1182 
1183 	__ops_memory_t   *mem_buf = NULL;
1184 	__ops_hash_t     *hash = NULL;
1185 
1186 	/* read input file into buf */
1187 
1188 	int             errnum;
1189 	mem_buf = __ops_write_mem_from_file(input_filename, &errnum);
1190 	if (errnum)
1191 		return false;
1192 
1193 	/* setup output file */
1194 
1195 	fd_out = open_output_file(&cinfo, input_filename, output_filename, use_armour, overwrite);
1196 
1197 	if (fd_out < 0) {
1198 		__ops_memory_free(mem_buf);
1199 		return false;
1200 	}
1201 	/* set up signature */
1202 	sig = __ops_create_signature_new();
1203 	__ops_signature_start_message_signature(sig, skey, hash_alg, sig_type);
1204 
1205 	/* set armoured/not armoured here */
1206 	if (use_armour)
1207 		__ops_writer_push_armoured_message(cinfo);
1208 
1209 	if (__ops_get_debug_level(__FILE__)) {
1210 		fprintf(stderr, "** Writing out one pass sig\n");
1211 	}
1212 	/* write one_pass_sig */
1213 	__ops_write_one_pass_sig(skey, hash_alg, sig_type, cinfo);
1214 
1215 	/* hash file contents */
1216 	hash = __ops_signature_get_hash(sig);
1217 	hash->add(hash, __ops_memory_get_data(mem_buf), __ops_memory_get_length(mem_buf));
1218 
1219 	/* output file contents as Literal Data packet */
1220 
1221 	if (__ops_get_debug_level(__FILE__)) {
1222 		fprintf(stderr, "** Writing out data now\n");
1223 	}
1224 	__ops_write_literal_data_from_buf(__ops_memory_get_data(mem_buf), __ops_memory_get_length(mem_buf), OPS_LDT_BINARY, cinfo);
1225 
1226 	if (__ops_get_debug_level(__FILE__)) {
1227 		fprintf(stderr, "** After Writing out data now\n");
1228 	}
1229 	/* add subpackets to signature */
1230 	/* - creation time */
1231 	/* - key id */
1232 
1233 	__ops_signature_add_creation_time(sig, time(NULL));
1234 
1235 	__ops_keyid(keyid, OPS_KEY_ID_SIZE, OPS_KEY_ID_SIZE, &skey->public_key);
1236 	__ops_signature_add_issuer_key_id(sig, keyid);
1237 
1238 	__ops_signature_hashed_subpackets_end(sig);
1239 
1240 	/* write out sig */
1241 	__ops_write_signature(sig, &skey->public_key, skey, cinfo);
1242 
1243 	__ops_teardown_file_write(cinfo, fd_out);
1244 
1245 	/* tidy up */
1246 	__ops_create_signature_delete(sig);
1247 	__ops_memory_free(mem_buf);
1248 
1249 	return true;
1250 }
1251 
1252 /**
1253 \ingroup HighLevel_Sign
1254 \brief Signs a buffer
1255 \param input Input text to be signed
1256 \param input_len Length of input text
1257 \param sig_type Signature type
1258 \param skey Secret Key
1259 \param use_armour Write armoured text, if set
1260 \return New __ops_memory_t struct containing signed text
1261 \note It is the caller's responsibility to call __ops_memory_free(me)
1262 
1263 Example Code:
1264 \code
1265 void example(const __ops_secret_key_t *skey)
1266 {
1267   const char* buf="Some example text";
1268   const size_t len=strlen(buf);
1269   const bool use_armour=true;
1270 
1271   __ops_memory_t* mem=NULL;
1272 
1273   mem=__ops_sign_buf(buf,len,OPS_SIG_BINARY,skey,use_armour);
1274   if (mem)
1275   {
1276     printf ("OK");
1277     __ops_memory_free(mem);
1278   }
1279   else
1280   {
1281     printf("ERR");
1282   }
1283 }
1284 \endcode
1285 */
1286 __ops_memory_t   *
1287 __ops_sign_buf(const void *input, const size_t input_len, const __ops_sig_type_t sig_type, const __ops_secret_key_t * skey, const bool use_armour)
1288 {
1289 	/* \todo allow choice of hash algorithams */
1290 	/* enforce use of SHA1 for now */
1291 
1292 	unsigned char   keyid[OPS_KEY_ID_SIZE];
1293 	__ops_create_signature_t *sig = NULL;
1294 
1295 	__ops_create_info_t *cinfo = NULL;
1296 	__ops_memory_t   *mem = __ops_memory_new();
1297 
1298 	__ops_hash_algorithm_t hash_alg = OPS_HASH_SHA1;
1299 	__ops_literal_data_type_t ld_type;
1300 	__ops_hash_t     *hash = NULL;
1301 
1302 	/* setup literal data packet type */
1303 	if (sig_type == OPS_SIG_BINARY)
1304 		ld_type = OPS_LDT_BINARY;
1305 	else
1306 		ld_type = OPS_LDT_TEXT;
1307 
1308 	/* set up signature */
1309 	sig = __ops_create_signature_new();
1310 	__ops_signature_start_message_signature(sig, skey, hash_alg, sig_type);
1311 
1312 	/* setup writer */
1313 	__ops_setup_memory_write(&cinfo, &mem, input_len);
1314 
1315 	/* set armoured/not armoured here */
1316 	if (use_armour)
1317 		__ops_writer_push_armoured_message(cinfo);
1318 
1319 	if (__ops_get_debug_level(__FILE__)) {
1320 		fprintf(stderr, "** Writing out one pass sig\n");
1321 	}
1322 	/* write one_pass_sig */
1323 	__ops_write_one_pass_sig(skey, hash_alg, sig_type, cinfo);
1324 
1325 	/* hash file contents */
1326 	hash = __ops_signature_get_hash(sig);
1327 	hash->add(hash, input, input_len);
1328 
1329 	/* output file contents as Literal Data packet */
1330 
1331 	if (__ops_get_debug_level(__FILE__)) {
1332 		fprintf(stderr, "** Writing out data now\n");
1333 	}
1334 	__ops_write_literal_data_from_buf(input, input_len, ld_type, cinfo);
1335 
1336 	if (__ops_get_debug_level(__FILE__)) {
1337 		fprintf(stderr, "** After Writing out data now\n");
1338 	}
1339 	/* add subpackets to signature */
1340 	/* - creation time */
1341 	/* - key id */
1342 
1343 	__ops_signature_add_creation_time(sig, time(NULL));
1344 
1345 	__ops_keyid(keyid, OPS_KEY_ID_SIZE, OPS_KEY_ID_SIZE, &skey->public_key);
1346 	__ops_signature_add_issuer_key_id(sig, keyid);
1347 
1348 	__ops_signature_hashed_subpackets_end(sig);
1349 
1350 	/* write out sig */
1351 	__ops_write_signature(sig, &skey->public_key, skey, cinfo);
1352 
1353 	/* tidy up */
1354 	__ops_writer_close(cinfo);
1355 	__ops_create_signature_delete(sig);
1356 
1357 	return mem;
1358 }
1359