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
;
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"
654 d
= strchr(iobuf
, ' ');
656 while(*d
== ' ') d
++;
657 t
= strchr(d
+1, ' ');
659 while(*t
== ' ') t
++;
660 y
= strchr(t
+1, ' ');
662 while(*y
== ' ') y
++;
663 z
= strchr(y
+1, ' ');
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
);
678 snprintf(buf
, sizeof(buf
), "%s/%s/%s", m
, d
, y
+ strlen(y
) - 2);
679 buf
[sizeof(buf
)-1] = '\0';
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
;
695 struct _finddata_t dbuf
;
696 char bufn
[_MAX_PATH
+ 4];
698 #endif /* !_WINDOWS */
700 int ret
= 0, nfiles
= 0, nerr
= 0;
703 if((dirp
= opendir(path
)) != NULL
){
704 while(!ret
&& (d
=readdir(dirp
)) != NULL
){
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
)){
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
);
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
);
743 for (cl
= *cdata
; cl
&& cl
->next
; cl
= cl
->next
);
755 } while(_findnext(findrv
, &dbuf
) == 0);
757 #endif /* ! _WINDOWS */
760 /* if all certificates fail to load */
761 if(nerr
> 0 && nerr
== nfiles
) ret
= -1;
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.
775 X509_STORE
*store
= NULL
;
777 dprint((9, "get_ca_store()"));
779 if(!(store
=X509_STORE_new())){
780 dprint((9, "X509_STORE_new() failed"));
784 if(!(lookup
=X509_STORE_add_lookup(store
, X509_LOOKUP_file()))){
785 dprint((9, "X509_STORE_add_lookup() failed"));
786 X509_STORE_free(store
);
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
);
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
);
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
);
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
);
822 load_key(PERSONAL_CERT
*pc
, char *pass
, int flag
)
825 EVP_PKEY
*key
= NULL
;
826 char buf
[MAXPATH
], file
[MAXPATH
];
828 if(!(ps_global
->smime
&& pc
&& pc
->name
))
831 if(ps_global
->smime
->privatetype
== Container
){
834 if(pc
->keytext
&& (q
= strstr(pc
->keytext
, "-----END")) != NULL
){
835 while(*q
&& *q
!= '\n')
841 if((in
= BIO_new_mem_buf(pc
->keytext
, q
-pc
->keytext
)) != NULL
){
842 key
= PEM_read_bio_PrivateKey(in
, NULL
, NULL
, pass
);
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")))
857 key
= PEM_read_bio_PrivateKey(in
, NULL
, NULL
, pass
);
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.
872 get_x509_subject_email(X509
*x
)
874 char **result
= NULL
;
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
));
883 X509_email_free(emails
);
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
900 save_cert_for(char *email
, X509
*cert
, WhichCerts ctype
)
902 if(!ps_global
->smime
|| ctype
== Private
)
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
){
912 SecCertificateRef secCertificateRef
;
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
,
927 CSSM_CERT_ENCODING_DER
,
928 &secCertificateRef
))){
930 /* add it to the default keychain */
931 if(!(rc
=SecCertificateAddToKeychain(secCertificateRef
, NULL
))){
934 else if(rc
== errSecDuplicateItem
){
935 dprint((9, "save_cert_for: certificate for %s already in keychain", email
));
938 dprint((9, "SecCertificateAddToKeychain failed"));
942 dprint((9, "SecCertificateCreateFromData failed"));
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
;
956 char *upath
= PATHCERTDIR(ctype
);
957 char *tempfile
= NULL
;
959 CertList
*clist
= DATACERT(ctype
);
961 add_to_end_of_certlist(&clist
, email
, X509_dup(cert
));
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;
973 if(IS_REMOTE(upath
)){
974 rd
= rd_create_remote(RemImap
, upath
, REMOTE_SMIME_SUBTYPE
,
976 _("Can't access remote smime configuration."));
981 (void) rd_read_metadata(rd
);
983 if(rd
->access
== MaybeRorW
){
984 if(rd
->read_status
== 'R')
985 rd
->access
= ReadOnly
;
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
;
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
);
1020 if(rd
->access
!= ReadWrite
|| rd_remote_is_readonly(rd
)){
1021 rd_close_remdata(&rd
);
1025 rd
->flags
|= DO_REMTRIM
;
1027 strncpy(path
, rd
->lf
, sizeof(path
)-1);
1028 path
[sizeof(path
)-1] = '\0';
1031 strncpy(path
, upath
, sizeof(path
)-1);
1032 path
[sizeof(path
)-1] = '\0';
1035 tempfile
= tempfile_in_same_dir(path
, "az", &ret_dir
);
1037 if(certlist_to_file(tempfile
, DATACERT(ctype
)))
1040 if(!err
&& ret_dir
){
1041 if(IS_REMOTE(upath
)){
1042 strncpy(fpath
, rd
->lf
, sizeof(fpath
));
1043 fpath
[sizeof(fpath
)-1] = '\0';
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);
1055 fs_give((void **)&ret_dir
);
1058 if(rename_file(tempfile
, fpath
) < 0){
1059 q_status_message2(SM_ORDER
, 3, 3,
1060 _("Can't rename %s to %s"), tempfile
, fpath
);
1065 if(!err
&& IS_REMOTE(upath
)){
1071 we_cancel
= busy_cue(_("Copying to remote smime container"), NULL
, 1);
1072 if((e
= rd_update_remote(rd
, datebuf
)) != 0){
1074 q_status_message2(SM_ORDER
| SM_DING
, 3, 5,
1075 _("Error opening temporary smime file %s: %s"),
1076 rd
->lf
, error_description(errno
));
1078 "write_remote_smime: error opening temp file %s\n",
1079 rd
->lf
? rd
->lf
: "?"));
1082 q_status_message2(SM_ORDER
| SM_DING
, 3, 5,
1083 _("Error copying to %s: %s"),
1084 rd
->rn
, error_description(errno
));
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"));
1094 rd_update_metadata(rd
, datebuf
);
1095 rd
->read_status
= 'W';
1098 rd_close_remdata(&rd
);
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
];
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");
1118 PEM_write_bio_X509(bio_out
, cert
);
1120 q_status_message1(SM_ORDER
, 1, 1, _("Saved certificate for <%s>"), email
);
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.
1134 get_cert_for(char *email
, WhichCerts ctype
, int tolower
)
1136 char certfilename
[MAXPATH
];
1137 char emailaddr
[MAXPATH
];
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
);
1151 /* could check email addr in cert matches */
1160 if(!ps_global
->smime
)
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) */
1172 emailstrclean(emailaddr
);
1174 if(ps_global
->smime
->publictype
== Keychain
){
1175 #ifdef APPLEKEYCHAIN
1178 SecKeychainItemRef itemRef
= nil
;
1179 SecKeychainAttributeList attrList
;
1180 SecKeychainAttribute attrib
;
1181 SecKeychainSearchRef searchRef
= nil
;
1184 /* low-level form of MacOS data */
1185 memset((void *) &certData
, 0, sizeof(certData
));
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
,
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"));
1216 dprint((9, "SecCertificateGetData failed"));
1219 else if(rc
== errSecItemNotFound
){
1220 dprint((9, "get_cert_for: Public cert for %s not found", emailaddr
));
1223 dprint((9, "SecKeychainSearchCopyNext failed"));
1227 dprint((9, "SecKeychainSearchCreateFromAttributes failed"));
1231 CFRelease(searchRef
);
1233 #endif /* APPLEKEYCHAIN */
1235 else if(SMHOLDERTYPE(ctype
) == Container
){
1238 for(cl
= DATACERT(ctype
); cl
; cl
= cl
->next
){
1239 if(cl
->name
&& !strucmp(emailaddr
, cl
->name
))
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
);
1256 /* could check email addr in cert matches */
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
)
1280 #else /* _WINDOWS */
1281 struct _finddata_t dbuf
;
1282 char bufn
[_MAX_PATH
+ 4];
1284 #endif /* ! _WINDOWS */
1289 char buf
[MAXPATH
+1], pathcert
[MAXPATH
+1], *fname
;
1291 if(pathdir
== NULL
|| pkey
== NULL
)
1294 if(certfile
) *certfile
= NULL
;
1295 if(pcert
) *pcert
= NULL
;
1298 if((dirp
= opendir(pathdir
)) != NULL
){
1299 while(rv
== 0 && (d
=readdir(dirp
)) != NULL
){
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){
1317 if(certfile
) *certfile
= cpystr(buf
);
1318 if(pcert
) *pcert
= x
;
1330 #else /* _WINDOWS */
1331 } while(_findnext(findrv
, &dbuf
) == 0);
1340 mem_to_personal_certs(char *contents
)
1342 PERSONAL_CERT
*result
= NULL
;
1343 char *p
, *q
, *line
, *name
, *keytext
, *save_p
;
1346 if(contents
&& *contents
){
1347 for(p
= contents
; *p
!= '\0';){
1350 while(*p
&& *p
!= '\n')
1359 if(strncmp(EMAILADDRLEADER
, line
, strlen(EMAILADDRLEADER
)) == 0){
1360 name
= line
+ strlen(EMAILADDRLEADER
);
1361 cert
= get_cert_for(name
, Public
, 1);
1364 /* advance p past this record */
1365 if((q
= strstr(keytext
, "-----END")) != NULL
){
1366 while(*q
&& *q
!= '\n')
1376 q_status_message(SM_ORDER
| SM_DING
, 3, 3, _("Error in privatekey container, missing END"));
1382 pc
= (PERSONAL_CERT
*) fs_get(sizeof(*pc
));
1384 pc
->name
= cpystr(name
);
1386 pc
->keytext
= keytext
; /* a pointer into contents */
1388 pc
->key
= load_key(pc
, "", SM_NORMALCERT
);
1405 mem_to_certlist(char *contents
, WhichCerts ctype
)
1407 CertList
*ret
= NULL
;
1408 char *p
, *q
, *line
, *name
, *certtext
, *save_p
;
1411 char *sep
= (ctype
== Public
|| ctype
== Private
)
1412 ? EMAILADDRLEADER
: CACERTSTORELEADER
;
1414 if(contents
&& *contents
){
1415 for(p
= contents
; *p
!= '\0';){
1418 while(*p
&& *p
!= '\n')
1427 if(strncmp(sep
, line
, strlen(sep
)) == 0){
1428 name
= line
+ strlen(sep
);
1430 certtext
= strstr(p
, "-----BEGIN");
1431 if(certtext
!= NULL
){
1432 if((q
= strstr(certtext
, sep
)) != NULL
)
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
);
1443 q_status_message2(SM_ORDER
| SM_DING
, 3, 3, _("Error in %scert container, missing BEGIN, certtext=%s"), ctype
== Public
? _("public") : _("ca"), p
);
1448 add_to_end_of_certlist(&ret
, name
, cert
);
1456 resort_certificates(&ret
, ctype
);
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
;
1472 int len
, failed
= 0;
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';){
1490 while(*p
&& *p
!= '\n')
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
){
1507 else{ /* end of file */
1508 q
= certtext
+ strlen(certtext
);
1512 in
= BIO_new_mem_buf(certtext
, q
-certtext
);
1514 tempfile
= temp_nam(NULL
, "az");
1515 out
= tempfile
!= NULL
? BIO_new_file(tempfile
, "w") : NULL
;
1517 while((len
= BIO_read(in
, iobuf
, sizeof(iobuf
))) > 0)
1518 BIO_write(out
, iobuf
, len
);
1521 if(!X509_LOOKUP_load_file(lookup
, tempfile
, X509_FILETYPE_PEM
))
1525 if(tempfile
!= NULL
){
1527 fs_give((void **) &tempfile
);
1535 q_status_message1(SM_ORDER
| SM_DING
, 3, 3, _("Error in cacert container, missing BEGIN, certtext=%s"), certtext
);
1540 q_status_message1(SM_ORDER
| SM_DING
, 3, 3, _("Error in cacert container, missing separator, line=%s"), line
);
1553 certlist_to_file(char *filename
, CertList
*certlist
)
1556 BIO
*bio_out
= NULL
;
1559 if(filename
&& (bio_out
=BIO_new_file(filename
, "w")) != NULL
){
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)))
1568 if(!PEM_write_bio_X509(bio_out
, (X509
*) cl
->x509_cert
))
1581 add_to_end_of_certlist(CertList
**cl
, char *name
, X509
*cert
)
1588 new = smime_X509_to_cert_info(cert
, name
);
1595 free_certlist(CertList
**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
);
1605 fs_give((void **) &(*cl
)->data
.md5
);
1608 fs_give((void **) &(*cl
)->name
);
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
);
1624 free_personal_certs(PERSONAL_CERT
**pc
)
1628 fs_give((void **) &(*pc
)->name
);
1631 fs_give((void **) &(*pc
)->cname
);
1634 X509_free((*pc
)->cert
);
1637 EVP_PKEY_free((*pc
)->key
);
1639 free_personal_certs(&(*pc
)->next
);
1641 fs_give((void **) pc
);