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>
17 #include <lib-lib/str.h>
18 #include <lib-lib/macros.h>
19 #include <lib-lib/file.h>
21 #include <lib-mime/mime.h>
26 #include "mutt_curses.h"
27 #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>
54 struct smime_command_context {
55 const char *key; /* %k */
56 const char *cryptalg; /* %a */
57 const char *fname; /* %f */
58 const char *sig_fname; /* %s */
59 const char *certificates; /* %c */
60 const char *intermediates; /* %i */
69 char trust; /* i=Invalid r=revoked e=expired u=unverified v=verified t=trusted */
70 short public; /* 1=public 0=private */
74 char SmimePass[STRING];
75 time_t SmimeExptime = 0; /* when does the cached passphrase expire? */
78 static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
79 static char SmimeCertToUse[_POSIX_PATH_MAX];
80 static char SmimeIntermediateToUse[_POSIX_PATH_MAX];
84 * Create a format string to be used with scanf.
85 * To use it, write, for instance, MUTT_FORMAT(HUGE_STRING).
87 * See K&R 2nd ed, p. 231 for an explanation.
89 #define _MUTT_FORMAT_2(a,b) "%" a b
90 #define _MUTT_FORMAT_1(a, b) _MUTT_FORMAT_2(#a, b)
91 #define MUTT_FORMAT(a) _MUTT_FORMAT_1(a, "s")
95 * Queries and passphrase handling.
99 /* these are copies from pgp.c */
102 void smime_void_passphrase (void)
104 p_clear(SmimePass, sizeof(SmimePass));
108 int smime_valid_passphrase (void)
110 time_t now = time (NULL);
112 if (now < SmimeExptime)
113 /* Use cached copy. */
116 smime_void_passphrase ();
118 if (mutt_get_field_unbuffered (_("Enter S/MIME passphrase:"), SmimePass,
119 sizeof (SmimePass), M_PASS) == 0) {
120 SmimeExptime = time (NULL) + SmimeTimeout;
131 * The OpenSSL interface
134 /* This is almost identical to ppgp's invoking interface. */
136 static const char *_mutt_fmt_smime_command (char *dest,
141 const char *ifstring,
142 const char *elsestring,
147 struct smime_command_context *cctx = (struct smime_command_context *) data;
148 int optional = (flags & M_FORMAT_OPTIONAL);
154 char path[_POSIX_PATH_MAX];
155 char buf1[LONG_STRING], buf2[LONG_STRING];
158 m_strcpy(path, sizeof(path), NONULL(SmimeCALocation));
159 mutt_expand_path (path, sizeof (path));
160 mutt_quote_filename (buf1, sizeof (buf1), path);
162 if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
163 snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
165 snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
167 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
168 snprintf (dest, destlen, fmt, buf2);
170 else if (!SmimeCALocation)
176 { /* certificate (list) */
178 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
179 snprintf (dest, destlen, fmt, NONULL (cctx->certificates));
181 else if (!cctx->certificates)
187 { /* intermediate certificates */
189 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
190 snprintf (dest, destlen, fmt, NONULL (cctx->intermediates));
192 else if (!cctx->intermediates)
198 { /* detached signature */
200 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
201 snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
203 else if (!cctx->sig_fname)
211 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
212 snprintf (dest, destlen, fmt, NONULL (cctx->key));
220 { /* algorithm for encryption */
222 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
223 snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
231 { /* file to process */
233 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
234 snprintf (dest, destlen, fmt, NONULL (cctx->fname));
236 else if (!cctx->fname)
247 mutt_FormatString (dest, destlen, ifstring, _mutt_fmt_smime_command,
249 else if (flags & M_FORMAT_OPTIONAL)
250 mutt_FormatString (dest, destlen, elsestring, _mutt_fmt_smime_command,
258 static void mutt_smime_command (char *d, size_t dlen,
259 struct smime_command_context *cctx,
262 mutt_FormatString (d, dlen, NONULL (fmt), _mutt_fmt_smime_command,
263 (unsigned long) cctx, 0);
264 debug_print (2, ("%s\n", d));
267 static pid_t smime_invoke (FILE ** smimein, FILE ** smimeout,
268 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
269 int smimeerrfd, const char *fname,
270 const char *sig_fname, const char *cryptalg,
271 const char *key, const char *certificates,
272 const char *intermediates, const char *format)
274 struct smime_command_context cctx;
275 char cmd[HUGE_STRING];
279 if (!format || !*format)
283 cctx.sig_fname = sig_fname;
285 cctx.cryptalg = cryptalg;
286 cctx.certificates = certificates;
287 cctx.intermediates = intermediates;
289 mutt_smime_command (cmd, sizeof (cmd), &cctx, format);
291 return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
292 smimeinfd, smimeoutfd, smimeerrfd);
301 * Key and certificate handling.
307 Search the certificate index for given mailbox.
308 return certificate file name.
311 static void smime_entry (char *s, size_t l, MUTTMENU * menu, int num)
313 smime_id *Table = (smime_id *) menu->data;
314 smime_id this = Table[num];
315 const char *truststate;
317 switch (this.trust) {
319 truststate = N_("Trusted ");
322 truststate = N_("Verified ");
325 truststate = N_("Unverified");
328 truststate = N_("Expired ");
331 truststate = N_("Revoked ");
334 truststate = N_("Invalid ");
337 truststate = N_("Unknown ");
340 snprintf (s, l, " 0x%.8X.%i %s %-35.35s %s", this.hash, this.suffix,
341 truststate, this.email, this.nick);
343 snprintf (s, l, " 0x%.8X.%i %-35.35s %s", this.hash, this.suffix,
344 this.email, this.nick);
351 char *smime_ask_for_key (char *prompt, char *mailbox, short public)
355 long cert_num; /* Will contain the number of certificates.
356 * To be able to get it, the .index file will be read twice... */
357 char index_file[_POSIX_PATH_MAX];
359 char buf[LONG_STRING];
360 char fields[5][STRING];
361 int numFields, hash_suffix, done, cur; /* The current entry */
364 char helpstr[HUGE_STRING * 3];
369 prompt = _("Enter keyID: ");
370 snprintf (index_file, sizeof (index_file), "%s/.index",
371 public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys));
373 index = fopen (index_file, "r");
375 mutt_perror (index_file);
380 while (!feof (index)) {
381 if (fgets (buf, sizeof (buf), index))
388 if (mutt_get_field (prompt, qry, sizeof (qry), 0))
390 snprintf (title, sizeof (title),
391 _("S/MIME certificates matching \"%s\"."), qry);
394 index = fopen (index_file, "r");
396 mutt_perror (index_file);
401 Table = p_new(smime_id, cert_num);
402 while (!feof (index)) {
404 fscanf (index, MUTT_FORMAT (STRING) " %x.%i " MUTT_FORMAT (STRING),
405 fields[0], &hash, &hash_suffix, fields[2]);
407 fscanf (index, MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) "\n",
408 fields[3], fields[4]);
410 /* 0=email 1=name 2=nick 3=intermediate 4=trust */
414 /* Check if query matches this certificate */
415 if (!m_stristr(fields[0], qry) && !m_stristr(fields[2], qry))
418 Table[cur].hash = hash;
419 Table[cur].suffix = hash_suffix;
420 m_strcpy(Table[cur].email, sizeof(Table[cur].email), fields[0]);
421 m_strcpy(Table[cur].nick, sizeof(Table[cur].nick), fields[2]);
422 Table[cur].trust = *fields[4];
423 Table[cur].public = public;
429 /* Make Helpstring */
431 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_SMIME, OP_EXIT);
432 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
433 mutt_make_help (buf, sizeof (buf), _("Select "), MENU_SMIME,
434 OP_GENERIC_SELECT_ENTRY);
435 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
436 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_SMIME, OP_HELP);
437 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
439 /* Create the menu */
440 menu = mutt_new_menu ();
442 menu->make_entry = smime_entry;
443 menu->menu = MENU_SMIME;
444 menu->help = helpstr;
447 /* sorting keys might be done later - TODO */
454 switch (mutt_menuLoop (menu)) {
455 case OP_GENERIC_SELECT_ENTRY:
467 fname = p_new(char, 13); /* Hash + '.' + Suffix + \0 */
468 sprintf (fname, "%.8x.%i", Table[cur].hash, Table[cur].suffix);
473 mutt_menuDestroy (&menu);
475 set_option (OPTNEEDREDRAW);
484 char *smime_get_field_from_db (char *mailbox, char *query, short public,
487 int addr_len, query_len, found = 0, ask = 0, choice = 0;
488 char cert_path[_POSIX_PATH_MAX];
489 char buf[LONG_STRING], prompt[STRING];
490 char fields[5][STRING];
494 char key_trust_level = 0;
497 if (!mailbox && !query)
500 addr_len = mailbox ? m_strlen(mailbox) : 0;
501 query_len = query ? m_strlen(query) : 0;
505 /* index-file format:
506 mailbox certfile label issuer_certfile trust_flags\n
508 certfile is a hash value generated by openssl.
509 Note that this was done according to the OpenSSL
510 specs on their CA-directory.
513 snprintf (cert_path, sizeof (cert_path), "%s/.index",
514 (public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys)));
516 if (!stat (cert_path, &info)) {
517 if ((fp = safe_fopen (cert_path, "r")) == NULL) {
518 mutt_perror (cert_path);
522 while (fgets (buf, sizeof (buf) - 1, fp) != NULL)
523 if (mailbox && !(m_strncasecmp(mailbox, buf, addr_len))) {
524 numFields = sscanf (buf,
525 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
526 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
527 MUTT_FORMAT (STRING) "\n",
528 fields[0], fields[1],
529 fields[2], fields[3], fields[4]);
532 if (mailbox && public &&
534 *fields[4] == 'i' || *fields[4] == 'e' || *fields[4] == 'r'))
538 if (public && *fields[4] == 'u')
539 snprintf (prompt, sizeof (prompt),
541 ("ID %s is unverified. Do you want to use it for %s ?"),
543 else if (public && *fields[4] == 'v')
544 snprintf (prompt, sizeof (prompt),
545 _("Use (untrusted!) ID %s for %s ?"),
548 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"),
552 if (may_ask && (choice = mutt_yesorno (prompt, M_NO)) == -1) {
558 else if (choice == M_NO) {
562 else if (choice == M_YES) {
563 m_strcpy(key, sizeof(key), fields[1]);
570 key_trust_level = *fields[4];
571 m_strcpy(key, sizeof(key), fields[1]);
576 numFields = sscanf (buf,
577 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
578 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
579 MUTT_FORMAT (STRING) "\n",
580 fields[0], fields[1],
581 fields[2], fields[3], fields[4]);
583 /* query = label: return certificate. */
584 if (numFields >= 3 &&
585 !(m_strncasecmp(query, fields[2], query_len))) {
587 m_strcpy(key, sizeof(key), fields[1]);
589 /* query = certificate: return intermediate certificate. */
590 else if (numFields >= 4 &&
591 !(m_strncasecmp(query, fields[1], query_len))) {
593 m_strcpy(key, sizeof(key), fields[3]);
600 if (public && *fields[4] == 'u')
601 snprintf (prompt, sizeof (prompt),
602 _("ID %s is unverified. Do you want to use it for %s ?"),
604 else if (public && *fields[4] == 'v')
605 snprintf (prompt, sizeof (prompt),
606 _("Use (untrusted!) ID %s for %s ?"), fields[1], mailbox);
608 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"), key,
610 choice = mutt_yesorno (prompt, M_NO);
611 if (choice == -1 || choice == M_NO)
614 else if (key_trust_level && may_ask) {
615 if (key_trust_level == 'u') {
616 snprintf (prompt, sizeof (prompt),
617 _("ID %s is unverified. Do you want to use it for %s ?"),
619 choice = mutt_yesorno (prompt, M_NO);
623 else if (key_trust_level == 'v') {
625 ("Warning: You have not yet decided to trust ID %s. (any key to continue)"),
633 /* Note: m_strdup("") returns NULL. */
634 return m_strdup(key);
641 This sets the '*ToUse' variables for an upcoming decryption, where
642 the reuquired key is different from SmimeDefaultKey.
645 void _smime_getkeys (char *mailbox)
650 k = smime_get_field_from_db (mailbox, NULL, 0, 1);
653 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), mailbox);
654 k = smime_ask_for_key (buf, mailbox, 0);
658 /* the key used last time. */
659 if (*SmimeKeyToUse &&
660 !m_strcasecmp(k, SmimeKeyToUse + m_strlen(SmimeKeys) + 1)) {
665 smime_void_passphrase ();
667 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
668 NONULL (SmimeKeys), k);
670 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
671 NONULL (SmimeCertificates), k);
673 if (m_strcasecmp(k, SmimeDefaultKey))
674 smime_void_passphrase ();
680 if (*SmimeKeyToUse) {
681 if (!m_strcasecmp(SmimeDefaultKey,
682 SmimeKeyToUse + m_strlen(SmimeKeys) + 1))
685 smime_void_passphrase ();
688 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
689 NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
691 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
692 NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
695 void smime_getkeys (ENVELOPE * env)
700 if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey) {
701 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
702 NONULL (SmimeKeys), SmimeDefaultKey);
704 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
705 NONULL (SmimeCertificates), SmimeDefaultKey);
710 for (t = env->to; !found && t; t = t->next)
711 if (mutt_addr_is_user (t)) {
713 _smime_getkeys (t->mailbox);
715 for (t = env->cc; !found && t; t = t->next)
716 if (mutt_addr_is_user (t)) {
718 _smime_getkeys (t->mailbox);
720 if (!found && (t = mutt_default_from ())) {
721 _smime_getkeys (t->mailbox);
726 /* This routine attempts to find the keyids of the recipients of a message.
727 * It returns NULL if any of the keys can not be found.
730 char *smime_findKeys (address_t * to, address_t * cc, address_t * bcc)
732 char *keyID, *keylist = NULL;
733 size_t keylist_size = 0;
734 size_t keylist_used = 0;
735 address_t *tmp = NULL, *addr = NULL;
736 address_t **last = &tmp;
740 const char *fqdn = mutt_fqdn (1);
742 for (i = 0; i < 3; i++) {
757 *last = address_list_dup (p);
759 last = &((*last)->next);
763 rfc822_qualify (tmp, fqdn);
765 tmp = mutt_remove_duplicates (tmp);
767 for (p = tmp; p; p = p->next) {
768 char buf[LONG_STRING];
772 if ((keyID = smime_get_field_from_db (q->mailbox, NULL, 1, 1)) == NULL) {
773 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), q->mailbox);
774 keyID = smime_ask_for_key (buf, q->mailbox, 1);
777 mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
779 address_delete (&tmp);
780 address_delete (&addr);
784 keylist_size += m_strlen(keyID) + 2;
785 p_realloc(&keylist, keylist_size);
786 sprintf (keylist + keylist_used, "%s\n", keyID); /* __SPRINTF_CHECKED__ */
787 keylist_used = m_strlen(keylist);
789 address_delete (&addr);
792 address_delete (&tmp);
801 static int smime_handle_cert_email (char *certificate, char *mailbox,
802 int copy, char ***buffer, int *num)
804 FILE *fpout = NULL, *fperr = NULL;
805 char tmpfname[_POSIX_PATH_MAX];
807 int ret = -1, count = 0;
810 mutt_mktemp (tmpfname);
811 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
812 mutt_perror (tmpfname);
815 mutt_unlink (tmpfname);
817 mutt_mktemp (tmpfname);
818 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
820 mutt_perror (tmpfname);
823 mutt_unlink (tmpfname);
825 if ((thepid = smime_invoke (NULL, NULL, NULL,
826 -1, fileno (fpout), fileno (fperr),
827 certificate, NULL, NULL, NULL, NULL, NULL,
828 SmimeGetCertEmailCommand)) == -1) {
829 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
835 mutt_wait_filter (thepid);
843 while ((fgets (email, sizeof (email), fpout))) {
844 *(email + m_strlen(email) - 1) = '\0';
845 if (m_strncasecmp(email, mailbox, m_strlen(mailbox)) == 0)
848 ret = ret < 0 ? 0 : ret;
854 mutt_copy_stream (fperr, stdout);
855 mutt_any_key_to_continue (_
856 ("Error: unable to create OpenSSL subprocess!"));
864 if (copy && buffer && num) {
866 *buffer = p_new(char *, count);
870 while ((fgets (email, sizeof (email), fpout))) {
871 *(email + m_strlen(email) - 1) = '\0';
872 (*buffer)[count] = p_dupstr(email, m_strlen(email));
887 static char *smime_extract_certificate (char *infile)
889 FILE *fpout = NULL, *fperr = NULL;
890 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
891 char tmpfname[_POSIX_PATH_MAX];
896 mutt_mktemp (tmpfname);
897 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
898 mutt_perror (tmpfname);
901 mutt_unlink (tmpfname);
903 mutt_mktemp (pk7out);
904 if ((fpout = safe_fopen (pk7out, "w+")) == NULL) {
906 mutt_perror (pk7out);
910 /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
911 extract the full set of certificates directly.
913 if ((thepid = smime_invoke (NULL, NULL, NULL,
914 -1, fileno (fpout), fileno (fperr),
915 infile, NULL, NULL, NULL, NULL, NULL,
916 SmimePk7outCommand)) == -1) {
917 mutt_any_key_to_continue (_
918 ("Error: unable to create OpenSSL subprocess!"));
921 mutt_unlink (pk7out);
925 mutt_wait_filter (thepid);
932 empty = (fgetc (fpout) == EOF);
934 mutt_perror (pk7out);
935 mutt_copy_stream (fperr, stdout);
938 mutt_unlink (pk7out);
945 mutt_mktemp (certfile);
946 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
948 mutt_unlink (pk7out);
949 mutt_perror (certfile);
953 /* Step 2: Extract the certificates from a PKCS#7 structure.
955 if ((thepid = smime_invoke (NULL, NULL, NULL,
956 -1, fileno (fpout), fileno (fperr),
957 pk7out, NULL, NULL, NULL, NULL, NULL,
958 SmimeGetCertCommand)) == -1) {
959 mutt_any_key_to_continue (_
960 ("Error: unable to create OpenSSL subprocess!"));
963 mutt_unlink (pk7out);
964 mutt_unlink (certfile);
968 mutt_wait_filter (thepid);
970 mutt_unlink (pk7out);
976 empty = (fgetc (fpout) == EOF);
978 mutt_copy_stream (fperr, stdout);
981 mutt_unlink (certfile);
988 return m_strdup(certfile);
991 static char *smime_extract_signer_certificate (char *infile)
993 FILE *fpout = NULL, *fperr = NULL;
994 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
995 char tmpfname[_POSIX_PATH_MAX];
1000 mutt_mktemp (tmpfname);
1001 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
1002 mutt_perror (tmpfname);
1005 mutt_unlink (tmpfname);
1008 mutt_mktemp (certfile);
1009 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
1011 mutt_perror (certfile);
1015 /* Extract signer's certificate
1017 if ((thepid = smime_invoke (NULL, NULL, NULL,
1018 -1, -1, fileno (fperr),
1019 infile, NULL, NULL, NULL, certfile, NULL,
1020 SmimeGetSignerCertCommand)) == -1) {
1021 mutt_any_key_to_continue (_
1022 ("Error: unable to create OpenSSL subprocess!"));
1025 mutt_unlink (pk7out);
1026 mutt_unlink (certfile);
1030 mutt_wait_filter (thepid);
1036 empty = (fgetc (fpout) == EOF);
1039 mutt_copy_stream (fperr, stdout);
1040 mutt_any_key_to_continue (NULL);
1043 mutt_unlink (certfile);
1050 return m_strdup(certfile);
1056 /* Add a certificate and update index file (externally). */
1058 void smime_invoke_import (char *infile, char *mailbox)
1060 char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
1061 FILE *smimein = NULL, *fpout = NULL, *fperr = NULL;
1064 mutt_mktemp (tmpfname);
1065 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
1066 mutt_perror (tmpfname);
1069 mutt_unlink (tmpfname);
1071 mutt_mktemp (tmpfname);
1072 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
1074 mutt_perror (tmpfname);
1077 mutt_unlink (tmpfname);
1081 if (option (OPTASKCERTLABEL))
1082 mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1085 if ((certfile = smime_extract_certificate (infile))) {
1088 if ((thepid = smime_invoke (&smimein, NULL, NULL,
1089 -1, fileno (fpout), fileno (fperr),
1090 certfile, NULL, NULL, NULL, NULL, NULL,
1091 SmimeImportCertCommand)) == -1) {
1092 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
1095 fputs (buf, smimein);
1096 fputc ('\n', smimein);
1099 mutt_wait_filter (thepid);
1101 mutt_unlink (certfile);
1102 p_delete(&certfile);
1110 mutt_copy_stream (fpout, stdout);
1111 mutt_copy_stream (fperr, stdout);
1120 int smime_verify_sender (HEADER * h)
1122 char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
1126 mutt_mktemp (tempfname);
1127 if (!(fpout = safe_fopen (tempfname, "w"))) {
1128 mutt_perror (tempfname);
1132 if (h->security & ENCRYPT)
1133 mutt_copy_message (fpout, Context, h,
1134 M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1135 CH_MIME | CH_WEED | CH_NONEWLINE);
1137 mutt_copy_message (fpout, Context, h, 0, 0);
1143 h->env->from = mutt_expand_aliases (h->env->from);
1144 mbox = h->env->from->mailbox;
1146 else if (h->env->sender) {
1147 h->env->sender = mutt_expand_aliases (h->env->sender);
1148 mbox = h->env->sender->mailbox;
1152 if ((certfile = smime_extract_signer_certificate (tempfname))) {
1153 mutt_unlink (tempfname);
1154 if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL)) {
1156 mutt_any_key_to_continue (NULL);
1160 mutt_unlink (certfile);
1161 p_delete(&certfile);
1164 mutt_any_key_to_continue (_("no certfile"));
1167 mutt_any_key_to_continue (_("no mbox"));
1169 mutt_unlink (tempfname);
1182 * Creating S/MIME - bodies.
1189 pid_t smime_invoke_encrypt (FILE ** smimein, FILE ** smimeout,
1190 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1191 int smimeerrfd, const char *fname,
1194 return smime_invoke (smimein, smimeout, smimeerr,
1195 smimeinfd, smimeoutfd, smimeerrfd,
1196 fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
1197 SmimeEncryptCommand);
1202 pid_t smime_invoke_sign (FILE ** smimein, FILE ** smimeout, FILE ** smimeerr,
1203 int smimeinfd, int smimeoutfd, int smimeerrfd,
1206 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1207 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1208 SmimeCertToUse, SmimeIntermediateToUse,
1215 BODY *smime_build_smime_entity (BODY * a, char *certlist)
1217 char buf[LONG_STRING], certfile[LONG_STRING];
1218 char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1219 char smimeinfile[_POSIX_PATH_MAX];
1220 char *cert_start = certlist, *cert_end = certlist;
1221 FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
1226 mutt_mktemp (tempfile);
1227 if ((fpout = safe_fopen (tempfile, "w+")) == NULL) {
1228 mutt_perror (tempfile);
1232 mutt_mktemp (smimeerrfile);
1233 if ((smimeerr = safe_fopen (smimeerrfile, "w+")) == NULL) {
1234 mutt_perror (smimeerrfile);
1236 mutt_unlink (tempfile);
1239 mutt_unlink (smimeerrfile);
1241 mutt_mktemp (smimeinfile);
1242 if ((fptmp = safe_fopen (smimeinfile, "w+")) == NULL) {
1243 mutt_perror (smimeinfile);
1244 mutt_unlink (tempfile);
1252 int off = m_strlen(certfile);
1254 while (*++cert_end && *cert_end != '\n');
1258 snprintf (certfile + off, sizeof (certfile) - off, " %s/%s",
1259 NONULL (SmimeCertificates), cert_start);
1261 cert_start = cert_end;
1265 /* write a MIME entity */
1266 mutt_write_mime_header (a, fptmp);
1267 fputc ('\n', fptmp);
1268 mutt_write_mime_body (a, fptmp);
1272 smime_invoke_encrypt (&smimein, NULL, NULL, -1,
1273 fileno (fpout), fileno (smimeerr),
1274 smimeinfile, certfile)) == -1) {
1276 mutt_unlink (smimeinfile);
1277 mutt_unlink (certfile);
1283 mutt_wait_filter (thepid);
1284 mutt_unlink (smimeinfile);
1285 mutt_unlink (certfile);
1289 empty = (fgetc (fpout) == EOF);
1294 while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL) {
1296 fputs (buf, stdout);
1300 /* pause if there is any error output from SMIME */
1302 mutt_any_key_to_continue (NULL);
1305 /* fatal error while trying to encrypt message */
1307 mutt_any_key_to_continue _("No output from OpenSSL..");
1309 mutt_unlink (tempfile);
1313 t = mutt_new_body ();
1314 t->type = TYPEAPPLICATION;
1315 t->subtype = m_strdup("x-pkcs7-mime");
1316 mutt_set_parameter ("name", "smime.p7m", &t->parameter);
1317 mutt_set_parameter ("smime-type", "enveloped-data", &t->parameter);
1318 t->encoding = ENCBASE64; /* The output of OpenSSL SHOULD be binary */
1320 t->disposition = DISPATTACH;
1321 t->d_filename = m_strdup("smime.p7m");
1322 t->filename = m_strdup(tempfile);
1323 t->unlink = 1; /*delete after sending the message */
1333 BODY *smime_sign_message (BODY * a)
1336 char buffer[LONG_STRING];
1337 char signedfile[_POSIX_PATH_MAX], filetosign[_POSIX_PATH_MAX];
1338 FILE *smimein = NULL, *smimeout = NULL, *smimeerr = NULL, *sfp = NULL;
1342 char *intermediates = smime_get_field_from_db (NULL, SmimeDefaultKey, 1, 1);
1344 if (!intermediates) {
1345 mutt_message (_("Warning: Intermediate certificate not found."));
1346 intermediates = SmimeDefaultKey; /* so openssl won't complain in any case */
1349 convert_to_7bit (a); /* Signed data _must_ be in 7-bit format. */
1351 mutt_mktemp (filetosign);
1352 if ((sfp = safe_fopen (filetosign, "w+")) == NULL) {
1353 mutt_perror (filetosign);
1357 mutt_mktemp (signedfile);
1358 if ((smimeout = safe_fopen (signedfile, "w+")) == NULL) {
1359 mutt_perror (signedfile);
1361 mutt_unlink (filetosign);
1365 mutt_write_mime_header (a, sfp);
1367 mutt_write_mime_body (a, sfp);
1372 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
1373 NONULL (SmimeKeys), SmimeDefaultKey);
1375 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
1376 NONULL (SmimeCertificates), SmimeDefaultKey);
1378 snprintf (SmimeIntermediateToUse, sizeof (SmimeIntermediateToUse), "%s/%s",
1379 NONULL (SmimeCertificates), intermediates);
1383 if ((thepid = smime_invoke_sign (&smimein, NULL, &smimeerr,
1384 -1, fileno (smimeout), -1,
1385 filetosign)) == -1) {
1386 mutt_perror (_("Can't open OpenSSL subprocess!"));
1389 mutt_unlink (signedfile);
1390 mutt_unlink (filetosign);
1393 fputs (SmimePass, smimein);
1394 fputc ('\n', smimein);
1398 mutt_wait_filter (thepid);
1400 /* check for errors from OpenSSL */
1404 while (fgets (buffer, sizeof (buffer) - 1, smimeerr) != NULL) {
1406 fputs (buffer, stdout);
1413 empty = (fgetc (smimeout) == EOF);
1416 mutt_unlink (filetosign);
1420 mutt_any_key_to_continue (NULL);
1423 mutt_any_key_to_continue _("No output from OpenSSL...");
1425 mutt_unlink (signedfile);
1426 return (NULL); /* fatal error while signing */
1429 t = mutt_new_body ();
1430 t->type = TYPEMULTIPART;
1431 t->subtype = m_strdup("signed");
1432 t->encoding = ENC7BIT;
1434 t->disposition = DISPINLINE;
1436 mutt_generate_boundary (&t->parameter);
1437 /* check if this can be extracted from private key somehow.... */
1438 mutt_set_parameter ("micalg", "sha1", &t->parameter);
1439 mutt_set_parameter ("protocol", "application/x-pkcs7-signature",
1445 t->parts->next = mutt_new_body ();
1447 t->type = TYPEAPPLICATION;
1448 t->subtype = m_strdup("x-pkcs7-signature");
1449 t->filename = m_strdup(signedfile);
1450 t->d_filename = m_strdup("smime.p7s");
1452 t->disposition = DISPATTACH;
1453 t->encoding = ENCBASE64;
1454 t->unlink = 1; /* ok to remove this file after sending. */
1466 * Handling S/MIME - bodies.
1475 pid_t smime_invoke_verify (FILE ** smimein, FILE ** smimeout,
1476 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1477 int smimeerrfd, const char *fname,
1478 const char *sig_fname, int opaque)
1480 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1481 smimeerrfd, fname, sig_fname, NULL, NULL, NULL, NULL,
1482 (opaque ? SmimeVerifyOpaqueCommand :
1483 SmimeVerifyCommand));
1488 pid_t smime_invoke_decrypt (FILE ** smimein, FILE ** smimeout,
1489 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1490 int smimeerrfd, const char *fname)
1492 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1493 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1494 SmimeCertToUse, NULL, SmimeDecryptCommand);
1499 int smime_verify_one (BODY * sigbdy, STATE * s, const char *tempfile)
1501 char signedfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1502 FILE *fp = NULL, *smimeout = NULL, *smimeerr = NULL;
1507 size_t tmplength = 0;
1508 int origType = sigbdy->type;
1509 char *savePrefix = NULL;
1512 snprintf (signedfile, sizeof (signedfile), "%s.sig", tempfile);
1514 /* decode to a tempfile, saving the original destination */
1516 if ((s->fpout = safe_fopen (signedfile, "w")) == NULL) {
1517 mutt_perror (signedfile);
1520 /* decoding the attachment changes the size and offset, so save a copy
1521 * of the "real" values now, and restore them after processing
1523 tmplength = sigbdy->length;
1524 tmpoffset = sigbdy->offset;
1526 /* if we are decoding binary bodies, we don't want to prefix each
1527 * line with the prefix or else the data will get corrupted.
1529 savePrefix = s->prefix;
1532 mutt_decode_attachment (sigbdy, s);
1534 sigbdy->length = ftello (s->fpout);
1538 /* restore final destination and substitute the tempfile for input */
1541 s->fpin = fopen (signedfile, "r");
1543 /* restore the prefix */
1544 s->prefix = savePrefix;
1546 sigbdy->type = origType;
1549 mutt_mktemp (smimeerrfile);
1550 if (!(smimeerr = safe_fopen (smimeerrfile, "w+"))) {
1551 mutt_perror (smimeerrfile);
1552 mutt_unlink (signedfile);
1556 crypt_current_time (s, "OpenSSL");
1558 if ((thepid = smime_invoke_verify (NULL, &smimeout, NULL,
1559 -1, -1, fileno (smimeerr),
1560 tempfile, signedfile, 0)) != -1) {
1564 if (mutt_wait_filter (thepid))
1574 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1575 if (linelen && !m_strcasecmp(line, "verification successful"))
1584 mutt_copy_stream (smimeerr, s->fpout);
1587 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1589 mutt_unlink (signedfile);
1590 mutt_unlink (smimeerrfile);
1592 sigbdy->length = tmplength;
1593 sigbdy->offset = tmpoffset;
1595 /* restore the original source stream */
1608 This handles application/pkcs7-mime which can either be a signed
1609 or an encrypted message.
1612 static BODY *smime_handle_entity (BODY * m, STATE * s, FILE * outFile)
1617 char buf[HUGE_STRING];
1618 char outfile[_POSIX_PATH_MAX], errfile[_POSIX_PATH_MAX];
1619 char tmpfname[_POSIX_PATH_MAX];
1620 char tmptmpfname[_POSIX_PATH_MAX];
1621 FILE *smimeout = NULL, *smimein = NULL, *smimeerr = NULL;
1622 FILE *tmpfp = NULL, *tmpfp_buffer = NULL, *fpout = NULL;
1626 unsigned int type = mutt_is_application_smime (m);
1628 if (!(type & APPLICATION_SMIME))
1631 mutt_mktemp (outfile);
1632 if ((smimeout = safe_fopen (outfile, "w+")) == NULL) {
1633 mutt_perror (outfile);
1637 mutt_mktemp (errfile);
1638 if ((smimeerr = safe_fopen (errfile, "w+")) == NULL) {
1639 mutt_perror (errfile);
1644 mutt_unlink (errfile);
1647 mutt_mktemp (tmpfname);
1648 if ((tmpfp = safe_fopen (tmpfname, "w+")) == NULL) {
1649 mutt_perror (tmpfname);
1657 fseeko (s->fpin, m->offset, 0);
1658 last_pos = m->offset;
1660 mutt_copy_bytes (s->fpin, tmpfp, m->length);
1665 if ((type & ENCRYPT) &&
1666 (thepid = smime_invoke_decrypt (&smimein, NULL, NULL, -1,
1667 fileno (smimeout), fileno (smimeerr),
1671 mutt_unlink (tmpfname);
1672 if (s->flags & M_DISPLAY)
1673 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1676 else if ((type & SIGNOPAQUE) &&
1677 (thepid = smime_invoke_verify (&smimein, NULL, NULL, -1,
1679 fileno (smimeerr), NULL, tmpfname,
1680 SIGNOPAQUE)) == -1) {
1683 mutt_unlink (tmpfname);
1684 if (s->flags & M_DISPLAY)
1685 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1690 if (type & ENCRYPT) {
1691 if (!smime_valid_passphrase ())
1692 smime_void_passphrase ();
1693 fputs (SmimePass, smimein);
1694 fputc ('\n', smimein);
1699 mutt_wait_filter (thepid);
1700 mutt_unlink (tmpfname);
1703 if (s->flags & M_DISPLAY) {
1706 if ((c = fgetc (smimeerr)) != EOF) {
1707 ungetc (c, smimeerr);
1709 crypt_current_time (s, "OpenSSL");
1710 mutt_copy_stream (smimeerr, s->fpout);
1711 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1715 state_attach_puts (_("[-- The following data is S/MIME"
1716 " encrypted --]\n"), s);
1718 state_attach_puts (_("[-- The following data is S/MIME signed --]\n"),
1729 mutt_mktemp (tmptmpfname);
1730 if ((fpout = safe_fopen (tmptmpfname, "w+")) == NULL) {
1731 mutt_perror (tmptmpfname);
1737 while (fgets (buf, sizeof (buf) - 1, smimeout) != NULL) {
1738 len = m_strlen(buf);
1739 if (len > 1 && buf[len - 2] == '\r') {
1740 buf[len - 2] = '\n';
1741 buf[len - 1] = '\0';
1749 if ((p = mutt_read_mime_header (fpout, 0)) != NULL) {
1750 fstat (fileno (fpout), &info);
1751 p->length = info.st_size - p->offset;
1753 mutt_parse_part (fpout, p);
1756 tmpfp_buffer = s->fpin;
1758 mutt_body_handler (p, s);
1759 s->fpin = tmpfp_buffer;
1765 mutt_unlink (outfile);
1769 mutt_unlink (tmptmpfname);
1774 if (s->flags & M_DISPLAY) {
1776 state_attach_puts (_("\n[-- End of S/MIME encrypted data. --]\n"), s);
1778 state_attach_puts (_("\n[-- End of S/MIME signed data. --]\n"), s);
1781 if (type & SIGNOPAQUE) {
1788 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1789 if (linelen && !m_strcasecmp(line, "verification successful"))
1794 m->goodsig = p->goodsig;
1795 m->badsig = p->badsig;
1806 int smime_decrypt_mime (FILE * fpin, FILE ** fpout, BODY * b, BODY ** cur)
1810 char tempfile[_POSIX_PATH_MAX];
1812 long tmpoffset = b->offset;
1813 size_t tmplength = b->length;
1814 int origType = b->type;
1818 if (!mutt_is_application_smime (b))
1826 fseeko (s.fpin, b->offset, 0);
1828 mutt_mktemp (tempfile);
1829 if ((tmpfp = safe_fopen (tempfile, "w+")) == NULL) {
1830 mutt_perror (tempfile);
1834 mutt_unlink (tempfile);
1836 mutt_decode_attachment (b, &s);
1838 b->length = ftello (s.fpout);
1844 mutt_mktemp (tempfile);
1845 if ((*fpout = safe_fopen (tempfile, "w+")) == NULL) {
1846 mutt_perror (tempfile);
1850 mutt_unlink (tempfile);
1852 if (!(*cur = smime_handle_entity (b, &s, *fpout))) {
1857 (*cur)->goodsig = b->goodsig;
1858 (*cur)->badsig = b->badsig;
1862 b->length = tmplength;
1863 b->offset = tmpoffset;
1865 safe_fclose (&tmpfp);
1872 int smime_application_smime_handler (BODY * m, STATE * s)
1874 return smime_handle_entity (m, s, NULL) ? 0 : -1;
1877 int smime_send_menu (HEADER * msg, int *redraw)
1881 switch (mutt_multi_choice
1882 (_("S/MIME (e)ncrypt, (s)ign, encrypt (w)ith, sign (a)s, (b)oth, or (c)lear? "),
1884 case 1: /* (e)ncrypt */
1885 msg->security |= ENCRYPT;
1886 msg->security &= ~SIGN;
1889 case 3: /* encrypt (w)ith */
1892 msg->security |= ENCRYPT;
1895 /* I use "dra" because "123" is recognized anyway */
1896 switch (mutt_multi_choice (_("Choose algorithm family:"
1897 " 1: DES, 2: RC2, 3: AES,"
1898 " or (c)lear? "), _("drac"))) {
1900 switch (choice = mutt_multi_choice (_("1: DES, 2: Triple-DES "),
1903 m_strreplace(&SmimeCryptAlg, "des");
1906 m_strreplace(&SmimeCryptAlg, "des3");
1912 switch (choice = mutt_multi_choice (_("1: RC2-40, 2: RC2-64, 3: RC2-128 "),
1915 m_strreplace(&SmimeCryptAlg, "rc2-40");
1918 m_strreplace(&SmimeCryptAlg, "rc2-64");
1921 m_strreplace(&SmimeCryptAlg, "rc2-128");
1927 switch (choice = mutt_multi_choice (_("1: AES128, 2: AES192, 3: AES256 "),
1930 m_strreplace(&SmimeCryptAlg, "aes128");
1933 m_strreplace(&SmimeCryptAlg, "aes192");
1936 m_strreplace(&SmimeCryptAlg, "aes256");
1941 case 4: /* (c)lear */
1942 p_delete(&SmimeCryptAlg);
1944 case -1: /* Ctrl-G or Enter */
1948 } while (choice == -1);
1952 case 2: /* (s)ign */
1954 if (!SmimeDefaultKey)
1955 mutt_message (_("Can't sign: No key specified. Use Sign As."));
1958 msg->security |= SIGN;
1959 msg->security &= ~ENCRYPT;
1963 case 4: /* sign (a)s */
1965 if ((p = smime_ask_for_key (_("Sign as: "), NULL, 0))) {
1966 m_strreplace(&SmimeDefaultKey, p);
1968 msg->security |= SIGN;
1970 /* probably need a different passphrase */
1971 crypt_smime_void_passphrase ();
1975 msg->security &= ~SIGN;
1978 *redraw = REDRAW_FULL;
1981 case 5: /* (b)oth */
1982 msg->security |= (ENCRYPT | SIGN);
1985 case 6: /* (f)orget it */
1986 case 7: /* (c)lear */
1991 if (msg->security && msg->security != APPLICATION_SMIME)
1992 msg->security |= APPLICATION_SMIME;
1996 return (msg->security);