No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / dist / heimdal / lib / hx509 / ks_file.c
blobfbdb4ef74941067dcdbb0706e22b5c4326823328
1 /*
2 * Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * 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.
17 * 3. Neither the name of the Institute nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
34 #include "hx_locl.h"
35 __RCSID("$Heimdal: ks_file.c 22465 2008-01-16 14:25:24Z lha $"
36 "$NetBSD$");
38 typedef enum { USE_PEM, USE_DER } outformat;
40 struct ks_file {
41 hx509_certs certs;
42 char *fn;
43 outformat format;
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)
56 hx509_cert cert;
57 int ret;
59 ret = hx509_cert_init_data(context, data, len, &cert);
60 if (ret)
61 return ret;
63 ret = _hx509_collector_certs_add(context, c, cert);
64 hx509_cert_free(cert);
65 return ret;
68 static int
69 try_decrypt(hx509_context context,
70 struct hx509_collector *collector,
71 const AlgorithmIdentifier *alg,
72 const EVP_CIPHER *c,
73 const void *ivdata,
74 const void *password,
75 size_t passwordlen,
76 const void *cipher,
77 size_t len)
79 heim_octet_string clear;
80 size_t keylen;
81 void *key;
82 int ret;
84 keylen = EVP_CIPHER_key_length(c);
86 key = malloc(keylen);
87 if (key == NULL) {
88 hx509_clear_error_string(context);
89 return ENOMEM;
92 ret = EVP_BytesToKey(c, EVP_md5(), ivdata,
93 password, passwordlen,
94 1, key, NULL);
95 if (ret <= 0) {
96 hx509_set_error_string(context, 0, HX509_CRYPTO_INTERNAL_ERROR,
97 "Failed to do string2key for private key");
98 return HX509_CRYPTO_INTERNAL_ERROR;
101 clear.data = malloc(len);
102 if (clear.data == NULL) {
103 hx509_set_error_string(context, 0, ENOMEM,
104 "Out of memory to decrypt for private key");
105 ret = ENOMEM;
106 goto out;
108 clear.length = len;
111 EVP_CIPHER_CTX ctx;
112 EVP_CIPHER_CTX_init(&ctx);
113 EVP_CipherInit_ex(&ctx, c, NULL, key, ivdata, 0);
114 EVP_Cipher(&ctx, clear.data, cipher, len);
115 EVP_CIPHER_CTX_cleanup(&ctx);
118 ret = _hx509_collector_private_key_add(context,
119 collector,
120 alg,
121 NULL,
122 &clear,
123 NULL);
125 memset(clear.data, 0, clear.length);
126 free(clear.data);
127 out:
128 memset(key, 0, keylen);
129 free(key);
130 return ret;
133 static int
134 parse_rsa_private_key(hx509_context context, const char *fn,
135 struct hx509_collector *c,
136 const hx509_pem_header *headers,
137 const void *data, size_t len)
139 int ret = 0;
140 const char *enc;
142 enc = hx509_pem_find_header(headers, "Proc-Type");
143 if (enc) {
144 const char *dek;
145 char *type, *iv;
146 ssize_t ssize, size;
147 void *ivdata;
148 const EVP_CIPHER *cipher;
149 const struct _hx509_password *pw;
150 hx509_lock lock;
151 int i, decrypted = 0;
153 lock = _hx509_collector_get_lock(c);
154 if (lock == NULL) {
155 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
156 "Failed to get password for "
157 "password protected file %s", fn);
158 return HX509_ALG_NOT_SUPP;
161 if (strcmp(enc, "4,ENCRYPTED") != 0) {
162 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
163 "RSA key encrypted in unknown method %s "
164 "in file",
165 enc, fn);
166 hx509_clear_error_string(context);
167 return HX509_PARSING_KEY_FAILED;
170 dek = hx509_pem_find_header(headers, "DEK-Info");
171 if (dek == NULL) {
172 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
173 "Encrypted RSA missing DEK-Info");
174 return HX509_PARSING_KEY_FAILED;
177 type = strdup(dek);
178 if (type == NULL) {
179 hx509_clear_error_string(context);
180 return ENOMEM;
183 iv = strchr(type, ',');
184 if (iv == NULL) {
185 free(type);
186 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
187 "IV missing");
188 return HX509_PARSING_KEY_FAILED;
191 *iv++ = '\0';
193 size = strlen(iv);
194 ivdata = malloc(size);
195 if (ivdata == NULL) {
196 hx509_clear_error_string(context);
197 free(type);
198 return ENOMEM;
201 cipher = EVP_get_cipherbyname(type);
202 if (cipher == NULL) {
203 free(ivdata);
204 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
205 "RSA key encrypted with "
206 "unsupported cipher: %s",
207 type);
208 free(type);
209 return HX509_ALG_NOT_SUPP;
212 #define PKCS5_SALT_LEN 8
214 ssize = hex_decode(iv, ivdata, size);
215 free(type);
216 type = NULL;
217 iv = NULL;
219 if (ssize < 0 || ssize < PKCS5_SALT_LEN || ssize < EVP_CIPHER_iv_length(cipher)) {
220 free(ivdata);
221 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
222 "Salt have wrong length in RSA key file");
223 return HX509_PARSING_KEY_FAILED;
226 pw = _hx509_lock_get_passwords(lock);
227 if (pw != NULL) {
228 const void *password;
229 size_t passwordlen;
231 for (i = 0; i < pw->len; i++) {
232 password = pw->val[i];
233 passwordlen = strlen(password);
235 ret = try_decrypt(context, c, hx509_signature_rsa(),
236 cipher, ivdata, password, passwordlen,
237 data, len);
238 if (ret == 0) {
239 decrypted = 1;
240 break;
244 if (!decrypted) {
245 hx509_prompt prompt;
246 char password[128];
248 memset(&prompt, 0, sizeof(prompt));
250 prompt.prompt = "Password for keyfile: ";
251 prompt.type = HX509_PROMPT_TYPE_PASSWORD;
252 prompt.reply.data = password;
253 prompt.reply.length = sizeof(password);
255 ret = hx509_lock_prompt(lock, &prompt);
256 if (ret == 0)
257 ret = try_decrypt(context, c, hx509_signature_rsa(),
258 cipher, ivdata, password, strlen(password),
259 data, len);
260 /* XXX add password to lock password collection ? */
261 memset(password, 0, sizeof(password));
263 free(ivdata);
265 } else {
266 heim_octet_string keydata;
268 keydata.data = rk_UNCONST(data);
269 keydata.length = len;
271 ret = _hx509_collector_private_key_add(context,
273 hx509_signature_rsa(),
274 NULL,
275 &keydata,
276 NULL);
279 return ret;
283 struct pem_formats {
284 const char *name;
285 int (*func)(hx509_context, const char *, struct hx509_collector *,
286 const hx509_pem_header *, const void *, size_t);
287 } formats[] = {
288 { "CERTIFICATE", parse_certificate },
289 { "RSA PRIVATE KEY", parse_rsa_private_key }
293 struct pem_ctx {
294 int flags;
295 struct hx509_collector *c;
298 static int
299 pem_func(hx509_context context, const char *type,
300 const hx509_pem_header *header,
301 const void *data, size_t len, void *ctx)
303 struct pem_ctx *pem_ctx = (struct pem_ctx*)ctx;
304 int ret = 0, j;
306 for (j = 0; j < sizeof(formats)/sizeof(formats[0]); j++) {
307 const char *q = formats[j].name;
308 if (strcasecmp(type, q) == 0) {
309 ret = (*formats[j].func)(context, NULL, pem_ctx->c, header, data, len);
310 if (ret == 0)
311 break;
314 if (j == sizeof(formats)/sizeof(formats[0])) {
315 ret = HX509_UNSUPPORTED_OPERATION;
316 hx509_set_error_string(context, 0, ret,
317 "Found no matching PEM format for %s", type);
318 return ret;
320 if (ret && (pem_ctx->flags & HX509_CERTS_UNPROTECT_ALL))
321 return ret;
322 return 0;
329 static int
330 file_init_common(hx509_context context,
331 hx509_certs certs, void **data, int flags,
332 const char *residue, hx509_lock lock, outformat format)
334 char *p, *pnext;
335 struct ks_file *f = NULL;
336 hx509_private_key *keys = NULL;
337 int ret;
338 struct pem_ctx pem_ctx;
340 pem_ctx.flags = flags;
341 pem_ctx.c = NULL;
343 *data = NULL;
345 if (lock == NULL)
346 lock = _hx509_empty_lock;
348 f = calloc(1, sizeof(*f));
349 if (f == NULL) {
350 hx509_clear_error_string(context);
351 return ENOMEM;
353 f->format = format;
355 f->fn = strdup(residue);
356 if (f->fn == NULL) {
357 hx509_clear_error_string(context);
358 ret = ENOMEM;
359 goto out;
363 * XXX this is broken, the function should parse the file before
364 * overwriting it
367 if (flags & HX509_CERTS_CREATE) {
368 ret = hx509_certs_init(context, "MEMORY:ks-file-create",
369 0, lock, &f->certs);
370 if (ret)
371 goto out;
372 *data = f;
373 return 0;
376 ret = _hx509_collector_alloc(context, lock, &pem_ctx.c);
377 if (ret)
378 goto out;
380 for (p = f->fn; p != NULL; p = pnext) {
381 FILE *f;
383 pnext = strchr(p, ',');
384 if (pnext)
385 *pnext++ = '\0';
388 if ((f = fopen(p, "r")) == NULL) {
389 ret = ENOENT;
390 hx509_set_error_string(context, 0, ret,
391 "Failed to open PEM file \"%s\": %s",
392 p, strerror(errno));
393 goto out;
396 ret = hx509_pem_read(context, f, pem_func, &pem_ctx);
397 fclose(f);
398 if (ret != 0 && ret != HX509_PARSING_KEY_FAILED)
399 goto out;
400 else if (ret == HX509_PARSING_KEY_FAILED) {
401 size_t length;
402 void *ptr;
403 int i;
405 ret = _hx509_map_file(p, &ptr, &length, NULL);
406 if (ret) {
407 hx509_clear_error_string(context);
408 goto out;
411 for (i = 0; i < sizeof(formats)/sizeof(formats[0]); i++) {
412 ret = (*formats[i].func)(context, p, pem_ctx.c, NULL, ptr, length);
413 if (ret == 0)
414 break;
416 _hx509_unmap_file(ptr, length);
417 if (ret)
418 goto out;
422 ret = _hx509_collector_collect_certs(context, pem_ctx.c, &f->certs);
423 if (ret)
424 goto out;
426 ret = _hx509_collector_collect_private_keys(context, pem_ctx.c, &keys);
427 if (ret == 0) {
428 int i;
430 for (i = 0; keys[i]; i++)
431 _hx509_certs_keys_add(context, f->certs, keys[i]);
432 _hx509_certs_keys_free(context, keys);
435 out:
436 if (ret == 0)
437 *data = f;
438 else {
439 if (f->fn)
440 free(f->fn);
441 free(f);
443 if (pem_ctx.c)
444 _hx509_collector_free(pem_ctx.c);
446 return ret;
449 static int
450 file_init_pem(hx509_context context,
451 hx509_certs certs, void **data, int flags,
452 const char *residue, hx509_lock lock)
454 return file_init_common(context, certs, data, flags, residue, lock, USE_PEM);
457 static int
458 file_init_der(hx509_context context,
459 hx509_certs certs, void **data, int flags,
460 const char *residue, hx509_lock lock)
462 return file_init_common(context, certs, data, flags, residue, lock, USE_DER);
465 static int
466 file_free(hx509_certs certs, void *data)
468 struct ks_file *f = data;
469 hx509_certs_free(&f->certs);
470 free(f->fn);
471 free(f);
472 return 0;
475 struct store_ctx {
476 FILE *f;
477 outformat format;
480 static int
481 store_func(hx509_context context, void *ctx, hx509_cert c)
483 struct store_ctx *sc = ctx;
484 heim_octet_string data;
485 int ret;
487 ret = hx509_cert_binary(context, c, &data);
488 if (ret)
489 return ret;
491 switch (sc->format) {
492 case USE_DER:
493 fwrite(data.data, data.length, 1, sc->f);
494 free(data.data);
495 break;
496 case USE_PEM:
497 hx509_pem_write(context, "CERTIFICATE", NULL, sc->f,
498 data.data, data.length);
499 free(data.data);
500 if (_hx509_cert_private_key_exportable(c)) {
501 hx509_private_key key = _hx509_cert_private_key(c);
502 ret = _hx509_private_key_export(context, key, &data);
503 if (ret)
504 break;
505 hx509_pem_write(context, _hx509_private_pem_name(key), NULL, sc->f,
506 data.data, data.length);
507 free(data.data);
509 break;
512 return 0;
515 static int
516 file_store(hx509_context context,
517 hx509_certs certs, void *data, int flags, hx509_lock lock)
519 struct ks_file *f = data;
520 struct store_ctx sc;
521 int ret;
523 sc.f = fopen(f->fn, "w");
524 if (sc.f == NULL) {
525 hx509_set_error_string(context, 0, ENOENT,
526 "Failed to open file %s for writing");
527 return ENOENT;
529 sc.format = f->format;
531 ret = hx509_certs_iter(context, f->certs, store_func, &sc);
532 fclose(sc.f);
533 return ret;
536 static int
537 file_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
539 struct ks_file *f = data;
540 return hx509_certs_add(context, f->certs, c);
543 static int
544 file_iter_start(hx509_context context,
545 hx509_certs certs, void *data, void **cursor)
547 struct ks_file *f = data;
548 return hx509_certs_start_seq(context, f->certs, cursor);
551 static int
552 file_iter(hx509_context context,
553 hx509_certs certs, void *data, void *iter, hx509_cert *cert)
555 struct ks_file *f = data;
556 return hx509_certs_next_cert(context, f->certs, iter, cert);
559 static int
560 file_iter_end(hx509_context context,
561 hx509_certs certs,
562 void *data,
563 void *cursor)
565 struct ks_file *f = data;
566 return hx509_certs_end_seq(context, f->certs, cursor);
569 static int
570 file_getkeys(hx509_context context,
571 hx509_certs certs,
572 void *data,
573 hx509_private_key **keys)
575 struct ks_file *f = data;
576 return _hx509_certs_keys_get(context, f->certs, keys);
579 static int
580 file_addkey(hx509_context context,
581 hx509_certs certs,
582 void *data,
583 hx509_private_key key)
585 struct ks_file *f = data;
586 return _hx509_certs_keys_add(context, f->certs, key);
589 static struct hx509_keyset_ops keyset_file = {
590 "FILE",
592 file_init_pem,
593 file_store,
594 file_free,
595 file_add,
596 NULL,
597 file_iter_start,
598 file_iter,
599 file_iter_end,
600 NULL,
601 file_getkeys,
602 file_addkey
605 static struct hx509_keyset_ops keyset_pemfile = {
606 "PEM-FILE",
608 file_init_pem,
609 file_store,
610 file_free,
611 file_add,
612 NULL,
613 file_iter_start,
614 file_iter,
615 file_iter_end,
616 NULL,
617 file_getkeys,
618 file_addkey
621 static struct hx509_keyset_ops keyset_derfile = {
622 "DER-FILE",
624 file_init_der,
625 file_store,
626 file_free,
627 file_add,
628 NULL,
629 file_iter_start,
630 file_iter,
631 file_iter_end,
632 NULL,
633 file_getkeys,
634 file_addkey
638 void
639 _hx509_ks_file_register(hx509_context context)
641 _hx509_ks_register(context, &keyset_file);
642 _hx509_ks_register(context, &keyset_pemfile);
643 _hx509_ks_register(context, &keyset_derfile);