xref: /netbsd-src/crypto/external/bsd/netpgp/dist/src/lib/keyring.c (revision bbde328be4e75ea9ad02e9715ea13ca54b797ada)
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: keyring.c,v 1.34 2010/04/14 00:23:09 agc Exp $");
61 #endif
62 
63 #ifdef HAVE_FCNTL_H
64 #include <fcntl.h>
65 #endif
66 
67 #include <regex.h>
68 #include <stdlib.h>
69 #include <string.h>
70 
71 #ifdef HAVE_TERMIOS_H
72 #include <termios.h>
73 #endif
74 
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78 
79 #include "types.h"
80 #include "keyring.h"
81 #include "packet-parse.h"
82 #include "signature.h"
83 #include "netpgpsdk.h"
84 #include "readerwriter.h"
85 #include "netpgpdefs.h"
86 #include "packet.h"
87 #include "crypto.h"
88 #include "validate.h"
89 #include "netpgpdigest.h"
90 
91 
92 
93 /**
94    \ingroup HighLevel_Keyring
95 
96    \brief Creates a new __ops_key_t struct
97 
98    \return A new __ops_key_t struct, initialised to zero.
99 
100    \note The returned __ops_key_t struct must be freed after use with __ops_keydata_free.
101 */
102 
103 __ops_key_t  *
104 __ops_keydata_new(void)
105 {
106 	return calloc(1, sizeof(__ops_key_t));
107 }
108 
109 
110 /**
111  \ingroup HighLevel_Keyring
112 
113  \brief Frees keydata and its memory
114 
115  \param keydata Key to be freed.
116 
117  \note This frees the keydata itself, as well as any other memory alloc-ed by it.
118 */
119 void
120 __ops_keydata_free(__ops_key_t *keydata)
121 {
122 	unsigned        n;
123 
124 	for (n = 0; n < keydata->uidc; ++n) {
125 		__ops_userid_free(&keydata->uids[n]);
126 	}
127 	free(keydata->uids);
128 	keydata->uids = NULL;
129 	keydata->uidc = 0;
130 
131 	for (n = 0; n < keydata->packetc; ++n) {
132 		__ops_subpacket_free(&keydata->packets[n]);
133 	}
134 	free(keydata->packets);
135 	keydata->packets = NULL;
136 	keydata->packetc = 0;
137 
138 	if (keydata->type == OPS_PTAG_CT_PUBLIC_KEY) {
139 		__ops_pubkey_free(&keydata->key.pubkey);
140 	} else {
141 		__ops_seckey_free(&keydata->key.seckey);
142 	}
143 
144 	free(keydata);
145 }
146 
147 /**
148  \ingroup HighLevel_KeyGeneral
149 
150  \brief Returns the public key in the given keydata.
151  \param keydata
152 
153   \return Pointer to public key
154 
155   \note This is not a copy, do not free it after use.
156 */
157 
158 const __ops_pubkey_t *
159 __ops_get_pubkey(const __ops_key_t *keydata)
160 {
161 	return (keydata->type == OPS_PTAG_CT_PUBLIC_KEY) ?
162 				&keydata->key.pubkey :
163 				&keydata->key.seckey.pubkey;
164 }
165 
166 /**
167 \ingroup HighLevel_KeyGeneral
168 
169 \brief Check whether this is a secret key or not.
170 */
171 
172 unsigned
173 __ops_is_key_secret(const __ops_key_t *data)
174 {
175 	return data->type != OPS_PTAG_CT_PUBLIC_KEY;
176 }
177 
178 /**
179  \ingroup HighLevel_KeyGeneral
180 
181  \brief Returns the secret key in the given keydata.
182 
183  \note This is not a copy, do not free it after use.
184 
185  \note This returns a const.  If you need to be able to write to this
186  pointer, use __ops_get_writable_seckey
187 */
188 
189 const __ops_seckey_t *
190 __ops_get_seckey(const __ops_key_t *data)
191 {
192 	return (data->type == OPS_PTAG_CT_SECRET_KEY) ?
193 				&data->key.seckey : NULL;
194 }
195 
196 /**
197  \ingroup HighLevel_KeyGeneral
198 
199   \brief Returns the secret key in the given keydata.
200 
201   \note This is not a copy, do not free it after use.
202 
203   \note If you do not need to be able to modify this key, there is an
204   equivalent read-only function __ops_get_seckey.
205 */
206 
207 __ops_seckey_t *
208 __ops_get_writable_seckey(__ops_key_t *data)
209 {
210 	return (data->type == OPS_PTAG_CT_SECRET_KEY) ?
211 				&data->key.seckey : NULL;
212 }
213 
214 /* utility function to zero out memory */
215 void
216 __ops_forget(void *vp, unsigned size)
217 {
218 	(void) memset(vp, 0x0, size);
219 }
220 
221 typedef struct {
222 	FILE			*passfp;
223 	const __ops_key_t	*key;
224 	char			*passphrase;
225 	__ops_seckey_t		*seckey;
226 } decrypt_t;
227 
228 static __ops_cb_ret_t
229 decrypt_cb(const __ops_packet_t *pkt, __ops_cbdata_t *cbinfo)
230 {
231 	const __ops_contents_t	*content = &pkt->u;
232 	decrypt_t		*decrypt;
233 	char			 pass[MAX_PASSPHRASE_LENGTH];
234 
235 	decrypt = __ops_callback_arg(cbinfo);
236 	switch (pkt->tag) {
237 	case OPS_PARSER_PTAG:
238 	case OPS_PTAG_CT_USER_ID:
239 	case OPS_PTAG_CT_SIGNATURE:
240 	case OPS_PTAG_CT_SIGNATURE_HEADER:
241 	case OPS_PTAG_CT_SIGNATURE_FOOTER:
242 	case OPS_PTAG_CT_TRUST:
243 		break;
244 
245 	case OPS_GET_PASSPHRASE:
246 		(void) __ops_getpassphrase(decrypt->passfp, pass, sizeof(pass));
247 		*content->skey_passphrase.passphrase = netpgp_strdup(pass);
248 		__ops_forget(pass, sizeof(pass));
249 		return OPS_KEEP_MEMORY;
250 
251 	case OPS_PARSER_ERRCODE:
252 		switch (content->errcode.errcode) {
253 		case OPS_E_P_MPI_FORMAT_ERROR:
254 			/* Generally this means a bad passphrase */
255 			fprintf(stderr, "Bad passphrase!\n");
256 			return OPS_RELEASE_MEMORY;
257 
258 		case OPS_E_P_PACKET_CONSUMED:
259 			/* And this is because of an error we've accepted */
260 			return OPS_RELEASE_MEMORY;
261 		default:
262 			break;
263 		}
264 		(void) fprintf(stderr, "parse error: %s\n",
265 				__ops_errcode(content->errcode.errcode));
266 		return OPS_FINISHED;
267 
268 	case OPS_PARSER_ERROR:
269 		fprintf(stderr, "parse error: %s\n", content->error.error);
270 		return OPS_FINISHED;
271 
272 	case OPS_PTAG_CT_SECRET_KEY:
273 		if ((decrypt->seckey = calloc(1, sizeof(*decrypt->seckey))) == NULL) {
274 			(void) fprintf(stderr, "decrypt_cb: bad alloc\n");
275 			return OPS_FINISHED;
276 		}
277 		decrypt->seckey->checkhash = calloc(1, OPS_CHECKHASH_SIZE);
278 		*decrypt->seckey = content->seckey;
279 		return OPS_KEEP_MEMORY;
280 
281 	case OPS_PARSER_PACKET_END:
282 		/* nothing to do */
283 		break;
284 
285 	default:
286 		fprintf(stderr, "Unexpected tag %d (0x%x)\n", pkt->tag,
287 			pkt->tag);
288 		return OPS_FINISHED;
289 	}
290 
291 	return OPS_RELEASE_MEMORY;
292 }
293 
294 /**
295 \ingroup Core_Keys
296 \brief Decrypts secret key from given keydata with given passphrase
297 \param key Key from which to get secret key
298 \param passphrase Passphrase to use to decrypt secret key
299 \return secret key
300 */
301 __ops_seckey_t *
302 __ops_decrypt_seckey(const __ops_key_t *key, void *passfp)
303 {
304 	__ops_stream_t	*stream;
305 	const int	 printerrors = 1;
306 	decrypt_t	 decrypt;
307 
308 	(void) memset(&decrypt, 0x0, sizeof(decrypt));
309 	decrypt.key = key;
310 	decrypt.passfp = passfp;
311 	stream = __ops_new(sizeof(*stream));
312 	__ops_keydata_reader_set(stream, key);
313 	__ops_set_callback(stream, decrypt_cb, &decrypt);
314 	stream->readinfo.accumulate = 1;
315 	__ops_parse(stream, !printerrors);
316 	return decrypt.seckey;
317 }
318 
319 /**
320 \ingroup Core_Keys
321 \brief Set secret key in content
322 \param content Content to be set
323 \param key Keydata to get secret key from
324 */
325 void
326 __ops_set_seckey(__ops_contents_t *cont, const __ops_key_t *key)
327 {
328 	*cont->get_seckey.seckey = &key->key.seckey;
329 }
330 
331 /**
332 \ingroup Core_Keys
333 \brief Get Key ID from keydata
334 \param key Keydata to get Key ID from
335 \return Pointer to Key ID inside keydata
336 */
337 const uint8_t *
338 __ops_get_key_id(const __ops_key_t *key)
339 {
340 	return key->key_id;
341 }
342 
343 /**
344 \ingroup Core_Keys
345 \brief How many User IDs in this key?
346 \param key Keydata to check
347 \return Num of user ids
348 */
349 unsigned
350 __ops_get_userid_count(const __ops_key_t *key)
351 {
352 	return key->uidc;
353 }
354 
355 /**
356 \ingroup Core_Keys
357 \brief Get indexed user id from key
358 \param key Key to get user id from
359 \param index Which key to get
360 \return Pointer to requested user id
361 */
362 const uint8_t *
363 __ops_get_userid(const __ops_key_t *key, unsigned subscript)
364 {
365 	return key->uids[subscript].userid;
366 }
367 
368 /**
369    \ingroup HighLevel_Supported
370    \brief Checks whether key's algorithm and type are supported by OpenPGP::SDK
371    \param keydata Key to be checked
372    \return 1 if key algorithm and type are supported by OpenPGP::SDK; 0 if not
373 */
374 
375 unsigned
376 __ops_is_key_supported(const __ops_key_t *key)
377 {
378 	if (key->type == OPS_PTAG_CT_PUBLIC_KEY) {
379 		if (key->key.pubkey.alg == OPS_PKA_RSA) {
380 			return 1;
381 		}
382 	} else if (key->type == OPS_PTAG_CT_PUBLIC_KEY) {
383 		if (key->key.pubkey.alg == OPS_PKA_DSA) {
384 			return 1;
385 		}
386 	}
387 	return 0;
388 }
389 
390 /* \todo check where userid pointers are copied */
391 /**
392 \ingroup Core_Keys
393 \brief Copy user id, including contents
394 \param dst Destination User ID
395 \param src Source User ID
396 \note If dst already has a userid, it will be freed.
397 */
398 static __ops_userid_t *
399 __ops_copy_userid(__ops_userid_t *dst, const __ops_userid_t *src)
400 {
401 	size_t          len;
402 
403 	len = strlen((char *) src->userid);
404 	if (dst->userid) {
405 		free(dst->userid);
406 	}
407 	if ((dst->userid = calloc(1, len + 1)) == NULL) {
408 		(void) fprintf(stderr, "__ops_copy_userid: bad alloc\n");
409 	} else {
410 		(void) memcpy(dst->userid, src->userid, len);
411 	}
412 	return dst;
413 }
414 
415 /* \todo check where pkt pointers are copied */
416 /**
417 \ingroup Core_Keys
418 \brief Copy packet, including contents
419 \param dst Destination packet
420 \param src Source packet
421 \note If dst already has a packet, it will be freed.
422 */
423 static __ops_subpacket_t *
424 __ops_copy_packet(__ops_subpacket_t *dst, const __ops_subpacket_t *src)
425 {
426 	if (dst->raw) {
427 		free(dst->raw);
428 	}
429 	if ((dst->raw = calloc(1, src->length)) == NULL) {
430 		(void) fprintf(stderr, "__ops_copy_packet: bad alloc\n");
431 	} else {
432 		dst->length = src->length;
433 		(void) memcpy(dst->raw, src->raw, src->length);
434 	}
435 	return dst;
436 }
437 
438 /**
439 \ingroup Core_Keys
440 \brief Add User ID to key
441 \param key Key to which to add User ID
442 \param userid User ID to add
443 \return Pointer to new User ID
444 */
445 __ops_userid_t  *
446 __ops_add_userid(__ops_key_t *key, const __ops_userid_t *userid)
447 {
448 	__ops_userid_t  *uidp;
449 
450 	EXPAND_ARRAY(key, uid);
451 	/* initialise new entry in array */
452 	uidp = &key->uids[key->uidc++];
453 	uidp->userid = NULL;
454 	/* now copy it */
455 	return __ops_copy_userid(uidp, userid);
456 }
457 
458 void print_packet_hex(const __ops_subpacket_t *pkt);
459 
460 /**
461 \ingroup Core_Keys
462 \brief Add packet to key
463 \param keydata Key to which to add packet
464 \param packet Packet to add
465 \return Pointer to new packet
466 */
467 __ops_subpacket_t   *
468 __ops_add_subpacket(__ops_key_t *keydata, const __ops_subpacket_t *packet)
469 {
470 	__ops_subpacket_t   *subpktp;
471 
472 	EXPAND_ARRAY(keydata, packet);
473 	/* initialise new entry in array */
474 	subpktp = &keydata->packets[keydata->packetc++];
475 	subpktp->length = 0;
476 	subpktp->raw = NULL;
477 	/* now copy it */
478 	return __ops_copy_packet(subpktp, packet);
479 }
480 
481 /**
482 \ingroup Core_Keys
483 \brief Add selfsigned User ID to key
484 \param keydata Key to which to add user ID
485 \param userid Self-signed User ID to add
486 \return 1 if OK; else 0
487 */
488 unsigned
489 __ops_add_selfsigned_userid(__ops_key_t *key, __ops_userid_t *userid)
490 {
491 	__ops_create_sig_t	*sig;
492 	__ops_subpacket_t	 sigpacket;
493 	__ops_memory_t		*mem_userid = NULL;
494 	__ops_output_t		*useridoutput = NULL;
495 	__ops_memory_t		*mem_sig = NULL;
496 	__ops_output_t		*sigoutput = NULL;
497 
498 	/*
499          * create signature packet for this userid
500          */
501 
502 	/* create userid pkt */
503 	__ops_setup_memory_write(&useridoutput, &mem_userid, 128);
504 	__ops_write_struct_userid(useridoutput, userid);
505 
506 	/* create sig for this pkt */
507 	sig = __ops_create_sig_new();
508 	__ops_sig_start_key_sig(sig, &key->key.seckey.pubkey, userid, OPS_CERT_POSITIVE);
509 	__ops_add_birthtime(sig, time(NULL));
510 	__ops_add_issuer_keyid(sig, key->key_id);
511 	__ops_add_primary_userid(sig, 1);
512 	__ops_end_hashed_subpkts(sig);
513 
514 	__ops_setup_memory_write(&sigoutput, &mem_sig, 128);
515 	__ops_write_sig(sigoutput, sig, &key->key.seckey.pubkey, &key->key.seckey);
516 
517 	/* add this packet to key */
518 	sigpacket.length = __ops_mem_len(mem_sig);
519 	sigpacket.raw = __ops_mem_data(mem_sig);
520 
521 	/* add userid to key */
522 	(void) __ops_add_userid(key, userid);
523 	(void) __ops_add_subpacket(key, &sigpacket);
524 
525 	/* cleanup */
526 	__ops_create_sig_delete(sig);
527 	__ops_output_delete(useridoutput);
528 	__ops_output_delete(sigoutput);
529 	__ops_memory_free(mem_userid);
530 	__ops_memory_free(mem_sig);
531 
532 	return 1;
533 }
534 
535 /**
536 \ingroup Core_Keys
537 \brief Initialise __ops_key_t
538 \param keydata Keydata to initialise
539 \param type OPS_PTAG_CT_PUBLIC_KEY or OPS_PTAG_CT_SECRET_KEY
540 */
541 void
542 __ops_keydata_init(__ops_key_t *keydata, const __ops_content_tag_t type)
543 {
544 	if (keydata->type != OPS_PTAG_CT_RESERVED) {
545 		(void) fprintf(stderr,
546 			"__ops_keydata_init: wrong keydata type\n");
547 	} else if (type != OPS_PTAG_CT_PUBLIC_KEY &&
548 		   type != OPS_PTAG_CT_SECRET_KEY) {
549 		(void) fprintf(stderr, "__ops_keydata_init: wrong type\n");
550 	} else {
551 		keydata->type = type;
552 	}
553 }
554 
555 /* used to point to data during keyring read */
556 typedef struct keyringcb_t {
557 	__ops_keyring_t		*keyring;	/* the keyring we're reading */
558 } keyringcb_t;
559 
560 
561 static __ops_cb_ret_t
562 cb_keyring_read(const __ops_packet_t *pkt, __ops_cbdata_t *cbinfo)
563 {
564 	__ops_keyring_t	*keyring;
565 	__ops_revoke_t	*revocation;
566 	__ops_key_t	*key;
567 	keyringcb_t	*cb;
568 
569 	cb = __ops_callback_arg(cbinfo);
570 	keyring = cb->keyring;
571 	switch (pkt->tag) {
572 	case OPS_PARSER_PTAG:
573 	case OPS_PTAG_CT_ENCRYPTED_SECRET_KEY:
574 		/* we get these because we didn't prompt */
575 		break;
576 	case OPS_PTAG_CT_SIGNATURE_HEADER:
577 		key = &keyring->keys[keyring->keyc - 1];
578 		EXPAND_ARRAY(key, subsig);
579 		key->subsigs[key->subsigc].uid = key->uidc - 1;
580 		(void) memcpy(&key->subsigs[key->subsigc].sig, &pkt->u.sig,
581 				sizeof(pkt->u.sig));
582 		key->subsigc += 1;
583 		break;
584 	case OPS_PTAG_CT_SIGNATURE:
585 		key = &keyring->keys[keyring->keyc - 1];
586 		EXPAND_ARRAY(key, subsig);
587 		key->subsigs[key->subsigc].uid = key->uidc - 1;
588 		(void) memcpy(&key->subsigs[key->subsigc].sig, &pkt->u.sig,
589 				sizeof(pkt->u.sig));
590 		key->subsigc += 1;
591 		break;
592 	case OPS_PTAG_CT_TRUST:
593 		key = &keyring->keys[keyring->keyc - 1];
594 		key->subsigs[key->subsigc - 1].trustlevel = pkt->u.ss_trust.level;
595 		key->subsigs[key->subsigc - 1].trustamount = pkt->u.ss_trust.amount;
596 		break;
597 	case OPS_PTAG_SS_KEY_EXPIRY:
598 		EXPAND_ARRAY(keyring, key);
599 		if (keyring->keyc > 0) {
600 			keyring->keys[keyring->keyc - 1].key.pubkey.duration = pkt->u.ss_time.time;
601 		}
602 		break;
603 	case OPS_PTAG_SS_ISSUER_KEY_ID:
604 		key = &keyring->keys[keyring->keyc - 1];
605 		(void) memcpy(&key->subsigs[key->subsigc - 1].sig.info.signer_id,
606 			      pkt->u.ss_issuer.key_id,
607 			      sizeof(pkt->u.ss_issuer.key_id));
608 		key->subsigs[key->subsigc - 1].sig.info.signer_id_set = 1;
609 		break;
610 	case OPS_PTAG_SS_CREATION_TIME:
611 		key = &keyring->keys[keyring->keyc - 1];
612 		key->subsigs[key->subsigc - 1].sig.info.birthtime = pkt->u.ss_time.time;
613 		key->subsigs[key->subsigc - 1].sig.info.birthtime_set = 1;
614 		break;
615 	case OPS_PTAG_SS_EXPIRATION_TIME:
616 		key = &keyring->keys[keyring->keyc - 1];
617 		key->subsigs[key->subsigc - 1].sig.info.duration = pkt->u.ss_time.time;
618 		key->subsigs[key->subsigc - 1].sig.info.duration_set = 1;
619 		break;
620 	case OPS_PTAG_SS_PRIMARY_USER_ID:
621 		key = &keyring->keys[keyring->keyc - 1];
622 		key->uid0 = key->uidc - 1;
623 		break;
624 	case OPS_PTAG_SS_REVOCATION_REASON:
625 		key = &keyring->keys[keyring->keyc - 1];
626 		if (key->uidc == 0) {
627 			/* revoke whole key */
628 			key->revoked = 1;
629 			revocation = &key->revocation;
630 		} else {
631 			/* revoke the user id */
632 			EXPAND_ARRAY(key, revoke);
633 			revocation = &key->revokes[key->revokec];
634 			key->revokes[key->revokec].uid = key->uidc - 1;
635 			key->revokec += 1;
636 		}
637 		revocation->code = pkt->u.ss_revocation.code;
638 		revocation->reason = netpgp_strdup(__ops_show_ss_rr_code(pkt->u.ss_revocation.code));
639 		break;
640 	case OPS_PTAG_CT_SIGNATURE_FOOTER:
641 	case OPS_PARSER_ERRCODE:
642 		break;
643 
644 	default:
645 		break;
646 	}
647 
648 	return OPS_RELEASE_MEMORY;
649 }
650 
651 /**
652    \ingroup HighLevel_KeyringRead
653 
654    \brief Reads a keyring from a file
655 
656    \param keyring Pointer to an existing __ops_keyring_t struct
657    \param armour 1 if file is armoured; else 0
658    \param filename Filename of keyring to be read
659 
660    \return __ops 1 if OK; 0 on error
661 
662    \note Keyring struct must already exist.
663 
664    \note Can be used with either a public or secret keyring.
665 
666    \note You must call __ops_keyring_free() after usage to free alloc-ed memory.
667 
668    \note If you call this twice on the same keyring struct, without calling
669    __ops_keyring_free() between these calls, you will introduce a memory leak.
670 
671    \sa __ops_keyring_read_from_mem()
672    \sa __ops_keyring_free()
673 
674 */
675 
676 unsigned
677 __ops_keyring_fileread(__ops_keyring_t *keyring,
678 			const unsigned armour,
679 			const char *filename)
680 {
681 	__ops_stream_t	*stream;
682 	keyringcb_t	 cb;
683 	unsigned	 res = 1;
684 	int		 fd;
685 
686 	(void) memset(&cb, 0x0, sizeof(cb));
687 	cb.keyring = keyring;
688 	stream = __ops_new(sizeof(*stream));
689 
690 	/* add this for the moment, */
691 	/*
692 	 * \todo need to fix the problems with reading signature subpackets
693 	 * later
694 	 */
695 
696 	/* __ops_parse_options(parse,OPS_PTAG_SS_ALL,OPS_PARSE_RAW); */
697 	__ops_parse_options(stream, OPS_PTAG_SS_ALL, OPS_PARSE_PARSED);
698 
699 #ifdef O_BINARY
700 	fd = open(filename, O_RDONLY | O_BINARY);
701 #else
702 	fd = open(filename, O_RDONLY);
703 #endif
704 	if (fd < 0) {
705 		__ops_stream_delete(stream);
706 		perror(filename);
707 		return 0;
708 	}
709 #ifdef USE_MMAP_FOR_FILES
710 	__ops_reader_set_mmap(stream, fd);
711 #else
712 	__ops_reader_set_fd(stream, fd);
713 #endif
714 
715 	__ops_set_callback(stream, cb_keyring_read, &cb);
716 
717 	if (armour) {
718 		__ops_reader_push_dearmour(stream);
719 	}
720 	res = __ops_parse_and_accumulate(keyring, stream);
721 	__ops_print_errors(__ops_stream_get_errors(stream));
722 
723 	if (armour) {
724 		__ops_reader_pop_dearmour(stream);
725 	}
726 
727 	(void)close(fd);
728 
729 	__ops_stream_delete(stream);
730 
731 	return res;
732 }
733 
734 /**
735    \ingroup HighLevel_KeyringRead
736 
737    \brief Reads a keyring from memory
738 
739    \param keyring Pointer to existing __ops_keyring_t struct
740    \param armour 1 if file is armoured; else 0
741    \param mem Pointer to a __ops_memory_t struct containing keyring to be read
742 
743    \return __ops 1 if OK; 0 on error
744 
745    \note Keyring struct must already exist.
746 
747    \note Can be used with either a public or secret keyring.
748 
749    \note You must call __ops_keyring_free() after usage to free alloc-ed memory.
750 
751    \note If you call this twice on the same keyring struct, without calling
752    __ops_keyring_free() between these calls, you will introduce a memory leak.
753 
754    \sa __ops_keyring_fileread
755    \sa __ops_keyring_free
756 */
757 unsigned
758 __ops_keyring_read_from_mem(__ops_io_t *io,
759 				__ops_keyring_t *keyring,
760 				const unsigned armour,
761 				__ops_memory_t *mem)
762 {
763 	__ops_stream_t	*stream;
764 	const unsigned	 noaccum = 0;
765 	keyringcb_t	 cb;
766 	unsigned	 res;
767 
768 	(void) memset(&cb, 0x0, sizeof(cb));
769 	cb.keyring = keyring;
770 	stream = __ops_new(sizeof(*stream));
771 	__ops_parse_options(stream, OPS_PTAG_SS_ALL, OPS_PARSE_PARSED);
772 	__ops_setup_memory_read(io, &stream, mem, &cb, cb_keyring_read,
773 					noaccum);
774 	if (armour) {
775 		__ops_reader_push_dearmour(stream);
776 	}
777 	res = (unsigned)__ops_parse_and_accumulate(keyring, stream);
778 	__ops_print_errors(__ops_stream_get_errors(stream));
779 	if (armour) {
780 		__ops_reader_pop_dearmour(stream);
781 	}
782 	/* don't call teardown_memory_read because memory was passed in */
783 	__ops_stream_delete(stream);
784 	return res;
785 }
786 
787 /**
788    \ingroup HighLevel_KeyringRead
789 
790    \brief Frees keyring's contents (but not keyring itself)
791 
792    \param keyring Keyring whose data is to be freed
793 
794    \note This does not free keyring itself, just the memory alloc-ed in it.
795  */
796 void
797 __ops_keyring_free(__ops_keyring_t *keyring)
798 {
799 	(void)free(keyring->keys);
800 	keyring->keys = NULL;
801 	keyring->keyc = keyring->keyvsize = 0;
802 }
803 
804 /* simple function to print out a binary keyid */
805 void
806 __ops_pkeyid(FILE *fp, const uint8_t *keyid, size_t size)
807 {
808 	size_t	i;
809 
810 	for (i = 0 ; i < size ; i++) {
811 		(void) fprintf(fp, "%02x", keyid[i]);
812 	}
813 }
814 
815 /**
816    \ingroup HighLevel_KeyringFind
817 
818    \brief Finds key in keyring from its Key ID
819 
820    \param keyring Keyring to be searched
821    \param keyid ID of required key
822 
823    \return Pointer to key, if found; NULL, if not found
824 
825    \note This returns a pointer to the key inside the given keyring,
826    not a copy.  Do not free it after use.
827 
828 */
829 const __ops_key_t *
830 __ops_getkeybyid(__ops_io_t *io, const __ops_keyring_t *keyring,
831 			   const uint8_t *keyid, unsigned *from)
832 {
833 	for ( ; keyring && *from < keyring->keyc; *from += 1) {
834 		if (__ops_get_debug_level(__FILE__)) {
835 			(void) fprintf(io->errs,
836 				"__ops_getkeybyid: keyring keyid ");
837 			__ops_pkeyid(io->errs, keyring->keys[*from].key_id,
838 				OPS_KEY_ID_SIZE);
839 			(void) fprintf(io->errs, ", keyid ");
840 			__ops_pkeyid(io->errs, keyid, OPS_KEY_ID_SIZE);
841 			(void) fprintf(io->errs, "\n");
842 		}
843 		if (memcmp(keyring->keys[*from].key_id, keyid,
844 				OPS_KEY_ID_SIZE) == 0) {
845 			return &keyring->keys[*from];
846 		}
847 		if (memcmp(&keyring->keys[*from].key_id[OPS_KEY_ID_SIZE / 2],
848 				keyid, OPS_KEY_ID_SIZE / 2) == 0) {
849 			return &keyring->keys[*from];
850 		}
851 	}
852 	return NULL;
853 }
854 
855 /* convert a string keyid into a binary keyid */
856 static void
857 str2keyid(const char *userid, uint8_t *keyid, size_t len)
858 {
859 	static const char	*uppers = "0123456789ABCDEF";
860 	static const char	*lowers = "0123456789abcdef";
861 	const char		*hi;
862 	const char		*lo;
863 	uint8_t			 hichar;
864 	uint8_t			 lochar;
865 	size_t			 j;
866 	int			 i;
867 
868 	for (i = j = 0 ; j < len && userid[i] && userid[i + 1] ; i += 2, j++) {
869 		if ((hi = strchr(uppers, userid[i])) == NULL) {
870 			if ((hi = strchr(lowers, userid[i])) == NULL) {
871 				break;
872 			}
873 			hichar = (hi - lowers);
874 		} else {
875 			hichar = (hi - uppers);
876 		}
877 		if ((lo = strchr(uppers, userid[i + 1])) == NULL) {
878 			if ((lo = strchr(lowers, userid[i + 1])) == NULL) {
879 				break;
880 			}
881 			lochar = (lo - lowers);
882 		} else {
883 			lochar = (lo - uppers);
884 		}
885 		keyid[j] = (hichar << 4) | (lochar);
886 	}
887 	keyid[j] = 0x0;
888 }
889 
890 /* return the next key which matches, starting searching at *from */
891 static const __ops_key_t *
892 getkeybyname(__ops_io_t *io,
893 			const __ops_keyring_t *keyring,
894 			const char *name,
895 			unsigned *from)
896 {
897 	const __ops_key_t	*kp;
898 	__ops_userid_t		*uidp;
899 	unsigned    	 i = 0;
900 	__ops_key_t		*keyp;
901 	unsigned		 savedstart;
902 	regex_t			 r;
903 	uint8_t		 	 keyid[OPS_KEY_ID_SIZE + 1];
904 	size_t          	 len;
905 
906 	if (!keyring) {
907 		return NULL;
908 	}
909 	len = strlen(name);
910 	if (__ops_get_debug_level(__FILE__)) {
911 		(void) fprintf(io->outs, "[%u] name '%s', len %zu\n",
912 			*from, name, len);
913 	}
914 	/* first try name as a keyid */
915 	(void) memset(keyid, 0x0, sizeof(keyid));
916 	str2keyid(name, keyid, sizeof(keyid));
917 	if (__ops_get_debug_level(__FILE__)) {
918 		(void) fprintf(io->outs,
919 			"name \"%s\", keyid %02x%02x%02x%02x\n",
920 			name,
921 			keyid[0], keyid[1], keyid[2], keyid[3]);
922 	}
923 	savedstart = *from;
924 	if ((kp = __ops_getkeybyid(io, keyring, keyid, from)) != NULL) {
925 		return kp;
926 	}
927 	*from = savedstart;
928 	if (__ops_get_debug_level(__FILE__)) {
929 		(void) fprintf(io->outs, "regex match '%s' from %u\n",
930 			name, *from);
931 	}
932 	/* match on full name or email address as a NOSUB, ICASE regexp */
933 	(void) regcomp(&r, name, REG_EXTENDED | REG_ICASE);
934 	for (keyp = &keyring->keys[*from]; *from < keyring->keyc; *from += 1, keyp++) {
935 		uidp = keyp->uids;
936 		for (i = 0 ; i < keyp->uidc; i++, uidp++) {
937 			if (__ops_get_debug_level(__FILE__)) {
938 				(void) fprintf(io->outs,
939 					"keyid \"%s\" len %"
940 					PRIsize "u, keyid[len] '%c'\n",
941 				       (char *) uidp->userid,
942 				       len, uidp->userid[len]);
943 			}
944 			if (regexec(&r, (char *)uidp->userid, 0, NULL, 0) == 0) {
945 				regfree(&r);
946 				return keyp;
947 			}
948 		}
949 	}
950 	regfree(&r);
951 	return NULL;
952 }
953 
954 /**
955    \ingroup HighLevel_KeyringFind
956 
957    \brief Finds key from its User ID
958 
959    \param keyring Keyring to be searched
960    \param userid User ID of required key
961 
962    \return Pointer to Key, if found; NULL, if not found
963 
964    \note This returns a pointer to the key inside the keyring, not a
965    copy.  Do not free it.
966 
967 */
968 const __ops_key_t *
969 __ops_getkeybyname(__ops_io_t *io,
970 			const __ops_keyring_t *keyring,
971 			const char *name)
972 {
973 	unsigned	from;
974 
975 	from = 0;
976 	return getkeybyname(io, keyring, name, &from);
977 }
978 
979 const __ops_key_t *
980 __ops_getnextkeybyname(__ops_io_t *io,
981 			const __ops_keyring_t *keyring,
982 			const char *name,
983 			unsigned *n)
984 {
985 	return getkeybyname(io, keyring, name, n);
986 }
987 
988 /**
989    \ingroup HighLevel_KeyringList
990 
991    \brief Prints all keys in keyring to stdout.
992 
993    \param keyring Keyring to use
994 
995    \return none
996 */
997 int
998 __ops_keyring_list(__ops_io_t *io, const __ops_keyring_t *keyring, const int psigs)
999 {
1000 	__ops_key_t		*key;
1001 	unsigned		 n;
1002 
1003 	(void) fprintf(io->res, "%u key%s\n", keyring->keyc,
1004 		(keyring->keyc == 1) ? "" : "s");
1005 	for (n = 0, key = keyring->keys; n < keyring->keyc; ++n, ++key) {
1006 		if (__ops_is_key_secret(key)) {
1007 			__ops_print_keydata(io, keyring, key, "sec",
1008 				&key->key.seckey.pubkey, 0);
1009 		} else {
1010 			__ops_print_keydata(io, keyring, key, "pub", &key->key.pubkey, psigs);
1011 		}
1012 		(void) fputc('\n', io->res);
1013 	}
1014 	return 1;
1015 }
1016 
1017 
1018 /* this interface isn't right - hook into callback for getting passphrase */
1019 char *
1020 __ops_export_key(__ops_io_t *io, const __ops_key_t *keydata, uint8_t *passphrase)
1021 {
1022 	__ops_output_t	*output;
1023 	__ops_memory_t	*mem;
1024 	char		*cp;
1025 
1026 	__OPS_USED(io);
1027 	__ops_setup_memory_write(&output, &mem, 128);
1028 	if (keydata->type == OPS_PTAG_CT_PUBLIC_KEY) {
1029 		__ops_write_xfer_pubkey(output, keydata, 1);
1030 	} else {
1031 		__ops_write_xfer_seckey(output, keydata, passphrase,
1032 					strlen((char *)passphrase), 1);
1033 	}
1034 	cp = netpgp_strdup(__ops_mem_data(mem));
1035 	__ops_teardown_memory_write(output, mem);
1036 	return cp;
1037 }
1038 
1039 /* add a key to a public keyring */
1040 int
1041 __ops_add_to_pubring(__ops_keyring_t *keyring, const __ops_pubkey_t *pubkey)
1042 {
1043 	__ops_key_t	*key;
1044 	time_t		 duration;
1045 
1046 	EXPAND_ARRAY(keyring, key);
1047 	key = &keyring->keys[keyring->keyc++];
1048 	duration = key->key.pubkey.duration;
1049 	(void) memset(key, 0x0, sizeof(*key));
1050 	__ops_keyid(key->key_id, OPS_KEY_ID_SIZE, pubkey);
1051 	__ops_fingerprint(&key->fingerprint, pubkey);
1052 	key->type = OPS_PTAG_CT_PUBLIC_KEY;
1053 	key->key.pubkey = *pubkey;
1054 	key->key.pubkey.duration = duration;
1055 	return 1;
1056 }
1057 
1058 /* add a key to a secret keyring */
1059 int
1060 __ops_add_to_secring(__ops_keyring_t *keyring, const __ops_seckey_t *seckey)
1061 {
1062 	const __ops_pubkey_t	*pubkey;
1063 	__ops_key_t		*key;
1064 
1065 	EXPAND_ARRAY(keyring, key);
1066 	key = &keyring->keys[keyring->keyc++];
1067 	(void) memset(key, 0x0, sizeof(*key));
1068 	pubkey = &seckey->pubkey;
1069 	__ops_keyid(key->key_id, OPS_KEY_ID_SIZE, pubkey);
1070 	__ops_fingerprint(&key->fingerprint, pubkey);
1071 	key->type = OPS_PTAG_CT_SECRET_KEY;
1072 	key->key.seckey = *seckey;
1073 	return 1;
1074 }
1075 
1076 /* append one keyring to another */
1077 int
1078 __ops_append_keyring(__ops_keyring_t *keyring, __ops_keyring_t *newring)
1079 {
1080 	unsigned	i;
1081 
1082 	for (i = 0 ; i < newring->keyc ; i++) {
1083 		EXPAND_ARRAY(keyring, key);
1084 		(void) memcpy(&keyring->keys[keyring->keyc], &newring->keys[i],
1085 				sizeof(newring->keys[i]));
1086 		keyring->keyc += 1;
1087 	}
1088 	return 1;
1089 }
1090