netpgp.c revision 1.86
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#include "config.h"
30
31#ifdef HAVE_SYS_CDEFS_H
32#include <sys/cdefs.h>
33#endif
34
35#if defined(__NetBSD__)
36__COPYRIGHT("@(#) Copyright (c) 2009 The NetBSD Foundation, Inc. All rights reserved.");
37__RCSID("$NetBSD: netpgp.c,v 1.86 2010/12/01 22:01:41 agc Exp $");
38#endif
39
40#include <sys/types.h>
41#include <sys/stat.h>
42#include <sys/param.h>
43#include <sys/mman.h>
44
45#ifdef HAVE_SYS_RESOURCE_H
46#include <sys/resource.h>
47#endif
48
49#ifdef HAVE_FCNTL_H
50#include <fcntl.h>
51#endif
52
53#include <errno.h>
54#include <regex.h>
55#include <stdarg.h>
56#include <stdlib.h>
57#include <string.h>
58#include <time.h>
59
60#ifdef HAVE_UNISTD_H
61#include <unistd.h>
62#endif
63
64#include <errno.h>
65
66#ifdef HAVE_LIMITS_H
67#include <limits.h>
68#endif
69
70#include <netpgp.h>
71
72#include "packet.h"
73#include "packet-parse.h"
74#include "keyring.h"
75#include "errors.h"
76#include "packet-show.h"
77#include "create.h"
78#include "netpgpsdk.h"
79#include "memory.h"
80#include "validate.h"
81#include "readerwriter.h"
82#include "netpgpdefs.h"
83#include "crypto.h"
84#include "ssh2pgp.h"
85#include "defs.h"
86
87/* read any gpg config file */
88static int
89conffile(netpgp_t *netpgp, char *homedir, char *userid, size_t length)
90{
91	regmatch_t	 matchv[10];
92	regex_t		 keyre;
93	char		 buf[BUFSIZ];
94	FILE		*fp;
95
96	__PGP_USED(netpgp);
97	(void) snprintf(buf, sizeof(buf), "%s/gpg.conf", homedir);
98	if ((fp = fopen(buf, "r")) == NULL) {
99		return 0;
100	}
101	(void) memset(&keyre, 0x0, sizeof(keyre));
102	(void) regcomp(&keyre, "^[ \t]*default-key[ \t]+([0-9a-zA-F]+)",
103		REG_EXTENDED);
104	while (fgets(buf, (int)sizeof(buf), fp) != NULL) {
105		if (regexec(&keyre, buf, 10, matchv, 0) == 0) {
106			(void) memcpy(userid, &buf[(int)matchv[1].rm_so],
107				MIN((unsigned)(matchv[1].rm_eo -
108						matchv[1].rm_so), length));
109			if (netpgp->passfp == NULL) {
110				(void) fprintf(stderr,
111				"netpgp: default key set to \"%.*s\"\n",
112				(int)(matchv[1].rm_eo - matchv[1].rm_so),
113				&buf[(int)matchv[1].rm_so]);
114			}
115		}
116	}
117	(void) fclose(fp);
118	regfree(&keyre);
119	return 1;
120}
121
122/* small function to pretty print an 8-character raw userid */
123static char    *
124userid_to_id(const uint8_t *userid, char *id)
125{
126	static const char *hexes = "0123456789abcdef";
127	int		   i;
128
129	for (i = 0; i < 8 ; i++) {
130		id[i * 2] = hexes[(unsigned)(userid[i] & 0xf0) >> 4];
131		id[(i * 2) + 1] = hexes[userid[i] & 0xf];
132	}
133	id[8 * 2] = 0x0;
134	return id;
135}
136
137/* print out the successful signature information */
138static void
139resultp(pgp_io_t *io,
140	const char *f,
141	pgp_validation_t *res,
142	pgp_keyring_t *ring)
143{
144	const pgp_key_t	*key;
145	pgp_pubkey_t		*sigkey;
146	unsigned		 from;
147	unsigned		 i;
148	time_t			 t;
149	char			 id[MAX_ID_LENGTH + 1];
150
151	for (i = 0; i < res->validc; i++) {
152		(void) fprintf(io->res,
153			"Good signature for %s made %s",
154			(f) ? f : "<stdin>",
155			ctime(&res->valid_sigs[i].birthtime));
156		if (res->duration > 0) {
157			t = res->birthtime + res->duration;
158			(void) fprintf(io->res, "Valid until %s", ctime(&t));
159		}
160		(void) fprintf(io->res,
161			"using %s key %s\n",
162			pgp_show_pka(res->valid_sigs[i].key_alg),
163			userid_to_id(res->valid_sigs[i].signer_id, id));
164		from = 0;
165		key = pgp_getkeybyid(io, ring,
166			(const uint8_t *) res->valid_sigs[i].signer_id,
167			&from, &sigkey);
168		if (sigkey == &key->enckey) {
169			(void) fprintf(io->res,
170				"WARNING: signature for %s made with encryption key\n",
171				(f) ? f : "<stdin>");
172		}
173		pgp_print_keydata(io, ring, key, "signature ", &key->key.pubkey, 0);
174	}
175}
176
177/* check there's enough space in the arrays */
178static int
179size_arrays(netpgp_t *netpgp, unsigned needed)
180{
181	char	**temp;
182
183	if (netpgp->size == 0) {
184		/* only get here first time around */
185		netpgp->size = needed;
186		if ((netpgp->name = calloc(sizeof(char *), needed)) == NULL) {
187			(void) fprintf(stderr, "size_arrays: bad alloc\n");
188			return 0;
189		}
190		if ((netpgp->value = calloc(sizeof(char *), needed)) == NULL) {
191			free(netpgp->name);
192			(void) fprintf(stderr, "size_arrays: bad alloc\n");
193			return 0;
194		}
195	} else if (netpgp->c == netpgp->size) {
196		/* only uses 'needed' when filled array */
197		netpgp->size += needed;
198		temp = realloc(netpgp->name, sizeof(char *) * needed);
199		if (temp == NULL) {
200			(void) fprintf(stderr, "size_arrays: bad alloc\n");
201			return 0;
202		}
203		netpgp->name = temp;
204		temp = realloc(netpgp->value, sizeof(char *) * needed);
205		if (temp == NULL) {
206			(void) fprintf(stderr, "size_arrays: bad alloc\n");
207			return 0;
208		}
209		netpgp->value = temp;
210	}
211	return 1;
212}
213
214/* find the name in the array */
215static int
216findvar(netpgp_t *netpgp, const char *name)
217{
218	unsigned	i;
219
220	for (i = 0 ; i < netpgp->c && strcmp(netpgp->name[i], name) != 0; i++) {
221	}
222	return (i == netpgp->c) ? -1 : (int)i;
223}
224
225/* read a keyring and return it */
226static void *
227readkeyring(netpgp_t *netpgp, const char *name)
228{
229	pgp_keyring_t	*keyring;
230	const unsigned	 noarmor = 0;
231	char		 f[MAXPATHLEN];
232	char		*filename;
233	char		*homedir;
234
235	homedir = netpgp_getvar(netpgp, "homedir");
236	if ((filename = netpgp_getvar(netpgp, name)) == NULL) {
237		(void) snprintf(f, sizeof(f), "%s/%s.gpg", homedir, name);
238		filename = f;
239	}
240	if ((keyring = calloc(1, sizeof(*keyring))) == NULL) {
241		(void) fprintf(stderr, "readkeyring: bad alloc\n");
242		return NULL;
243	}
244	if (!pgp_keyring_fileread(keyring, noarmor, filename)) {
245		free(keyring);
246		(void) fprintf(stderr, "Can't read %s %s\n", name, filename);
247		return NULL;
248	}
249	netpgp_setvar(netpgp, name, filename);
250	return keyring;
251}
252
253/* read keys from ssh key files */
254static int
255readsshkeys(netpgp_t *netpgp, char *homedir, const char *needseckey)
256{
257	pgp_keyring_t	*pubring;
258	pgp_keyring_t	*secring;
259	struct stat	 st;
260	unsigned	 hashtype;
261	char		*hash;
262	char		 f[MAXPATHLEN];
263	char		*filename;
264
265	if ((filename = netpgp_getvar(netpgp, "sshkeyfile")) == NULL) {
266		/* set reasonable default for RSA key */
267		(void) snprintf(f, sizeof(f), "%s/id_rsa.pub", homedir);
268		filename = f;
269	} else if (strcmp(&filename[strlen(filename) - 4], ".pub") != 0) {
270		/* got ssh keys, check for pub file name */
271		(void) snprintf(f, sizeof(f), "%s.pub", filename);
272		filename = f;
273	}
274	/* check the pub file exists */
275	if (stat(filename, &st) != 0) {
276		(void) fprintf(stderr, "readsshkeys: bad pubkey filename '%s'\n", filename);
277		return 0;
278	}
279	if ((pubring = calloc(1, sizeof(*pubring))) == NULL) {
280		(void) fprintf(stderr, "readsshkeys: bad alloc\n");
281		return 0;
282	}
283	/* openssh2 keys use md5 by default */
284	hashtype = PGP_HASH_MD5;
285	if ((hash = netpgp_getvar(netpgp, "hash")) != NULL) {
286		/* openssh 2 hasn't really caught up to anything else yet */
287		if (netpgp_strcasecmp(hash, "md5") == 0) {
288			hashtype = PGP_HASH_MD5;
289		} else if (netpgp_strcasecmp(hash, "sha1") == 0) {
290			hashtype = PGP_HASH_SHA1;
291		} else if (netpgp_strcasecmp(hash, "sha256") == 0) {
292			hashtype = PGP_HASH_SHA256;
293		}
294	}
295	if (!pgp_ssh2_readkeys(netpgp->io, pubring, NULL, filename, NULL, hashtype)) {
296		free(pubring);
297		(void) fprintf(stderr, "readsshkeys: can't read %s\n",
298				filename);
299		return 0;
300	}
301	if (netpgp->pubring == NULL) {
302		netpgp->pubring = pubring;
303	} else {
304		pgp_append_keyring(netpgp->pubring, pubring);
305	}
306	if (needseckey) {
307		netpgp_setvar(netpgp, "sshpubfile", filename);
308		/* try to take the ".pub" off the end */
309		if (filename == f) {
310			f[strlen(f) - 4] = 0x0;
311		} else {
312			(void) snprintf(f, sizeof(f), "%.*s",
313					(int)strlen(filename) - 4, filename);
314			filename = f;
315		}
316		if ((secring = calloc(1, sizeof(*secring))) == NULL) {
317			(void) fprintf(stderr, "readsshkeys: bad alloc\n");
318			return 0;
319		}
320		if (!pgp_ssh2_readkeys(netpgp->io, pubring, secring, NULL, filename, hashtype)) {
321			(void) fprintf(stderr, "readsshkeys: can't read sec %s\n", filename);
322			return 0;
323		}
324		netpgp->secring = secring;
325		netpgp_setvar(netpgp, "sshsecfile", filename);
326	}
327	return 1;
328}
329
330/* set ssh uid to first one in pubring */
331static void
332set_first_pubring(pgp_keyring_t *pubring, char *id, size_t len, int last)
333{
334	uint8_t	*src;
335	int	 i;
336	int	 n;
337
338	(void) memset(id, 0x0, len);
339	src = pubring->keys[(last) ? pubring->keyc - 1 : 0].sigid;
340	for (i = 0, n = 0 ; i < PGP_KEY_ID_SIZE ; i += 2) {
341		n += snprintf(&id[n], len - n, "%02x%02x", src[i], src[i + 1]);
342	}
343	id[n] = 0x0;
344}
345
346/* find the time - in a specific %Y-%m-%d format - using a regexp */
347static int
348grabdate(char *s, int64_t *t)
349{
350	static regex_t	r;
351	static int	compiled;
352	regmatch_t	matches[10];
353	struct tm	tm;
354
355	if (!compiled) {
356		compiled = 1;
357		(void) regcomp(&r, "([0-9][0-9][0-9][0-9])[-/]([0-9][0-9])[-/]([0-9][0-9])", REG_EXTENDED);
358	}
359	if (regexec(&r, s, 10, matches, 0) == 0) {
360		(void) memset(&tm, 0x0, sizeof(tm));
361		tm.tm_year = (int)strtol(&s[(int)matches[1].rm_so], NULL, 10);
362		tm.tm_mon = (int)strtol(&s[(int)matches[2].rm_so], NULL, 10) - 1;
363		tm.tm_mday = (int)strtol(&s[(int)matches[3].rm_so], NULL, 10);
364		*t = mktime(&tm);
365		return 1;
366	}
367	return 0;
368}
369
370/* get expiration in seconds */
371static uint64_t
372get_duration(char *s)
373{
374	uint64_t	 now;
375	int64_t	 	 t;
376	char		*mult;
377
378	if (s == NULL) {
379		return 0;
380	}
381	now = (uint64_t)strtoull(s, NULL, 10);
382	if ((mult = strchr("hdwmy", s[strlen(s) - 1])) != NULL) {
383		switch(*mult) {
384		case 'h':
385			return now * 60 * 60;
386		case 'd':
387			return now * 60 * 60 * 24;
388		case 'w':
389			return now * 60 * 60 * 24 * 7;
390		case 'm':
391			return now * 60 * 60 * 24 * 31;
392		case 'y':
393			return now * 60 * 60 * 24 * 365;
394		}
395	}
396	if (grabdate(s, &t)) {
397		return t;
398	}
399	return (uint64_t)strtoll(s, NULL, 10);
400}
401
402/* get birthtime in seconds */
403static int64_t
404get_birthtime(char *s)
405{
406	int64_t	t;
407
408	if (s == NULL) {
409		return time(NULL);
410	}
411	if (grabdate(s, &t)) {
412		return t;
413	}
414	return (uint64_t)strtoll(s, NULL, 10);
415}
416
417/* resolve the userid */
418static const pgp_key_t *
419resolve_userid(netpgp_t *netpgp, const pgp_keyring_t *keyring, const char *userid)
420{
421	const pgp_key_t	*key;
422	pgp_io_t		*io;
423
424	if (userid == NULL) {
425		userid = netpgp_getvar(netpgp, "userid");
426		if (userid == NULL)
427			return NULL;
428	} else if (userid[0] == '0' && userid[1] == 'x') {
429		userid += 2;
430	}
431	io = netpgp->io;
432	if ((key = pgp_getkeybyname(io, keyring, userid)) == NULL) {
433		(void) fprintf(io->errs, "Can't find key '%s'\n", userid);
434	}
435	return key;
436}
437
438/* append a key to a keyring */
439static int
440appendkey(pgp_io_t *io, pgp_key_t *key, char *ringfile)
441{
442	pgp_output_t	*create;
443	const unsigned	 noarmor = 0;
444	int		 fd;
445
446	if ((fd = pgp_setup_file_append(&create, ringfile)) < 0) {
447		fd = pgp_setup_file_write(&create, ringfile, 0);
448	}
449	if (fd < 0) {
450		(void) fprintf(io->errs, "can't open pubring '%s'\n", ringfile);
451		return 0;
452	}
453	if (!pgp_write_xfer_pubkey(create, key, noarmor)) {
454		(void) fprintf(io->errs, "Cannot write pubkey\n");
455		return 0;
456	}
457	pgp_teardown_file_write(create, fd);
458	return 1;
459}
460
461/* return 1 if the file contains ascii-armoured text */
462static unsigned
463isarmoured(pgp_io_t *io, const char *f, const void *memory, const char *text)
464{
465	regmatch_t	 matches[10];
466	unsigned	 armoured;
467	regex_t		 r;
468	FILE		*fp;
469	char	 	 buf[BUFSIZ];
470
471	armoured = 0;
472	(void) regcomp(&r, text, REG_EXTENDED);
473	if (f) {
474		if ((fp = fopen(f, "r")) == NULL) {
475			(void) fprintf(io->errs, "isarmoured: can't open '%s'\n", f);
476			regfree(&r);
477			return 0;
478		}
479		if (fgets(buf, (int)sizeof(buf), fp) != NULL) {
480			if (regexec(&r, buf, 10, matches, 0) == 0) {
481				armoured = 1;
482			}
483		}
484		(void) fclose(fp);
485	} else {
486		if (regexec(&r, memory, 10, matches, 0) == 0) {
487			armoured = 1;
488		}
489	}
490	regfree(&r);
491	return armoured;
492}
493
494/* vararg print function */
495static void
496p(FILE *fp, const char *s, ...)
497{
498	va_list	args;
499
500	va_start(args, s);
501	while (s != NULL) {
502		(void) fprintf(fp, "%s", s);
503		s = va_arg(args, char *);
504	}
505	va_end(args);
506}
507
508/* print a JSON object to the FILE stream */
509static void
510pobj(FILE *fp, mj_t *obj, int depth)
511{
512	unsigned	i;
513
514	if (obj == NULL) {
515		(void) fprintf(stderr, "No object found\n");
516		return;
517	}
518	for (i = 0 ; i < (unsigned)depth ; i++) {
519		p(fp, " ", NULL);
520	}
521	switch(obj->type) {
522	case MJ_NULL:
523	case MJ_FALSE:
524	case MJ_TRUE:
525		p(fp, (obj->type == MJ_NULL) ? "null" : (obj->type == MJ_FALSE) ? "false" : "true", NULL);
526		break;
527	case MJ_NUMBER:
528		p(fp, obj->value.s, NULL);
529		break;
530	case MJ_STRING:
531		(void) fprintf(fp, "%.*s", (int)(obj->c), obj->value.s);
532		break;
533	case MJ_ARRAY:
534		for (i = 0 ; i < obj->c ; i++) {
535			pobj(fp, &obj->value.v[i], depth + 1);
536			if (i < obj->c - 1) {
537				(void) fprintf(fp, ", ");
538			}
539		}
540		(void) fprintf(fp, "\n");
541		break;
542	case MJ_OBJECT:
543		for (i = 0 ; i < obj->c ; i += 2) {
544			pobj(fp, &obj->value.v[i], depth + 1);
545			p(fp, ": ", NULL);
546			pobj(fp, &obj->value.v[i + 1], 0);
547			if (i < obj->c - 1) {
548				p(fp, ", ", NULL);
549			}
550		}
551		p(fp, "\n", NULL);
552		break;
553	default:
554		break;
555	}
556}
557
558/* return the time as a string */
559static char *
560ptimestr(char *dest, size_t size, time_t t)
561{
562	struct tm      *tm;
563
564	tm = gmtime(&t);
565	(void) snprintf(dest, size, "%04d-%02d-%02d",
566		tm->tm_year + 1900,
567		tm->tm_mon + 1,
568		tm->tm_mday);
569	return dest;
570}
571
572/* format a JSON object */
573static void
574format_json_key(FILE *fp, mj_t *obj, const int psigs)
575{
576	int64_t	 birthtime;
577	int64_t	 duration;
578	time_t	 now;
579	char	 tbuf[32];
580	char	*s;
581	mj_t	*sub;
582	int	 i;
583
584	if (pgp_get_debug_level(__FILE__)) {
585		mj_asprint(&s, obj);
586		(void) fprintf(stderr, "formatobj: json is '%s'\n", s);
587		free(s);
588	}
589	if (obj->c == 2 && obj->value.v[1].type == MJ_STRING &&
590	    strcmp(obj->value.v[1].value.s, "[REVOKED]") == 0) {
591		/* whole key has been rovoked - just return */
592		return;
593	}
594	pobj(fp, &obj->value.v[mj_object_find(obj, "header", 0, 2) + 1], 0);
595	p(fp, " ", NULL);
596	pobj(fp, &obj->value.v[mj_object_find(obj, "key bits", 0, 2) + 1], 0);
597	p(fp, "/", NULL);
598	pobj(fp, &obj->value.v[mj_object_find(obj, "pka", 0, 2) + 1], 0);
599	p(fp, " ", NULL);
600	pobj(fp, &obj->value.v[mj_object_find(obj, "key id", 0, 2) + 1], 0);
601	birthtime = strtoll(obj->value.v[mj_object_find(obj, "birthtime", 0, 2) + 1].value.s, NULL, 10);
602	p(fp, " ", ptimestr(tbuf, sizeof(tbuf), birthtime), NULL);
603	duration = strtoll(obj->value.v[mj_object_find(obj, "duration", 0, 2) + 1].value.s, NULL, 10);
604	if (duration > 0) {
605		now = time(NULL);
606		p(fp, " ", (birthtime + duration < now) ? "[EXPIRED " : "[EXPIRES ",
607			ptimestr(tbuf, sizeof(tbuf), birthtime + duration), "]", NULL);
608	}
609	p(fp, "\n", "Key fingerprint: ", NULL);
610	pobj(fp, &obj->value.v[mj_object_find(obj, "fingerprint", 0, 2) + 1], 0);
611	p(fp, "\n", NULL);
612	/* go to field after \"duration\" */
613	for (i = mj_object_find(obj, "duration", 0, 2) + 2; i < mj_arraycount(obj) ; i += 2) {
614		if (strcmp(obj->value.v[i].value.s, "uid") == 0) {
615			sub = &obj->value.v[i + 1];
616			p(fp, "uid", NULL);
617			pobj(fp, &sub->value.v[0], (psigs) ? 4 : 14); /* human name */
618			pobj(fp, &sub->value.v[1], 1); /* any revocation */
619			p(fp, "\n", NULL);
620		} else if (strcmp(obj->value.v[i].value.s, "encryption") == 0) {
621			sub = &obj->value.v[i + 1];
622			p(fp, "encryption", NULL);
623			pobj(fp, &sub->value.v[0], 1);	/* size */
624			p(fp, "/", NULL);
625			pobj(fp, &sub->value.v[1], 0); /* alg */
626			p(fp, " ", NULL);
627			pobj(fp, &sub->value.v[2], 0); /* id */
628			p(fp, " ", ptimestr(tbuf, sizeof(tbuf), strtoll(sub->value.v[3].value.s, NULL, 10)),
629				"\n", NULL);
630		} else if (strcmp(obj->value.v[i].value.s, "sig") == 0) {
631			sub = &obj->value.v[i + 1];
632			p(fp, "sig", NULL);
633			pobj(fp, &sub->value.v[0], 8);	/* size */
634			p(fp, "  ", ptimestr(tbuf, sizeof(tbuf), strtoll(sub->value.v[1].value.s, NULL, 10)),
635				" ", NULL); /* time */
636			pobj(fp, &sub->value.v[2], 0); /* human name */
637			p(fp, "\n", NULL);
638		} else {
639			fprintf(stderr, "weird '%s'\n", obj->value.v[i].value.s);
640			pobj(fp, &obj->value.v[i], 0); /* human name */
641		}
642	}
643	p(fp, "\n", NULL);
644}
645
646/* save a pgp pubkey to a temp file */
647static int
648savepubkey(char *res, char *f, size_t size)
649{
650	size_t	len;
651	int	cc;
652	int	wc;
653	int	fd;
654
655	(void) snprintf(f, size, "/tmp/pgp2ssh.XXXXXXX");
656	if ((fd = mkstemp(f)) < 0) {
657		(void) fprintf(stderr, "can't create temp file '%s'\n", f);
658		return 0;
659	}
660	len = strlen(res);
661	for (cc = 0 ; (wc = write(fd, &res[cc], len - cc)) > 0 ; cc += wc) {
662	}
663	(void) close(fd);
664	return 1;
665}
666
667/* format a uint32_t */
668static int
669formatu32(uint8_t *buffer, uint32_t value)
670{
671	buffer[0] = (uint8_t)(value >> 24) & 0xff;
672	buffer[1] = (uint8_t)(value >> 16) & 0xff;
673	buffer[2] = (uint8_t)(value >> 8) & 0xff;
674	buffer[3] = (uint8_t)value & 0xff;
675	return sizeof(uint32_t);
676}
677
678/* format a string as (len, string) */
679static int
680formatstring(char *buffer, const uint8_t *s, size_t len)
681{
682	int	cc;
683
684	cc = formatu32((uint8_t *)buffer, len);
685	(void) memcpy(&buffer[cc], s, len);
686	return cc + len;
687}
688
689/* format a bignum, checking for "interesting" high bit values */
690static int
691formatbignum(char *buffer, BIGNUM *bn)
692{
693	size_t	 len;
694	uint8_t	*cp;
695	int	 cc;
696
697	len = (size_t) BN_num_bytes(bn);
698	if ((cp = calloc(1, len + 1)) == NULL) {
699		(void) fprintf(stderr, "calloc failure in formatbignum\n");
700		return 0;
701	}
702	(void) BN_bn2bin(bn, cp + 1);
703	cp[0] = 0x0;
704	cc = (cp[1] & 0x80) ? formatstring(buffer, cp, len + 1) : formatstring(buffer, &cp[1], len);
705	free(cp);
706	return cc;
707}
708
709#define MAX_PASSPHRASE_ATTEMPTS	3
710#define INFINITE_ATTEMPTS	-1
711
712/* get the passphrase from the user */
713static int
714find_passphrase(FILE *passfp, const char *id, char *passphrase, size_t size, int attempts)
715{
716	char	 prompt[BUFSIZ];
717	char	 buf[128];
718	char	*cp;
719	int	 cc;
720	int	 i;
721
722	if (passfp) {
723		if (fgets(passphrase, (int)size, passfp) == NULL) {
724			return 0;
725		}
726		return strlen(passphrase);
727	}
728	for (i = 0 ; i < attempts ; i++) {
729		(void) snprintf(prompt, sizeof(prompt), "Enter passphrase for %.16s: ", id);
730		if ((cp = getpass(prompt)) == NULL) {
731			break;
732		}
733		cc = snprintf(buf, sizeof(buf), "%s", cp);
734		(void) snprintf(prompt, sizeof(prompt), "Repeat passphrase for %.16s: ", id);
735		if ((cp = getpass(prompt)) == NULL) {
736			break;
737		}
738		cc = snprintf(passphrase, size, "%s", cp);
739		if (strcmp(buf, passphrase) == 0) {
740			(void) memset(buf, 0x0, sizeof(buf));
741			return cc;
742		}
743	}
744	(void) memset(buf, 0x0, sizeof(buf));
745	(void) memset(passphrase, 0x0, size);
746	return 0;
747}
748
749/***************************************************************************/
750/* exported functions start here */
751/***************************************************************************/
752
753/* initialise a netpgp_t structure */
754int
755netpgp_init(netpgp_t *netpgp)
756{
757	pgp_io_t	*io;
758	char		 id[MAX_ID_LENGTH];
759	char		*homedir;
760	char		*userid;
761	char		*stream;
762	char		*passfd;
763	char		*results;
764	int		 coredumps;
765	int		 last;
766
767#ifdef HAVE_SYS_RESOURCE_H
768	struct rlimit	limit;
769
770	coredumps = netpgp_getvar(netpgp, "coredumps") != NULL;
771	if (!coredumps) {
772		(void) memset(&limit, 0x0, sizeof(limit));
773		if (setrlimit(RLIMIT_CORE, &limit) != 0) {
774			(void) fprintf(stderr,
775			"netpgp: warning - can't turn off core dumps\n");
776			coredumps = 1;
777		}
778	}
779#else
780	coredumps = 1;
781#endif
782	if ((io = calloc(1, sizeof(*io))) == NULL) {
783		(void) fprintf(stderr, "netpgp_init: bad alloc\n");
784		return 0;
785	}
786	io->outs = stdout;
787	if ((stream = netpgp_getvar(netpgp, "outs")) != NULL &&
788	    strcmp(stream, "<stderr>") == 0) {
789		io->outs = stderr;
790	}
791	io->errs = stderr;
792	if ((stream = netpgp_getvar(netpgp, "errs")) != NULL &&
793	    strcmp(stream, "<stdout>") == 0) {
794		io->errs = stdout;
795	}
796	if ((results = netpgp_getvar(netpgp, "res")) == NULL) {
797		io->res = io->errs;
798	} else if (strcmp(results, "<stdout>") == 0) {
799		io->res = stdout;
800	} else if (strcmp(results, "<stderr>") == 0) {
801		io->res = stderr;
802	} else {
803		if ((io->res = fopen(results, "w")) == NULL) {
804			(void) fprintf(io->errs, "Can't open results %s for writing\n",
805				results);
806			free(io);
807			return 0;
808		}
809	}
810	netpgp->io = io;
811	if ((passfd = netpgp_getvar(netpgp, "pass-fd")) != NULL &&
812	    (netpgp->passfp = fdopen(atoi(passfd), "r")) == NULL) {
813		(void) fprintf(io->errs, "Can't open fd %s for reading\n",
814			passfd);
815		return 0;
816	}
817	if (coredumps) {
818		(void) fprintf(io->errs,
819			"netpgp: warning: core dumps enabled\n");
820	}
821	if ((homedir = netpgp_getvar(netpgp, "homedir")) == NULL) {
822		(void) fprintf(io->errs, "netpgp: bad homedir\n");
823		return 0;
824	}
825	/* read from either gpg files or ssh keys */
826	if (netpgp_getvar(netpgp, "ssh keys") == NULL) {
827		if ((userid = netpgp_getvar(netpgp, "userid")) == NULL) {
828			(void) memset(id, 0x0, sizeof(id));
829			(void) conffile(netpgp, homedir, id, sizeof(id));
830			if (id[0] != 0x0) {
831				netpgp_setvar(netpgp, "userid", userid = id);
832			}
833		}
834		if (userid == NULL) {
835			if (netpgp_getvar(netpgp, "need userid") != NULL) {
836				(void) fprintf(io->errs,
837						"Cannot find user id\n");
838				return 0;
839			}
840		} else {
841			(void) netpgp_setvar(netpgp, "userid", userid);
842		}
843		netpgp->pubring = readkeyring(netpgp, "pubring");
844		if (netpgp->pubring == NULL) {
845			(void) fprintf(io->errs, "Can't read pub keyring\n");
846			return 0;
847		}
848		netpgp->secring = readkeyring(netpgp, "secring");
849		if (netpgp->secring == NULL) {
850			(void) fprintf(io->errs, "Can't read sec keyring\n");
851			return 0;
852		}
853	} else {
854		last = (netpgp->pubring != NULL);
855		if (!readsshkeys(netpgp, homedir, netpgp_getvar(netpgp, "need seckey"))) {
856			(void) fprintf(io->errs, "Can't read ssh keys\n");
857			return 0;
858		}
859		if ((userid = netpgp_getvar(netpgp, "userid")) == NULL) {
860			set_first_pubring(netpgp->pubring, id, sizeof(id), last);
861			netpgp_setvar(netpgp, "userid", userid = id);
862		}
863		if (userid == NULL) {
864			if (netpgp_getvar(netpgp, "need userid") != NULL) {
865				(void) fprintf(io->errs,
866						"Cannot find user id\n");
867				return 0;
868			}
869		} else {
870			(void) netpgp_setvar(netpgp, "userid", userid);
871		}
872	}
873	return 1;
874}
875
876/* finish off with the netpgp_t struct */
877int
878netpgp_end(netpgp_t *netpgp)
879{
880	unsigned	i;
881
882	for (i = 0 ; i < netpgp->c ; i++) {
883		if (netpgp->name[i] != NULL) {
884			free(netpgp->name[i]);
885		}
886		if (netpgp->value[i] != NULL) {
887			free(netpgp->value[i]);
888		}
889	}
890	if (netpgp->name != NULL) {
891		free(netpgp->name);
892	}
893	if (netpgp->value != NULL) {
894		free(netpgp->value);
895	}
896	if (netpgp->pubring != NULL) {
897		pgp_keyring_free(netpgp->pubring);
898	}
899	if (netpgp->secring != NULL) {
900		pgp_keyring_free(netpgp->secring);
901	}
902	free(netpgp->io);
903	return 1;
904}
905
906/* list the keys in a keyring */
907int
908netpgp_list_keys(netpgp_t *netpgp, const int psigs)
909{
910	if (netpgp->pubring == NULL) {
911		(void) fprintf(stderr, "No keyring\n");
912		return 0;
913	}
914	return pgp_keyring_list(netpgp->io, netpgp->pubring, psigs);
915}
916
917/* list the keys in a keyring, returning a JSON string */
918int
919netpgp_list_keys_json(netpgp_t *netpgp, char **json, const int psigs)
920{
921	mj_t	obj;
922	int	ret;
923
924	if (netpgp->pubring == NULL) {
925		(void) fprintf(stderr, "No keyring\n");
926		return 0;
927	}
928	(void) memset(&obj, 0x0, sizeof(obj));
929	if (!pgp_keyring_json(netpgp->io, netpgp->pubring, &obj, psigs)) {
930		(void) fprintf(stderr, "No keys in keyring\n");
931		return 0;
932	}
933	ret = mj_asprint(json, &obj);
934	mj_delete(&obj);
935	return ret;
936}
937
938DEFINE_ARRAY(strings_t, char *);
939
940#ifndef HKP_VERSION
941#define HKP_VERSION	1
942#endif
943
944/* find and list some keys in a keyring */
945int
946netpgp_match_keys(netpgp_t *netpgp, char *name, const char *fmt, void *vp, const int psigs)
947{
948	const pgp_key_t	*key;
949	unsigned		 k;
950	strings_t		 pubs;
951	FILE			*fp = (FILE *)vp;
952
953	if (name[0] == '0' && name[1] == 'x') {
954		name += 2;
955	}
956	(void) memset(&pubs, 0x0, sizeof(pubs));
957	k = 0;
958	do {
959		key = pgp_getnextkeybyname(netpgp->io, netpgp->pubring,
960						name, &k);
961		if (key != NULL) {
962			ALLOC(char *, pubs.v, pubs.size, pubs.c, 10, 10,
963					"netpgp_match_keys", return 0);
964			if (strcmp(fmt, "mr") == 0) {
965				pgp_hkp_sprint_keydata(netpgp->io, netpgp->pubring,
966						key, &pubs.v[pubs.c],
967						&key->key.pubkey, psigs);
968			} else {
969				pgp_sprint_keydata(netpgp->io, netpgp->pubring,
970						key, &pubs.v[pubs.c],
971						"signature ",
972						&key->key.pubkey, psigs);
973			}
974			if (pubs.v[pubs.c] != NULL) {
975				pubs.c += 1;
976			}
977			k += 1;
978		}
979	} while (key != NULL);
980	if (strcmp(fmt, "mr") == 0) {
981		(void) fprintf(fp, "info:%d:%d\n", HKP_VERSION, pubs.c);
982	} else {
983		(void) fprintf(fp, "%d key%s found\n", pubs.c,
984			(pubs.c == 1) ? "" : "s");
985	}
986	for (k = 0 ; k < pubs.c ; k++) {
987		(void) fprintf(fp, "%s%s", pubs.v[k], (k < pubs.c - 1) ? "\n" : "");
988		free(pubs.v[k]);
989	}
990	free(pubs.v);
991	return pubs.c;
992}
993
994/* find and list some keys in a keyring - return JSON string */
995int
996netpgp_match_keys_json(netpgp_t *netpgp, char **json, char *name, const char *fmt, const int psigs)
997{
998	const pgp_key_t	*key;
999	unsigned		 k;
1000	mj_t			 id_array;
1001	int			 ret;
1002
1003	if (name[0] == '0' && name[1] == 'x') {
1004		name += 2;
1005	}
1006	(void) memset(&id_array, 0x0, sizeof(id_array));
1007	k = 0;
1008	*json = NULL;
1009	mj_create(&id_array, "array");
1010	do {
1011		key = pgp_getnextkeybyname(netpgp->io, netpgp->pubring,
1012						name, &k);
1013		if (key != NULL) {
1014			if (strcmp(fmt, "mr") == 0) {
1015#if 0
1016				pgp_hkp_sprint_keydata(netpgp->io, netpgp->pubring,
1017						key, &pubs.v[pubs.c],
1018						&key->key.pubkey, psigs);
1019#endif
1020			} else {
1021				ALLOC(mj_t, id_array.value.v, id_array.size,
1022					id_array.c, 10, 10, "netpgp_match_keys_json", return 0);
1023				pgp_sprint_mj(netpgp->io, netpgp->pubring,
1024						key, &id_array.value.v[id_array.c++],
1025						"signature ",
1026						&key->key.pubkey, psigs);
1027			}
1028			k += 1;
1029		}
1030	} while (key != NULL);
1031	ret = mj_asprint(json, &id_array);
1032	mj_delete(&id_array);
1033	return ret;
1034}
1035
1036/* find and list some public keys in a keyring */
1037int
1038netpgp_match_pubkeys(netpgp_t *netpgp, char *name, void *vp)
1039{
1040	const pgp_key_t	*key;
1041	unsigned		 k;
1042	strings_t		 pubs;
1043	FILE			*fp = (FILE *)vp;
1044
1045	(void) memset(&pubs, 0x0, sizeof(pubs));
1046	do {
1047		key = pgp_getnextkeybyname(netpgp->io, netpgp->pubring,
1048						name, &k);
1049		if (key != NULL) {
1050			char	out[1024 * 64];
1051
1052			ALLOC(char *, pubs.v, pubs.size, pubs.c, 10, 10,
1053					"netpgp_match_pubkeys", return 0);
1054			(void) pgp_sprint_pubkey(key, out, sizeof(out));
1055			pubs.v[pubs.c++] = netpgp_strdup(out);
1056			k += 1;
1057		}
1058	} while (key != NULL);
1059	(void) fprintf(fp, "info:%d:%d\n", HKP_VERSION, pubs.c);
1060	for (k = 0 ; k < pubs.c ; k++) {
1061		(void) fprintf(fp, "%s", pubs.v[k]);
1062		free(pubs.v[k]);
1063	}
1064	free(pubs.v);
1065	return pubs.c;
1066}
1067
1068/* find a key in a keyring */
1069int
1070netpgp_find_key(netpgp_t *netpgp, char *id)
1071{
1072	pgp_io_t	*io;
1073
1074	io = netpgp->io;
1075	if (id == NULL) {
1076		(void) fprintf(io->errs, "NULL id to search for\n");
1077		return 0;
1078	}
1079	return pgp_getkeybyname(netpgp->io, netpgp->pubring, id) != NULL;
1080}
1081
1082/* get a key in a keyring */
1083char *
1084netpgp_get_key(netpgp_t *netpgp, const char *name, const char *fmt)
1085{
1086	const pgp_key_t	*key;
1087	char			*newkey;
1088
1089	if ((key = resolve_userid(netpgp, netpgp->pubring, name)) == NULL) {
1090		return NULL;
1091	}
1092	if (strcmp(fmt, "mr") == 0) {
1093		return (pgp_hkp_sprint_keydata(netpgp->io, netpgp->pubring,
1094				key, &newkey,
1095				&key->key.pubkey,
1096				netpgp_getvar(netpgp, "subkey sigs") != NULL) > 0) ? newkey : NULL;
1097	}
1098	return (pgp_sprint_keydata(netpgp->io, netpgp->pubring,
1099				key, &newkey, "signature",
1100				&key->key.pubkey,
1101				netpgp_getvar(netpgp, "subkey sigs") != NULL) > 0) ? newkey : NULL;
1102}
1103
1104/* export a given key */
1105char *
1106netpgp_export_key(netpgp_t *netpgp, char *name)
1107{
1108	const pgp_key_t	*key;
1109	pgp_io_t		*io;
1110
1111	io = netpgp->io;
1112	if ((key = resolve_userid(netpgp, netpgp->pubring, name)) == NULL) {
1113		return NULL;
1114	}
1115	return pgp_export_key(io, key, NULL);
1116}
1117
1118#define IMPORT_ARMOR_HEAD	"-----BEGIN PGP PUBLIC KEY BLOCK-----"
1119
1120/* import a key into our keyring */
1121int
1122netpgp_import_key(netpgp_t *netpgp, char *f)
1123{
1124	pgp_io_t	*io;
1125	unsigned	 realarmor;
1126	int		 done;
1127
1128	io = netpgp->io;
1129	realarmor = isarmoured(io, f, NULL, IMPORT_ARMOR_HEAD);
1130	done = pgp_keyring_fileread(netpgp->pubring, realarmor, f);
1131	if (!done) {
1132		(void) fprintf(io->errs, "Cannot import key from file %s\n", f);
1133		return 0;
1134	}
1135	return pgp_keyring_list(io, netpgp->pubring, 0);
1136}
1137
1138#define ID_OFFSET	38
1139
1140/* generate a new key */
1141int
1142netpgp_generate_key(netpgp_t *netpgp, char *id, int numbits)
1143{
1144	pgp_output_t		*create;
1145	const unsigned		 noarmor = 0;
1146	pgp_key_t		*key;
1147	pgp_io_t		*io;
1148	uint8_t			*uid;
1149	char			 passphrase[128];
1150	char			 newid[1024];
1151	char			 filename[MAXPATHLEN];
1152	char			 dir[MAXPATHLEN];
1153	char			*cp;
1154	char			*ringfile;
1155	char			*numtries;
1156	int             	 attempts;
1157	int             	 passc;
1158	int             	 fd;
1159	int             	 cc;
1160
1161	uid = NULL;
1162	io = netpgp->io;
1163	/* generate a new key */
1164	if (id) {
1165		(void) snprintf(newid, sizeof(newid), "%s", id);
1166	} else {
1167		(void) snprintf(newid, sizeof(newid),
1168			"RSA %d-bit key <%s@localhost>", numbits, getenv("LOGNAME"));
1169	}
1170	uid = (uint8_t *)newid;
1171	key = pgp_rsa_new_selfsign_key(numbits, 65537UL, uid,
1172			netpgp_getvar(netpgp, "hash"),
1173			netpgp_getvar(netpgp, "cipher"));
1174	if (key == NULL) {
1175		(void) fprintf(io->errs, "Cannot generate key\n");
1176		return 0;
1177	}
1178	cp = NULL;
1179	pgp_sprint_keydata(netpgp->io, NULL, key, &cp, "signature ", &key->key.seckey.pubkey, 0);
1180	(void) fprintf(stdout, "%s", cp);
1181	/* write public key */
1182	cc = snprintf(dir, sizeof(dir), "%s/%.16s", netpgp_getvar(netpgp, "homedir"), &cp[ID_OFFSET]);
1183	netpgp_setvar(netpgp, "userid", &dir[cc - 16]);
1184	if (mkdir(dir, 0700) < 0) {
1185		(void) fprintf(io->errs, "can't mkdir '%s'\n", dir);
1186		return 0;
1187	}
1188	(void) fprintf(io->errs, "netpgp: generated keys in directory %s\n", dir);
1189	(void) snprintf(ringfile = filename, sizeof(filename), "%s/pubring.gpg", dir);
1190	if (!appendkey(io, key, ringfile)) {
1191		(void) fprintf(io->errs, "Cannot write pubkey to '%s'\n", ringfile);
1192		return 0;
1193	}
1194	if (netpgp->pubring != NULL) {
1195		pgp_keyring_free(netpgp->pubring);
1196	}
1197	/* write secret key */
1198	(void) snprintf(ringfile = filename, sizeof(filename), "%s/secring.gpg", dir);
1199	if ((fd = pgp_setup_file_append(&create, ringfile)) < 0) {
1200		fd = pgp_setup_file_write(&create, ringfile, 0);
1201	}
1202	if (fd < 0) {
1203		(void) fprintf(io->errs, "can't append secring '%s'\n", ringfile);
1204		return 0;
1205	}
1206	/* get the passphrase */
1207	if ((numtries = netpgp_getvar(netpgp, "numtries")) == NULL ||
1208	    (attempts = atoi(numtries)) <= 0) {
1209		attempts = MAX_PASSPHRASE_ATTEMPTS;
1210	} else if (strcmp(numtries, "unlimited") == 0) {
1211		attempts = INFINITE_ATTEMPTS;
1212	}
1213	passc = find_passphrase(netpgp->passfp, &cp[ID_OFFSET], passphrase, sizeof(passphrase), attempts);
1214	if (!pgp_write_xfer_seckey(create, key, (uint8_t *)passphrase, (const unsigned)passc, noarmor)) {
1215		(void) fprintf(io->errs, "Cannot write seckey\n");
1216		return 0;
1217	}
1218	pgp_teardown_file_write(create, fd);
1219	if (netpgp->secring != NULL) {
1220		pgp_keyring_free(netpgp->secring);
1221	}
1222	pgp_keydata_free(key);
1223	free(cp);
1224	return 1;
1225}
1226
1227/* encrypt a file */
1228int
1229netpgp_encrypt_file(netpgp_t *netpgp,
1230			const char *userid,
1231			const char *f,
1232			char *out,
1233			int armored)
1234{
1235	const pgp_key_t	*key;
1236	const unsigned		 overwrite = 1;
1237	const char		*suffix;
1238	pgp_io_t		*io;
1239	char			 outname[MAXPATHLEN];
1240
1241	io = netpgp->io;
1242	if (f == NULL) {
1243		(void) fprintf(io->errs,
1244			"netpgp_encrypt_file: no filename specified\n");
1245		return 0;
1246	}
1247	suffix = (armored) ? ".asc" : ".gpg";
1248	/* get key with which to sign */
1249	if ((key = resolve_userid(netpgp, netpgp->pubring, userid)) == NULL) {
1250		return 0;
1251	}
1252	if (out == NULL) {
1253		(void) snprintf(outname, sizeof(outname), "%s%s", f, suffix);
1254		out = outname;
1255	}
1256	return (int)pgp_encrypt_file(io, f, out, key, (unsigned)armored,
1257				overwrite, netpgp_getvar(netpgp, "cipher"));
1258}
1259
1260#define ARMOR_HEAD	"-----BEGIN PGP MESSAGE-----"
1261
1262/* decrypt a file */
1263int
1264netpgp_decrypt_file(netpgp_t *netpgp, const char *f, char *out, int armored)
1265{
1266	const unsigned	 overwrite = 1;
1267	pgp_io_t	*io;
1268	unsigned	 realarmor;
1269	unsigned	 sshkeys;
1270	char		*numtries;
1271	int            	 attempts;
1272
1273	__PGP_USED(armored);
1274	io = netpgp->io;
1275	if (f == NULL) {
1276		(void) fprintf(io->errs,
1277			"netpgp_decrypt_file: no filename specified\n");
1278		return 0;
1279	}
1280	realarmor = isarmoured(io, f, NULL, ARMOR_HEAD);
1281	sshkeys = (unsigned)(netpgp_getvar(netpgp, "ssh keys") != NULL);
1282	if ((numtries = netpgp_getvar(netpgp, "numtries")) == NULL ||
1283	    (attempts = atoi(numtries)) <= 0) {
1284		attempts = MAX_PASSPHRASE_ATTEMPTS;
1285	} else if (strcmp(numtries, "unlimited") == 0) {
1286		attempts = INFINITE_ATTEMPTS;
1287	}
1288	return pgp_decrypt_file(netpgp->io, f, out, netpgp->secring,
1289				netpgp->pubring,
1290				realarmor, overwrite, sshkeys,
1291				netpgp->passfp, attempts, get_passphrase_cb);
1292}
1293
1294/* sign a file */
1295int
1296netpgp_sign_file(netpgp_t *netpgp,
1297		const char *userid,
1298		const char *f,
1299		char *out,
1300		int armored,
1301		int cleartext,
1302		int detached)
1303{
1304	const pgp_key_t		*keypair;
1305	const pgp_key_t		*pubkey;
1306	const unsigned		 overwrite = 1;
1307	pgp_seckey_t		*seckey;
1308	const char		*hashalg;
1309	pgp_io_t		*io;
1310	char			*numtries;
1311	int			 attempts;
1312	int			 ret;
1313	int			 i;
1314
1315	io = netpgp->io;
1316	if (f == NULL) {
1317		(void) fprintf(io->errs,
1318			"netpgp_sign_file: no filename specified\n");
1319		return 0;
1320	}
1321	/* get key with which to sign */
1322	if ((keypair = resolve_userid(netpgp, netpgp->secring, userid)) == NULL) {
1323		return 0;
1324	}
1325	ret = 1;
1326	if ((numtries = netpgp_getvar(netpgp, "numtries")) == NULL ||
1327	    (attempts = atoi(numtries)) <= 0) {
1328		attempts = MAX_PASSPHRASE_ATTEMPTS;
1329	} else if (strcmp(numtries, "unlimited") == 0) {
1330		attempts = INFINITE_ATTEMPTS;
1331	}
1332	for (i = 0, seckey = NULL ; !seckey && (i < attempts || attempts == INFINITE_ATTEMPTS) ; i++) {
1333		if (netpgp->passfp == NULL) {
1334			/* print out the user id */
1335			pubkey = pgp_getkeybyname(io, netpgp->pubring, userid);
1336			if (pubkey == NULL) {
1337				(void) fprintf(io->errs,
1338					"netpgp: warning - using pubkey from secring\n");
1339				pgp_print_keydata(io, netpgp->pubring, keypair, "signature ",
1340					&keypair->key.seckey.pubkey, 0);
1341			} else {
1342				pgp_print_keydata(io, netpgp->pubring, pubkey, "signature ",
1343					&pubkey->key.pubkey, 0);
1344			}
1345		}
1346		if (netpgp_getvar(netpgp, "ssh keys") == NULL) {
1347			/* now decrypt key */
1348			seckey = pgp_decrypt_seckey(keypair, netpgp->passfp);
1349			if (seckey == NULL) {
1350				(void) fprintf(io->errs, "Bad passphrase\n");
1351			}
1352		} else {
1353			pgp_keyring_t	*secring;
1354
1355			secring = netpgp->secring;
1356			seckey = &secring->keys[0].key.seckey;
1357		}
1358	}
1359	if (seckey == NULL) {
1360		(void) fprintf(io->errs, "Bad passphrase\n");
1361		return 0;
1362	}
1363	/* sign file */
1364	hashalg = netpgp_getvar(netpgp, "hash");
1365	if (seckey->pubkey.alg == PGP_PKA_DSA) {
1366		hashalg = "sha1";
1367	}
1368	if (detached) {
1369		ret = pgp_sign_detached(io, f, out, seckey, hashalg,
1370				get_birthtime(netpgp_getvar(netpgp, "birthtime")),
1371				get_duration(netpgp_getvar(netpgp, "duration")),
1372				(unsigned)armored,
1373				overwrite);
1374	} else {
1375		ret = pgp_sign_file(io, f, out, seckey, hashalg,
1376				get_birthtime(netpgp_getvar(netpgp, "birthtime")),
1377				get_duration(netpgp_getvar(netpgp, "duration")),
1378				(unsigned)armored, (unsigned)cleartext,
1379				overwrite);
1380	}
1381	pgp_forget(seckey, (unsigned)sizeof(*seckey));
1382	return ret;
1383}
1384
1385#define ARMOR_SIG_HEAD	"-----BEGIN PGP (SIGNATURE|SIGNED MESSAGE)-----"
1386
1387/* verify a file */
1388int
1389netpgp_verify_file(netpgp_t *netpgp, const char *in, const char *out, int armored)
1390{
1391	pgp_validation_t	 result;
1392	pgp_io_t		*io;
1393	unsigned		 realarmor;
1394
1395	__PGP_USED(armored);
1396	(void) memset(&result, 0x0, sizeof(result));
1397	io = netpgp->io;
1398	if (in == NULL) {
1399		(void) fprintf(io->errs,
1400			"netpgp_verify_file: no filename specified\n");
1401		return 0;
1402	}
1403	realarmor = isarmoured(io, in, NULL, ARMOR_SIG_HEAD);
1404	if (pgp_validate_file(io, &result, in, out, (const int)realarmor, netpgp->pubring)) {
1405		resultp(io, in, &result, netpgp->pubring);
1406		return 1;
1407	}
1408	if (result.validc + result.invalidc + result.unknownc == 0) {
1409		(void) fprintf(io->errs,
1410		"\"%s\": No signatures found - is this a signed file?\n",
1411			in);
1412	} else if (result.invalidc == 0 && result.unknownc == 0) {
1413		(void) fprintf(io->errs,
1414			"\"%s\": file verification failure: invalid signature time\n", in);
1415	} else {
1416		(void) fprintf(io->errs,
1417"\"%s\": verification failure: %u invalid signatures, %u unknown signatures\n",
1418			in, result.invalidc, result.unknownc);
1419	}
1420	return 0;
1421}
1422
1423/* sign some memory */
1424int
1425netpgp_sign_memory(netpgp_t *netpgp,
1426		const char *userid,
1427		char *mem,
1428		size_t size,
1429		char *out,
1430		size_t outsize,
1431		const unsigned armored,
1432		const unsigned cleartext)
1433{
1434	const pgp_key_t		*keypair;
1435	const pgp_key_t		*pubkey;
1436	pgp_seckey_t		*seckey;
1437	pgp_memory_t		*signedmem;
1438	const char		*hashalg;
1439	pgp_io_t		*io;
1440	char 			*numtries;
1441	int			 attempts;
1442	int			 ret;
1443	int			 i;
1444
1445	io = netpgp->io;
1446	if (mem == NULL) {
1447		(void) fprintf(io->errs,
1448			"netpgp_sign_memory: no memory to sign\n");
1449		return 0;
1450	}
1451	if ((keypair = resolve_userid(netpgp, netpgp->secring, userid)) == NULL) {
1452		return 0;
1453	}
1454	ret = 1;
1455	if ((numtries = netpgp_getvar(netpgp, "numtries")) == NULL ||
1456	    (attempts = atoi(numtries)) <= 0) {
1457		attempts = MAX_PASSPHRASE_ATTEMPTS;
1458	} else if (strcmp(numtries, "unlimited") == 0) {
1459		attempts = INFINITE_ATTEMPTS;
1460	}
1461	for (i = 0, seckey = NULL ; !seckey && (i < attempts || attempts == INFINITE_ATTEMPTS) ; i++) {
1462		if (netpgp->passfp == NULL) {
1463			/* print out the user id */
1464			pubkey = pgp_getkeybyname(io, netpgp->pubring, userid);
1465			if (pubkey == NULL) {
1466				(void) fprintf(io->errs,
1467					"netpgp: warning - using pubkey from secring\n");
1468				pgp_print_keydata(io, netpgp->pubring, keypair, "signature ",
1469					&keypair->key.seckey.pubkey, 0);
1470			} else {
1471				pgp_print_keydata(io, netpgp->pubring, pubkey, "signature ",
1472					&pubkey->key.pubkey, 0);
1473			}
1474		}
1475		/* now decrypt key */
1476		seckey = pgp_decrypt_seckey(keypair, netpgp->passfp);
1477		if (seckey == NULL) {
1478			(void) fprintf(io->errs, "Bad passphrase\n");
1479		}
1480	}
1481	if (seckey == NULL) {
1482		(void) fprintf(io->errs, "Bad passphrase\n");
1483		return 0;
1484	}
1485	/* sign file */
1486	(void) memset(out, 0x0, outsize);
1487	hashalg = netpgp_getvar(netpgp, "hash");
1488	if (seckey->pubkey.alg == PGP_PKA_DSA) {
1489		hashalg = "sha1";
1490	}
1491	signedmem = pgp_sign_buf(io, mem, size, seckey,
1492				get_birthtime(netpgp_getvar(netpgp, "birthtime")),
1493				get_duration(netpgp_getvar(netpgp, "duration")),
1494				hashalg, armored, cleartext);
1495	if (signedmem) {
1496		size_t	m;
1497
1498		m = MIN(pgp_mem_len(signedmem), outsize);
1499		(void) memcpy(out, pgp_mem_data(signedmem), m);
1500		pgp_memory_free(signedmem);
1501		ret = (int)m;
1502	} else {
1503		ret = 0;
1504	}
1505	pgp_forget(seckey, (unsigned)sizeof(*seckey));
1506	return ret;
1507}
1508
1509/* verify memory */
1510int
1511netpgp_verify_memory(netpgp_t *netpgp, const void *in, const size_t size,
1512			void *out, size_t outsize, const int armored)
1513{
1514	pgp_validation_t	 result;
1515	pgp_memory_t		*signedmem;
1516	pgp_memory_t		*cat;
1517	pgp_io_t		*io;
1518	size_t			 m;
1519	int			 ret;
1520
1521	(void) memset(&result, 0x0, sizeof(result));
1522	io = netpgp->io;
1523	if (in == NULL) {
1524		(void) fprintf(io->errs,
1525			"netpgp_verify_memory: no memory to verify\n");
1526		return 0;
1527	}
1528	signedmem = pgp_memory_new();
1529	pgp_memory_add(signedmem, in, size);
1530	if (out) {
1531		cat = pgp_memory_new();
1532	}
1533	ret = pgp_validate_mem(io, &result, signedmem,
1534				(out) ? &cat : NULL,
1535				armored, netpgp->pubring);
1536	pgp_memory_free(signedmem);
1537	if (ret) {
1538		resultp(io, "<stdin>", &result, netpgp->pubring);
1539		if (out) {
1540			m = MIN(pgp_mem_len(cat), outsize);
1541			(void) memcpy(out, pgp_mem_data(cat), m);
1542			pgp_memory_free(cat);
1543		} else {
1544			m = 1;
1545		}
1546		return (int)m;
1547	}
1548	if (result.validc + result.invalidc + result.unknownc == 0) {
1549		(void) fprintf(io->errs,
1550		"No signatures found - is this memory signed?\n");
1551	} else if (result.invalidc == 0 && result.unknownc == 0) {
1552		(void) fprintf(io->errs,
1553			"memory verification failure: invalid signature time\n");
1554	} else {
1555		(void) fprintf(io->errs,
1556"memory verification failure: %u invalid signatures, %u unknown signatures\n",
1557			result.invalidc, result.unknownc);
1558	}
1559	return 0;
1560}
1561
1562/* encrypt some memory */
1563int
1564netpgp_encrypt_memory(netpgp_t *netpgp,
1565			const char *userid,
1566			void *in,
1567			const size_t insize,
1568			char *out,
1569			size_t outsize,
1570			int armored)
1571{
1572	const pgp_key_t	*keypair;
1573	pgp_memory_t		*enc;
1574	pgp_io_t		*io;
1575	size_t			 m;
1576
1577	io = netpgp->io;
1578	if (in == NULL) {
1579		(void) fprintf(io->errs,
1580			"netpgp_encrypt_buf: no memory to encrypt\n");
1581		return 0;
1582	}
1583	if ((keypair = resolve_userid(netpgp, netpgp->pubring, userid)) == NULL) {
1584		return 0;
1585	}
1586	if (in == out) {
1587		(void) fprintf(io->errs,
1588			"netpgp_encrypt_buf: input and output bufs need to be different\n");
1589		return 0;
1590	}
1591	if (outsize < insize) {
1592		(void) fprintf(io->errs,
1593			"netpgp_encrypt_buf: input size is larger than output size\n");
1594		return 0;
1595	}
1596	enc = pgp_encrypt_buf(io, in, insize, keypair, (unsigned)armored,
1597				netpgp_getvar(netpgp, "cipher"));
1598	m = MIN(pgp_mem_len(enc), outsize);
1599	(void) memcpy(out, pgp_mem_data(enc), m);
1600	pgp_memory_free(enc);
1601	return (int)m;
1602}
1603
1604/* decrypt a chunk of memory */
1605int
1606netpgp_decrypt_memory(netpgp_t *netpgp, const void *input, const size_t insize,
1607			char *out, size_t outsize, const int armored)
1608{
1609	pgp_memory_t	*mem;
1610	pgp_io_t	*io;
1611	unsigned	 realarmour;
1612	unsigned	 sshkeys;
1613	size_t		 m;
1614	char		*numtries;
1615	int            	 attempts;
1616
1617	__PGP_USED(armored);
1618	io = netpgp->io;
1619	if (input == NULL) {
1620		(void) fprintf(io->errs,
1621			"netpgp_decrypt_memory: no memory\n");
1622		return 0;
1623	}
1624	realarmour = isarmoured(io, NULL, input, ARMOR_HEAD);
1625	sshkeys = (unsigned)(netpgp_getvar(netpgp, "ssh keys") != NULL);
1626	if ((numtries = netpgp_getvar(netpgp, "numtries")) == NULL ||
1627	    (attempts = atoi(numtries)) <= 0) {
1628		attempts = MAX_PASSPHRASE_ATTEMPTS;
1629	} else if (strcmp(numtries, "unlimited") == 0) {
1630		attempts = INFINITE_ATTEMPTS;
1631	}
1632	mem = pgp_decrypt_buf(netpgp->io, input, insize, netpgp->secring,
1633				netpgp->pubring,
1634				realarmour, sshkeys,
1635				netpgp->passfp,
1636				attempts,
1637				get_passphrase_cb);
1638	if (mem == NULL) {
1639		return -1;
1640	}
1641	m = MIN(pgp_mem_len(mem), outsize);
1642	(void) memcpy(out, pgp_mem_data(mem), m);
1643	pgp_memory_free(mem);
1644	return (int)m;
1645}
1646
1647/* wrappers for the ops_debug_level functions we added to openpgpsdk */
1648
1649/* set the debugging level per filename */
1650int
1651netpgp_set_debug(const char *f)
1652{
1653	return pgp_set_debug_level(f);
1654}
1655
1656/* get the debugging level per filename */
1657int
1658netpgp_get_debug(const char *f)
1659{
1660	return pgp_get_debug_level(f);
1661}
1662
1663/* return the version for the library */
1664const char *
1665netpgp_get_info(const char *type)
1666{
1667	return pgp_get_info(type);
1668}
1669
1670/* list all the packets in a file */
1671int
1672netpgp_list_packets(netpgp_t *netpgp, char *f, int armor, char *pubringname)
1673{
1674	pgp_keyring_t	*keyring;
1675	const unsigned	 noarmor = 0;
1676	struct stat	 st;
1677	pgp_io_t	*io;
1678	char		 ringname[MAXPATHLEN];
1679	char		*homedir;
1680	int		 ret;
1681
1682	io = netpgp->io;
1683	if (f == NULL) {
1684		(void) fprintf(io->errs, "No file containing packets\n");
1685		return 0;
1686	}
1687	if (stat(f, &st) < 0) {
1688		(void) fprintf(io->errs, "No such file '%s'\n", f);
1689		return 0;
1690	}
1691	homedir = netpgp_getvar(netpgp, "homedir");
1692	if (pubringname == NULL) {
1693		(void) snprintf(ringname, sizeof(ringname),
1694				"%s/pubring.gpg", homedir);
1695		pubringname = ringname;
1696	}
1697	if ((keyring = calloc(1, sizeof(*keyring))) == NULL) {
1698		(void) fprintf(io->errs, "netpgp_list_packets: bad alloc\n");
1699		return 0;
1700	}
1701	if (!pgp_keyring_fileread(keyring, noarmor, pubringname)) {
1702		free(keyring);
1703		(void) fprintf(io->errs, "Cannot read pub keyring %s\n",
1704			pubringname);
1705		return 0;
1706	}
1707	netpgp->pubring = keyring;
1708	netpgp_setvar(netpgp, "pubring", pubringname);
1709	ret = pgp_list_packets(io, f, (unsigned)armor,
1710					netpgp->secring,
1711					netpgp->pubring,
1712					netpgp->passfp,
1713					get_passphrase_cb);
1714	free(keyring);
1715	return ret;
1716}
1717
1718/* set a variable */
1719int
1720netpgp_setvar(netpgp_t *netpgp, const char *name, const char *value)
1721{
1722	char	*newval;
1723	int	 i;
1724
1725	/* protect against the case where 'value' is netpgp->value[i] */
1726	newval = netpgp_strdup(value);
1727	if ((i = findvar(netpgp, name)) < 0) {
1728		/* add the element to the array */
1729		if (size_arrays(netpgp, netpgp->size + 15)) {
1730			netpgp->name[i = netpgp->c++] = netpgp_strdup(name);
1731		}
1732	} else {
1733		/* replace the element in the array */
1734		if (netpgp->value[i]) {
1735			free(netpgp->value[i]);
1736			netpgp->value[i] = NULL;
1737		}
1738	}
1739	/* sanity checks for range of values */
1740	if (strcmp(name, "hash") == 0 || strcmp(name, "algorithm") == 0) {
1741		if (pgp_str_to_hash_alg(newval) == PGP_HASH_UNKNOWN) {
1742			free(newval);
1743			return 0;
1744		}
1745	}
1746	netpgp->value[i] = newval;
1747	return 1;
1748}
1749
1750/* unset a variable */
1751int
1752netpgp_unsetvar(netpgp_t *netpgp, const char *name)
1753{
1754	int	i;
1755
1756	if ((i = findvar(netpgp, name)) >= 0) {
1757		if (netpgp->value[i]) {
1758			free(netpgp->value[i]);
1759			netpgp->value[i] = NULL;
1760		}
1761		netpgp->value[i] = NULL;
1762		return 1;
1763	}
1764	return 0;
1765}
1766
1767/* get a variable's value (NULL if not set) */
1768char *
1769netpgp_getvar(netpgp_t *netpgp, const char *name)
1770{
1771	int	i;
1772
1773	return ((i = findvar(netpgp, name)) < 0) ? NULL : netpgp->value[i];
1774}
1775
1776/* increment a value */
1777int
1778netpgp_incvar(netpgp_t *netpgp, const char *name, const int delta)
1779{
1780	char	*cp;
1781	char	 num[16];
1782	int	 val;
1783
1784	val = 0;
1785	if ((cp = netpgp_getvar(netpgp, name)) != NULL) {
1786		val = atoi(cp);
1787	}
1788	(void) snprintf(num, sizeof(num), "%d", val + delta);
1789	netpgp_setvar(netpgp, name, num);
1790	return 1;
1791}
1792
1793/* set the home directory value to "home/subdir" */
1794int
1795netpgp_set_homedir(netpgp_t *netpgp, char *home, const char *subdir, const int quiet)
1796{
1797	struct stat	st;
1798	char		d[MAXPATHLEN];
1799
1800	if (home == NULL) {
1801		if (!quiet) {
1802			(void) fprintf(stderr, "NULL HOME directory\n");
1803		}
1804		return 0;
1805	}
1806	(void) snprintf(d, sizeof(d), "%s%s", home, (subdir) ? subdir : "");
1807	if (stat(d, &st) == 0) {
1808		if ((st.st_mode & S_IFMT) == S_IFDIR) {
1809			netpgp_setvar(netpgp, "homedir", d);
1810			return 1;
1811		}
1812		(void) fprintf(stderr, "netpgp: homedir \"%s\" is not a dir\n",
1813					d);
1814		return 0;
1815	}
1816	if (!quiet) {
1817		(void) fprintf(stderr,
1818			"netpgp: warning homedir \"%s\" not found\n", d);
1819	}
1820	netpgp_setvar(netpgp, "homedir", d);
1821	return 1;
1822}
1823
1824/* validate all sigs in the pub keyring */
1825int
1826netpgp_validate_sigs(netpgp_t *netpgp)
1827{
1828	pgp_validation_t	result;
1829
1830	return (int)pgp_validate_all_sigs(&result, netpgp->pubring, NULL);
1831}
1832
1833/* print the json out on 'fp' */
1834int
1835netpgp_format_json(void *vp, const char *json, const int psigs)
1836{
1837	mj_t	 ids;
1838	FILE	*fp;
1839	int	 from;
1840	int	 idc;
1841	int	 tok;
1842	int	 to;
1843	int	 i;
1844
1845	if ((fp = (FILE *)vp) == NULL || json == NULL) {
1846		return 0;
1847	}
1848	/* ids is an array of strings, each containing 1 entry */
1849	(void) memset(&ids, 0x0, sizeof(ids));
1850	from = to = tok = 0;
1851	/* convert from string into an mj structure */
1852	(void) mj_parse(&ids, json, &from, &to, &tok);
1853	if ((idc = mj_arraycount(&ids)) == 1 && strchr(json, '{') == NULL) {
1854		idc = 0;
1855	}
1856	(void) fprintf(fp, "%d key%s found\n", idc, (idc == 1) ? "" : "s");
1857	for (i = 0 ; i < idc ; i++) {
1858		format_json_key(fp, &ids.value.v[i], psigs);
1859	}
1860	/* clean up */
1861	mj_delete(&ids);
1862	return idc;
1863}
1864
1865/* find a key in keyring, and write it in ssh format */
1866int
1867netpgp_write_sshkey(netpgp_t *netpgp, char *s, const char *userid, char *out, size_t size)
1868{
1869	const pgp_key_t	*key;
1870	pgp_keyring_t		*keyring;
1871	pgp_io_t		*io;
1872	unsigned		 k;
1873	size_t			 cc;
1874	char			 f[MAXPATHLEN];
1875
1876	if ((io = calloc(1, sizeof(pgp_io_t))) == NULL) {
1877		(void) fprintf(stderr, "netpgp_save_sshpub: bad alloc 1\n");
1878		return 0;
1879	}
1880	io->outs = stdout;
1881	io->errs = stderr;
1882	io->res = stderr;
1883	netpgp->io = io;
1884	/* write new to temp file */
1885	savepubkey(s, f, sizeof(f));
1886	if ((keyring = calloc(1, sizeof(*keyring))) == NULL) {
1887		(void) fprintf(stderr, "netpgp_save_sshpub: bad alloc 2\n");
1888		return 0;
1889	}
1890	if (!pgp_keyring_fileread(netpgp->pubring = keyring, 1, f)) {
1891		(void) fprintf(stderr, "can't import key\n");
1892		return 0;
1893	}
1894	/* get rsa key */
1895	k = 0;
1896	key = pgp_getnextkeybyname(netpgp->io, netpgp->pubring, userid, &k);
1897	if (key == NULL) {
1898		(void) fprintf(stderr, "no key found for '%s'\n", userid);
1899		return 0;
1900	}
1901	if (key->key.pubkey.alg != PGP_PKA_RSA) {
1902		/* we're not interested in supporting DSA either :-) */
1903		(void) fprintf(stderr, "key not RSA '%s'\n", userid);
1904		return 0;
1905	}
1906	/* XXX - check trust sigs */
1907	/* XXX - check expiry */
1908	/* XXX - check start */
1909	/* XXX - check not weak key */
1910	/* get rsa e and n */
1911	(void) memset(out, 0x0, size);
1912	cc = formatstring((char *)out, (const uint8_t *)"ssh-rsa", 7);
1913	cc += formatbignum((char *)&out[cc], key->key.pubkey.key.rsa.e);
1914	cc += formatbignum((char *)&out[cc], key->key.pubkey.key.rsa.n);
1915	free(io);
1916	free(keyring);
1917	return cc;
1918}
1919