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: create.c,v 1.37 2010/11/07 08:39:59 agc Exp $");
61#endif
62
63#include <sys/types.h>
64#include <sys/param.h>
65#include <sys/stat.h>
66
67#ifdef HAVE_FCNTL_H
68#include <fcntl.h>
69#endif
70
71#include <string.h>
72
73#ifdef HAVE_UNISTD_H
74#include <unistd.h>
75#endif
76
77#ifdef HAVE_OPENSSL_CAST_H
78#include <openssl/cast.h>
79#endif
80
81#include "create.h"
82#include "keyring.h"
83#include "packet.h"
84#include "signature.h"
85#include "writer.h"
86#include "readerwriter.h"
87#include "memory.h"
88#include "netpgpdefs.h"
89#include "netpgpdigest.h"
90
91/**
92 * \ingroup Core_Create
93 * \param length
94 * \param type
95 * \param output
96 * \return 1 if OK, otherwise 0
97 */
98
99unsigned
100pgp_write_ss_header(pgp_output_t *output,
101			unsigned length,
102			pgp_content_enum type)
103{
104	return pgp_write_length(output, length) &&
105		pgp_write_scalar(output, (unsigned)(type -
106				(unsigned)PGP_PTAG_SIG_SUBPKT_BASE), 1);
107}
108
109/*
110 * XXX: the general idea of _fast_ is that it doesn't copy stuff the safe
111 * (i.e. non _fast_) version will, and so will also need to be freed.
112 */
113
114/**
115 * \ingroup Core_Create
116 *
117 * pgp_fast_create_userid() sets id->userid to the given userid.
118 * This is fast because it is only copying a char*. However, if userid
119 * is changed or freed in the future, this could have injurious results.
120 * \param id
121 * \param userid
122 */
123
124void
125pgp_fast_create_userid(uint8_t **id, uint8_t *userid)
126{
127	*id = userid;
128}
129
130/**
131 * \ingroup Core_WritePackets
132 * \brief Writes a User Id packet
133 * \param id
134 * \param output
135 * \return 1 if OK, otherwise 0
136 */
137unsigned
138pgp_write_struct_userid(pgp_output_t *output, const uint8_t *id)
139{
140	return pgp_write_ptag(output, PGP_PTAG_CT_USER_ID) &&
141		pgp_write_length(output, (unsigned)strlen((const char *) id)) &&
142		pgp_write(output, id, (unsigned)strlen((const char *) id));
143}
144
145/**
146 * \ingroup Core_WritePackets
147 * \brief Write a User Id packet.
148 * \param userid
149 * \param output
150 *
151 * \return return value from pgp_write_struct_userid()
152 */
153unsigned
154pgp_write_userid(const uint8_t *userid, pgp_output_t *output)
155{
156	return pgp_write_struct_userid(output, userid);
157}
158
159/**
160\ingroup Core_MPI
161*/
162static unsigned
163mpi_length(const BIGNUM *bn)
164{
165	return (unsigned)(2 + (BN_num_bits(bn) + 7) / 8);
166}
167
168static unsigned
169pubkey_length(const pgp_pubkey_t *key)
170{
171	switch (key->alg) {
172	case PGP_PKA_DSA:
173		return mpi_length(key->key.dsa.p) + mpi_length(key->key.dsa.q) +
174			mpi_length(key->key.dsa.g) + mpi_length(key->key.dsa.y);
175
176	case PGP_PKA_RSA:
177		return mpi_length(key->key.rsa.n) + mpi_length(key->key.rsa.e);
178
179	default:
180		(void) fprintf(stderr,
181			"pubkey_length: unknown key algorithm\n");
182	}
183	return 0;
184}
185
186static unsigned
187seckey_length(const pgp_seckey_t *key)
188{
189	int             len;
190
191	len = 0;
192	switch (key->pubkey.alg) {
193	case PGP_PKA_DSA:
194		return (unsigned)(mpi_length(key->key.dsa.x) + pubkey_length(&key->pubkey));
195	case PGP_PKA_RSA:
196		len = mpi_length(key->key.rsa.d) + mpi_length(key->key.rsa.p) +
197			mpi_length(key->key.rsa.q) + mpi_length(key->key.rsa.u);
198
199		return (unsigned)(len + pubkey_length(&key->pubkey));
200	default:
201		(void) fprintf(stderr,
202			"seckey_length: unknown key algorithm\n");
203	}
204	return 0;
205}
206
207/**
208 * \ingroup Core_Create
209 * \param key
210 * \param t
211 * \param n
212 * \param e
213*/
214void
215pgp_fast_create_rsa_pubkey(pgp_pubkey_t *key, time_t t,
216			       BIGNUM *n, BIGNUM *e)
217{
218	key->version = PGP_V4;
219	key->birthtime = t;
220	key->alg = PGP_PKA_RSA;
221	key->key.rsa.n = n;
222	key->key.rsa.e = e;
223}
224
225/*
226 * Note that we support v3 keys here because they're needed for for
227 * verification - the writer doesn't allow them, though
228 */
229static unsigned
230write_pubkey_body(const pgp_pubkey_t *key, pgp_output_t *output)
231{
232	if (!(pgp_write_scalar(output, (unsigned)key->version, 1) &&
233	      pgp_write_scalar(output, (unsigned)key->birthtime, 4))) {
234		return 0;
235	}
236
237	if (key->version != 4 &&
238	    !pgp_write_scalar(output, key->days_valid, 2)) {
239		return 0;
240	}
241
242	if (!pgp_write_scalar(output, (unsigned)key->alg, 1)) {
243		return 0;
244	}
245
246	switch (key->alg) {
247	case PGP_PKA_DSA:
248		return pgp_write_mpi(output, key->key.dsa.p) &&
249			pgp_write_mpi(output, key->key.dsa.q) &&
250			pgp_write_mpi(output, key->key.dsa.g) &&
251			pgp_write_mpi(output, key->key.dsa.y);
252
253	case PGP_PKA_RSA:
254	case PGP_PKA_RSA_ENCRYPT_ONLY:
255	case PGP_PKA_RSA_SIGN_ONLY:
256		return pgp_write_mpi(output, key->key.rsa.n) &&
257			pgp_write_mpi(output, key->key.rsa.e);
258
259	case PGP_PKA_ELGAMAL:
260		return pgp_write_mpi(output, key->key.elgamal.p) &&
261			pgp_write_mpi(output, key->key.elgamal.g) &&
262			pgp_write_mpi(output, key->key.elgamal.y);
263
264	default:
265		(void) fprintf(stderr,
266			"write_pubkey_body: bad algorithm\n");
267		break;
268	}
269	return 0;
270}
271
272/*
273 * Note that we support v3 keys here because they're needed for
274 * verification.
275 */
276static unsigned
277write_seckey_body(const pgp_seckey_t *key,
278		      const uint8_t *passphrase,
279		      const size_t pplen,
280		      pgp_output_t *output)
281{
282	/* RFC4880 Section 5.5.3 Secret-Key Packet Formats */
283
284	pgp_crypt_t   crypted;
285	pgp_hash_t    hash;
286	unsigned	done = 0;
287	unsigned	i = 0;
288	uint8_t		*hashed;
289	uint8_t		sesskey[CAST_KEY_LENGTH];
290
291	if (!write_pubkey_body(&key->pubkey, output)) {
292		return 0;
293	}
294	if (key->s2k_usage != PGP_S2KU_ENCRYPTED_AND_HASHED) {
295		(void) fprintf(stderr, "write_seckey_body: s2k usage\n");
296		return 0;
297	}
298	if (!pgp_write_scalar(output, (unsigned)key->s2k_usage, 1)) {
299		return 0;
300	}
301
302	if (key->alg != PGP_SA_CAST5) {
303		(void) fprintf(stderr, "write_seckey_body: algorithm\n");
304		return 0;
305	}
306	if (!pgp_write_scalar(output, (unsigned)key->alg, 1)) {
307		return 0;
308	}
309
310	if (key->s2k_specifier != PGP_S2KS_SIMPLE &&
311	    key->s2k_specifier != PGP_S2KS_SALTED) {
312		/* = 1 \todo could also be iterated-and-salted */
313		(void) fprintf(stderr, "write_seckey_body: s2k spec\n");
314		return 0;
315	}
316	if (!pgp_write_scalar(output, (unsigned)key->s2k_specifier, 1)) {
317		return 0;
318	}
319	if (!pgp_write_scalar(output, (unsigned)key->hash_alg, 1)) {
320		return 0;
321	}
322
323	switch (key->s2k_specifier) {
324	case PGP_S2KS_SIMPLE:
325		/* nothing more to do */
326		break;
327
328	case PGP_S2KS_SALTED:
329		/* 8-octet salt value */
330		pgp_random(__UNCONST(&key->salt[0]), PGP_SALT_SIZE);
331		if (!pgp_write(output, key->salt, PGP_SALT_SIZE)) {
332			return 0;
333		}
334		break;
335
336		/*
337		 * \todo case PGP_S2KS_ITERATED_AND_SALTED: // 8-octet salt
338		 * value // 1-octet count break;
339		 */
340
341	default:
342		(void) fprintf(stderr,
343			"invalid/unsupported s2k specifier %d\n",
344			key->s2k_specifier);
345		return 0;
346	}
347
348	if (!pgp_write(output, &key->iv[0], pgp_block_size(key->alg))) {
349		return 0;
350	}
351
352	/*
353	 * create the session key for encrypting the algorithm-specific
354	 * fields
355	 */
356
357	switch (key->s2k_specifier) {
358	case PGP_S2KS_SIMPLE:
359	case PGP_S2KS_SALTED:
360		/* RFC4880: section 3.7.1.1 and 3.7.1.2 */
361
362		for (done = 0, i = 0; done < CAST_KEY_LENGTH; i++) {
363			unsigned 	hashsize;
364			unsigned 	j;
365			unsigned	needed;
366			unsigned	size;
367			uint8_t		zero = 0;
368
369			/* Hard-coded SHA1 for session key */
370			pgp_hash_any(&hash, PGP_HASH_SHA1);
371			hashsize = pgp_hash_size(key->hash_alg);
372			needed = CAST_KEY_LENGTH - done;
373			size = MIN(needed, hashsize);
374			if ((hashed = calloc(1, hashsize)) == NULL) {
375				(void) fprintf(stderr, "write_seckey_body: bad alloc\n");
376				return 0;
377			}
378			if (!hash.init(&hash)) {
379				(void) fprintf(stderr, "write_seckey_body: bad alloc\n");
380				return 0;
381			}
382
383			/* preload if iterating  */
384			for (j = 0; j < i; j++) {
385				/*
386				 * Coverity shows a DEADCODE error on this
387				 * line. This is expected since the hardcoded
388				 * use of SHA1 and CAST5 means that it will
389				 * not used. This will change however when
390				 * other algorithms are supported.
391				 */
392				hash.add(&hash, &zero, 1);
393			}
394
395			if (key->s2k_specifier == PGP_S2KS_SALTED) {
396				hash.add(&hash, key->salt, PGP_SALT_SIZE);
397			}
398			hash.add(&hash, passphrase, (unsigned)pplen);
399			hash.finish(&hash, hashed);
400
401			/*
402			 * if more in hash than is needed by session key, use
403			 * the leftmost octets
404			 */
405			(void) memcpy(&sesskey[i * hashsize],
406					hashed, (unsigned)size);
407			done += (unsigned)size;
408			if (done > CAST_KEY_LENGTH) {
409				(void) fprintf(stderr,
410					"write_seckey_body: short add\n");
411				return 0;
412			}
413		}
414
415		break;
416
417		/*
418		 * \todo case PGP_S2KS_ITERATED_AND_SALTED: * 8-octet salt
419		 * value * 1-octet count break;
420		 */
421
422	default:
423		(void) fprintf(stderr,
424			"invalid/unsupported s2k specifier %d\n",
425			key->s2k_specifier);
426		return 0;
427	}
428
429	/* use this session key to encrypt */
430
431	pgp_crypt_any(&crypted, key->alg);
432	crypted.set_iv(&crypted, key->iv);
433	crypted.set_crypt_key(&crypted, sesskey);
434	pgp_encrypt_init(&crypted);
435
436	if (pgp_get_debug_level(__FILE__)) {
437		hexdump(stderr, "writing: iv=", key->iv, pgp_block_size(key->alg));
438		hexdump(stderr, "key= ", sesskey, CAST_KEY_LENGTH);
439		(void) fprintf(stderr, "\nturning encryption on...\n");
440	}
441	pgp_push_enc_crypt(output, &crypted);
442
443	switch (key->pubkey.alg) {
444	case PGP_PKA_RSA:
445	case PGP_PKA_RSA_ENCRYPT_ONLY:
446	case PGP_PKA_RSA_SIGN_ONLY:
447		if (!pgp_write_mpi(output, key->key.rsa.d) ||
448		    !pgp_write_mpi(output, key->key.rsa.p) ||
449		    !pgp_write_mpi(output, key->key.rsa.q) ||
450		    !pgp_write_mpi(output, key->key.rsa.u)) {
451			if (pgp_get_debug_level(__FILE__)) {
452				(void) fprintf(stderr,
453					"4 x mpi not written - problem\n");
454			}
455			return 0;
456		}
457		break;
458	case PGP_PKA_DSA:
459		return pgp_write_mpi(output, key->key.dsa.x);
460	case PGP_PKA_ELGAMAL:
461		return pgp_write_mpi(output, key->key.elgamal.x);
462	default:
463		return 0;
464	}
465
466	if (!pgp_write(output, key->checkhash, PGP_CHECKHASH_SIZE)) {
467		return 0;
468	}
469
470	pgp_writer_pop(output);
471
472	return 1;
473}
474
475/**
476 * \ingroup Core_WritePackets
477 * \brief Writes a Public Key packet
478 * \param key
479 * \param output
480 * \return 1 if OK, otherwise 0
481 */
482static unsigned
483write_struct_pubkey(pgp_output_t *output, const pgp_pubkey_t *key)
484{
485	return pgp_write_ptag(output, PGP_PTAG_CT_PUBLIC_KEY) &&
486		pgp_write_length(output, 1 + 4 + 1 + pubkey_length(key)) &&
487		write_pubkey_body(key, output);
488}
489
490
491/**
492   \ingroup HighLevel_KeyWrite
493
494   \brief Writes a transferable PGP public key to the given output stream.
495
496   \param keydata Key to be written
497   \param armoured Flag is set for armoured output
498   \param output Output stream
499
500*/
501
502unsigned
503pgp_write_xfer_pubkey(pgp_output_t *output,
504			const pgp_key_t *key,
505			const unsigned armoured)
506{
507	unsigned    i, j;
508
509	if (armoured) {
510		pgp_writer_push_armoured(output, PGP_PGP_PUBLIC_KEY_BLOCK);
511	}
512	/* public key */
513	if (!write_struct_pubkey(output, &key->key.pubkey)) {
514		return 0;
515	}
516
517	/* TODO: revocation signatures go here */
518
519	/* user ids and corresponding signatures */
520	for (i = 0; i < key->uidc; i++) {
521		if (!pgp_write_struct_userid(output, key->uids[i])) {
522			return 0;
523		}
524		for (j = 0; j < key->packetc; j++) {
525			if (!pgp_write(output, key->packets[j].raw, (unsigned)key->packets[j].length)) {
526				return 0;
527			}
528		}
529	}
530
531	/* TODO: user attributes and corresponding signatures */
532
533	/*
534	 * subkey packets and corresponding signatures and optional
535	 * revocation
536	 */
537
538	if (armoured) {
539		pgp_writer_info_finalise(&output->errors, &output->writer);
540		pgp_writer_pop(output);
541	}
542	return 1;
543}
544
545/**
546   \ingroup HighLevel_KeyWrite
547
548   \brief Writes a transferable PGP secret key to the given output stream.
549
550   \param keydata Key to be written
551   \param passphrase
552   \param pplen
553   \param armoured Flag is set for armoured output
554   \param output Output stream
555
556*/
557
558unsigned
559pgp_write_xfer_seckey(pgp_output_t *output,
560				const pgp_key_t *key,
561				const uint8_t *passphrase,
562				const size_t pplen,
563				unsigned armoured)
564{
565	unsigned	i, j;
566
567	if (armoured) {
568		pgp_writer_push_armoured(output, PGP_PGP_PRIVATE_KEY_BLOCK);
569	}
570	/* public key */
571	if (!pgp_write_struct_seckey(&key->key.seckey, passphrase,
572			pplen, output)) {
573		return 0;
574	}
575
576	/* TODO: revocation signatures go here */
577
578	/* user ids and corresponding signatures */
579	for (i = 0; i < key->uidc; i++) {
580		if (!pgp_write_struct_userid(output, key->uids[i])) {
581			return 0;
582		}
583		for (j = 0; j < key->packetc; j++) {
584			if (!pgp_write(output, key->packets[j].raw, (unsigned)key->packets[j].length)) {
585				return 0;
586			}
587		}
588	}
589
590	/* TODO: user attributes and corresponding signatures */
591
592	/*
593	 * subkey packets and corresponding signatures and optional
594	 * revocation
595	 */
596
597	if (armoured) {
598		pgp_writer_info_finalise(&output->errors, &output->writer);
599		pgp_writer_pop(output);
600	}
601	return 1;
602}
603
604/**
605 * \ingroup Core_WritePackets
606 * \brief Writes one RSA public key packet.
607 * \param t Creation time
608 * \param n RSA public modulus
609 * \param e RSA public encryption exponent
610 * \param output Writer settings
611 *
612 * \return 1 if OK, otherwise 0
613 */
614
615unsigned
616pgp_write_rsa_pubkey(time_t t, const BIGNUM *n,
617			 const BIGNUM *e,
618			 pgp_output_t *output)
619{
620	pgp_pubkey_t key;
621
622	pgp_fast_create_rsa_pubkey(&key, t, __UNCONST(n), __UNCONST(e));
623	return write_struct_pubkey(output, &key);
624}
625
626/**
627 * \ingroup Core_Create
628 * \param out
629 * \param key
630 * \param make_packet
631 */
632
633void
634pgp_build_pubkey(pgp_memory_t *out, const pgp_pubkey_t *key,
635		     unsigned make_packet)
636{
637	pgp_output_t *output;
638
639	output = pgp_output_new();
640	pgp_memory_init(out, 128);
641	pgp_writer_set_memory(output, out);
642	write_pubkey_body(key, output);
643	if (make_packet) {
644		pgp_memory_make_packet(out, PGP_PTAG_CT_PUBLIC_KEY);
645	}
646	pgp_output_delete(output);
647}
648
649/**
650 * \ingroup Core_Create
651 *
652 * Create an RSA secret key structure. If a parameter is marked as
653 * [OPTIONAL], then it can be omitted and will be calculated from
654 * other params - or, in the case of e, will default to 0x10001.
655 *
656 * Parameters are _not_ copied, so will be freed if the structure is
657 * freed.
658 *
659 * \param key The key structure to be initialised.
660 * \param t
661 * \param d The RSA parameter d (=e^-1 mod (p-1)(q-1)) [OPTIONAL]
662 * \param p The RSA parameter p
663 * \param q The RSA parameter q (q > p)
664 * \param u The RSA parameter u (=p^-1 mod q) [OPTIONAL]
665 * \param n The RSA public parameter n (=p*q) [OPTIONAL]
666 * \param e The RSA public parameter e */
667
668void
669pgp_fast_create_rsa_seckey(pgp_seckey_t *key, time_t t,
670			     BIGNUM *d, BIGNUM *p, BIGNUM *q, BIGNUM *u,
671			       BIGNUM *n, BIGNUM *e)
672{
673	pgp_fast_create_rsa_pubkey(&key->pubkey, t, n, e);
674
675	/* XXX: calculate optionals */
676	key->key.rsa.d = d;
677	key->key.rsa.p = p;
678	key->key.rsa.q = q;
679	key->key.rsa.u = u;
680
681	key->s2k_usage = PGP_S2KU_NONE;
682
683	/* XXX: sanity check and add errors... */
684}
685
686/**
687 * \ingroup Core_WritePackets
688 * \brief Writes a Secret Key packet.
689 * \param key The secret key
690 * \param passphrase The passphrase
691 * \param pplen Length of passphrase
692 * \param output
693 * \return 1 if OK; else 0
694 */
695unsigned
696pgp_write_struct_seckey(const pgp_seckey_t *key,
697			    const uint8_t *passphrase,
698			    const size_t pplen,
699			    pgp_output_t *output)
700{
701	int             length = 0;
702
703	if (key->pubkey.version != 4) {
704		(void) fprintf(stderr,
705			"pgp_write_struct_seckey: public key version\n");
706		return 0;
707	}
708
709	/* Ref: RFC4880 Section 5.5.3 */
710
711	/* pubkey, excluding MPIs */
712	length += 1 + 4 + 1 + 1;
713
714	/* s2k usage */
715	length += 1;
716
717	switch (key->s2k_usage) {
718	case PGP_S2KU_NONE:
719		/* nothing to add */
720		break;
721
722	case PGP_S2KU_ENCRYPTED_AND_HASHED:	/* 254 */
723	case PGP_S2KU_ENCRYPTED:	/* 255 */
724
725		/* Ref: RFC4880 Section 3.7 */
726		length += 1;	/* s2k_specifier */
727
728		switch (key->s2k_specifier) {
729		case PGP_S2KS_SIMPLE:
730			length += 1;	/* hash algorithm */
731			break;
732
733		case PGP_S2KS_SALTED:
734			length += 1 + 8;	/* hash algorithm + salt */
735			break;
736
737		case PGP_S2KS_ITERATED_AND_SALTED:
738			length += 1 + 8 + 1;	/* hash algorithm, salt +
739						 * count */
740			break;
741
742		default:
743			(void) fprintf(stderr,
744				"pgp_write_struct_seckey: s2k spec\n");
745			return 0;
746		}
747		break;
748
749	default:
750		(void) fprintf(stderr,
751			"pgp_write_struct_seckey: s2k usage\n");
752		return 0;
753	}
754
755	/* IV */
756	if (key->s2k_usage) {
757		length += pgp_block_size(key->alg);
758	}
759	/* checksum or hash */
760	switch (key->s2k_usage) {
761	case PGP_S2KU_NONE:
762	case PGP_S2KU_ENCRYPTED:
763		length += 2;
764		break;
765
766	case PGP_S2KU_ENCRYPTED_AND_HASHED:
767		length += PGP_CHECKHASH_SIZE;
768		break;
769
770	default:
771		(void) fprintf(stderr,
772			"pgp_write_struct_seckey: s2k cksum usage\n");
773		return 0;
774	}
775
776	/* secret key and public key MPIs */
777	length += (unsigned)seckey_length(key);
778
779	return pgp_write_ptag(output, PGP_PTAG_CT_SECRET_KEY) &&
780		/* pgp_write_length(output,1+4+1+1+seckey_length(key)+2) && */
781		pgp_write_length(output, (unsigned)length) &&
782		write_seckey_body(key, passphrase, pplen, output);
783}
784
785/**
786 * \ingroup Core_Create
787 *
788 * \brief Create a new pgp_output_t structure.
789 *
790 * \return the new structure.
791 * \note It is the responsiblity of the caller to call pgp_output_delete().
792 * \sa pgp_output_delete()
793 */
794pgp_output_t *
795pgp_output_new(void)
796{
797	return calloc(1, sizeof(pgp_output_t));
798}
799
800/**
801 * \ingroup Core_Create
802 * \brief Delete an pgp_output_t strucut and associated resources.
803 *
804 * Delete an pgp_output_t structure. If a writer is active, then
805 * that is also deleted.
806 *
807 * \param info the structure to be deleted.
808 */
809void
810pgp_output_delete(pgp_output_t *output)
811{
812	pgp_writer_info_delete(&output->writer);
813	free(output);
814}
815
816/**
817 \ingroup Core_Create
818 \brief Calculate the checksum for a session key
819 \param sesskey Session Key to use
820 \param cs Checksum to be written
821 \return 1 if OK; else 0
822*/
823unsigned
824pgp_calc_sesskey_checksum(pgp_pk_sesskey_t *sesskey, uint8_t cs[2])
825{
826	uint32_t   checksum = 0;
827	unsigned    i;
828
829	if (!pgp_is_sa_supported(sesskey->symm_alg)) {
830		return 0;
831	}
832
833	for (i = 0; i < pgp_key_size(sesskey->symm_alg); i++) {
834		checksum += sesskey->key[i];
835	}
836	checksum = checksum % 65536;
837
838	cs[0] = (uint8_t)((checksum >> 8) & 0xff);
839	cs[1] = (uint8_t)(checksum & 0xff);
840
841	if (pgp_get_debug_level(__FILE__)) {
842		hexdump(stderr, "nm buf checksum:", cs, 2);
843	}
844	return 1;
845}
846
847static unsigned
848create_unencoded_m_buf(pgp_pk_sesskey_t *sesskey, pgp_crypt_t *cipherinfo, uint8_t *m_buf)
849{
850	unsigned	i;
851
852	/* m_buf is the buffer which will be encoded in PKCS#1 block
853	* encoding to form the "m" value used in the Public Key
854	* Encrypted Session Key Packet as defined in RFC Section 5.1
855	* "Public-Key Encrypted Session Key Packet"
856	 */
857	m_buf[0] = sesskey->symm_alg;
858	for (i = 0; i < cipherinfo->keysize ; i++) {
859		/* XXX - Flexelint - Warning 679: Suspicious Truncation in arithmetic expression combining with pointer */
860		m_buf[1 + i] = sesskey->key[i];
861	}
862
863	return pgp_calc_sesskey_checksum(sesskey,
864				m_buf + 1 + cipherinfo->keysize);
865}
866
867/**
868\ingroup Core_Create
869\brief implementation of EME-PKCS1-v1_5-ENCODE, as defined in OpenPGP RFC
870\param M
871\param mLen
872\param pubkey
873\param EM
874\return 1 if OK; else 0
875*/
876unsigned
877encode_m_buf(const uint8_t *M, size_t mLen, const pgp_pubkey_t * pubkey,
878	     uint8_t *EM)
879{
880	unsigned    k;
881	unsigned        i;
882
883	/* implementation of EME-PKCS1-v1_5-ENCODE, as defined in OpenPGP RFC */
884	switch (pubkey->alg) {
885	case PGP_PKA_RSA:
886		k = (unsigned)BN_num_bytes(pubkey->key.rsa.n);
887		if (mLen > k - 11) {
888			(void) fprintf(stderr, "encode_m_buf: message too long\n");
889			return 0;
890		}
891		break;
892	case PGP_PKA_DSA:
893	case PGP_PKA_ELGAMAL:
894		k = (unsigned)BN_num_bytes(pubkey->key.elgamal.p);
895		if (mLen > k - 11) {
896			(void) fprintf(stderr, "encode_m_buf: message too long\n");
897			return 0;
898		}
899		break;
900	default:
901		(void) fprintf(stderr, "encode_m_buf: pubkey algorithm\n");
902		return 0;
903	}
904	/* these two bytes defined by RFC */
905	EM[0] = 0x00;
906	EM[1] = 0x02;
907	/* add non-zero random bytes of length k - mLen -3 */
908	for (i = 2; i < (k - mLen) - 1; ++i) {
909		do {
910			pgp_random(EM + i, 1);
911		} while (EM[i] == 0);
912	}
913	if (i < 8 + 2) {
914		(void) fprintf(stderr, "encode_m_buf: bad i len\n");
915		return 0;
916	}
917	EM[i++] = 0;
918	(void) memcpy(EM + i, M, mLen);
919	if (pgp_get_debug_level(__FILE__)) {
920		hexdump(stderr, "Encoded Message:", EM, mLen);
921	}
922	return 1;
923}
924
925/**
926 \ingroup Core_Create
927\brief Creates an pgp_pk_sesskey_t struct from keydata
928\param key Keydata to use
929\return pgp_pk_sesskey_t struct
930\note It is the caller's responsiblity to free the returned pointer
931\note Currently hard-coded to use CAST5
932\note Currently hard-coded to use RSA
933*/
934pgp_pk_sesskey_t *
935pgp_create_pk_sesskey(const pgp_key_t *key, const char *ciphername)
936{
937	/*
938         * Creates a random session key and encrypts it for the given key
939         *
940         * Encryption used is PK,
941         * can be any, we're hardcoding RSA for now
942         */
943
944	const pgp_pubkey_t	*pubkey;
945	pgp_pk_sesskey_t	*sesskey;
946	pgp_symm_alg_t	 cipher;
947	const uint8_t		*id;
948	pgp_crypt_t		 cipherinfo;
949	uint8_t			*unencoded_m_buf;
950	uint8_t			*encoded_m_buf;
951	size_t			 sz_encoded_m_buf;
952
953	if (memcmp(key->encid, "\0\0\0\0\0\0\0\0", 8) == 0) {
954		pubkey = pgp_get_pubkey(key);
955		id = key->sigid;
956	} else {
957		pubkey = &key->enckey;
958		id = key->encid;
959	}
960	/* allocate unencoded_m_buf here */
961	(void) memset(&cipherinfo, 0x0, sizeof(cipherinfo));
962	pgp_crypt_any(&cipherinfo,
963		cipher = pgp_str_to_cipher((ciphername) ? ciphername : "cast5"));
964	unencoded_m_buf = calloc(1, cipherinfo.keysize + 1 + 2);
965	if (unencoded_m_buf == NULL) {
966		(void) fprintf(stderr,
967			"pgp_create_pk_sesskey: can't allocate\n");
968		return NULL;
969	}
970	switch(pubkey->alg) {
971	case PGP_PKA_RSA:
972		sz_encoded_m_buf = BN_num_bytes(pubkey->key.rsa.n);
973		break;
974	case PGP_PKA_DSA:
975	case PGP_PKA_ELGAMAL:
976		sz_encoded_m_buf = BN_num_bytes(pubkey->key.elgamal.p);
977		break;
978	default:
979		sz_encoded_m_buf = 0;
980		break;
981	}
982	if ((encoded_m_buf = calloc(1, sz_encoded_m_buf)) == NULL) {
983		(void) fprintf(stderr,
984			"pgp_create_pk_sesskey: can't allocate\n");
985		free(unencoded_m_buf);
986		return NULL;
987	}
988	if ((sesskey = calloc(1, sizeof(*sesskey))) == NULL) {
989		(void) fprintf(stderr,
990			"pgp_create_pk_sesskey: can't allocate\n");
991		free(unencoded_m_buf);
992		free(encoded_m_buf);
993		return NULL;
994	}
995	if (key->type != PGP_PTAG_CT_PUBLIC_KEY) {
996		(void) fprintf(stderr,
997			"pgp_create_pk_sesskey: bad type\n");
998		free(unencoded_m_buf);
999		free(encoded_m_buf);
1000		free(sesskey);
1001		return NULL;
1002	}
1003	sesskey->version = PGP_PKSK_V3;
1004	(void) memcpy(sesskey->key_id, id, sizeof(sesskey->key_id));
1005
1006	if (pgp_get_debug_level(__FILE__)) {
1007		hexdump(stderr, "Encrypting for keyid", id, sizeof(sesskey->key_id));
1008	}
1009	switch (pubkey->alg) {
1010	case PGP_PKA_RSA:
1011	case PGP_PKA_DSA:
1012	case PGP_PKA_ELGAMAL:
1013		break;
1014	default:
1015		(void) fprintf(stderr,
1016			"pgp_create_pk_sesskey: bad pubkey algorithm\n");
1017		free(unencoded_m_buf);
1018		free(encoded_m_buf);
1019		free(sesskey);
1020		return NULL;
1021	}
1022	sesskey->alg = pubkey->alg;
1023
1024	sesskey->symm_alg = cipher;
1025	pgp_random(sesskey->key, cipherinfo.keysize);
1026
1027	if (pgp_get_debug_level(__FILE__)) {
1028		hexdump(stderr, "sesskey created", sesskey->key,
1029			cipherinfo.keysize + 1 + 2);
1030	}
1031	if (create_unencoded_m_buf(sesskey, &cipherinfo, &unencoded_m_buf[0]) == 0) {
1032		free(unencoded_m_buf);
1033		free(encoded_m_buf);
1034		free(sesskey);
1035		return NULL;
1036	}
1037	if (pgp_get_debug_level(__FILE__)) {
1038		hexdump(stderr, "uuencoded m buf", unencoded_m_buf, cipherinfo.keysize + 1 + 2);
1039	}
1040	encode_m_buf(unencoded_m_buf, cipherinfo.keysize + 1 + 2, pubkey, encoded_m_buf);
1041
1042	/* and encrypt it */
1043	switch (key->key.pubkey.alg) {
1044	case PGP_PKA_RSA:
1045		if (!pgp_rsa_encrypt_mpi(encoded_m_buf, sz_encoded_m_buf, pubkey,
1046				&sesskey->params)) {
1047			free(unencoded_m_buf);
1048			free(encoded_m_buf);
1049			free(sesskey);
1050			return NULL;
1051		}
1052		break;
1053	case PGP_PKA_DSA:
1054	case PGP_PKA_ELGAMAL:
1055		if (!pgp_elgamal_encrypt_mpi(encoded_m_buf, sz_encoded_m_buf, pubkey,
1056				&sesskey->params)) {
1057			free(unencoded_m_buf);
1058			free(encoded_m_buf);
1059			free(sesskey);
1060			return NULL;
1061		}
1062		break;
1063	default:
1064		/* will not get here - for lint only */
1065		break;
1066	}
1067	free(unencoded_m_buf);
1068	free(encoded_m_buf);
1069	return sesskey;
1070}
1071
1072/**
1073\ingroup Core_WritePackets
1074\brief Writes Public Key Session Key packet
1075\param info Write settings
1076\param pksk Public Key Session Key to write out
1077\return 1 if OK; else 0
1078*/
1079unsigned
1080pgp_write_pk_sesskey(pgp_output_t *output, pgp_pk_sesskey_t *pksk)
1081{
1082	/* XXX - Flexelint - Pointer parameter 'pksk' (line 1076) could be declared as pointing to const */
1083	if (pksk == NULL) {
1084		(void) fprintf(stderr,
1085			"pgp_write_pk_sesskey: NULL pksk\n");
1086		return 0;
1087	}
1088	switch (pksk->alg) {
1089	case PGP_PKA_RSA:
1090		return pgp_write_ptag(output, PGP_PTAG_CT_PK_SESSION_KEY) &&
1091			pgp_write_length(output, (unsigned)(1 + 8 + 1 +
1092				BN_num_bytes(pksk->params.rsa.encrypted_m) + 2)) &&
1093			pgp_write_scalar(output, (unsigned)pksk->version, 1) &&
1094			pgp_write(output, pksk->key_id, 8) &&
1095			pgp_write_scalar(output, (unsigned)pksk->alg, 1) &&
1096			pgp_write_mpi(output, pksk->params.rsa.encrypted_m)
1097			/* ??	&& pgp_write_scalar(output, 0, 2); */
1098			;
1099	case PGP_PKA_DSA:
1100	case PGP_PKA_ELGAMAL:
1101		return pgp_write_ptag(output, PGP_PTAG_CT_PK_SESSION_KEY) &&
1102			pgp_write_length(output, (unsigned)(1 + 8 + 1 +
1103				BN_num_bytes(pksk->params.elgamal.g_to_k) + 2 +
1104				BN_num_bytes(pksk->params.elgamal.encrypted_m) + 2)) &&
1105			pgp_write_scalar(output, (unsigned)pksk->version, 1) &&
1106			pgp_write(output, pksk->key_id, 8) &&
1107			pgp_write_scalar(output, (unsigned)pksk->alg, 1) &&
1108			pgp_write_mpi(output, pksk->params.elgamal.g_to_k) &&
1109			pgp_write_mpi(output, pksk->params.elgamal.encrypted_m)
1110			/* ??	&& pgp_write_scalar(output, 0, 2); */
1111			;
1112	default:
1113		(void) fprintf(stderr,
1114			"pgp_write_pk_sesskey: bad algorithm\n");
1115		return 0;
1116	}
1117}
1118
1119/**
1120\ingroup Core_WritePackets
1121\brief Writes MDC packet
1122\param hashed Hash for MDC
1123\param output Write settings
1124\return 1 if OK; else 0
1125*/
1126
1127unsigned
1128pgp_write_mdc(pgp_output_t *output, const uint8_t *hashed)
1129{
1130	/* write it out */
1131	return pgp_write_ptag(output, PGP_PTAG_CT_MDC) &&
1132		pgp_write_length(output, PGP_SHA1_HASH_SIZE) &&
1133		pgp_write(output, hashed, PGP_SHA1_HASH_SIZE);
1134}
1135
1136/**
1137\ingroup Core_WritePackets
1138\brief Writes Literal Data packet from buffer
1139\param data Buffer to write out
1140\param maxlen Max length of buffer
1141\param type Literal Data Type
1142\param output Write settings
1143\return 1 if OK; else 0
1144*/
1145unsigned
1146pgp_write_litdata(pgp_output_t *output,
1147			const uint8_t *data,
1148			const int maxlen,
1149			const pgp_litdata_enum type)
1150{
1151	/*
1152         * RFC4880 does not specify a meaning for filename or date.
1153         * It is implementation-dependent.
1154         * We will not implement them.
1155         */
1156	/* \todo do we need to check text data for <cr><lf> line endings ? */
1157	return pgp_write_ptag(output, PGP_PTAG_CT_LITDATA) &&
1158		pgp_write_length(output, (unsigned)(1 + 1 + 4 + maxlen)) &&
1159		pgp_write_scalar(output, (unsigned)type, 1) &&
1160		pgp_write_scalar(output, 0, 1) &&
1161		pgp_write_scalar(output, 0, 4) &&
1162		pgp_write(output, data, (unsigned)maxlen);
1163}
1164
1165/**
1166\ingroup Core_WritePackets
1167\brief Writes Literal Data packet from contents of file
1168\param filename Name of file to read from
1169\param type Literal Data Type
1170\param output Write settings
1171\return 1 if OK; else 0
1172*/
1173
1174unsigned
1175pgp_fileread_litdata(const char *filename,
1176				 const pgp_litdata_enum type,
1177				 pgp_output_t *output)
1178{
1179	pgp_memory_t	*mem;
1180	unsigned   	 ret;
1181	int		 len;
1182
1183	mem = pgp_memory_new();
1184	if (!pgp_mem_readfile(mem, filename)) {
1185		(void) fprintf(stderr, "pgp_mem_readfile of '%s' failed\n", filename);
1186		return 0;
1187	}
1188	len = (int)pgp_mem_len(mem);
1189	ret = pgp_write_litdata(output, pgp_mem_data(mem), len, type);
1190	pgp_memory_free(mem);
1191	return ret;
1192}
1193
1194/**
1195   \ingroup HighLevel_General
1196
1197   \brief Writes contents of buffer into file
1198
1199   \param filename Filename to write to
1200   \param buf Buffer to write to file
1201   \param len Size of buffer
1202   \param overwrite Flag to set whether to overwrite an existing file
1203   \return 1 if OK; 0 if error
1204*/
1205
1206int
1207pgp_filewrite(const char *filename, const char *buf,
1208			const size_t len, const unsigned overwrite)
1209{
1210	int		flags;
1211	int		fd;
1212
1213	flags = O_WRONLY | O_CREAT;
1214	if (overwrite) {
1215		flags |= O_TRUNC;
1216	} else {
1217		flags |= O_EXCL;
1218	}
1219#ifdef O_BINARY
1220	flags |= O_BINARY;
1221#endif
1222	fd = open(filename, flags, 0600);
1223	if (fd < 0) {
1224		(void) fprintf(stderr, "can't open '%s'\n", filename);
1225		return 0;
1226	}
1227	if (write(fd, buf, len) != (int)len) {
1228		(void) close(fd);
1229		return 0;
1230	}
1231
1232	return (close(fd) == 0);
1233}
1234
1235/**
1236\ingroup Core_WritePackets
1237\brief Write Symmetrically Encrypted packet
1238\param data Data to encrypt
1239\param len Length of data
1240\param output Write settings
1241\return 1 if OK; else 0
1242\note Hard-coded to use AES256
1243*/
1244unsigned
1245pgp_write_symm_enc_data(const uint8_t *data,
1246				       const int len,
1247				       pgp_output_t * output)
1248{
1249	pgp_crypt_t	crypt_info;
1250	uint8_t		*encrypted = (uint8_t *) NULL;
1251	size_t		encrypted_sz;
1252	int             done = 0;
1253
1254	/* \todo assume AES256 for now */
1255	pgp_crypt_any(&crypt_info, PGP_SA_AES_256);
1256	pgp_encrypt_init(&crypt_info);
1257
1258	encrypted_sz = (size_t)(len + crypt_info.blocksize + 2);
1259	if ((encrypted = calloc(1, encrypted_sz)) == NULL) {
1260		(void) fprintf(stderr, "can't allocate %" PRIsize "d\n",
1261			encrypted_sz);
1262		return 0;
1263	}
1264
1265	done = (int)pgp_encrypt_se(&crypt_info, encrypted, data, (unsigned)len);
1266	if (done != len) {
1267		(void) fprintf(stderr,
1268			"pgp_write_symm_enc_data: done != len\n");
1269		return 0;
1270	}
1271
1272	return pgp_write_ptag(output, PGP_PTAG_CT_SE_DATA) &&
1273		pgp_write_length(output, (unsigned)(1 + encrypted_sz)) &&
1274		pgp_write(output, data, (unsigned)len);
1275}
1276
1277/**
1278\ingroup Core_WritePackets
1279\brief Write a One Pass Signature packet
1280\param seckey Secret Key to use
1281\param hash_alg Hash Algorithm to use
1282\param sig_type Signature type
1283\param output Write settings
1284\return 1 if OK; else 0
1285*/
1286unsigned
1287pgp_write_one_pass_sig(pgp_output_t *output,
1288			const pgp_seckey_t *seckey,
1289			const pgp_hash_alg_t hash_alg,
1290			const pgp_sig_type_t sig_type)
1291{
1292	uint8_t   keyid[PGP_KEY_ID_SIZE];
1293
1294	pgp_keyid(keyid, PGP_KEY_ID_SIZE, &seckey->pubkey, PGP_HASH_SHA1); /* XXX - hardcoded */
1295	return pgp_write_ptag(output, PGP_PTAG_CT_1_PASS_SIG) &&
1296		pgp_write_length(output, 1 + 1 + 1 + 1 + 8 + 1) &&
1297		pgp_write_scalar(output, 3, 1)	/* version */ &&
1298		pgp_write_scalar(output, (unsigned)sig_type, 1) &&
1299		pgp_write_scalar(output, (unsigned)hash_alg, 1) &&
1300		pgp_write_scalar(output, (unsigned)seckey->pubkey.alg, 1) &&
1301		pgp_write(output, keyid, 8) &&
1302		pgp_write_scalar(output, 1, 1);
1303}
1304