1 #if !defined(lint) && !defined(DOS)
2 static char rcsid
[] = "$Id: smkeys.c 1266 2009-07-14 18:39:12Z hubert@u.washington.edu $";
6 * ========================================================================
7 * Copyright 2013-2018 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"
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"
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
59 password_policy_check(char *password
)
65 if(password
== NULL
|| password
[0] == '\0'){
66 error
= _("Password cannot be blank");
68 } else if(strlen(password
) < 8){
69 error
= _("Password is too short");
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
);
82 create_master_password(char *pass
, size_t passlen
, int first_time
)
86 char prompt
[MAILTMPLEN
];
87 char passbackup
[MAILTMPLEN
];
90 q_status_message(SM_ORDER
, 3, 3,
91 _(" Creating a Master Password for your Password file "));
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';
102 /* rv == 1 means cancel */
103 rv
= (pith_smime_enter_password
)(prompt
, pass
, passlen
);
104 if(rv
== 1 || password_policy_check(pass
) == 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';
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
))
118 if(trial
+ 1 < MAXTRIAL
)
119 q_status_message(SM_ORDER
, 2, 2, _("Passwords do not match, try again."));
121 q_status_message(SM_ORDER
, 2, 2, _("Passwords do not match, too many failures."));
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);
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
140 ALPINE_self_signed_certificate(char *template, int version
, char *pathdir
, char *fname
)
143 X509_NAME
*name
= NULL
;
144 X509_REQ
*req
= NULL
;
147 char tmp
[MAXPATH
+1], password
[1024];
148 char *keyfile
= NULL
, *certfile
= NULL
;
149 char *extensions
= NULL
;
152 PERSONAL_CERT
*pc
= NULL
;
153 EVP_PKEY
*pkey
= NULL
;
155 CONF
*req_conf
= NULL
;
156 static int first_time
= 1;
162 if((out
= BIO_new_file(template, "r")) == NULL
){
163 q_status_message(SM_ORDER
, 2, 2, _("Problem reading configuration file"));
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
){
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
);
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
)){
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
))){
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
);
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
);
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
));
260 pc
->cname
= certfile
;
267 smime_X509_to_cert_info(X509
*x
, char *name
)
272 if(x
== NULL
) return NULL
;
274 cert
= fs_get(sizeof(CertList
));
275 memset((void *)cert
, 0, sizeof(CertList
));
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
);
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 */
301 char p
[MAXPATH
+1]; /* path to where the backup is */
302 char buf
[MAXPATH
+1], buf2
[MAXPATH
+1];
307 struct dirent
*df
; /* file in the directory */
309 struct _finddata_t dbuf
;
310 char bufn
[_MAX_PATH
+ 4];
312 #endif /* !_WINDOWS */
313 CertList
*cert
, *cl2
;
317 return rv
; /* remove when this function is complete */
319 if(SMHOLDERTYPE(ctype
) == Directory
){
320 d
= PATHCERTDIR(ctype
);
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
);
325 if(our_stat(p
, &sbuf
) < 0){
326 if(our_mkpath(p
, 0700) != 0)
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)
335 else if((sbuf
.st_mode
& S_IFMT
) == S_IFDIR
)
338 strncpy(p
, buf2
, MAXPATH
);
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
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;
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;
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)
368 } else if((sbuf
.st_mode
& S_IFMT
) == S_IFREG
)
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
);
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
);
393 for (cl2
= data
; cl2
&& cl2
->next
; cl2
= cl2
->next
);
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
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
417 if ((dirp
= opendir(p
)) != NULL
) {
418 while ((df
= readdir(dirp
)) != NULL
) {
421 if (fname
&& *fname
== '.') /* no hidden files here */
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) {
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
)
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)
444 /* ok, if it is not in the list, and it is a certificate. Add it */
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 */
462 /* here we must check it is a key of some cert....*/
465 default: alpine_panic("Bad ctype (1)");
471 } while (_findnext(findrv
, &dbuf
) == 0);
473 #endif /* ! _WINDOWS */
475 /* Now that we are here, we have all the information in the backup
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 */
493 smime_get_cn(X509
*x
)
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
));
510 compare_certs_by_name(const void *data1
, const void *data2
)
515 CertList
*cl1
= *(CertList
**) data1
;
516 CertList
*cl2
= *(CertList
**) data2
;
519 if((s
= strchr(cl1
->name
, '@')) != NULL
){
524 if((s
= strchr(cl2
->name
, '@')) != NULL
){
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
] = '@';
537 resort_certificates(CertList
**data
, WhichCerts ctype
)
540 CertList
*cl
= *data
;
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';
553 cll
= fs_get(i
*sizeof(CertList
*));
554 for(cl
= *data
, i
= 0; cl
; cl
= cl
->next
, i
++)
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
;
570 get_fingerprint(X509
*cert
, const EVP_MD
*type
, char *buf
, size_t maxLen
, char *s
)
572 unsigned char md
[128];
578 X509_digest(cert
, type
, md
, &len
);
582 for(i
=0; i
<len
; i
++){
586 if(i
!= 0 && s
&& *s
)
589 snprintf(b
, maxLen
- (b
-buf
), "%02x", md
[i
]);
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
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 */
633 smime_get_date(const ASN1_TIME
*tm
)
635 BIO
*mb
= BIO_new(BIO_s_mem());
637 char date
[MAILTMPLEN
];
638 char buf
[MAILTMPLEN
];
639 char *m
, *d
, *t
, *y
, *z
;
644 (void) BIO_reset(mb
);
645 if(ASN1_TIME_print(mb
, tm
) == 0)
646 return cpystr(_("Invalid"));
648 (void) BIO_flush(mb
);
649 len
= BIO_read(mb
, iobuf
, sizeof(iobuf
));
652 /* openssl returns the date in the format:
653 * "MONTH (as name) DAY (as number) TIME(hh:mm:ss) YEAR GMT"
656 d
= strchr(iobuf
, ' ');
658 while(*d
== ' ') d
++;
659 t
= strchr(d
+1, ' ');
661 while(*t
== ' ') t
++;
662 y
= strchr(t
+1, ' ');
664 while(*y
== ' ') y
++;
665 z
= strchr(y
+1, ' ');
667 while(*z
== ' ') z
++;
669 snprintf(date
, sizeof(date
), "%s %s %s %s (%s)", d
, m
, y
, t
, z
);
670 date
[sizeof(date
)-1] = '\0';
671 if(F_ON(F_DATES_TO_LOCAL
,ps_global
)){
672 parse_date(convert_date_to_local(date
), &smd
);
673 memset(&smtm
, 0, sizeof(smtm
));
674 smtm
.tm_year
= smd
.year
- 1900;
675 smtm
.tm_mon
= MIN(MAX(smd
.month
-1, 0), 11);
676 smtm
.tm_mday
= MIN(MAX(smd
.day
, 1), 31);
677 our_strftime(buf
, sizeof(buf
), "%x", &smtm
);
680 snprintf(buf
, sizeof(buf
), "%s/%s/%s", m
, d
, y
+ strlen(y
) - 2);
681 buf
[sizeof(buf
)-1] = '\0';
688 * Add a lookup for each "*.crt*" file in the given directory.
691 add_certs_in_dir(X509_LOOKUP
*lookup
, char *path
, char *ext
, CertList
**cdata
)
693 char buf
[MAXPATH
], *fname
;
698 struct _finddata_t dbuf
;
699 char bufn
[_MAX_PATH
+ 4];
701 #endif /* !_WINDOWS */
703 int ret
= 0, nfiles
= 0, nerr
= 0;
706 if((dirp
= opendir(path
)) != NULL
){
707 while(!ret
&& (d
=readdir(dirp
)) != NULL
){
710 snprintf(bufn
, sizeof(bufn
), "%s%s*.*", path
, (path
[strlen(path
)-1] == '\\') ? "" : "\\");
711 bufn
[sizeof(bufn
)-1] = '\0';
712 if((findrv
= _findfirst(bufn
, &dbuf
)) >= 0){
714 fname
= fname_to_utf8(dbuf
.name
);
715 #endif /* ! _WINDOWS */
716 if(srchrstr(fname
, ext
)){
718 build_path(buf
, path
, fname
, sizeof(buf
));
720 if(!X509_LOOKUP_load_file(lookup
, buf
, X509_FILETYPE_PEM
)){
721 q_status_message1(SM_ORDER
, 3, 3, _("Error loading file %s"), buf
);
728 cert
= fs_get(sizeof(CertList
));
729 memset((void *)cert
, 0, sizeof(CertList
));
730 cert
->name
= cpystr(fname
);
731 /* read buf into a bio and fill the CertData structure */
732 if((in
= BIO_new_file(buf
, "r"))!=0){
733 if((x
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
)) != NULL
){
734 cert
->data
.date_from
= smime_get_date(X509_get0_notBefore(x
));
735 cert
->data
.date_to
= smime_get_date(X509_get0_notAfter(x
));
736 get_fingerprint(x
, EVP_md5(), buf
, sizeof(buf
), NULL
);
737 cert
->data
.md5
= cpystr(buf
);
738 cert
->cn
= smime_get_cn(x
);
746 for (cl
= *cdata
; cl
&& cl
->next
; cl
= cl
->next
);
758 } while(_findnext(findrv
, &dbuf
) == 0);
760 #endif /* ! _WINDOWS */
763 /* if all certificates fail to load */
764 if(nerr
> 0 && nerr
== nfiles
) ret
= -1;
770 * Get an X509_STORE. This consists of the system
771 * certs directory and any certificates in the user's
772 * ~/.alpine-smime/ca directory.
778 X509_STORE
*store
= NULL
;
780 dprint((9, "get_ca_store()"));
782 if(!(store
=X509_STORE_new())){
783 dprint((9, "X509_STORE_new() failed"));
787 if(!(lookup
=X509_STORE_add_lookup(store
, X509_LOOKUP_file()))){
788 dprint((9, "X509_STORE_add_lookup() failed"));
789 X509_STORE_free(store
);
793 if(ps_global
->smime
&& ps_global
->smime
->catype
== Container
794 && ps_global
->smime
->cacontent
){
796 if(!mem_add_extra_cacerts(ps_global
->smime
->cacontent
, lookup
)){
797 X509_STORE_free(store
);
801 else if(ps_global
->smime
&& ps_global
->smime
->catype
== Directory
802 && ps_global
->smime
->capath
){
803 if(add_certs_in_dir(lookup
, ps_global
->smime
->capath
, ".crt", &ps_global
->smime
->cacertlist
) < 0){
804 X509_STORE_free(store
);
807 resort_certificates(&ps_global
->smime
->cacertlist
, CACert
);
810 if(!(lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir()))){
811 X509_STORE_free(store
);
815 #ifdef SMIME_SSLCERTS
816 dprint((9, "get_ca_store(): adding cacerts from %s", SMIME_SSLCERTS
));
817 X509_LOOKUP_add_dir(lookup
, SMIME_SSLCERTS
, X509_FILETYPE_PEM
);
825 load_key(PERSONAL_CERT
*pc
, char *pass
, int flag
)
828 EVP_PKEY
*key
= NULL
;
829 char buf
[MAXPATH
], file
[MAXPATH
];
831 if(!(ps_global
->smime
&& pc
&& pc
->name
))
834 if(ps_global
->smime
->privatetype
== Container
){
837 if(pc
->keytext
&& (q
= strstr(pc
->keytext
, "-----END")) != NULL
){
838 while(*q
&& *q
!= '\n')
844 if((in
= BIO_new_mem_buf(pc
->keytext
, q
-pc
->keytext
)) != NULL
){
845 key
= PEM_read_bio_PrivateKey(in
, NULL
, NULL
, pass
);
850 else if(ps_global
->smime
->privatetype
== Directory
){
851 /* filename is path/name.key */
852 strncpy(buf
, pc
->name
, sizeof(buf
)-5);
853 buf
[sizeof(buf
)-5] = '\0';
854 strncat(buf
, ".key", 5);
855 build_path(file
, ps_global
->smime
->privatepath
, buf
, sizeof(file
));
857 if(!(in
= BIO_new_file(file
, "r")))
860 key
= PEM_read_bio_PrivateKey(in
, NULL
, NULL
, pass
);
868 #include <openssl/x509v3.h>
870 * This newer version is from Adrian Vogel. It looks for the email
871 * address not only in the email address field, but also in an
872 * X509v3 extension field, Subject Altenative Name.
875 get_x509_subject_email(X509
*x
)
877 char **result
= NULL
;
879 STACK_OF(OPENSSL_STRING
) *emails
= X509_get1_email(x
);
880 if ((n
= sk_OPENSSL_STRING_num(emails
)) > 0) {
881 result
= fs_get((n
+1)*sizeof(char *));
882 for(i
= 0; i
< n
; i
++)
883 result
[i
] = cpystr(sk_OPENSSL_STRING_value(emails
, i
));
886 X509_email_free(emails
);
892 * Save the certificate for the given email address in
893 * ~/.alpine-smime/public.
895 * Should consider the security hazards in making a file with
896 * the email address that has come from the certificate.
898 * The argument email is destroyed.
900 * args: ctype says where the user wants to save the certificate
903 save_cert_for(char *email
, X509
*cert
, WhichCerts ctype
)
905 if(!ps_global
->smime
|| ctype
== Private
)
908 dprint((9, "save_cert_for(%s, %s)", email
? email
: "?", ctype
== Public
? _("Public") : ctype
== Private
? _("Private") : "CACert"));
909 emailstrclean(email
);
911 if(ps_global
->smime
->publictype
== Keychain
){
915 SecCertificateRef secCertificateRef
;
918 memset((void *) &certData
, 0, sizeof(certData
));
919 memset((void *) &secCertificateRef
, 0, sizeof(secCertificateRef
));
921 /* convert OpenSSL X509 cert data to MacOS certData */
922 if((certData
.Length
= i2d_X509(cert
, &(certData
.Data
))) > 0){
925 * Put that certData into a SecCertificateRef.
926 * Version 3 should work for versions 1-3.
928 if(!(rc
=SecCertificateCreateFromData(&certData
,
930 CSSM_CERT_ENCODING_DER
,
931 &secCertificateRef
))){
933 /* add it to the default keychain */
934 if(!(rc
=SecCertificateAddToKeychain(secCertificateRef
, NULL
))){
937 else if(rc
== errSecDuplicateItem
){
938 dprint((9, "save_cert_for: certificate for %s already in keychain", email
));
941 dprint((9, "SecCertificateAddToKeychain failed"));
945 dprint((9, "SecCertificateCreateFromData failed"));
949 dprint((9, "i2d_X509 failed"));
952 #endif /* APPLEKEYCHAIN */
954 else if(SMHOLDERTYPE(ctype
) == Container
){
955 REMDATA_S
*rd
= NULL
;
956 char *ret_dir
= NULL
;
959 char *upath
= PATHCERTDIR(ctype
);
960 char *tempfile
= NULL
;
962 CertList
*clist
= DATACERT(ctype
);
964 add_to_end_of_certlist(&clist
, email
, X509_dup(cert
));
967 case Private
: ps_global
->smime
->privatecertlist
= clist
; break;
968 case Public
: ps_global
->smime
->publiccertlist
= clist
; break;
969 case CACert
: ps_global
->smime
->cacertlist
= clist
; break;
976 if(IS_REMOTE(upath
)){
977 rd
= rd_create_remote(RemImap
, upath
, REMOTE_SMIME_SUBTYPE
,
979 _("Can't access remote smime configuration."));
984 (void) rd_read_metadata(rd
);
986 if(rd
->access
== MaybeRorW
){
987 if(rd
->read_status
== 'R')
988 rd
->access
= ReadOnly
;
990 rd
->access
= ReadWrite
;
993 if(rd
->access
!= NoExists
){
995 rd_check_remvalid(rd
, 1L);
998 * If the cached info says it is readonly but
999 * it looks like it's been fixed now, change it to readwrite.
1001 if(rd
->read_status
== 'R'){
1002 rd_check_readonly_access(rd
);
1003 if(rd
->read_status
== 'W'){
1004 rd
->access
= ReadWrite
;
1005 rd
->flags
|= REM_OUTOFDATE
;
1008 rd
->access
= ReadOnly
;
1012 if(rd
->flags
& REM_OUTOFDATE
){
1013 if(rd_update_local(rd
) != 0){
1015 dprint((1, "save_cert_for: rd_update_local failed\n"));
1016 rd_close_remdata(&rd
);
1023 if(rd
->access
!= ReadWrite
|| rd_remote_is_readonly(rd
)){
1024 rd_close_remdata(&rd
);
1028 rd
->flags
|= DO_REMTRIM
;
1030 strncpy(path
, rd
->lf
, sizeof(path
)-1);
1031 path
[sizeof(path
)-1] = '\0';
1034 strncpy(path
, upath
, sizeof(path
)-1);
1035 path
[sizeof(path
)-1] = '\0';
1038 tempfile
= tempfile_in_same_dir(path
, "az", &ret_dir
);
1040 if(certlist_to_file(tempfile
, DATACERT(ctype
)))
1043 if(!err
&& ret_dir
){
1044 if(IS_REMOTE(upath
)){
1045 strncpy(fpath
, rd
->lf
, sizeof(fpath
));
1046 fpath
[sizeof(fpath
)-1] = '\0';
1049 if(strlen(path
) + strlen(tempfile
) - strlen(ret_dir
) + 1 < sizeof(path
))
1050 snprintf(fpath
, sizeof(fpath
), "%s%c%s",
1051 path
, tempfile
[strlen(ret_dir
)], tempfile
+ strlen(ret_dir
) + 1);
1058 fs_give((void **)&ret_dir
);
1061 if(rename_file(tempfile
, fpath
) < 0){
1062 q_status_message2(SM_ORDER
, 3, 3,
1063 _("Can't rename %s to %s"), tempfile
, fpath
);
1068 if(!err
&& IS_REMOTE(upath
)){
1074 we_cancel
= busy_cue(_("Copying to remote smime container"), NULL
, 1);
1075 if((e
= rd_update_remote(rd
, datebuf
)) != 0){
1077 q_status_message2(SM_ORDER
| SM_DING
, 3, 5,
1078 _("Error opening temporary smime file %s: %s"),
1079 rd
->lf
, error_description(errno
));
1081 "write_remote_smime: error opening temp file %s\n",
1082 rd
->lf
? rd
->lf
: "?"));
1085 q_status_message2(SM_ORDER
| SM_DING
, 3, 5,
1086 _("Error copying to %s: %s"),
1087 rd
->rn
, error_description(errno
));
1089 "write_remote_smime: error copying from %s to %s\n",
1090 rd
->lf
? rd
->lf
: "?", rd
->rn
? rd
->rn
: "?"));
1093 q_status_message(SM_ORDER
| SM_DING
, 5, 5,
1094 _("Copy of smime cert to remote folder failed, changes NOT saved remotely"));
1097 rd_update_metadata(rd
, datebuf
);
1098 rd
->read_status
= 'W';
1101 rd_close_remdata(&rd
);
1104 cancel_busy_cue(-1);
1107 fs_give((void **) &tempfile
);
1110 else if(SMHOLDERTYPE(ctype
) == Directory
){
1111 char *path
= PATHCERTDIR(ctype
);
1112 char certfilename
[MAXPATH
];
1115 build_path(certfilename
, path
, email
, sizeof(certfilename
));
1116 strncat(certfilename
, ".crt", sizeof(certfilename
)-1-strlen(certfilename
));
1117 certfilename
[sizeof(certfilename
)-1] = 0;
1119 bio_out
= BIO_new_file(certfilename
, "w");
1121 PEM_write_bio_X509(bio_out
, cert
);
1123 q_status_message1(SM_ORDER
, 1, 1, _("Saved certificate for <%s>"), email
);
1126 q_status_message1(SM_ORDER
, 1, 1, _("Couldn't save certificate for <%s>"), email
);
1133 * Try to retrieve the certificate for the given email address.
1134 * The caller should free the cert.
1137 get_cert_for(char *email
, WhichCerts ctype
, int tolower
)
1139 char certfilename
[MAXPATH
];
1140 char emailaddr
[MAXPATH
];
1144 if(ctype
== Password
){
1145 build_path(certfilename
, PATHCERTDIR(ctype
), email
, sizeof(certfilename
));
1146 strncat(certfilename
, EXTCERT(Public
), sizeof(certfilename
)-1-strlen(certfilename
));
1147 certfilename
[sizeof(certfilename
)-1] = 0;
1149 if((in
= BIO_new_file(certfilename
, "r"))!=0){
1151 cert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
1154 /* could check email addr in cert matches */
1163 if(!ps_global
->smime
)
1166 dprint((9, "get_cert_for(%s, %s)", email
? email
: "?", "none yet"));
1168 if(ctype
== Private
) /* there is no private certificate info */
1169 ctype
= Public
; /* return public information instead */
1170 strncpy(emailaddr
, email
, sizeof(emailaddr
)-1);
1171 emailaddr
[sizeof(emailaddr
)-1] = 0;
1173 /* clean it up (lowercase, space removal) */
1175 emailstrclean(emailaddr
);
1177 if(ps_global
->smime
->publictype
== Keychain
){
1178 #ifdef APPLEKEYCHAIN
1181 SecKeychainItemRef itemRef
= nil
;
1182 SecKeychainAttributeList attrList
;
1183 SecKeychainAttribute attrib
;
1184 SecKeychainSearchRef searchRef
= nil
;
1187 /* low-level form of MacOS data */
1188 memset((void *) &certData
, 0, sizeof(certData
));
1191 attrList
.attr
= &attrib
;
1193 /* kSecAlias means email address for a certificate */
1194 attrib
.tag
= kSecAlias
;
1195 attrib
.data
= emailaddr
;
1196 attrib
.length
= strlen(attrib
.data
);
1198 /* Find the certificate in the default keychain */
1199 if(!(rc
=SecKeychainSearchCreateFromAttributes(NULL
,
1200 kSecCertificateItemClass
,
1204 if(!(rc
=SecKeychainSearchCopyNext(searchRef
, &itemRef
))){
1206 /* extract the data portion of the certificate */
1207 if(!(rc
=SecCertificateGetData((SecCertificateRef
) itemRef
, &certData
))){
1210 * Convert it from MacOS form to OpenSSL form.
1211 * The input is certData from above and the output
1212 * is the X509 *cert.
1214 if(!d2i_X509(&cert
, &(certData
.Data
), certData
.Length
)){
1215 dprint((9, "d2i_X509 failed"));
1219 dprint((9, "SecCertificateGetData failed"));
1222 else if(rc
== errSecItemNotFound
){
1223 dprint((9, "get_cert_for: Public cert for %s not found", emailaddr
));
1226 dprint((9, "SecKeychainSearchCopyNext failed"));
1230 dprint((9, "SecKeychainSearchCreateFromAttributes failed"));
1234 CFRelease(searchRef
);
1236 #endif /* APPLEKEYCHAIN */
1238 else if(SMHOLDERTYPE(ctype
) == Container
){
1241 for(cl
= DATACERT(ctype
); cl
; cl
= cl
->next
){
1242 if(cl
->name
&& !strucmp(emailaddr
, cl
->name
))
1247 cert
= X509_dup((X509
*) cl
->x509_cert
);
1249 else if(SMHOLDERTYPE(ctype
) == Directory
){
1250 build_path(certfilename
, PATHCERTDIR(ctype
), emailaddr
, sizeof(certfilename
));
1251 strncat(certfilename
, EXTCERT(ctype
), sizeof(certfilename
)-1-strlen(certfilename
));
1252 certfilename
[sizeof(certfilename
)-1] = 0;
1254 if((in
= BIO_new_file(certfilename
, "r"))!=0){
1256 cert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
1259 /* could check email addr in cert matches */
1271 * load_cert_for_key finds a certificate in pathdir that matches a private key
1272 * pkey. It returns its name in certfile, and the certificate in *pcert.
1273 * return value: success: different from zero, failure 0. If both certfile
1274 * and pcert are NULL, this function returns if there is certificate that
1275 * matches the given key.
1278 load_cert_for_key(char *pathdir
, EVP_PKEY
*pkey
, char **certfile
, X509
**pcert
)
1283 #else /* _WINDOWS */
1284 struct _finddata_t dbuf
;
1285 char bufn
[_MAX_PATH
+ 4];
1287 #endif /* ! _WINDOWS */
1292 char buf
[MAXPATH
+1], pathcert
[MAXPATH
+1], *fname
;
1294 if(pathdir
== NULL
|| pkey
== NULL
)
1297 if(certfile
) *certfile
= NULL
;
1298 if(pcert
) *pcert
= NULL
;
1301 if((dirp
= opendir(pathdir
)) != NULL
){
1302 while(rv
== 0 && (d
=readdir(dirp
)) != NULL
){
1305 snprintf(bufn
, sizeof(bufn
), "%s%s*.*", pathdir
, (pathdir
[strlen(pathdir
)-1] == '\\') ? "" : "\\");
1306 bufn
[sizeof(bufn
)-1] = '\0';
1307 if((findrv
= _findfirst(bufn
, &dbuf
)) >= 0){
1309 fname
= fname_to_utf8(dbuf
.name
);
1310 #endif /* ! _WINDOWS */
1311 if((ll
=strlen(fname
)) && ll
> 4){
1312 if(!strcmp(fname
+ll
-4, ".crt")){
1313 strncpy(buf
, fname
, sizeof(buf
));
1314 buf
[sizeof(buf
)-1] = '\0';
1315 build_path(pathcert
, pathdir
, buf
, sizeof(pathcert
));
1316 if((in
= BIO_new_file(pathcert
, "r")) != NULL
){
1317 if((x
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
)) != NULL
){
1318 if(X509_check_private_key(x
, pkey
) > 0){
1320 if(certfile
) *certfile
= cpystr(buf
);
1321 if(pcert
) *pcert
= x
;
1333 #else /* _WINDOWS */
1334 } while(_findnext(findrv
, &dbuf
) == 0);
1343 mem_to_personal_certs(char *contents
)
1345 PERSONAL_CERT
*result
= NULL
;
1346 char *p
, *q
, *line
, *name
, *keytext
, *save_p
;
1349 if(contents
&& *contents
){
1350 for(p
= contents
; *p
!= '\0';){
1353 while(*p
&& *p
!= '\n')
1362 if(strncmp(EMAILADDRLEADER
, line
, strlen(EMAILADDRLEADER
)) == 0){
1363 name
= line
+ strlen(EMAILADDRLEADER
);
1364 cert
= get_cert_for(name
, Public
, 1);
1367 /* advance p past this record */
1368 if((q
= strstr(keytext
, "-----END")) != NULL
){
1369 while(*q
&& *q
!= '\n')
1379 q_status_message(SM_ORDER
| SM_DING
, 3, 3, _("Error in privatekey container, missing END"));
1385 pc
= (PERSONAL_CERT
*) fs_get(sizeof(*pc
));
1387 pc
->name
= cpystr(name
);
1389 pc
->keytext
= keytext
; /* a pointer into contents */
1391 pc
->key
= load_key(pc
, "", SM_NORMALCERT
);
1408 mem_to_certlist(char *contents
, WhichCerts ctype
)
1410 CertList
*ret
= NULL
;
1411 char *p
, *q
, *line
, *name
, *certtext
, *save_p
;
1414 char *sep
= (ctype
== Public
|| ctype
== Private
)
1415 ? EMAILADDRLEADER
: CACERTSTORELEADER
;
1417 if(contents
&& *contents
){
1418 for(p
= contents
; *p
!= '\0';){
1421 while(*p
&& *p
!= '\n')
1430 if(strncmp(sep
, line
, strlen(sep
)) == 0){
1431 name
= line
+ strlen(sep
);
1433 certtext
= strstr(p
, "-----BEGIN");
1434 if(certtext
!= NULL
){
1435 if((q
= strstr(certtext
, sep
)) != NULL
)
1438 p
= q
= certtext
+strlen(certtext
);
1440 if((in
= BIO_new_mem_buf(certtext
, q
-certtext
)) != 0){
1441 cert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
1446 q_status_message2(SM_ORDER
| SM_DING
, 3, 3, _("Error in %scert container, missing BEGIN, certtext=%s"), ctype
== Public
? _("public") : _("ca"), p
);
1451 add_to_end_of_certlist(&ret
, name
, cert
);
1459 resort_certificates(&ret
, ctype
);
1466 * Add the CACert Container contents into the CACert store.
1468 * Returns > 0 for success, 0 for failure
1471 mem_add_extra_cacerts(char *contents
, X509_LOOKUP
*lookup
)
1473 char *p
, *q
, *line
, *certtext
, *save_p
;
1475 int len
, failed
= 0;
1480 * The most straight-forward way to do this is to write
1481 * the container contents to a temp file and then load the
1482 * contents of the file with X509_LOOKUP_load_file(), like
1483 * is done in add_certs_in_dir(). What we don't know is if
1484 * each file should consist of one cacert or if they can all
1485 * just be jammed together into one file. To be safe, we'll use
1486 * one file per and do each in a separate operation.
1489 if(contents
&& *contents
){
1490 for(p
= contents
; *p
!= '\0';){
1493 while(*p
&& *p
!= '\n')
1502 /* look for separator line */
1503 if(strncmp(CACERTSTORELEADER
, line
, strlen(CACERTSTORELEADER
)) == 0){
1504 /* certtext is the content that should go in a file */
1505 certtext
= strstr(p
, "-----BEGIN");
1506 if(certtext
!= NULL
){
1507 if((q
= strstr(certtext
, CACERTSTORELEADER
)) != NULL
){
1510 else{ /* end of file */
1511 q
= certtext
+ strlen(certtext
);
1515 in
= BIO_new_mem_buf(certtext
, q
-certtext
);
1517 tempfile
= temp_nam(NULL
, "az");
1518 out
= tempfile
!= NULL
? BIO_new_file(tempfile
, "w") : NULL
;
1520 while((len
= BIO_read(in
, iobuf
, sizeof(iobuf
))) > 0)
1521 BIO_write(out
, iobuf
, len
);
1524 if(!X509_LOOKUP_load_file(lookup
, tempfile
, X509_FILETYPE_PEM
))
1528 if(tempfile
!= NULL
){
1530 fs_give((void **) &tempfile
);
1538 q_status_message1(SM_ORDER
| SM_DING
, 3, 3, _("Error in cacert container, missing BEGIN, certtext=%s"), certtext
);
1543 q_status_message1(SM_ORDER
| SM_DING
, 3, 3, _("Error in cacert container, missing separator, line=%s"), line
);
1556 certlist_to_file(char *filename
, CertList
*certlist
)
1559 BIO
*bio_out
= NULL
;
1562 if(filename
&& (bio_out
=BIO_new_file(filename
, "w")) != NULL
){
1564 for(cl
= certlist
; cl
; cl
= cl
->next
){
1565 if(cl
->name
&& cl
->name
[0] && cl
->x509_cert
){
1566 if(!((BIO_puts(bio_out
, EMAILADDRLEADER
) > 0)
1567 && (BIO_puts(bio_out
, cl
->name
) > 0)
1568 && (BIO_puts(bio_out
, "\n") > 0)))
1571 if(!PEM_write_bio_X509(bio_out
, (X509
*) cl
->x509_cert
))
1584 add_to_end_of_certlist(CertList
**cl
, char *name
, X509
*cert
)
1591 new = smime_X509_to_cert_info(cert
, name
);
1598 free_certlist(CertList
**cl
)
1601 if((*cl
)->data
.date_from
)
1602 fs_give((void **) &(*cl
)->data
.date_from
);
1604 if((*cl
)->data
.date_to
)
1605 fs_give((void **) &(*cl
)->data
.date_to
);
1608 fs_give((void **) &(*cl
)->data
.md5
);
1611 fs_give((void **) &(*cl
)->name
);
1614 fs_give((void **) &(*cl
)->cn
);
1616 if((*cl
)->x509_cert
)
1617 X509_free((X509
*) (*cl
)->x509_cert
);
1619 free_certlist(&(*cl
)->next
);
1621 fs_give((void **) cl
);
1627 free_personal_certs(PERSONAL_CERT
**pc
)
1631 fs_give((void **) &(*pc
)->name
);
1634 fs_give((void **) &(*pc
)->cname
);
1637 X509_free((*pc
)->cert
);
1640 EVP_PKEY_free((*pc
)->key
);
1642 free_personal_certs(&(*pc
)->next
);
1644 fs_give((void **) pc
);