2 * Copyright notice from original mutt:
3 * Copyright (C) 2001,2002 Oliver Ehli <elmy@acm.org>
4 * Copyright (C) 2002 Mike Schiraldi <raldi@research.netsol.com>
5 * Copyright (C) 2004 g10 Code GmbH
7 * This file is part of mutt-ng, see http://www.muttng.org/.
8 * It's licensed under the GNU General Public License,
9 * please see the file GPL in the top level source directory.
16 #include <lib-lib/mem.h>
21 #include "mutt_curses.h"
22 #include "mutt_menu.h"
30 #include "lib/debug.h"
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
48 #ifdef HAVE_SYS_RESOURCE_H
49 # include <sys/resource.h>
52 #ifdef CRYPT_BACKEND_CLASSIC_SMIME
54 #include "mutt_crypt.h"
56 struct smime_command_context {
57 const char *key; /* %k */
58 const char *cryptalg; /* %a */
59 const char *fname; /* %f */
60 const char *sig_fname; /* %s */
61 const char *certificates; /* %c */
62 const char *intermediates; /* %i */
71 char trust; /* i=Invalid r=revoked e=expired u=unverified v=verified t=trusted */
72 short public; /* 1=public 0=private */
76 char SmimePass[STRING];
77 time_t SmimeExptime = 0; /* when does the cached passphrase expire? */
80 static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
81 static char SmimeCertToUse[_POSIX_PATH_MAX];
82 static char SmimeIntermediateToUse[_POSIX_PATH_MAX];
86 * Queries and passphrase handling.
92 /* these are copies from pgp.c */
95 void smime_void_passphrase (void)
97 memset (SmimePass, 0, sizeof (SmimePass));
101 int smime_valid_passphrase (void)
103 time_t now = time (NULL);
105 if (now < SmimeExptime)
106 /* Use cached copy. */
109 smime_void_passphrase ();
111 if (mutt_get_field_unbuffered (_("Enter S/MIME passphrase:"), SmimePass,
112 sizeof (SmimePass), M_PASS) == 0) {
113 SmimeExptime = time (NULL) + SmimeTimeout;
124 * The OpenSSL interface
127 /* This is almost identical to ppgp's invoking interface. */
129 static const char *_mutt_fmt_smime_command (char *dest,
134 const char *ifstring,
135 const char *elsestring,
140 struct smime_command_context *cctx = (struct smime_command_context *) data;
141 int optional = (flags & M_FORMAT_OPTIONAL);
147 char path[_POSIX_PATH_MAX];
148 char buf1[LONG_STRING], buf2[LONG_STRING];
151 strfcpy (path, NONULL (SmimeCALocation), sizeof (path));
152 mutt_expand_path (path, sizeof (path));
153 mutt_quote_filename (buf1, sizeof (buf1), path);
155 if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
156 snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
158 snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
160 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
161 snprintf (dest, destlen, fmt, buf2);
163 else if (!SmimeCALocation)
169 { /* certificate (list) */
171 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
172 snprintf (dest, destlen, fmt, NONULL (cctx->certificates));
174 else if (!cctx->certificates)
180 { /* intermediate certificates */
182 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
183 snprintf (dest, destlen, fmt, NONULL (cctx->intermediates));
185 else if (!cctx->intermediates)
191 { /* detached signature */
193 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
194 snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
196 else if (!cctx->sig_fname)
204 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
205 snprintf (dest, destlen, fmt, NONULL (cctx->key));
213 { /* algorithm for encryption */
215 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
216 snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
224 { /* file to process */
226 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
227 snprintf (dest, destlen, fmt, NONULL (cctx->fname));
229 else if (!cctx->fname)
240 mutt_FormatString (dest, destlen, ifstring, _mutt_fmt_smime_command,
242 else if (flags & M_FORMAT_OPTIONAL)
243 mutt_FormatString (dest, destlen, elsestring, _mutt_fmt_smime_command,
251 static void mutt_smime_command (char *d, size_t dlen,
252 struct smime_command_context *cctx,
255 mutt_FormatString (d, dlen, NONULL (fmt), _mutt_fmt_smime_command,
256 (unsigned long) cctx, 0);
257 debug_print (2, ("%s\n", d));
260 static pid_t smime_invoke (FILE ** smimein, FILE ** smimeout,
261 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
262 int smimeerrfd, const char *fname,
263 const char *sig_fname, const char *cryptalg,
264 const char *key, const char *certificates,
265 const char *intermediates, const char *format)
267 struct smime_command_context cctx;
268 char cmd[HUGE_STRING];
270 memset (&cctx, 0, sizeof (cctx));
272 if (!format || !*format)
276 cctx.sig_fname = sig_fname;
278 cctx.cryptalg = cryptalg;
279 cctx.certificates = certificates;
280 cctx.intermediates = intermediates;
282 mutt_smime_command (cmd, sizeof (cmd), &cctx, format);
284 return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
285 smimeinfd, smimeoutfd, smimeerrfd);
294 * Key and certificate handling.
300 Search the certificate index for given mailbox.
301 return certificate file name.
304 static void smime_entry (char *s, size_t l, MUTTMENU * menu, int num)
306 smime_id *Table = (smime_id *) menu->data;
307 smime_id this = Table[num];
308 const char *truststate;
310 switch (this.trust) {
312 truststate = N_("Trusted ");
315 truststate = N_("Verified ");
318 truststate = N_("Unverified");
321 truststate = N_("Expired ");
324 truststate = N_("Revoked ");
327 truststate = N_("Invalid ");
330 truststate = N_("Unknown ");
333 snprintf (s, l, " 0x%.8X.%i %s %-35.35s %s", this.hash, this.suffix,
334 truststate, this.email, this.nick);
336 snprintf (s, l, " 0x%.8X.%i %-35.35s %s", this.hash, this.suffix,
337 this.email, this.nick);
344 char *smime_ask_for_key (char *prompt, char *mailbox, short public)
348 long cert_num; /* Will contain the number of certificates.
349 * To be able to get it, the .index file will be read twice... */
350 char index_file[_POSIX_PATH_MAX];
352 char buf[LONG_STRING];
353 char fields[5][STRING];
354 int numFields, hash_suffix, done, cur; /* The current entry */
357 char helpstr[HUGE_STRING * 3];
362 prompt = _("Enter keyID: ");
363 snprintf (index_file, sizeof (index_file), "%s/.index",
364 public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys));
366 index = fopen (index_file, "r");
368 mutt_perror (index_file);
373 while (!feof (index)) {
374 if (fgets (buf, sizeof (buf), index))
381 if (mutt_get_field (prompt, qry, sizeof (qry), 0))
383 snprintf (title, sizeof (title),
384 _("S/MIME certificates matching \"%s\"."), qry);
387 index = fopen (index_file, "r");
389 mutt_perror (index_file);
394 Table = mem_calloc (cert_num, sizeof (smime_id));
395 while (!feof (index)) {
397 fscanf (index, MUTT_FORMAT (STRING) " %x.%i " MUTT_FORMAT (STRING),
398 fields[0], &hash, &hash_suffix, fields[2]);
400 fscanf (index, MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) "\n",
401 fields[3], fields[4]);
403 /* 0=email 1=name 2=nick 3=intermediate 4=trust */
407 /* Check if query matches this certificate */
408 if (!str_isstr (fields[0], qry) && !str_isstr (fields[2], qry))
411 Table[cur].hash = hash;
412 Table[cur].suffix = hash_suffix;
413 strncpy (Table[cur].email, fields[0], sizeof (Table[cur].email));
414 strncpy (Table[cur].nick, fields[2], sizeof (Table[cur].nick));
415 Table[cur].trust = *fields[4];
416 Table[cur].public = public;
422 /* Make Helpstring */
424 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_SMIME, OP_EXIT);
425 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
426 mutt_make_help (buf, sizeof (buf), _("Select "), MENU_SMIME,
427 OP_GENERIC_SELECT_ENTRY);
428 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
429 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_SMIME, OP_HELP);
430 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
432 /* Create the menu */
433 menu = mutt_new_menu ();
435 menu->make_entry = smime_entry;
436 menu->menu = MENU_SMIME;
437 menu->help = helpstr;
440 /* sorting keys might be done later - TODO */
447 switch (mutt_menuLoop (menu)) {
448 case OP_GENERIC_SELECT_ENTRY:
460 fname = p_new(char, 13); /* Hash + '.' + Suffix + \0 */
461 sprintf (fname, "%.8x.%i", Table[cur].hash, Table[cur].suffix);
466 mutt_menuDestroy (&menu);
468 set_option (OPTNEEDREDRAW);
477 char *smime_get_field_from_db (char *mailbox, char *query, short public,
480 int addr_len, query_len, found = 0, ask = 0, choice = 0;
481 char cert_path[_POSIX_PATH_MAX];
482 char buf[LONG_STRING], prompt[STRING];
483 char fields[5][STRING];
487 char key_trust_level = 0;
490 if (!mailbox && !query)
493 addr_len = mailbox ? str_len (mailbox) : 0;
494 query_len = query ? str_len (query) : 0;
498 /* index-file format:
499 mailbox certfile label issuer_certfile trust_flags\n
501 certfile is a hash value generated by openssl.
502 Note that this was done according to the OpenSSL
503 specs on their CA-directory.
506 snprintf (cert_path, sizeof (cert_path), "%s/.index",
507 (public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys)));
509 if (!stat (cert_path, &info)) {
510 if ((fp = safe_fopen (cert_path, "r")) == NULL) {
511 mutt_perror (cert_path);
515 while (fgets (buf, sizeof (buf) - 1, fp) != NULL)
516 if (mailbox && !(str_ncasecmp (mailbox, buf, addr_len))) {
517 numFields = sscanf (buf,
518 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
519 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
520 MUTT_FORMAT (STRING) "\n",
521 fields[0], fields[1],
522 fields[2], fields[3], fields[4]);
525 if (mailbox && public &&
527 *fields[4] == 'i' || *fields[4] == 'e' || *fields[4] == 'r'))
531 if (public && *fields[4] == 'u')
532 snprintf (prompt, sizeof (prompt),
534 ("ID %s is unverified. Do you want to use it for %s ?"),
536 else if (public && *fields[4] == 'v')
537 snprintf (prompt, sizeof (prompt),
538 _("Use (untrusted!) ID %s for %s ?"),
541 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"),
545 if (may_ask && (choice = mutt_yesorno (prompt, M_NO)) == -1) {
551 else if (choice == M_NO) {
555 else if (choice == M_YES) {
556 strfcpy (key, fields[1], sizeof (key));
563 key_trust_level = *fields[4];
564 strfcpy (key, fields[1], sizeof (key));
569 numFields = sscanf (buf,
570 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
571 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
572 MUTT_FORMAT (STRING) "\n",
573 fields[0], fields[1],
574 fields[2], fields[3], fields[4]);
576 /* query = label: return certificate. */
577 if (numFields >= 3 &&
578 !(str_ncasecmp (query, fields[2], query_len))) {
580 strfcpy (key, fields[1], sizeof (key));
582 /* query = certificate: return intermediate certificate. */
583 else if (numFields >= 4 &&
584 !(str_ncasecmp (query, fields[1], query_len))) {
586 strfcpy (key, fields[3], sizeof (key));
593 if (public && *fields[4] == 'u')
594 snprintf (prompt, sizeof (prompt),
595 _("ID %s is unverified. Do you want to use it for %s ?"),
597 else if (public && *fields[4] == 'v')
598 snprintf (prompt, sizeof (prompt),
599 _("Use (untrusted!) ID %s for %s ?"), fields[1], mailbox);
601 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"), key,
603 choice = mutt_yesorno (prompt, M_NO);
604 if (choice == -1 || choice == M_NO)
607 else if (key_trust_level && may_ask) {
608 if (key_trust_level == 'u') {
609 snprintf (prompt, sizeof (prompt),
610 _("ID %s is unverified. Do you want to use it for %s ?"),
612 choice = mutt_yesorno (prompt, M_NO);
616 else if (key_trust_level == 'v') {
618 ("Warning: You have not yet decided to trust ID %s. (any key to continue)"),
626 /* Note: str_dup ("") returns NULL. */
627 return str_dup (key);
634 This sets the '*ToUse' variables for an upcoming decryption, where
635 the reuquired key is different from SmimeDefaultKey.
638 void _smime_getkeys (char *mailbox)
643 k = smime_get_field_from_db (mailbox, NULL, 0, 1);
646 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), mailbox);
647 k = smime_ask_for_key (buf, mailbox, 0);
651 /* the key used last time. */
652 if (*SmimeKeyToUse &&
653 !str_casecmp (k, SmimeKeyToUse + str_len (SmimeKeys) + 1)) {
658 smime_void_passphrase ();
660 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
661 NONULL (SmimeKeys), k);
663 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
664 NONULL (SmimeCertificates), k);
666 if (str_casecmp (k, SmimeDefaultKey))
667 smime_void_passphrase ();
673 if (*SmimeKeyToUse) {
674 if (!str_casecmp (SmimeDefaultKey,
675 SmimeKeyToUse + str_len (SmimeKeys) + 1))
678 smime_void_passphrase ();
681 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
682 NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
684 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
685 NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
688 void smime_getkeys (ENVELOPE * env)
693 if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey) {
694 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
695 NONULL (SmimeKeys), SmimeDefaultKey);
697 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
698 NONULL (SmimeCertificates), SmimeDefaultKey);
703 for (t = env->to; !found && t; t = t->next)
704 if (mutt_addr_is_user (t)) {
706 _smime_getkeys (t->mailbox);
708 for (t = env->cc; !found && t; t = t->next)
709 if (mutt_addr_is_user (t)) {
711 _smime_getkeys (t->mailbox);
713 if (!found && (t = mutt_default_from ())) {
714 _smime_getkeys (t->mailbox);
715 rfc822_free_address (&t);
719 /* This routine attempts to find the keyids of the recipients of a message.
720 * It returns NULL if any of the keys can not be found.
723 char *smime_findKeys (ADDRESS * to, ADDRESS * cc, ADDRESS * bcc)
725 char *keyID, *keylist = NULL;
726 size_t keylist_size = 0;
727 size_t keylist_used = 0;
728 ADDRESS *tmp = NULL, *addr = NULL;
729 ADDRESS **last = &tmp;
733 const char *fqdn = mutt_fqdn (1);
735 for (i = 0; i < 3; i++) {
750 *last = rfc822_cpy_adr (p);
752 last = &((*last)->next);
756 rfc822_qualify (tmp, fqdn);
758 tmp = mutt_remove_duplicates (tmp);
760 for (p = tmp; p; p = p->next) {
761 char buf[LONG_STRING];
765 if ((keyID = smime_get_field_from_db (q->mailbox, NULL, 1, 1)) == NULL) {
766 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), q->mailbox);
767 keyID = smime_ask_for_key (buf, q->mailbox, 1);
770 mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
772 rfc822_free_address (&tmp);
773 rfc822_free_address (&addr);
777 keylist_size += str_len (keyID) + 2;
778 mem_realloc (&keylist, keylist_size);
779 sprintf (keylist + keylist_used, "%s\n", keyID); /* __SPRINTF_CHECKED__ */
780 keylist_used = str_len (keylist);
782 rfc822_free_address (&addr);
785 rfc822_free_address (&tmp);
794 static int smime_handle_cert_email (char *certificate, char *mailbox,
795 int copy, char ***buffer, int *num)
797 FILE *fpout = NULL, *fperr = NULL;
798 char tmpfname[_POSIX_PATH_MAX];
800 int ret = -1, count = 0;
803 mutt_mktemp (tmpfname);
804 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
805 mutt_perror (tmpfname);
808 mutt_unlink (tmpfname);
810 mutt_mktemp (tmpfname);
811 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
813 mutt_perror (tmpfname);
816 mutt_unlink (tmpfname);
818 if ((thepid = smime_invoke (NULL, NULL, NULL,
819 -1, fileno (fpout), fileno (fperr),
820 certificate, NULL, NULL, NULL, NULL, NULL,
821 SmimeGetCertEmailCommand)) == -1) {
822 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
828 mutt_wait_filter (thepid);
836 while ((fgets (email, sizeof (email), fpout))) {
837 *(email + str_len (email) - 1) = '\0';
838 if (str_ncasecmp (email, mailbox, str_len (mailbox)) == 0)
841 ret = ret < 0 ? 0 : ret;
847 mutt_copy_stream (fperr, stdout);
848 mutt_any_key_to_continue (_
849 ("Error: unable to create OpenSSL subprocess!"));
857 if (copy && buffer && num) {
859 *buffer = mem_calloc (sizeof (char *), count);
863 while ((fgets (email, sizeof (email), fpout))) {
864 *(email + str_len (email) - 1) = '\0';
865 (*buffer)[count] = mem_calloc (1, str_len (email) + 1);
866 strncpy ((*buffer)[count], email, str_len (email));
881 static char *smime_extract_certificate (char *infile)
883 FILE *fpout = NULL, *fperr = NULL;
884 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
885 char tmpfname[_POSIX_PATH_MAX];
890 mutt_mktemp (tmpfname);
891 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
892 mutt_perror (tmpfname);
895 mutt_unlink (tmpfname);
897 mutt_mktemp (pk7out);
898 if ((fpout = safe_fopen (pk7out, "w+")) == NULL) {
900 mutt_perror (pk7out);
904 /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
905 extract the full set of certificates directly.
907 if ((thepid = smime_invoke (NULL, NULL, NULL,
908 -1, fileno (fpout), fileno (fperr),
909 infile, NULL, NULL, NULL, NULL, NULL,
910 SmimePk7outCommand)) == -1) {
911 mutt_any_key_to_continue (_
912 ("Error: unable to create OpenSSL subprocess!"));
915 mutt_unlink (pk7out);
919 mutt_wait_filter (thepid);
926 empty = (fgetc (fpout) == EOF);
928 mutt_perror (pk7out);
929 mutt_copy_stream (fperr, stdout);
932 mutt_unlink (pk7out);
939 mutt_mktemp (certfile);
940 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
942 mutt_unlink (pk7out);
943 mutt_perror (certfile);
947 /* Step 2: Extract the certificates from a PKCS#7 structure.
949 if ((thepid = smime_invoke (NULL, NULL, NULL,
950 -1, fileno (fpout), fileno (fperr),
951 pk7out, NULL, NULL, NULL, NULL, NULL,
952 SmimeGetCertCommand)) == -1) {
953 mutt_any_key_to_continue (_
954 ("Error: unable to create OpenSSL subprocess!"));
957 mutt_unlink (pk7out);
958 mutt_unlink (certfile);
962 mutt_wait_filter (thepid);
964 mutt_unlink (pk7out);
970 empty = (fgetc (fpout) == EOF);
972 mutt_copy_stream (fperr, stdout);
975 mutt_unlink (certfile);
982 return str_dup (certfile);
985 static char *smime_extract_signer_certificate (char *infile)
987 FILE *fpout = NULL, *fperr = NULL;
988 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
989 char tmpfname[_POSIX_PATH_MAX];
994 mutt_mktemp (tmpfname);
995 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
996 mutt_perror (tmpfname);
999 mutt_unlink (tmpfname);
1002 mutt_mktemp (certfile);
1003 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
1005 mutt_perror (certfile);
1009 /* Extract signer's certificate
1011 if ((thepid = smime_invoke (NULL, NULL, NULL,
1012 -1, -1, fileno (fperr),
1013 infile, NULL, NULL, NULL, certfile, NULL,
1014 SmimeGetSignerCertCommand)) == -1) {
1015 mutt_any_key_to_continue (_
1016 ("Error: unable to create OpenSSL subprocess!"));
1019 mutt_unlink (pk7out);
1020 mutt_unlink (certfile);
1024 mutt_wait_filter (thepid);
1030 empty = (fgetc (fpout) == EOF);
1033 mutt_copy_stream (fperr, stdout);
1034 mutt_any_key_to_continue (NULL);
1037 mutt_unlink (certfile);
1044 return str_dup (certfile);
1050 /* Add a certificate and update index file (externally). */
1052 void smime_invoke_import (char *infile, char *mailbox)
1054 char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
1055 FILE *smimein = NULL, *fpout = NULL, *fperr = NULL;
1058 mutt_mktemp (tmpfname);
1059 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
1060 mutt_perror (tmpfname);
1063 mutt_unlink (tmpfname);
1065 mutt_mktemp (tmpfname);
1066 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
1068 mutt_perror (tmpfname);
1071 mutt_unlink (tmpfname);
1075 if (option (OPTASKCERTLABEL))
1076 mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1079 if ((certfile = smime_extract_certificate (infile))) {
1082 if ((thepid = smime_invoke (&smimein, NULL, NULL,
1083 -1, fileno (fpout), fileno (fperr),
1084 certfile, NULL, NULL, NULL, NULL, NULL,
1085 SmimeImportCertCommand)) == -1) {
1086 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
1089 fputs (buf, smimein);
1090 fputc ('\n', smimein);
1093 mutt_wait_filter (thepid);
1095 mutt_unlink (certfile);
1096 p_delete(&certfile);
1104 mutt_copy_stream (fpout, stdout);
1105 mutt_copy_stream (fperr, stdout);
1114 int smime_verify_sender (HEADER * h)
1116 char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
1120 mutt_mktemp (tempfname);
1121 if (!(fpout = safe_fopen (tempfname, "w"))) {
1122 mutt_perror (tempfname);
1126 if (h->security & ENCRYPT)
1127 mutt_copy_message (fpout, Context, h,
1128 M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1129 CH_MIME | CH_WEED | CH_NONEWLINE);
1131 mutt_copy_message (fpout, Context, h, 0, 0);
1137 h->env->from = mutt_expand_aliases (h->env->from);
1138 mbox = h->env->from->mailbox;
1140 else if (h->env->sender) {
1141 h->env->sender = mutt_expand_aliases (h->env->sender);
1142 mbox = h->env->sender->mailbox;
1146 if ((certfile = smime_extract_signer_certificate (tempfname))) {
1147 mutt_unlink (tempfname);
1148 if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL)) {
1150 mutt_any_key_to_continue (NULL);
1154 mutt_unlink (certfile);
1155 p_delete(&certfile);
1158 mutt_any_key_to_continue (_("no certfile"));
1161 mutt_any_key_to_continue (_("no mbox"));
1163 mutt_unlink (tempfname);
1176 * Creating S/MIME - bodies.
1183 pid_t smime_invoke_encrypt (FILE ** smimein, FILE ** smimeout,
1184 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1185 int smimeerrfd, const char *fname,
1188 return smime_invoke (smimein, smimeout, smimeerr,
1189 smimeinfd, smimeoutfd, smimeerrfd,
1190 fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
1191 SmimeEncryptCommand);
1196 pid_t smime_invoke_sign (FILE ** smimein, FILE ** smimeout, FILE ** smimeerr,
1197 int smimeinfd, int smimeoutfd, int smimeerrfd,
1200 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1201 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1202 SmimeCertToUse, SmimeIntermediateToUse,
1209 BODY *smime_build_smime_entity (BODY * a, char *certlist)
1211 char buf[LONG_STRING], certfile[LONG_STRING];
1212 char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1213 char smimeinfile[_POSIX_PATH_MAX];
1214 char *cert_start = certlist, *cert_end = certlist;
1215 FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
1220 mutt_mktemp (tempfile);
1221 if ((fpout = safe_fopen (tempfile, "w+")) == NULL) {
1222 mutt_perror (tempfile);
1226 mutt_mktemp (smimeerrfile);
1227 if ((smimeerr = safe_fopen (smimeerrfile, "w+")) == NULL) {
1228 mutt_perror (smimeerrfile);
1230 mutt_unlink (tempfile);
1233 mutt_unlink (smimeerrfile);
1235 mutt_mktemp (smimeinfile);
1236 if ((fptmp = safe_fopen (smimeinfile, "w+")) == NULL) {
1237 mutt_perror (smimeinfile);
1238 mutt_unlink (tempfile);
1246 int off = str_len (certfile);
1248 while (*++cert_end && *cert_end != '\n');
1252 snprintf (certfile + off, sizeof (certfile) - off, " %s/%s",
1253 NONULL (SmimeCertificates), cert_start);
1255 cert_start = cert_end;
1259 /* write a MIME entity */
1260 mutt_write_mime_header (a, fptmp);
1261 fputc ('\n', fptmp);
1262 mutt_write_mime_body (a, fptmp);
1266 smime_invoke_encrypt (&smimein, NULL, NULL, -1,
1267 fileno (fpout), fileno (smimeerr),
1268 smimeinfile, certfile)) == -1) {
1270 mutt_unlink (smimeinfile);
1271 mutt_unlink (certfile);
1277 mutt_wait_filter (thepid);
1278 mutt_unlink (smimeinfile);
1279 mutt_unlink (certfile);
1283 empty = (fgetc (fpout) == EOF);
1288 while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL) {
1290 fputs (buf, stdout);
1294 /* pause if there is any error output from SMIME */
1296 mutt_any_key_to_continue (NULL);
1299 /* fatal error while trying to encrypt message */
1301 mutt_any_key_to_continue _("No output from OpenSSL..");
1303 mutt_unlink (tempfile);
1307 t = mutt_new_body ();
1308 t->type = TYPEAPPLICATION;
1309 t->subtype = str_dup ("x-pkcs7-mime");
1310 mutt_set_parameter ("name", "smime.p7m", &t->parameter);
1311 mutt_set_parameter ("smime-type", "enveloped-data", &t->parameter);
1312 t->encoding = ENCBASE64; /* The output of OpenSSL SHOULD be binary */
1314 t->disposition = DISPATTACH;
1315 t->d_filename = str_dup ("smime.p7m");
1316 t->filename = str_dup (tempfile);
1317 t->unlink = 1; /*delete after sending the message */
1327 BODY *smime_sign_message (BODY * a)
1330 char buffer[LONG_STRING];
1331 char signedfile[_POSIX_PATH_MAX], filetosign[_POSIX_PATH_MAX];
1332 FILE *smimein = NULL, *smimeout = NULL, *smimeerr = NULL, *sfp = NULL;
1336 char *intermediates = smime_get_field_from_db (NULL, SmimeDefaultKey, 1, 1);
1338 if (!intermediates) {
1339 mutt_message (_("Warning: Intermediate certificate not found."));
1340 intermediates = SmimeDefaultKey; /* so openssl won't complain in any case */
1343 convert_to_7bit (a); /* Signed data _must_ be in 7-bit format. */
1345 mutt_mktemp (filetosign);
1346 if ((sfp = safe_fopen (filetosign, "w+")) == NULL) {
1347 mutt_perror (filetosign);
1351 mutt_mktemp (signedfile);
1352 if ((smimeout = safe_fopen (signedfile, "w+")) == NULL) {
1353 mutt_perror (signedfile);
1355 mutt_unlink (filetosign);
1359 mutt_write_mime_header (a, sfp);
1361 mutt_write_mime_body (a, sfp);
1366 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
1367 NONULL (SmimeKeys), SmimeDefaultKey);
1369 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
1370 NONULL (SmimeCertificates), SmimeDefaultKey);
1372 snprintf (SmimeIntermediateToUse, sizeof (SmimeIntermediateToUse), "%s/%s",
1373 NONULL (SmimeCertificates), intermediates);
1377 if ((thepid = smime_invoke_sign (&smimein, NULL, &smimeerr,
1378 -1, fileno (smimeout), -1,
1379 filetosign)) == -1) {
1380 mutt_perror (_("Can't open OpenSSL subprocess!"));
1383 mutt_unlink (signedfile);
1384 mutt_unlink (filetosign);
1387 fputs (SmimePass, smimein);
1388 fputc ('\n', smimein);
1392 mutt_wait_filter (thepid);
1394 /* check for errors from OpenSSL */
1398 while (fgets (buffer, sizeof (buffer) - 1, smimeerr) != NULL) {
1400 fputs (buffer, stdout);
1407 empty = (fgetc (smimeout) == EOF);
1410 mutt_unlink (filetosign);
1414 mutt_any_key_to_continue (NULL);
1417 mutt_any_key_to_continue _("No output from OpenSSL...");
1419 mutt_unlink (signedfile);
1420 return (NULL); /* fatal error while signing */
1423 t = mutt_new_body ();
1424 t->type = TYPEMULTIPART;
1425 t->subtype = str_dup ("signed");
1426 t->encoding = ENC7BIT;
1428 t->disposition = DISPINLINE;
1430 mutt_generate_boundary (&t->parameter);
1431 /* check if this can be extracted from private key somehow.... */
1432 mutt_set_parameter ("micalg", "sha1", &t->parameter);
1433 mutt_set_parameter ("protocol", "application/x-pkcs7-signature",
1439 t->parts->next = mutt_new_body ();
1441 t->type = TYPEAPPLICATION;
1442 t->subtype = str_dup ("x-pkcs7-signature");
1443 t->filename = str_dup (signedfile);
1444 t->d_filename = str_dup ("smime.p7s");
1446 t->disposition = DISPATTACH;
1447 t->encoding = ENCBASE64;
1448 t->unlink = 1; /* ok to remove this file after sending. */
1460 * Handling S/MIME - bodies.
1469 pid_t smime_invoke_verify (FILE ** smimein, FILE ** smimeout,
1470 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1471 int smimeerrfd, const char *fname,
1472 const char *sig_fname, int opaque)
1474 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1475 smimeerrfd, fname, sig_fname, NULL, NULL, NULL, NULL,
1476 (opaque ? SmimeVerifyOpaqueCommand :
1477 SmimeVerifyCommand));
1482 pid_t smime_invoke_decrypt (FILE ** smimein, FILE ** smimeout,
1483 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1484 int smimeerrfd, const char *fname)
1486 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1487 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1488 SmimeCertToUse, NULL, SmimeDecryptCommand);
1493 int smime_verify_one (BODY * sigbdy, STATE * s, const char *tempfile)
1495 char signedfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1496 FILE *fp = NULL, *smimeout = NULL, *smimeerr = NULL;
1501 size_t tmplength = 0;
1502 int origType = sigbdy->type;
1503 char *savePrefix = NULL;
1506 snprintf (signedfile, sizeof (signedfile), "%s.sig", tempfile);
1508 /* decode to a tempfile, saving the original destination */
1510 if ((s->fpout = safe_fopen (signedfile, "w")) == NULL) {
1511 mutt_perror (signedfile);
1514 /* decoding the attachment changes the size and offset, so save a copy
1515 * of the "real" values now, and restore them after processing
1517 tmplength = sigbdy->length;
1518 tmpoffset = sigbdy->offset;
1520 /* if we are decoding binary bodies, we don't want to prefix each
1521 * line with the prefix or else the data will get corrupted.
1523 savePrefix = s->prefix;
1526 mutt_decode_attachment (sigbdy, s);
1528 sigbdy->length = ftello (s->fpout);
1532 /* restore final destination and substitute the tempfile for input */
1535 s->fpin = fopen (signedfile, "r");
1537 /* restore the prefix */
1538 s->prefix = savePrefix;
1540 sigbdy->type = origType;
1543 mutt_mktemp (smimeerrfile);
1544 if (!(smimeerr = safe_fopen (smimeerrfile, "w+"))) {
1545 mutt_perror (smimeerrfile);
1546 mutt_unlink (signedfile);
1550 crypt_current_time (s, "OpenSSL");
1552 if ((thepid = smime_invoke_verify (NULL, &smimeout, NULL,
1553 -1, -1, fileno (smimeerr),
1554 tempfile, signedfile, 0)) != -1) {
1558 if (mutt_wait_filter (thepid))
1568 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1569 if (linelen && !str_casecmp (line, "verification successful"))
1578 mutt_copy_stream (smimeerr, s->fpout);
1581 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1583 mutt_unlink (signedfile);
1584 mutt_unlink (smimeerrfile);
1586 sigbdy->length = tmplength;
1587 sigbdy->offset = tmpoffset;
1589 /* restore the original source stream */
1602 This handles application/pkcs7-mime which can either be a signed
1603 or an encrypted message.
1606 static BODY *smime_handle_entity (BODY * m, STATE * s, FILE * outFile)
1611 char buf[HUGE_STRING];
1612 char outfile[_POSIX_PATH_MAX], errfile[_POSIX_PATH_MAX];
1613 char tmpfname[_POSIX_PATH_MAX];
1614 char tmptmpfname[_POSIX_PATH_MAX];
1615 FILE *smimeout = NULL, *smimein = NULL, *smimeerr = NULL;
1616 FILE *tmpfp = NULL, *tmpfp_buffer = NULL, *fpout = NULL;
1620 unsigned int type = mutt_is_application_smime (m);
1622 if (!(type & APPLICATION_SMIME))
1625 mutt_mktemp (outfile);
1626 if ((smimeout = safe_fopen (outfile, "w+")) == NULL) {
1627 mutt_perror (outfile);
1631 mutt_mktemp (errfile);
1632 if ((smimeerr = safe_fopen (errfile, "w+")) == NULL) {
1633 mutt_perror (errfile);
1638 mutt_unlink (errfile);
1641 mutt_mktemp (tmpfname);
1642 if ((tmpfp = safe_fopen (tmpfname, "w+")) == NULL) {
1643 mutt_perror (tmpfname);
1651 fseeko (s->fpin, m->offset, 0);
1652 last_pos = m->offset;
1654 mutt_copy_bytes (s->fpin, tmpfp, m->length);
1659 if ((type & ENCRYPT) &&
1660 (thepid = smime_invoke_decrypt (&smimein, NULL, NULL, -1,
1661 fileno (smimeout), fileno (smimeerr),
1665 mutt_unlink (tmpfname);
1666 if (s->flags & M_DISPLAY)
1667 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1670 else if ((type & SIGNOPAQUE) &&
1671 (thepid = smime_invoke_verify (&smimein, NULL, NULL, -1,
1673 fileno (smimeerr), NULL, tmpfname,
1674 SIGNOPAQUE)) == -1) {
1677 mutt_unlink (tmpfname);
1678 if (s->flags & M_DISPLAY)
1679 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1684 if (type & ENCRYPT) {
1685 if (!smime_valid_passphrase ())
1686 smime_void_passphrase ();
1687 fputs (SmimePass, smimein);
1688 fputc ('\n', smimein);
1693 mutt_wait_filter (thepid);
1694 mutt_unlink (tmpfname);
1697 if (s->flags & M_DISPLAY) {
1700 if ((c = fgetc (smimeerr)) != EOF) {
1701 ungetc (c, smimeerr);
1703 crypt_current_time (s, "OpenSSL");
1704 mutt_copy_stream (smimeerr, s->fpout);
1705 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1709 state_attach_puts (_("[-- The following data is S/MIME"
1710 " encrypted --]\n"), s);
1712 state_attach_puts (_("[-- The following data is S/MIME signed --]\n"),
1723 mutt_mktemp (tmptmpfname);
1724 if ((fpout = safe_fopen (tmptmpfname, "w+")) == NULL) {
1725 mutt_perror (tmptmpfname);
1731 while (fgets (buf, sizeof (buf) - 1, smimeout) != NULL) {
1732 len = str_len (buf);
1733 if (len > 1 && buf[len - 2] == '\r') {
1734 buf[len - 2] = '\n';
1735 buf[len - 1] = '\0';
1743 if ((p = mutt_read_mime_header (fpout, 0)) != NULL) {
1744 fstat (fileno (fpout), &info);
1745 p->length = info.st_size - p->offset;
1747 mutt_parse_part (fpout, p);
1750 tmpfp_buffer = s->fpin;
1752 mutt_body_handler (p, s);
1753 s->fpin = tmpfp_buffer;
1759 mutt_unlink (outfile);
1763 mutt_unlink (tmptmpfname);
1768 if (s->flags & M_DISPLAY) {
1770 state_attach_puts (_("\n[-- End of S/MIME encrypted data. --]\n"), s);
1772 state_attach_puts (_("\n[-- End of S/MIME signed data. --]\n"), s);
1775 if (type & SIGNOPAQUE) {
1782 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1783 if (linelen && !str_casecmp (line, "verification successful"))
1788 m->goodsig = p->goodsig;
1789 m->badsig = p->badsig;
1800 int smime_decrypt_mime (FILE * fpin, FILE ** fpout, BODY * b, BODY ** cur)
1804 char tempfile[_POSIX_PATH_MAX];
1806 long tmpoffset = b->offset;
1807 size_t tmplength = b->length;
1808 int origType = b->type;
1812 if (!mutt_is_application_smime (b))
1818 memset (&s, 0, sizeof (s));
1820 fseeko (s.fpin, b->offset, 0);
1822 mutt_mktemp (tempfile);
1823 if ((tmpfp = safe_fopen (tempfile, "w+")) == NULL) {
1824 mutt_perror (tempfile);
1828 mutt_unlink (tempfile);
1830 mutt_decode_attachment (b, &s);
1832 b->length = ftello (s.fpout);
1838 mutt_mktemp (tempfile);
1839 if ((*fpout = safe_fopen (tempfile, "w+")) == NULL) {
1840 mutt_perror (tempfile);
1844 mutt_unlink (tempfile);
1846 if (!(*cur = smime_handle_entity (b, &s, *fpout))) {
1851 (*cur)->goodsig = b->goodsig;
1852 (*cur)->badsig = b->badsig;
1856 b->length = tmplength;
1857 b->offset = tmpoffset;
1859 safe_fclose (&tmpfp);
1866 int smime_application_smime_handler (BODY * m, STATE * s)
1868 return smime_handle_entity (m, s, NULL) ? 0 : -1;
1871 int smime_send_menu (HEADER * msg, int *redraw)
1875 if (!(WithCrypto & APPLICATION_SMIME))
1876 return msg->security;
1878 switch (mutt_multi_choice
1880 ("S/MIME (e)ncrypt, (s)ign, encrypt (w)ith, sign (a)s, (b)oth, or (c)lear? "),
1882 case 1: /* (e)ncrypt */
1883 msg->security |= ENCRYPT;
1884 msg->security &= ~SIGN;
1887 case 3: /* encrypt (w)ith */
1890 msg->security |= ENCRYPT;
1893 /* I use "dra" because "123" is recognized anyway */
1894 switch (mutt_multi_choice (_("Choose algorithm family:"
1895 " 1: DES, 2: RC2, 3: AES,"
1896 " or (c)lear? "), _("drac"))) {
1898 switch (choice = mutt_multi_choice (_("1: DES, 2: Triple-DES "),
1901 str_replace (&SmimeCryptAlg, "des");
1904 str_replace (&SmimeCryptAlg, "des3");
1910 switch (choice = mutt_multi_choice (_("1: RC2-40, 2: RC2-64, 3: RC2-128 "),
1913 str_replace (&SmimeCryptAlg, "rc2-40");
1916 str_replace (&SmimeCryptAlg, "rc2-64");
1919 str_replace (&SmimeCryptAlg, "rc2-128");
1925 switch (choice = mutt_multi_choice (_("1: AES128, 2: AES192, 3: AES256 "),
1928 str_replace (&SmimeCryptAlg, "aes128");
1931 str_replace (&SmimeCryptAlg, "aes192");
1934 str_replace (&SmimeCryptAlg, "aes256");
1939 case 4: /* (c)lear */
1940 p_delete(&SmimeCryptAlg);
1942 case -1: /* Ctrl-G or Enter */
1946 } while (choice == -1);
1950 case 2: /* (s)ign */
1952 if (!SmimeDefaultKey)
1953 mutt_message (_("Can't sign: No key specified. Use Sign As."));
1956 msg->security |= SIGN;
1957 msg->security &= ~ENCRYPT;
1961 case 4: /* sign (a)s */
1963 if ((p = smime_ask_for_key (_("Sign as: "), NULL, 0))) {
1964 str_replace (&SmimeDefaultKey, p);
1966 msg->security |= SIGN;
1968 /* probably need a different passphrase */
1969 crypt_smime_void_passphrase ();
1973 msg->security &= ~SIGN;
1976 *redraw = REDRAW_FULL;
1979 case 5: /* (b)oth */
1980 msg->security |= (ENCRYPT | SIGN);
1983 case 6: /* (f)orget it */
1984 case 7: /* (c)lear */
1989 if (msg->security && msg->security != APPLICATION_SMIME)
1990 msg->security |= APPLICATION_SMIME;
1994 return (msg->security);
1998 #endif /* CRYPT_BACKEND_CLASSIC_SMIME */