1 /*	$NetBSD: ks_file.c,v 1.1.1.1 2011/04/13 18:15:11 elric Exp $	*/
2 
3 /*
4  * Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan
5  * (Royal Institute of Technology, Stockholm, Sweden).
6  * All rights reserved.
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  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * 3. Neither the name of the Institute nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include "hx_locl.h"
37 
38 typedef enum { USE_PEM, USE_DER } outformat;
39 
40 struct ks_file {
41     hx509_certs certs;
42     char *fn;
43     outformat format;
44 };
45 
46 /*
47  *
48  */
49 
50 static int
51 parse_certificate(hx509_context context, const char *fn,
52 		  struct hx509_collector *c,
53 		  const hx509_pem_header *headers,
54 		  const void *data, size_t len,
55 		  const AlgorithmIdentifier *ai)
56 {
57     hx509_cert cert;
58     int ret;
59 
60     ret = hx509_cert_init_data(context, data, len, &cert);
61     if (ret)
62 	return ret;
63 
64     ret = _hx509_collector_certs_add(context, c, cert);
65     hx509_cert_free(cert);
66     return ret;
67 }
68 
69 static int
70 try_decrypt(hx509_context context,
71 	    struct hx509_collector *collector,
72 	    const AlgorithmIdentifier *alg,
73 	    const EVP_CIPHER *c,
74 	    const void *ivdata,
75 	    const void *password,
76 	    size_t passwordlen,
77 	    const void *cipher,
78 	    size_t len)
79 {
80     heim_octet_string clear;
81     size_t keylen;
82     void *key;
83     int ret;
84 
85     keylen = EVP_CIPHER_key_length(c);
86 
87     key = malloc(keylen);
88     if (key == NULL) {
89 	hx509_clear_error_string(context);
90 	return ENOMEM;
91     }
92 
93     ret = EVP_BytesToKey(c, EVP_md5(), ivdata,
94 			 password, passwordlen,
95 			 1, key, NULL);
96     if (ret <= 0) {
97 	hx509_set_error_string(context, 0, HX509_CRYPTO_INTERNAL_ERROR,
98 			       "Failed to do string2key for private key");
99 	return HX509_CRYPTO_INTERNAL_ERROR;
100     }
101 
102     clear.data = malloc(len);
103     if (clear.data == NULL) {
104 	hx509_set_error_string(context, 0, ENOMEM,
105 			       "Out of memory to decrypt for private key");
106 	ret = ENOMEM;
107 	goto out;
108     }
109     clear.length = len;
110 
111     {
112 	EVP_CIPHER_CTX ctx;
113 	EVP_CIPHER_CTX_init(&ctx);
114 	EVP_CipherInit_ex(&ctx, c, NULL, key, ivdata, 0);
115 	EVP_Cipher(&ctx, clear.data, cipher, len);
116 	EVP_CIPHER_CTX_cleanup(&ctx);
117     }
118 
119     ret = _hx509_collector_private_key_add(context,
120 					   collector,
121 					   alg,
122 					   NULL,
123 					   &clear,
124 					   NULL);
125 
126     memset(clear.data, 0, clear.length);
127     free(clear.data);
128 out:
129     memset(key, 0, keylen);
130     free(key);
131     return ret;
132 }
133 
134 static int
135 parse_pkcs8_private_key(hx509_context context, const char *fn,
136 			struct hx509_collector *c,
137 			const hx509_pem_header *headers,
138 			const void *data, size_t length,
139 			const AlgorithmIdentifier *ai)
140 {
141     PKCS8PrivateKeyInfo ki;
142     heim_octet_string keydata;
143 
144     int ret;
145 
146     ret = decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL);
147     if (ret)
148 	return ret;
149 
150     keydata.data = rk_UNCONST(data);
151     keydata.length = length;
152 
153     ret = _hx509_collector_private_key_add(context,
154 					   c,
155 					   &ki.privateKeyAlgorithm,
156 					   NULL,
157 					   &ki.privateKey,
158 					   &keydata);
159     free_PKCS8PrivateKeyInfo(&ki);
160     return ret;
161 }
162 
163 static int
164 parse_pem_private_key(hx509_context context, const char *fn,
165 		      struct hx509_collector *c,
166 		      const hx509_pem_header *headers,
167 		      const void *data, size_t len,
168 		      const AlgorithmIdentifier *ai)
169 {
170     int ret = 0;
171     const char *enc;
172 
173     enc = hx509_pem_find_header(headers, "Proc-Type");
174     if (enc) {
175 	const char *dek;
176 	char *type, *iv;
177 	ssize_t ssize, size;
178 	void *ivdata;
179 	const EVP_CIPHER *cipher;
180 	const struct _hx509_password *pw;
181 	hx509_lock lock;
182 	int i, decrypted = 0;
183 
184 	lock = _hx509_collector_get_lock(c);
185 	if (lock == NULL) {
186 	    hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
187 				   "Failed to get password for "
188 				   "password protected file %s", fn);
189 	    return HX509_ALG_NOT_SUPP;
190 	}
191 
192 	if (strcmp(enc, "4,ENCRYPTED") != 0) {
193 	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
194 				   "Private key encrypted in unknown method %s "
195 				   "in file",
196 				   enc, fn);
197 	    hx509_clear_error_string(context);
198 	    return HX509_PARSING_KEY_FAILED;
199 	}
200 
201 	dek = hx509_pem_find_header(headers, "DEK-Info");
202 	if (dek == NULL) {
203 	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
204 				   "Encrypted private key missing DEK-Info");
205 	    return HX509_PARSING_KEY_FAILED;
206 	}
207 
208 	type = strdup(dek);
209 	if (type == NULL) {
210 	    hx509_clear_error_string(context);
211 	    return ENOMEM;
212 	}
213 
214 	iv = strchr(type, ',');
215 	if (iv == NULL) {
216 	    free(type);
217 	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
218 				   "IV missing");
219 	    return HX509_PARSING_KEY_FAILED;
220 	}
221 
222 	*iv++ = '\0';
223 
224 	size = strlen(iv);
225 	ivdata = malloc(size);
226 	if (ivdata == NULL) {
227 	    hx509_clear_error_string(context);
228 	    free(type);
229 	    return ENOMEM;
230 	}
231 
232 	cipher = EVP_get_cipherbyname(type);
233 	if (cipher == NULL) {
234 	    free(ivdata);
235 	    hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
236 				   "Private key encrypted with "
237 				   "unsupported cipher: %s",
238 				   type);
239 	    free(type);
240 	    return HX509_ALG_NOT_SUPP;
241 	}
242 
243 #define PKCS5_SALT_LEN 8
244 
245 	ssize = hex_decode(iv, ivdata, size);
246 	free(type);
247 	type = NULL;
248 	iv = NULL;
249 
250 	if (ssize < 0 || ssize < PKCS5_SALT_LEN || ssize < EVP_CIPHER_iv_length(cipher)) {
251 	    free(ivdata);
252 	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
253 				   "Salt have wrong length in "
254 				   "private key file");
255 	    return HX509_PARSING_KEY_FAILED;
256 	}
257 
258 	pw = _hx509_lock_get_passwords(lock);
259 	if (pw != NULL) {
260 	    const void *password;
261 	    size_t passwordlen;
262 
263 	    for (i = 0; i < pw->len; i++) {
264 		password = pw->val[i];
265 		passwordlen = strlen(password);
266 
267 		ret = try_decrypt(context, c, ai, cipher, ivdata,
268 				  password, passwordlen, data, len);
269 		if (ret == 0) {
270 		    decrypted = 1;
271 		    break;
272 		}
273 	    }
274 	}
275 	if (!decrypted) {
276 	    hx509_prompt prompt;
277 	    char password[128];
278 
279 	    memset(&prompt, 0, sizeof(prompt));
280 
281 	    prompt.prompt = "Password for keyfile: ";
282 	    prompt.type = HX509_PROMPT_TYPE_PASSWORD;
283 	    prompt.reply.data = password;
284 	    prompt.reply.length = sizeof(password);
285 
286 	    ret = hx509_lock_prompt(lock, &prompt);
287 	    if (ret == 0)
288 		ret = try_decrypt(context, c, ai, cipher, ivdata, password,
289 				  strlen(password), data, len);
290 	    /* XXX add password to lock password collection ? */
291 	    memset(password, 0, sizeof(password));
292 	}
293 	free(ivdata);
294 
295     } else {
296 	heim_octet_string keydata;
297 
298 	keydata.data = rk_UNCONST(data);
299 	keydata.length = len;
300 
301 	ret = _hx509_collector_private_key_add(context, c, ai, NULL,
302 					       &keydata, NULL);
303     }
304 
305     return ret;
306 }
307 
308 
309 struct pem_formats {
310     const char *name;
311     int (*func)(hx509_context, const char *, struct hx509_collector *,
312 		const hx509_pem_header *, const void *, size_t,
313 		const AlgorithmIdentifier *);
314     const AlgorithmIdentifier *(*ai)(void);
315 } formats[] = {
316     { "CERTIFICATE", parse_certificate, NULL },
317     { "PRIVATE KEY", parse_pkcs8_private_key, NULL },
318     { "RSA PRIVATE KEY", parse_pem_private_key, hx509_signature_rsa },
319     { "EC PRIVATE KEY", parse_pem_private_key, hx509_signature_ecPublicKey }
320 };
321 
322 
323 struct pem_ctx {
324     int flags;
325     struct hx509_collector *c;
326 };
327 
328 static int
329 pem_func(hx509_context context, const char *type,
330 	 const hx509_pem_header *header,
331 	 const void *data, size_t len, void *ctx)
332 {
333     struct pem_ctx *pem_ctx = (struct pem_ctx*)ctx;
334     int ret = 0, j;
335 
336     for (j = 0; j < sizeof(formats)/sizeof(formats[0]); j++) {
337 	const char *q = formats[j].name;
338 	if (strcasecmp(type, q) == 0) {
339 	    const AlgorithmIdentifier *ai = NULL;
340 	    if (formats[j].ai != NULL)
341 		ai = (*formats[j].ai)();
342 
343 	    ret = (*formats[j].func)(context, NULL, pem_ctx->c,
344 				     header, data, len, ai);
345 	    if (ret && (pem_ctx->flags & HX509_CERTS_UNPROTECT_ALL)) {
346 		hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
347 				       "Failed parseing PEM format %s", type);
348 		return ret;
349 	    }
350 	    break;
351 	}
352     }
353     if (j == sizeof(formats)/sizeof(formats[0])) {
354 	ret = HX509_UNSUPPORTED_OPERATION;
355 	hx509_set_error_string(context, 0, ret,
356 			       "Found no matching PEM format for %s", type);
357 	return ret;
358     }
359     return 0;
360 }
361 
362 /*
363  *
364  */
365 
366 static int
367 file_init_common(hx509_context context,
368 		 hx509_certs certs, void **data, int flags,
369 		 const char *residue, hx509_lock lock, outformat format)
370 {
371     char *p, *pnext;
372     struct ks_file *ksf = NULL;
373     hx509_private_key *keys = NULL;
374     int ret;
375     struct pem_ctx pem_ctx;
376 
377     pem_ctx.flags = flags;
378     pem_ctx.c = NULL;
379 
380     *data = NULL;
381 
382     if (lock == NULL)
383 	lock = _hx509_empty_lock;
384 
385     ksf = calloc(1, sizeof(*ksf));
386     if (ksf == NULL) {
387 	hx509_clear_error_string(context);
388 	return ENOMEM;
389     }
390     ksf->format = format;
391 
392     ksf->fn = strdup(residue);
393     if (ksf->fn == NULL) {
394 	hx509_clear_error_string(context);
395 	ret = ENOMEM;
396 	goto out;
397     }
398 
399     /*
400      * XXX this is broken, the function should parse the file before
401      * overwriting it
402      */
403 
404     if (flags & HX509_CERTS_CREATE) {
405 	ret = hx509_certs_init(context, "MEMORY:ks-file-create",
406 			       0, lock, &ksf->certs);
407 	if (ret)
408 	    goto out;
409 	*data = ksf;
410 	return 0;
411     }
412 
413     ret = _hx509_collector_alloc(context, lock, &pem_ctx.c);
414     if (ret)
415 	goto out;
416 
417     for (p = ksf->fn; p != NULL; p = pnext) {
418 	FILE *f;
419 
420 	pnext = strchr(p, ',');
421 	if (pnext)
422 	    *pnext++ = '\0';
423 
424 
425 	if ((f = fopen(p, "r")) == NULL) {
426 	    ret = ENOENT;
427 	    hx509_set_error_string(context, 0, ret,
428 				   "Failed to open PEM file \"%s\": %s",
429 				   p, strerror(errno));
430 	    goto out;
431 	}
432 	rk_cloexec_file(f);
433 
434 	ret = hx509_pem_read(context, f, pem_func, &pem_ctx);
435 	fclose(f);
436 	if (ret != 0 && ret != HX509_PARSING_KEY_FAILED)
437 	    goto out;
438 	else if (ret == HX509_PARSING_KEY_FAILED) {
439 	    size_t length;
440 	    void *ptr;
441 	    int i;
442 
443 	    ret = rk_undumpdata(p, &ptr, &length);
444 	    if (ret) {
445 		hx509_clear_error_string(context);
446 		goto out;
447 	    }
448 
449 	    for (i = 0; i < sizeof(formats)/sizeof(formats[0]); i++) {
450 		const AlgorithmIdentifier *ai = NULL;
451 		if (formats[i].ai != NULL)
452 		    ai = (*formats[i].ai)();
453 
454 		ret = (*formats[i].func)(context, p, pem_ctx.c, NULL, ptr, length, ai);
455 		if (ret == 0)
456 		    break;
457 	    }
458 	    rk_xfree(ptr);
459 	    if (ret) {
460 		hx509_clear_error_string(context);
461 		goto out;
462 	    }
463 	}
464     }
465 
466     ret = _hx509_collector_collect_certs(context, pem_ctx.c, &ksf->certs);
467     if (ret)
468 	goto out;
469 
470     ret = _hx509_collector_collect_private_keys(context, pem_ctx.c, &keys);
471     if (ret == 0) {
472 	int i;
473 
474 	for (i = 0; keys[i]; i++)
475 	    _hx509_certs_keys_add(context, ksf->certs, keys[i]);
476 	_hx509_certs_keys_free(context, keys);
477     }
478 
479 out:
480     if (ret == 0)
481 	*data = ksf;
482     else {
483 	if (ksf->fn)
484 	    free(ksf->fn);
485 	free(ksf);
486     }
487     if (pem_ctx.c)
488 	_hx509_collector_free(pem_ctx.c);
489 
490     return ret;
491 }
492 
493 static int
494 file_init_pem(hx509_context context,
495 	      hx509_certs certs, void **data, int flags,
496 	      const char *residue, hx509_lock lock)
497 {
498     return file_init_common(context, certs, data, flags, residue, lock, USE_PEM);
499 }
500 
501 static int
502 file_init_der(hx509_context context,
503 	      hx509_certs certs, void **data, int flags,
504 	      const char *residue, hx509_lock lock)
505 {
506     return file_init_common(context, certs, data, flags, residue, lock, USE_DER);
507 }
508 
509 static int
510 file_free(hx509_certs certs, void *data)
511 {
512     struct ks_file *ksf = data;
513     hx509_certs_free(&ksf->certs);
514     free(ksf->fn);
515     free(ksf);
516     return 0;
517 }
518 
519 struct store_ctx {
520     FILE *f;
521     outformat format;
522 };
523 
524 static int
525 store_func(hx509_context context, void *ctx, hx509_cert c)
526 {
527     struct store_ctx *sc = ctx;
528     heim_octet_string data;
529     int ret;
530 
531     ret = hx509_cert_binary(context, c, &data);
532     if (ret)
533 	return ret;
534 
535     switch (sc->format) {
536     case USE_DER:
537 	fwrite(data.data, data.length, 1, sc->f);
538 	free(data.data);
539 	break;
540     case USE_PEM:
541 	hx509_pem_write(context, "CERTIFICATE", NULL, sc->f,
542 			data.data, data.length);
543 	free(data.data);
544 	if (_hx509_cert_private_key_exportable(c)) {
545 	    hx509_private_key key = _hx509_cert_private_key(c);
546 	    ret = _hx509_private_key_export(context, key,
547 					    HX509_KEY_FORMAT_DER, &data);
548 	    if (ret)
549 		break;
550 	    hx509_pem_write(context, _hx509_private_pem_name(key), NULL, sc->f,
551 			    data.data, data.length);
552 	    free(data.data);
553 	}
554 	break;
555     }
556 
557     return 0;
558 }
559 
560 static int
561 file_store(hx509_context context,
562 	   hx509_certs certs, void *data, int flags, hx509_lock lock)
563 {
564     struct ks_file *ksf = data;
565     struct store_ctx sc;
566     int ret;
567 
568     sc.f = fopen(ksf->fn, "w");
569     if (sc.f == NULL) {
570 	hx509_set_error_string(context, 0, ENOENT,
571 			       "Failed to open file %s for writing");
572 	return ENOENT;
573     }
574     rk_cloexec_file(sc.f);
575     sc.format = ksf->format;
576 
577     ret = hx509_certs_iter_f(context, ksf->certs, store_func, &sc);
578     fclose(sc.f);
579     return ret;
580 }
581 
582 static int
583 file_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
584 {
585     struct ks_file *ksf = data;
586     return hx509_certs_add(context, ksf->certs, c);
587 }
588 
589 static int
590 file_iter_start(hx509_context context,
591 		hx509_certs certs, void *data, void **cursor)
592 {
593     struct ks_file *ksf = data;
594     return hx509_certs_start_seq(context, ksf->certs, cursor);
595 }
596 
597 static int
598 file_iter(hx509_context context,
599 	  hx509_certs certs, void *data, void *iter, hx509_cert *cert)
600 {
601     struct ks_file *ksf = data;
602     return hx509_certs_next_cert(context, ksf->certs, iter, cert);
603 }
604 
605 static int
606 file_iter_end(hx509_context context,
607 	      hx509_certs certs,
608 	      void *data,
609 	      void *cursor)
610 {
611     struct ks_file *ksf = data;
612     return hx509_certs_end_seq(context, ksf->certs, cursor);
613 }
614 
615 static int
616 file_getkeys(hx509_context context,
617 	     hx509_certs certs,
618 	     void *data,
619 	     hx509_private_key **keys)
620 {
621     struct ks_file *ksf = data;
622     return _hx509_certs_keys_get(context, ksf->certs, keys);
623 }
624 
625 static int
626 file_addkey(hx509_context context,
627 	     hx509_certs certs,
628 	     void *data,
629 	     hx509_private_key key)
630 {
631     struct ks_file *ksf = data;
632     return _hx509_certs_keys_add(context, ksf->certs, key);
633 }
634 
635 static struct hx509_keyset_ops keyset_file = {
636     "FILE",
637     0,
638     file_init_pem,
639     file_store,
640     file_free,
641     file_add,
642     NULL,
643     file_iter_start,
644     file_iter,
645     file_iter_end,
646     NULL,
647     file_getkeys,
648     file_addkey
649 };
650 
651 static struct hx509_keyset_ops keyset_pemfile = {
652     "PEM-FILE",
653     0,
654     file_init_pem,
655     file_store,
656     file_free,
657     file_add,
658     NULL,
659     file_iter_start,
660     file_iter,
661     file_iter_end,
662     NULL,
663     file_getkeys,
664     file_addkey
665 };
666 
667 static struct hx509_keyset_ops keyset_derfile = {
668     "DER-FILE",
669     0,
670     file_init_der,
671     file_store,
672     file_free,
673     file_add,
674     NULL,
675     file_iter_start,
676     file_iter,
677     file_iter_end,
678     NULL,
679     file_getkeys,
680     file_addkey
681 };
682 
683 
684 void
685 _hx509_ks_file_register(hx509_context context)
686 {
687     _hx509_ks_register(context, &keyset_file);
688     _hx509_ks_register(context, &keyset_pemfile);
689     _hx509_ks_register(context, &keyset_derfile);
690 }
691