Merge branch 'ical'
[alpine.git] / pith / smkeys.c
blob2f849244c5b0f36dd639c1d5b225991e41ab6714
1 #if !defined(lint) && !defined(DOS)
2 static char rcsid[] = "$Id: smkeys.c 1266 2009-07-14 18:39:12Z hubert@u.washington.edu $";
3 #endif
5 /*
6 * ========================================================================
7 * Copyright 2013-2017 Eduardo Chappa
8 * Copyright 2008 University of Washington
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * ========================================================================
20 * This is based on a contribution from Jonathan Paisley, see smime.c
24 #include "../pith/headers.h"
26 #ifdef SMIME
28 #include "../pith/status.h"
29 #include "../pith/conf.h"
30 #include "../pith/remote.h"
31 #include "../pith/tempfile.h"
32 #include "../pith/busy.h"
33 #include "../pith/osdep/lstcmpnt.h"
34 #include "../pith/util.h"
35 #include "../pith/mailindx.h"
36 #include "../pith/readfile.h"
37 #include "smkeys.h"
39 #ifdef APPLEKEYCHAIN
40 #include <Security/SecKeychain.h>
41 #include <Security/SecKeychainItem.h>
42 #include <Security/SecKeychainSearch.h>
43 #include <Security/SecCertificate.h>
44 #endif /* APPLEKEYCHAIN */
47 /* internal prototypes */
48 static char *emailstrclean(char *string);
49 static int mem_add_extra_cacerts(char *contents, X509_LOOKUP *lookup);
50 int compare_certs_by_name(const void *data1, const void *data2);
51 int password_policy_check(char *);
53 int (*pith_smime_enter_password)(char *, char *, size_t);
55 /* test if password passes a predetermined policy.
56 * return value: 0 - does not pass; 1 - it passes
58 int
59 password_policy_check(char *password)
61 int rv = 1;
62 char *error;
63 char tmp[1024];
65 if(password == NULL || password[0] == '\0'){
66 error = _("Password cannot be blank");
67 rv = 0;
68 } else if(strlen(password) < 8){
69 error = _("Password is too short");
70 rv = 0;
72 if(rv == 0){
73 snprintf(tmp, sizeof(tmp), "%s%s", error, _(". Enter password again"));
74 tmp[sizeof(tmp) - 1] = '\0';
75 q_status_message(SM_ORDER, 3, 3, tmp);
77 return rv;
81 int
82 create_master_password(char *pass, size_t passlen, int first_time)
84 #define MAXTRIAL 3
85 int rv, trial;
86 char prompt[MAILTMPLEN];
87 char passbackup[MAILTMPLEN];
89 if(first_time)
90 q_status_message(SM_ORDER, 3, 3,
91 _(" Creating a Master Password for your Password file "));
92 else
93 q_status_message(SM_ORDER, 3, 3,
94 _(" Retrying to create a Master Password for your Password file "));
96 for(trial = 0; trial < MAXTRIAL; trial++){
97 snprintf(prompt, sizeof(prompt),
98 _("Create master password (attempt %d of %d): "), trial+1, MAXTRIAL);
99 prompt[sizeof(prompt)- 1] = '\0';
100 pass[0] = '\0';
101 do {
102 /* rv == 1 means cancel */
103 rv = (pith_smime_enter_password)(prompt, pass, passlen);
104 if(rv == 1 || password_policy_check(pass) == 0)
105 pass[0] = '\0';
106 if(rv == 1) return 0;
107 } while ((rv != 0 && rv != 1) || (rv == 0 && pass[0] == '\0'));
109 snprintf(prompt, sizeof(prompt),
110 _("Confirm master password (attempt %d of %d): "), trial+1, MAXTRIAL);
111 prompt[sizeof(prompt)- 1] = '\0';
112 passbackup[0] = '\0';
113 do {
114 rv = (pith_smime_enter_password)(prompt, passbackup, sizeof(passbackup));
115 } while ((rv !=0 && rv !=1 && rv > 0) || passbackup[0] == '\0');
116 if(!strcmp(pass, passbackup))
117 break;
118 if(trial + 1 < MAXTRIAL)
119 q_status_message(SM_ORDER, 2, 2, _("Passwords do not match, try again."));
120 else{
121 q_status_message(SM_ORDER, 2, 2, _("Passwords do not match, too many failures."));
122 pass[0] = '\0';
125 return (trial < MAXTRIAL) ? 1 : 0;
129 * Create a self signed certificate with root name _fname_, in directory
130 * _pathdir_. If _version_ is 3, we use the _template_ file as configuration
131 * file for openssl. At this moment, we only call this function with template = NULL
132 * and version = 0, but a sensible call is
133 * ALPINE_self_signed_certificate("/etc/ssl/openssl.cnf", 2, pathdir, fname, first_time);
134 * or so.
135 * _pathdir_ is the directory to save the file,
136 * _fname_ is the root of the name to use. Append ".key" and ".crt" to this name
137 * _first_time_ is an indicator to tell us if this is the first time we call this function
139 PERSONAL_CERT *
140 ALPINE_self_signed_certificate(char *template, int version, char *pathdir, char *fname)
142 BIGNUM *b = NULL;
143 X509_NAME *name = NULL;
144 X509_REQ *req = NULL;
145 EVP_PKEY_CTX *pkctx;
146 BIO *out = NULL;
147 char tmp[MAXPATH+1], password[1024];
148 char *keyfile = NULL, *certfile = NULL;
149 char *extensions = NULL;
150 FILE *fp;
151 long errline = -1L;
152 PERSONAL_CERT *pc = NULL;
153 EVP_PKEY *pkey = NULL;
154 X509 *pcert = NULL;
155 CONF *req_conf = NULL;
156 static int first_time = 1;
158 if(pathdir == NULL)
159 return NULL;
161 if(template){
162 if((out = BIO_new_file(template, "r")) == NULL){
163 q_status_message(SM_ORDER, 2, 2, _("Problem reading configuration file"));
164 return pc;
167 if((req_conf = NCONF_new(NULL)) != NULL
168 && NCONF_load_bio(req_conf, out, &errline) > 0){
169 if((extensions = NCONF_get_string(req_conf, "req", "x509_extensions")) != NULL){
170 X509V3_CTX ctx;
171 X509V3_set_ctx_test(&ctx);
172 X509V3_set_nconf(&ctx, req_conf);
173 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
174 q_status_message(SM_ORDER, 2, 2, _("Problem loading openssl configuration"));
175 NCONF_free(req_conf);
176 return pc;
180 BIO_free(out);
181 out = NULL;
184 if(create_master_password(password, sizeof(password), first_time)
185 && (pkctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL)) != NULL
186 && EVP_PKEY_keygen_init(pkctx) > 0
187 && EVP_PKEY_CTX_set_rsa_keygen_bits(pkctx, 2048) > 0 /* RSA:2048 */
188 && EVP_PKEY_keygen(pkctx, &pkey) > 0){
189 snprintf(tmp, sizeof(tmp), "%s.key", fname);
190 tmp[sizeof(tmp)-1] = '\0';
191 keyfile = cpystr(tmp);
192 build_path(tmp, pathdir, keyfile, sizeof(tmp));
193 keyfile[strlen(keyfile)-4] = '\0'; /* keyfile does not have .key extension */
194 if((fp = fopen(tmp, "w")) != NULL
195 && (out = BIO_new_fp(fp, BIO_CLOSE | BIO_FP_TEXT)) != NULL
196 && PEM_write_bio_PrivateKey(out, pkey, EVP_des_ede3_cbc(),
197 NULL, 0, NULL, password)){
198 BIO_free(out);
199 out = NULL;
201 memset((void *)password, 0, sizeof(password));
202 if((req = X509_REQ_new()) != NULL
203 && X509_REQ_set_version(req, 0L)){
204 name = X509_REQ_get_subject_name(req);
205 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, "Password File Certificate and Key Pair", -1, -1, 0);
206 if(X509_REQ_set_pubkey(req, pkey)
207 && (pcert = X509_new()) != NULL){
208 if(X509_set_version(pcert, version)
209 && (b = BN_new()) != NULL
210 && BN_set_word(b, 65537)
211 && BN_pseudo_rand(b, 64, 0, 0)
212 && X509_get_serialNumber(pcert)
213 && BN_to_ASN1_INTEGER(b, X509_get_serialNumber(pcert)) /* set serial */
214 && X509_set_issuer_name(pcert, X509_REQ_get_subject_name(req))
215 && X509_set_subject_name(pcert, X509_REQ_get_subject_name(req))){
216 X509V3_CTX ext_ctx;
217 EVP_PKEY *tmppkey;
219 X509_gmtime_adj(X509_getm_notBefore(pcert), 0);
220 X509_time_adj_ex(X509_getm_notAfter(pcert), 1095, 0, NULL);
222 if((tmppkey = X509_REQ_get0_pubkey(req)) != NULL
223 && X509_set_pubkey(pcert, tmppkey)){
224 if(extensions != NULL && version == 2){
225 X509V3_set_ctx(&ext_ctx, pcert, pcert, NULL, NULL, 0);
226 if(req_conf){ /* only if template is not null */
227 X509V3_set_nconf(&ext_ctx, req_conf);
228 X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions, pcert);
231 EVP_PKEY_free(tmppkey);
232 X509_sign(pcert, pkey, NULL);
234 BN_free(b);
239 snprintf(tmp, sizeof(tmp), "%s.crt", fname);
240 tmp[sizeof(tmp)-1] = '\0';
241 certfile = cpystr(tmp);
242 build_path(tmp, pathdir, certfile, sizeof(tmp));
243 if((fp = fopen(tmp, "w")) != NULL
244 &&(out = BIO_new_fp(fp, BIO_FP_TEXT)) != NULL){
245 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
246 PEM_write_bio_X509(out, pcert);
247 BIO_flush(out);
248 BIO_free(out);
249 out = NULL;
251 if(req_conf)
252 NCONF_free(req_conf);
254 if(keyfile && certfile && pkey && pcert){
255 pc = (PERSONAL_CERT *) fs_get(sizeof(PERSONAL_CERT));
256 memset((void *)pc, 0, sizeof(PERSONAL_CERT));
257 pc->name = keyfile;
258 pc->key = pkey;
259 pc->cert = pcert;
260 pc->cname = certfile;
262 first_time = 0;
263 return pc;
266 CertList *
267 smime_X509_to_cert_info(X509 *x, char *name)
269 CertList *cert;
270 char buf[MAXPATH+1];
272 if(x == NULL) return NULL;
274 cert = fs_get(sizeof(CertList));
275 memset((void *)cert, 0, sizeof(CertList));
276 cert->x509_cert = x;
277 cert->name = name ? cpystr(name) : NULL;
278 cert->data.date_from = smime_get_date(X509_get0_notBefore(x));
279 cert->data.date_to = smime_get_date(X509_get0_notAfter(x));
280 cert->cn = smime_get_cn(x);
281 get_fingerprint(x, EVP_md5(), buf, sizeof(buf), NULL);
282 cert->data.md5 = cpystr(buf);
284 return cert;
287 #define SMIME_BACKUP_DIR ".backup"
288 #define MAX_TRY_BACKUP 100
290 /* return value: 0 - success, -1 error
291 * Call this function after setting up paths in ps_global->smime
292 * and reading certificates names in certlist.
295 setup_certs_backup_by_type(WhichCerts ctype)
297 int rv = 0; /* assume success */
298 int len;
299 int i, done;
300 char *d, *fname;
301 char p[MAXPATH+1]; /* path to where the backup is */
302 char buf[MAXPATH+1], buf2[MAXPATH+1];
303 struct stat sbuf;
304 CertList *data, *cl;
305 #ifndef _WINDOWS
306 DIR *dirp;
307 struct dirent *df; /* file in the directory */
308 #else /* _WINDOWS */
309 struct _finddata_t dbuf;
310 char bufn[_MAX_PATH + 4];
311 long findrv;
312 #endif /* !_WINDOWS */
313 CertList *cert, *cl2;
314 X509 *x;
315 BIO *in;
317 return rv; /* remove when this function is complete */
319 if(SMHOLDERTYPE(ctype) == Directory){
320 d = PATHCERTDIR(ctype);
321 if(d != NULL){
322 len = strlen(d) + strlen(S_FILESEP) + strlen(SMIME_BACKUP_DIR) + 1;
323 snprintf(p, MAXPATH, "%s%s%s", d, S_FILESEP, SMIME_BACKUP_DIR);
324 p[MAXPATH] = '\0';
325 if(our_stat(p, &sbuf) < 0){
326 if(our_mkpath(p, 0700) != 0)
327 return -1;
328 } else if((sbuf.st_mode & S_IFMT) != S_IFDIR){
329 for(i = 0, done = 0; done == 0 && i < MAX_TRY_BACKUP; i++){
330 snprintf(buf2, len+2, "%s%d", p, i);
331 if(our_stat(buf2, &sbuf) < 0){
332 if(our_mkpath(buf2, 0700) == 0)
333 done++;
335 else if((sbuf.st_mode & S_IFMT) == S_IFDIR)
336 done++;
337 if(done){
338 strncpy(p, buf2, MAXPATH);
339 p[MAXPATH] = '\0';
342 if(done == 0)
343 return -1;
345 /* if we are here, we have a backup directory where to
346 * backup certificates/keys, so now we will go
347 * through the list of certificates and back them up
348 * if we need to.
350 data = BACKUPDATACERT(ctype);
351 for(cl = DATACERT(ctype); cl; cl = cl->next){
352 char clname[MAXPATH+1];
354 snprintf(clname, MAXPATH, "%s%s", cl->name, ctype == Private ? ".key" : "");
355 clname[MAXPATH] = '\0';
356 len = strlen(d) + strlen(clname) + 2;
357 if(len < MAXPATH){
358 snprintf(buf, len, "%s%s%s", d, S_FILESEP, clname);
359 buf[sizeof(buf)-1] = '\0';
360 len = strlen(p) + strlen(clname) + strlen(cl->data.md5) + 3;
361 if(len < MAXPATH){
362 snprintf(buf2, len, "%s%s%s.%s", p, S_FILESEP, clname, cl->data.md5);
363 buf2[sizeof(buf2)-1] = '\0';
364 done = 0; /* recycle done: it means we have a file that may be a certifificate*/
365 if(stat(buf2, &sbuf) < 0){
366 if (our_copy(buf2, buf) == 0)
367 done++;
368 } else if((sbuf.st_mode & S_IFMT) == S_IFREG)
369 done++;
371 if(done){
372 switch(ctype){
373 case Public:
374 case CACert:
375 if((in = BIO_new_file(buf2, "r"))!=0){
376 cert = fs_get(sizeof(CertList));
377 memset((void *)cert, 0, sizeof(CertList));
378 cert->x509_cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
379 if(cl->data.date_from != NULL)
380 cert->data.date_from = cpystr(cl->data.date_from);
381 if(cl->data.date_to != NULL)
382 cert->data.date_to = cpystr(cl->data.date_to);
383 if(cl->data.md5 != NULL)
384 cert->data.md5 = cpystr(cl->data.md5);
385 if(cl->cn != NULL)
386 cert->cn = cpystr(cl->cn);
387 snprintf(buf2, len, "%s.%s", cl->name, cl->data.md5);
388 buf2[sizeof(buf2)-1] = '\0';
389 cert->name = cpystr(buf2);
390 if(data == NULL)
391 data = cert;
392 else{
393 for (cl2 = data; cl2 && cl2->next; cl2 = cl2->next);
394 cl2->next = cert;
396 BIO_free(in);
398 break;
400 case Private: break;
401 default: alpine_panic("Bad ctype (0)");
407 /* if we are here, it means we just loaded the backup variable with
408 * a copy of the data that comes from the certlist not coming from
409 * backup. Now we are going to load the contents of the .backup
410 * directory.
413 /* Here is the plan: read the backup directory (in the variable "p")
414 * and attempt to add it. If already there, skip it; otherwise continue
416 #ifndef _WINDOWS
417 if ((dirp = opendir(p)) != NULL) {
418 while ((df = readdir(dirp)) != NULL) {
419 fname = df->d_name;
421 if (fname && *fname == '.') /* no hidden files here */
422 continue;
423 #else
424 snprintf(bufn, sizeof(bufn), "%s%s*.*", p, (p[strlen(p) - 1] == '\\') ? "" : "\\");
425 bufn[sizeof(bufn) - 1] = '\0';
426 if ((findrv = _findfirst(bufn, &dbuf)) >= 0) {
427 do {
428 fname = fname_to_utf8(dbuf.name);
429 #endif /* ! _WINDOWS */
430 /* make sure that we have a file */
431 snprintf(buf2, sizeof(buf2), "%s%s%s", p, S_FILESEP, fname);
432 buf2[sizeof(buf2) - 1] = '\0';
433 if (our_stat(buf2, &sbuf) == 0
434 && (sbuf.st_mode & S_IFMT) != S_IFREG)
435 continue;
437 /* make sure it is not already in the list */
438 for (cl = data; cl; cl = cl->next)
439 if (strcmp(cl->name, fname) == 0)
440 break;
441 if (cl != NULL)
442 continue;
444 /* ok, if it is not in the list, and it is a certificate. Add it */
445 switch (ctype) {
446 case Public:
447 case CACert:
448 if ((in = BIO_new_file(buf2, "r")) != 0) {
449 x = PEM_read_bio_X509(in, NULL, NULL, NULL);
450 if (x) { /* for now copy this information */
451 cert = smime_X509_to_cert_info(x, fname);
452 /* we will use the cert->data.md5 variable to find a backup
453 certificate, not the name */
454 cert->next = data;
455 data = cert;
457 BIO_free(in);
459 break;
461 case Private:
462 /* here we must check it is a key of some cert....*/
463 break;
465 default: alpine_panic("Bad ctype (1)");
466 } /* end switch */
467 #ifndef _WINDOWS
469 closedir(dirp);
470 #else /* _WINDOWS */
471 } while (_findnext(findrv, &dbuf) == 0);
472 _findclose(findrv);
473 #endif /* ! _WINDOWS */
475 /* Now that we are here, we have all the information in the backup
476 * directory
479 switch (ctype) {
480 case Public: ps_global->smime->backuppubliccertlist = data; break;
481 case Private: ps_global->smime->backupprivatecertlist = data; break;
482 case CACert: ps_global->smime->backupcacertlist = data; break;
483 default: alpine_panic("Bad ctype (n)");
486 } else if(SMHOLDERTYPE(ctype) == Container){
488 } /* else APPLEKEYCHAIN */
489 return rv;
492 char *
493 smime_get_cn(X509 *x)
495 X509_NAME_ENTRY *e;
496 X509_NAME *subject;
497 char buf[256];
498 char *rv = NULL;
500 subject = X509_get_subject_name(x);
501 if((e = X509_NAME_get_entry(subject, X509_NAME_entry_count(subject)-1)) != NULL){
502 X509_NAME_get_text_by_OBJ(subject, X509_NAME_ENTRY_get_object(e), buf, sizeof(buf));
503 rv = cpystr(buf);
506 return rv;
510 compare_certs_by_name(const void *data1, const void *data2)
512 int rv, i, j;
513 char *s;
515 CertList *cl1 = *(CertList **) data1;
516 CertList *cl2 = *(CertList **) data2;
518 i = j = -1;
519 if((s = strchr(cl1->name, '@')) != NULL){
520 i = s - cl1->name;
521 *s = '\0';
524 if((s = strchr(cl2->name, '@')) != NULL){
525 j = s - cl2->name;
526 *s = '\0';
529 if((rv = strucmp(cl1->name, cl2->name)) == 0)
530 rv = strucmp(cl1->name + i + 1, cl2->name + j + 1);
531 if(i >= 0) cl1->name[i] = '@';
532 if(j >= 0) cl2->name[j] = '@';
533 return rv;
536 void
537 resort_certificates(CertList **data, WhichCerts ctype)
539 int i, j;
540 CertList *cl = *data;
541 CertList **cll;
542 char *s, *t;
544 if(cl == NULL)
545 return;
547 for(i = 0; cl; cl = cl->next, i++)
548 if(SMHOLDERTYPE(ctype) == Directory && ctype != Private){
549 for(t = s = cl->name; (t = strstr(s, ".crt")) != NULL; s = t+1);
550 if (s) *(s-1) = '\0';
552 j = i;
553 cll = fs_get(i*sizeof(CertList *));
554 for(cl = *data, i = 0; cl; cl = cl->next, i++)
555 cll[i] = cl;
556 qsort((void *)cll, j, sizeof(CertList *), compare_certs_by_name);
557 for(i = 0; i < j - 1; i++){
558 cll[i]->next = cll[i+1];
559 if(SMHOLDERTYPE(ctype) == Directory && ctype != Private)
560 cll[i]->name[strlen(cll[i]->name)]= '.'; /* restore ".crt" part */
562 if(SMHOLDERTYPE(ctype) == Directory && ctype != Private)
563 cll[j-1]->name[strlen(cll[j-1]->name)]= '.'; /* restore ".crt" part */
564 cll[j-1]->next = NULL;
565 *data = cll[0];
569 void
570 get_fingerprint(X509 *cert, const EVP_MD *type, char *buf, size_t maxLen, char *s)
572 unsigned char md[128];
573 char *b;
574 unsigned int len, i;
576 len = sizeof(md);
578 X509_digest(cert, type, md, &len);
580 b = buf;
581 *b = 0;
582 for(i=0; i<len; i++){
583 if(b-buf+3>=maxLen)
584 break;
586 if(i != 0 && s && *s)
587 *b++ = *s;
589 snprintf(b, maxLen - (b-buf), "%02x", md[i]);
590 b+=2;
596 * Remove leading whitespace, trailing whitespace and convert
597 * to lowercase. Also remove slash characters
599 * Args: s, -- The string to clean
601 * Result: the cleaned string
603 static char *
604 emailstrclean(char *string)
606 char *s = string, *sc = NULL, *p = NULL;
608 for(; *s; s++){ /* single pass */
609 if(!isspace((unsigned char) (*s))){
610 p = NULL; /* not start of blanks */
611 if(!sc) /* first non-blank? */
612 sc = string; /* start copying */
614 else if(!p) /* it's OK if sc == NULL */
615 p = sc; /* start of blanks? */
617 if(sc && *s!='/' && *s!='\\') /* if copying, copy */
618 *sc++ = isupper((unsigned char) (*s))
619 ? (unsigned char) tolower((unsigned char) (*s))
620 : (unsigned char) (*s);
623 if(p) /* if ending blanks */
624 *p = '\0'; /* tie off beginning */
625 else if(!sc) /* never saw a non-blank */
626 *string = '\0'; /* so tie whole thing off */
628 return(string);
632 char *
633 smime_get_date(const ASN1_TIME *tm)
635 BIO *mb = BIO_new(BIO_s_mem());
636 char iobuf[4096];
637 char date[MAILTMPLEN];
638 char buf[MAILTMPLEN];
639 char *m, *d, *t, *y, *z;
640 struct date smd;
641 struct tm smtm;
643 (void) BIO_reset(mb);
644 if(ASN1_TIME_print(mb, tm) == 0)
645 return cpystr(_("Invalid"));
647 (void) BIO_flush(mb);
648 BIO_read(mb, iobuf, sizeof(iobuf));
650 /* openssl returns the date in the format:
651 * "MONTH (as name) DAY (as number) TIME(hh:mm:ss) YEAR GMT"
653 m = iobuf;
654 d = strchr(iobuf, ' ');
655 *d++ = '\0';
656 while(*d == ' ') d++;
657 t = strchr(d+1, ' ');
658 *t++ = '\0';
659 while(*t == ' ') t++;
660 y = strchr(t+1, ' ');
661 *y++ = '\0';
662 while(*y == ' ') y++;
663 z = strchr(y+1, ' ');
664 *z++ = '\0';
665 while(*z == ' ') z++;
667 snprintf(date, sizeof(date), "%s %s %s %s (%s)", d, m, y, t, z);
668 date[sizeof(date)-1] = '\0';
669 if(F_ON(F_DATES_TO_LOCAL,ps_global)){
670 parse_date(convert_date_to_local(date), &smd);
671 memset(&smtm, 0, sizeof(smtm));
672 smtm.tm_year = smd.year - 1900;
673 smtm.tm_mon = MIN(MAX(smd.month-1, 0), 11);
674 smtm.tm_mday = MIN(MAX(smd.day, 1), 31);
675 our_strftime(buf, sizeof(buf), "%x", &smtm);
677 else
678 snprintf(buf, sizeof(buf), "%s/%s/%s", m, d, y + strlen(y) - 2);
679 buf[sizeof(buf)-1] = '\0';
681 return cpystr(buf);
685 * Add a lookup for each "*.crt*" file in the given directory.
688 add_certs_in_dir(X509_LOOKUP *lookup, char *path, char *ext, CertList **cdata)
690 char buf[MAXPATH], *fname;
691 #ifndef _WINDOWS
692 struct direct *d;
693 DIR *dirp;
694 #else /* _WINDOWS */
695 struct _finddata_t dbuf;
696 char bufn[_MAX_PATH + 4];
697 long findrv;
698 #endif /* !_WINDOWS */
699 CertList *cert, *cl;
700 int ret = 0, nfiles = 0, nerr = 0;
702 #ifndef _WINDOWS
703 if((dirp = opendir(path)) != NULL){
704 while(!ret && (d=readdir(dirp)) != NULL){
705 fname = d->d_name;
706 #else /* _WINDOWS */
707 snprintf(bufn, sizeof(bufn), "%s%s*.*", path, (path[strlen(path)-1] == '\\') ? "" : "\\");
708 bufn[sizeof(bufn)-1] = '\0';
709 if((findrv = _findfirst(bufn, &dbuf)) >= 0){
711 fname = fname_to_utf8(dbuf.name);
712 #endif /* ! _WINDOWS */
713 if(srchrstr(fname, ext)){
714 nfiles++;
715 build_path(buf, path, fname, sizeof(buf));
717 if(!X509_LOOKUP_load_file(lookup, buf, X509_FILETYPE_PEM)){
718 q_status_message1(SM_ORDER, 3, 3, _("Error loading file %s"), buf);
719 nerr++;
720 } else {
721 if(cdata){
722 BIO *in;
723 X509 *x;
725 cert = fs_get(sizeof(CertList));
726 memset((void *)cert, 0, sizeof(CertList));
727 cert->name = cpystr(fname);
728 /* read buf into a bio and fill the CertData structure */
729 if((in = BIO_new_file(buf, "r"))!=0){
730 if((x = PEM_read_bio_X509(in, NULL, NULL, NULL)) != NULL){
731 cert->data.date_from = smime_get_date(X509_get0_notBefore(x));
732 cert->data.date_to = smime_get_date(X509_get0_notAfter(x));
733 get_fingerprint(x, EVP_md5(), buf, sizeof(buf), NULL);
734 cert->data.md5 = cpystr(buf);
735 cert->cn = smime_get_cn(x);
736 X509_free(x);
738 BIO_free(in);
740 if(*cdata == NULL)
741 *cdata = cert;
742 else{
743 for (cl = *cdata; cl && cl->next; cl = cl->next);
744 cl->next = cert;
751 #ifndef _WINDOWS
753 closedir(dirp);
754 #else /* _WINDOWS */
755 } while(_findnext(findrv, &dbuf) == 0);
756 _findclose(findrv);
757 #endif /* ! _WINDOWS */
760 /* if all certificates fail to load */
761 if(nerr > 0 && nerr == nfiles) ret = -1;
762 return ret;
767 * Get an X509_STORE. This consists of the system
768 * certs directory and any certificates in the user's
769 * ~/.alpine-smime/ca directory.
771 X509_STORE *
772 get_ca_store(void)
774 X509_LOOKUP *lookup;
775 X509_STORE *store = NULL;
777 dprint((9, "get_ca_store()"));
779 if(!(store=X509_STORE_new())){
780 dprint((9, "X509_STORE_new() failed"));
781 return store;
784 if(!(lookup=X509_STORE_add_lookup(store, X509_LOOKUP_file()))){
785 dprint((9, "X509_STORE_add_lookup() failed"));
786 X509_STORE_free(store);
787 return NULL;
790 if(ps_global->smime && ps_global->smime->catype == Container
791 && ps_global->smime->cacontent){
793 if(!mem_add_extra_cacerts(ps_global->smime->cacontent, lookup)){
794 X509_STORE_free(store);
795 return NULL;
798 else if(ps_global->smime && ps_global->smime->catype == Directory
799 && ps_global->smime->capath){
800 if(add_certs_in_dir(lookup, ps_global->smime->capath, ".crt", &ps_global->smime->cacertlist) < 0){
801 X509_STORE_free(store);
802 return NULL;
804 resort_certificates(&ps_global->smime->cacertlist, CACert);
807 if(!(lookup=X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()))){
808 X509_STORE_free(store);
809 return NULL;
812 #ifdef SMIME_SSLCERTS
813 dprint((9, "get_ca_store(): adding cacerts from %s", SMIME_SSLCERTS));
814 X509_LOOKUP_add_dir(lookup, SMIME_SSLCERTS, X509_FILETYPE_PEM);
815 #endif
817 return store;
821 EVP_PKEY *
822 load_key(PERSONAL_CERT *pc, char *pass, int flag)
824 BIO *in;
825 EVP_PKEY *key = NULL;
826 char buf[MAXPATH], file[MAXPATH];
828 if(!(ps_global->smime && pc && pc->name))
829 return key;
831 if(ps_global->smime->privatetype == Container){
832 char *q;
834 if(pc->keytext && (q = strstr(pc->keytext, "-----END")) != NULL){
835 while(*q && *q != '\n')
836 q++;
838 if(*q == '\n')
839 q++;
841 if((in = BIO_new_mem_buf(pc->keytext, q-pc->keytext)) != NULL){
842 key = PEM_read_bio_PrivateKey(in, NULL, NULL, pass);
843 BIO_free(in);
847 else if(ps_global->smime->privatetype == Directory){
848 /* filename is path/name.key */
849 strncpy(buf, pc->name, sizeof(buf)-5);
850 buf[sizeof(buf)-5] = '\0';
851 strncat(buf, ".key", 5);
852 build_path(file, ps_global->smime->privatepath, buf, sizeof(file));
854 if(!(in = BIO_new_file(file, "r")))
855 return NULL;
857 key = PEM_read_bio_PrivateKey(in, NULL, NULL, pass);
858 BIO_free(in);
861 return key;
865 #include <openssl/x509v3.h>
867 * This newer version is from Adrian Vogel. It looks for the email
868 * address not only in the email address field, but also in an
869 * X509v3 extension field, Subject Altenative Name.
871 char **
872 get_x509_subject_email(X509 *x)
874 char **result = NULL;
875 int i, n;
876 STACK_OF(OPENSSL_STRING) *emails = X509_get1_email(x);
877 if ((n = sk_OPENSSL_STRING_num(emails)) > 0) {
878 result = fs_get((n+1)*sizeof(char *));
879 for(i = 0; i < n; i++)
880 result[i] = cpystr(sk_OPENSSL_STRING_value(emails, i));
881 result[i] = NULL;
883 X509_email_free(emails);
884 return result;
889 * Save the certificate for the given email address in
890 * ~/.alpine-smime/public.
892 * Should consider the security hazards in making a file with
893 * the email address that has come from the certificate.
895 * The argument email is destroyed.
897 * args: ctype says where the user wants to save the certificate
899 void
900 save_cert_for(char *email, X509 *cert, WhichCerts ctype)
902 if(!ps_global->smime || ctype == Private)
903 return;
905 dprint((9, "save_cert_for(%s, %s)", email ? email : "?", ctype == Public ? _("Public") : ctype == Private ? _("Private") : "CACert"));
906 emailstrclean(email);
908 if(ps_global->smime->publictype == Keychain){
909 #ifdef APPLEKEYCHAIN
911 OSStatus rc;
912 SecCertificateRef secCertificateRef;
913 CSSM_DATA certData;
915 memset((void *) &certData, 0, sizeof(certData));
916 memset((void *) &secCertificateRef, 0, sizeof(secCertificateRef));
918 /* convert OpenSSL X509 cert data to MacOS certData */
919 if((certData.Length = i2d_X509(cert, &(certData.Data))) > 0){
922 * Put that certData into a SecCertificateRef.
923 * Version 3 should work for versions 1-3.
925 if(!(rc=SecCertificateCreateFromData(&certData,
926 CSSM_CERT_X_509v3,
927 CSSM_CERT_ENCODING_DER,
928 &secCertificateRef))){
930 /* add it to the default keychain */
931 if(!(rc=SecCertificateAddToKeychain(secCertificateRef, NULL))){
932 /* ok */
934 else if(rc == errSecDuplicateItem){
935 dprint((9, "save_cert_for: certificate for %s already in keychain", email));
937 else{
938 dprint((9, "SecCertificateAddToKeychain failed"));
941 else{
942 dprint((9, "SecCertificateCreateFromData failed"));
945 else{
946 dprint((9, "i2d_X509 failed"));
949 #endif /* APPLEKEYCHAIN */
951 else if(SMHOLDERTYPE(ctype) == Container){
952 REMDATA_S *rd = NULL;
953 char *ret_dir = NULL;
954 char path[MAXPATH];
955 char fpath[MAXPATH];
956 char *upath = PATHCERTDIR(ctype);
957 char *tempfile = NULL;
958 int err = 0;
959 CertList *clist = DATACERT(ctype);
961 add_to_end_of_certlist(&clist, email, X509_dup(cert));
963 switch(ctype){
964 case Private: ps_global->smime->privatecertlist = clist; break;
965 case Public : ps_global->smime->publiccertlist = clist; break;
966 case CACert : ps_global->smime->cacertlist = clist; break;
967 default: break;
970 if(!upath)
971 return;
973 if(IS_REMOTE(upath)){
974 rd = rd_create_remote(RemImap, upath, REMOTE_SMIME_SUBTYPE,
975 NULL, "Error: ",
976 _("Can't access remote smime configuration."));
977 if(!rd){
978 return;
981 (void) rd_read_metadata(rd);
983 if(rd->access == MaybeRorW){
984 if(rd->read_status == 'R')
985 rd->access = ReadOnly;
986 else
987 rd->access = ReadWrite;
990 if(rd->access != NoExists){
992 rd_check_remvalid(rd, 1L);
995 * If the cached info says it is readonly but
996 * it looks like it's been fixed now, change it to readwrite.
998 if(rd->read_status == 'R'){
999 rd_check_readonly_access(rd);
1000 if(rd->read_status == 'W'){
1001 rd->access = ReadWrite;
1002 rd->flags |= REM_OUTOFDATE;
1004 else
1005 rd->access = ReadOnly;
1009 if(rd->flags & REM_OUTOFDATE){
1010 if(rd_update_local(rd) != 0){
1012 dprint((1, "save_cert_for: rd_update_local failed\n"));
1013 rd_close_remdata(&rd);
1014 return;
1017 else
1018 rd_open_remote(rd);
1020 if(rd->access != ReadWrite || rd_remote_is_readonly(rd)){
1021 rd_close_remdata(&rd);
1022 return;
1025 rd->flags |= DO_REMTRIM;
1027 strncpy(path, rd->lf, sizeof(path)-1);
1028 path[sizeof(path)-1] = '\0';
1030 else{
1031 strncpy(path, upath, sizeof(path)-1);
1032 path[sizeof(path)-1] = '\0';
1035 tempfile = tempfile_in_same_dir(path, "az", &ret_dir);
1036 if(tempfile){
1037 if(certlist_to_file(tempfile, DATACERT(ctype)))
1038 err++;
1040 if(!err && ret_dir){
1041 if(IS_REMOTE(upath)){
1042 strncpy(fpath, rd->lf, sizeof(fpath));
1043 fpath[sizeof(fpath)-1] = '\0';
1045 else{
1046 if(strlen(path) + strlen(tempfile) - strlen(ret_dir) + 1 < sizeof(path))
1047 snprintf(fpath, sizeof(fpath), "%s%c%s",
1048 path, tempfile[strlen(ret_dir)], tempfile + strlen(ret_dir) + 1);
1049 else
1050 err++;
1053 else err++;
1055 fs_give((void **)&ret_dir);
1057 if(!err){
1058 if(rename_file(tempfile, fpath) < 0){
1059 q_status_message2(SM_ORDER, 3, 3,
1060 _("Can't rename %s to %s"), tempfile, fpath);
1061 err++;
1065 if(!err && IS_REMOTE(upath)){
1066 int e, we_cancel;
1067 char datebuf[200];
1069 datebuf[0] = '\0';
1071 we_cancel = busy_cue(_("Copying to remote smime container"), NULL, 1);
1072 if((e = rd_update_remote(rd, datebuf)) != 0){
1073 if(e == -1){
1074 q_status_message2(SM_ORDER | SM_DING, 3, 5,
1075 _("Error opening temporary smime file %s: %s"),
1076 rd->lf, error_description(errno));
1077 dprint((1,
1078 "write_remote_smime: error opening temp file %s\n",
1079 rd->lf ? rd->lf : "?"));
1081 else{
1082 q_status_message2(SM_ORDER | SM_DING, 3, 5,
1083 _("Error copying to %s: %s"),
1084 rd->rn, error_description(errno));
1085 dprint((1,
1086 "write_remote_smime: error copying from %s to %s\n",
1087 rd->lf ? rd->lf : "?", rd->rn ? rd->rn : "?"));
1090 q_status_message(SM_ORDER | SM_DING, 5, 5,
1091 _("Copy of smime cert to remote folder failed, changes NOT saved remotely"));
1093 else{
1094 rd_update_metadata(rd, datebuf);
1095 rd->read_status = 'W';
1098 rd_close_remdata(&rd);
1100 if(we_cancel)
1101 cancel_busy_cue(-1);
1104 fs_give((void **) &tempfile);
1107 else if(SMHOLDERTYPE(ctype) == Directory){
1108 char *path = PATHCERTDIR(ctype);
1109 char certfilename[MAXPATH];
1110 BIO *bio_out;
1112 build_path(certfilename, path, email, sizeof(certfilename));
1113 strncat(certfilename, ".crt", sizeof(certfilename)-1-strlen(certfilename));
1114 certfilename[sizeof(certfilename)-1] = 0;
1116 bio_out = BIO_new_file(certfilename, "w");
1117 if(bio_out){
1118 PEM_write_bio_X509(bio_out, cert);
1119 BIO_free(bio_out);
1120 q_status_message1(SM_ORDER, 1, 1, _("Saved certificate for <%s>"), email);
1122 else{
1123 q_status_message1(SM_ORDER, 1, 1, _("Couldn't save certificate for <%s>"), email);
1130 * Try to retrieve the certificate for the given email address.
1131 * The caller should free the cert.
1133 X509 *
1134 get_cert_for(char *email, WhichCerts ctype, int tolower)
1136 char certfilename[MAXPATH];
1137 char emailaddr[MAXPATH];
1138 X509 *cert = NULL;
1139 BIO *in;
1141 if(ctype == Password){
1142 build_path(certfilename, PATHCERTDIR(ctype), email, sizeof(certfilename));
1143 strncat(certfilename, EXTCERT(Public), sizeof(certfilename)-1-strlen(certfilename));
1144 certfilename[sizeof(certfilename)-1] = 0;
1146 if((in = BIO_new_file(certfilename, "r"))!=0){
1148 cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
1150 if(cert){
1151 /* could check email addr in cert matches */
1154 BIO_free(in);
1157 return cert;
1160 if(!ps_global->smime)
1161 return cert;
1163 dprint((9, "get_cert_for(%s, %s)", email ? email : "?", "none yet"));
1165 if(ctype == Private) /* there is no private certificate info */
1166 ctype = Public; /* return public information instead */
1167 strncpy(emailaddr, email, sizeof(emailaddr)-1);
1168 emailaddr[sizeof(emailaddr)-1] = 0;
1170 /* clean it up (lowercase, space removal) */
1171 if(tolower)
1172 emailstrclean(emailaddr);
1174 if(ps_global->smime->publictype == Keychain){
1175 #ifdef APPLEKEYCHAIN
1177 OSStatus rc;
1178 SecKeychainItemRef itemRef = nil;
1179 SecKeychainAttributeList attrList;
1180 SecKeychainAttribute attrib;
1181 SecKeychainSearchRef searchRef = nil;
1182 CSSM_DATA certData;
1184 /* low-level form of MacOS data */
1185 memset((void *) &certData, 0, sizeof(certData));
1187 attrList.count = 1;
1188 attrList.attr = &attrib;
1190 /* kSecAlias means email address for a certificate */
1191 attrib.tag = kSecAlias;
1192 attrib.data = emailaddr;
1193 attrib.length = strlen(attrib.data);
1195 /* Find the certificate in the default keychain */
1196 if(!(rc=SecKeychainSearchCreateFromAttributes(NULL,
1197 kSecCertificateItemClass,
1198 &attrList,
1199 &searchRef))){
1201 if(!(rc=SecKeychainSearchCopyNext(searchRef, &itemRef))){
1203 /* extract the data portion of the certificate */
1204 if(!(rc=SecCertificateGetData((SecCertificateRef) itemRef, &certData))){
1207 * Convert it from MacOS form to OpenSSL form.
1208 * The input is certData from above and the output
1209 * is the X509 *cert.
1211 if(!d2i_X509(&cert, &(certData.Data), certData.Length)){
1212 dprint((9, "d2i_X509 failed"));
1215 else{
1216 dprint((9, "SecCertificateGetData failed"));
1219 else if(rc == errSecItemNotFound){
1220 dprint((9, "get_cert_for: Public cert for %s not found", emailaddr));
1222 else{
1223 dprint((9, "SecKeychainSearchCopyNext failed"));
1226 else{
1227 dprint((9, "SecKeychainSearchCreateFromAttributes failed"));
1230 if(searchRef)
1231 CFRelease(searchRef);
1233 #endif /* APPLEKEYCHAIN */
1235 else if(SMHOLDERTYPE(ctype) == Container){
1236 CertList *cl;
1238 for(cl = DATACERT(ctype); cl; cl = cl->next){
1239 if(cl->name && !strucmp(emailaddr, cl->name))
1240 break;
1243 if(cl)
1244 cert = X509_dup((X509 *) cl->x509_cert);
1246 else if(SMHOLDERTYPE(ctype) == Directory){
1247 build_path(certfilename, PATHCERTDIR(ctype), emailaddr, sizeof(certfilename));
1248 strncat(certfilename, EXTCERT(ctype), sizeof(certfilename)-1-strlen(certfilename));
1249 certfilename[sizeof(certfilename)-1] = 0;
1251 if((in = BIO_new_file(certfilename, "r"))!=0){
1253 cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
1255 if(cert){
1256 /* could check email addr in cert matches */
1259 BIO_free(in);
1264 return cert;
1268 * load_cert_for_key finds a certificate in pathdir that matches a private key
1269 * pkey. It returns its name in certfile, and the certificate in *pcert.
1270 * return value: success: different from zero, failure 0. If both certfile
1271 * and pcert are NULL, this function returns if there is certificate that
1272 * matches the given key.
1275 load_cert_for_key(char *pathdir, EVP_PKEY *pkey, char **certfile, X509 **pcert)
1277 #ifndef _WINDOWS
1278 DIR *dirp;
1279 struct dirent *d;
1280 #else /* _WINDOWS */
1281 struct _finddata_t dbuf;
1282 char bufn[_MAX_PATH + 4];
1283 long findrv;
1284 #endif /* ! _WINDOWS */
1285 size_t ll;
1286 int rv = 0;
1287 BIO *in;
1288 X509 *x;
1289 char buf[MAXPATH+1], pathcert[MAXPATH+1], *fname;
1291 if(pathdir == NULL || pkey == NULL)
1292 return 0;
1294 if(certfile) *certfile = NULL;
1295 if(pcert) *pcert = NULL;
1297 #ifndef _WINDOWS
1298 if((dirp = opendir(pathdir)) != NULL){
1299 while(rv == 0 && (d=readdir(dirp)) != NULL){
1300 fname = d->d_name;
1301 #else
1302 snprintf(bufn, sizeof(bufn), "%s%s*.*", pathdir, (pathdir[strlen(pathdir)-1] == '\\') ? "" : "\\");
1303 bufn[sizeof(bufn)-1] = '\0';
1304 if((findrv = _findfirst(bufn, &dbuf)) >= 0){
1306 fname = fname_to_utf8(dbuf.name);
1307 #endif /* ! _WINDOWS */
1308 if((ll=strlen(fname)) && ll > 4){
1309 if(!strcmp(fname+ll-4, ".crt")){
1310 strncpy(buf, fname, sizeof(buf));
1311 buf[sizeof(buf)-1] = '\0';
1312 build_path(pathcert, pathdir, buf, sizeof(pathcert));
1313 if((in = BIO_new_file(pathcert, "r")) != NULL){
1314 if((x = PEM_read_bio_X509(in, NULL, NULL, NULL)) != NULL){
1315 if(X509_check_private_key(x, pkey) > 0){
1316 rv = 1;
1317 if(certfile) *certfile = cpystr(buf);
1318 if(pcert) *pcert = x;
1320 else
1321 X509_free(x);
1323 BIO_free(in);
1327 #ifndef _WINDOWS
1329 closedir(dirp);
1330 #else /* _WINDOWS */
1331 } while(_findnext(findrv, &dbuf) == 0);
1332 _findclose(findrv);
1333 #endif
1335 return rv;
1339 PERSONAL_CERT *
1340 mem_to_personal_certs(char *contents)
1342 PERSONAL_CERT *result = NULL;
1343 char *p, *q, *line, *name, *keytext, *save_p;
1344 X509 *cert = NULL;
1346 if(contents && *contents){
1347 for(p = contents; *p != '\0';){
1348 line = p;
1350 while(*p && *p != '\n')
1351 p++;
1353 save_p = NULL;
1354 if(*p == '\n'){
1355 save_p = p;
1356 *p++ = '\0';
1359 if(strncmp(EMAILADDRLEADER, line, strlen(EMAILADDRLEADER)) == 0){
1360 name = line + strlen(EMAILADDRLEADER);
1361 cert = get_cert_for(name, Public, 1);
1362 keytext = p;
1364 /* advance p past this record */
1365 if((q = strstr(keytext, "-----END")) != NULL){
1366 while(*q && *q != '\n')
1367 q++;
1369 if(*q == '\n')
1370 q++;
1372 p = q;
1374 else{
1375 p = p + strlen(p);
1376 q_status_message(SM_ORDER | SM_DING, 3, 3, _("Error in privatekey container, missing END"));
1379 if(cert){
1380 PERSONAL_CERT *pc;
1382 pc = (PERSONAL_CERT *) fs_get(sizeof(*pc));
1383 pc->cert = cert;
1384 pc->name = cpystr(name);
1385 pc->cname = NULL;
1386 pc->keytext = keytext; /* a pointer into contents */
1388 pc->key = load_key(pc, "", SM_NORMALCERT);
1390 pc->next = result;
1391 result = pc;
1395 if(save_p)
1396 *save_p = '\n';
1400 return result;
1404 CertList *
1405 mem_to_certlist(char *contents, WhichCerts ctype)
1407 CertList *ret = NULL;
1408 char *p, *q, *line, *name, *certtext, *save_p;
1409 X509 *cert = NULL;
1410 BIO *in;
1411 char *sep = (ctype == Public || ctype == Private)
1412 ? EMAILADDRLEADER : CACERTSTORELEADER;
1414 if(contents && *contents){
1415 for(p = contents; *p != '\0';){
1416 line = p;
1418 while(*p && *p != '\n')
1419 p++;
1421 save_p = NULL;
1422 if(*p == '\n'){
1423 save_p = p;
1424 *p++ = '\0';
1427 if(strncmp(sep, line, strlen(sep)) == 0){
1428 name = line + strlen(sep);
1429 cert = NULL;
1430 certtext = strstr(p, "-----BEGIN");
1431 if(certtext != NULL){
1432 if((q = strstr(certtext, sep)) != NULL)
1433 p = q;
1434 else
1435 p = q = certtext+strlen(certtext);
1437 if((in = BIO_new_mem_buf(certtext, q-certtext)) != 0){
1438 cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
1439 BIO_free(in);
1442 else{
1443 q_status_message2(SM_ORDER | SM_DING, 3, 3, _("Error in %scert container, missing BEGIN, certtext=%s"), ctype == Public ? _("public") : _("ca"), p);
1444 p = p + strlen(p);
1447 if(name && cert)
1448 add_to_end_of_certlist(&ret, name, cert);
1451 if(save_p)
1452 *save_p = '\n';
1455 if(ret != NULL)
1456 resort_certificates(&ret, ctype);
1458 return ret;
1463 * Add the CACert Container contents into the CACert store.
1465 * Returns > 0 for success, 0 for failure
1468 mem_add_extra_cacerts(char *contents, X509_LOOKUP *lookup)
1470 char *p, *q, *line, *certtext, *save_p;
1471 BIO *in, *out;
1472 int len, failed = 0;
1473 char *tempfile;
1474 char iobuf[4096];
1477 * The most straight-forward way to do this is to write
1478 * the container contents to a temp file and then load the
1479 * contents of the file with X509_LOOKUP_load_file(), like
1480 * is done in add_certs_in_dir(). What we don't know is if
1481 * each file should consist of one cacert or if they can all
1482 * just be jammed together into one file. To be safe, we'll use
1483 * one file per and do each in a separate operation.
1486 if(contents && *contents){
1487 for(p = contents; *p != '\0';){
1488 line = p;
1490 while(*p && *p != '\n')
1491 p++;
1493 save_p = NULL;
1494 if(*p == '\n'){
1495 save_p = p;
1496 *p++ = '\0';
1499 /* look for separator line */
1500 if(strncmp(CACERTSTORELEADER, line, strlen(CACERTSTORELEADER)) == 0){
1501 /* certtext is the content that should go in a file */
1502 certtext = strstr(p, "-----BEGIN");
1503 if(certtext != NULL){
1504 if((q = strstr(certtext, CACERTSTORELEADER)) != NULL){
1505 p = q;
1507 else{ /* end of file */
1508 q = certtext + strlen(certtext);
1509 p = q;
1512 in = BIO_new_mem_buf(certtext, q-certtext);
1513 if(in){
1514 tempfile = temp_nam(NULL, "az");
1515 out = tempfile != NULL ? BIO_new_file(tempfile, "w") : NULL;
1516 if(out != NULL){
1517 while((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
1518 BIO_write(out, iobuf, len);
1520 BIO_free(out);
1521 if(!X509_LOOKUP_load_file(lookup, tempfile, X509_FILETYPE_PEM))
1522 failed++;
1525 if(tempfile != NULL){
1526 unlink(tempfile);
1527 fs_give((void **) &tempfile);
1530 BIO_free(in);
1533 else{
1534 p = p + strlen(p);
1535 q_status_message1(SM_ORDER | SM_DING, 3, 3, _("Error in cacert container, missing BEGIN, certtext=%s"), certtext);
1538 else{
1539 p = p + strlen(p);
1540 q_status_message1(SM_ORDER | SM_DING, 3, 3, _("Error in cacert container, missing separator, line=%s"), line);
1543 if(save_p)
1544 *save_p = '\n';
1548 return(!failed);
1553 certlist_to_file(char *filename, CertList *certlist)
1555 CertList *cl;
1556 BIO *bio_out = NULL;
1557 int ret = -1;
1559 if(filename && (bio_out=BIO_new_file(filename, "w")) != NULL){
1560 ret = 0;
1561 for(cl = certlist; cl; cl = cl->next){
1562 if(cl->name && cl->name[0] && cl->x509_cert){
1563 if(!((BIO_puts(bio_out, EMAILADDRLEADER) > 0)
1564 && (BIO_puts(bio_out, cl->name) > 0)
1565 && (BIO_puts(bio_out, "\n") > 0)))
1566 ret = -1;
1568 if(!PEM_write_bio_X509(bio_out, (X509 *) cl->x509_cert))
1569 ret = -1;
1573 BIO_free(bio_out);
1576 return ret;
1580 void
1581 add_to_end_of_certlist(CertList **cl, char *name, X509 *cert)
1583 CertList *new;
1585 if(!cl)
1586 return;
1588 new = smime_X509_to_cert_info(cert, name);
1589 new->next = *cl;
1590 *cl = new;
1594 void
1595 free_certlist(CertList **cl)
1597 if(cl && *cl){
1598 if((*cl)->data.date_from)
1599 fs_give((void **) &(*cl)->data.date_from);
1601 if((*cl)->data.date_to)
1602 fs_give((void **) &(*cl)->data.date_to);
1604 if((*cl)->data.md5)
1605 fs_give((void **) &(*cl)->data.md5);
1607 if((*cl)->name)
1608 fs_give((void **) &(*cl)->name);
1610 if((*cl)->cn)
1611 fs_give((void **) &(*cl)->cn);
1613 if((*cl)->x509_cert)
1614 X509_free((X509 *) (*cl)->x509_cert);
1616 free_certlist(&(*cl)->next);
1618 fs_give((void **) cl);
1623 void
1624 free_personal_certs(PERSONAL_CERT **pc)
1626 if(pc && *pc){
1627 if((*pc)->name)
1628 fs_give((void **) &(*pc)->name);
1630 if((*pc)->cname)
1631 fs_give((void **) &(*pc)->cname);
1633 if((*pc)->cert)
1634 X509_free((*pc)->cert);
1636 if((*pc)->key)
1637 EVP_PKEY_free((*pc)->key);
1639 free_personal_certs(&(*pc)->next);
1641 fs_give((void **) pc);
1645 #endif /* SMIME */