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.
12 #include <lib-lib/lib-lib.h>
14 #ifdef HAVE_SYS_RESOURCE_H
15 # include <sys/resource.h>
18 #include <lib-mime/mime.h>
19 #include <lib-sys/unix.h>
21 #include <lib-ui/curses.h>
22 #include <lib-ui/enter.h>
23 #include <lib-ui/menu.h>
33 struct smime_command_context {
34 const char *key; /* %k */
35 const char *cryptalg; /* %a */
36 const char *fname; /* %f */
37 const char *sig_fname; /* %s */
38 const char *certificates; /* %c */
39 const char *intermediates; /* %i */
48 char trust; /* i=Invalid r=revoked e=expired u=unverified v=verified t=trusted */
49 short public; /* 1=public 0=private */
53 char SmimePass[STRING];
54 time_t SmimeExptime = 0; /* when does the cached passphrase expire? */
57 static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
58 static char SmimeCertToUse[_POSIX_PATH_MAX];
59 static char SmimeIntermediateToUse[_POSIX_PATH_MAX];
63 * Create a format string to be used with scanf.
64 * To use it, write, for instance, MUTT_FORMAT(HUGE_STRING).
66 * See K&R 2nd ed, p. 231 for an explanation.
68 #define _MUTT_FORMAT_2(a,b) "%" a b
69 #define _MUTT_FORMAT_1(a, b) _MUTT_FORMAT_2(#a, b)
70 #define MUTT_FORMAT(a) _MUTT_FORMAT_1(a, "s")
74 * Queries and passphrase handling.
78 /* these are copies from pgp.c */
81 void smime_void_passphrase (void)
83 p_clear(SmimePass, countof(SmimePass));
87 int smime_valid_passphrase (void)
89 time_t now = time (NULL);
91 if (now < SmimeExptime)
92 /* Use cached copy. */
95 smime_void_passphrase ();
97 if (mutt_get_field_unbuffered (_("Enter S/MIME passphrase:"), SmimePass,
98 sizeof (SmimePass), M_PASS) == 0) {
99 SmimeExptime = time (NULL) + SmimeTimeout;
110 * The OpenSSL interface
113 /* This is almost identical to ppgp's invoking interface. */
116 _mutt_fmt_smime_command (char *dest, ssize_t destlen, char op,
117 const char *src, const char *prefix,
118 const char *ifstr, const char *elstr,
119 anytype data, format_flag flags)
122 struct smime_command_context *cctx = data.ptr;
123 int optional = (flags & M_FORMAT_OPTIONAL);
129 char path[_POSIX_PATH_MAX];
130 char buf1[LONG_STRING], buf2[LONG_STRING];
133 m_strcpy(path, sizeof(path), NONULL(SmimeCALocation));
134 mutt_expand_path (path, sizeof (path));
135 mutt_quote_filename (buf1, sizeof (buf1), path);
137 if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
138 snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
140 snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
142 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
143 snprintf (dest, destlen, fmt, buf2);
145 else if (!SmimeCALocation)
151 { /* certificate (list) */
153 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
154 snprintf (dest, destlen, fmt, NONULL (cctx->certificates));
156 else if (!cctx->certificates)
162 { /* intermediate certificates */
164 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
165 snprintf (dest, destlen, fmt, NONULL (cctx->intermediates));
167 else if (!cctx->intermediates)
173 { /* detached signature */
175 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
176 snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
178 else if (!cctx->sig_fname)
186 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
187 snprintf (dest, destlen, fmt, NONULL (cctx->key));
195 { /* algorithm for encryption */
197 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
198 snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
206 { /* file to process */
208 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
209 snprintf (dest, destlen, fmt, NONULL (cctx->fname));
211 else if (!cctx->fname)
222 m_strformat(dest, destlen, ifstr, _mutt_fmt_smime_command, data, 0);
223 else if (flags & M_FORMAT_OPTIONAL)
224 m_strformat(dest, destlen, elstr, _mutt_fmt_smime_command, data, 0);
231 static void mutt_smime_command (char *d, ssize_t dlen,
232 struct smime_command_context *cctx,
235 m_strformat(d, dlen, NONULL (fmt), _mutt_fmt_smime_command, cctx, 0);
238 static pid_t smime_invoke (FILE ** smimein, FILE ** smimeout,
239 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
240 int smimeerrfd, const char *fname,
241 const char *sig_fname, const char *cryptalg,
242 const char *key, const char *certificates,
243 const char *intermediates, const char *format)
245 struct smime_command_context cctx;
246 char cmd[HUGE_STRING];
250 if (!format || !*format)
254 cctx.sig_fname = sig_fname;
256 cctx.cryptalg = cryptalg;
257 cctx.certificates = certificates;
258 cctx.intermediates = intermediates;
260 mutt_smime_command (cmd, sizeof (cmd), &cctx, format);
262 return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
263 smimeinfd, smimeoutfd, smimeerrfd);
272 * Key and certificate handling.
278 Search the certificate index for given mailbox.
279 return certificate file name.
282 static void smime_entry (char *s, ssize_t l, MUTTMENU * menu, int num)
284 smime_id *Table = (smime_id *) menu->data;
285 smime_id this = Table[num];
286 const char *truststate;
288 switch (this.trust) {
290 truststate = N_("Trusted ");
293 truststate = N_("Verified ");
296 truststate = N_("Unverified");
299 truststate = N_("Expired ");
302 truststate = N_("Revoked ");
305 truststate = N_("Invalid ");
308 truststate = N_("Unknown ");
311 snprintf (s, l, " 0x%.8X.%i %s %-35.35s %s", this.hash, this.suffix,
312 truststate, this.email, this.nick);
314 snprintf (s, l, " 0x%.8X.%i %-35.35s %s", this.hash, this.suffix,
315 this.email, this.nick);
322 char *smime_ask_for_key (char *prompt, char *mailbox __attribute__((unused)),
327 long cert_num; /* Will contain the number of certificates.
328 * To be able to get it, the .index file will be read twice... */
329 char index_file[_POSIX_PATH_MAX];
331 char buf[LONG_STRING];
332 char fields[5][STRING];
333 int numFields, hash_suffix, done, cur; /* The current entry */
336 char helpstr[HUGE_STRING * 3];
341 prompt = _("Enter keyID: ");
342 snprintf (index_file, sizeof (index_file), "%s/.index",
343 public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys));
345 idx = fopen (index_file, "r");
347 mutt_perror (index_file);
352 while (!feof (idx)) {
353 if (fgets (buf, sizeof (buf), idx))
360 if (mutt_get_field (prompt, qry, sizeof (qry), 0))
362 snprintf (title, sizeof (title),
363 _("S/MIME certificates matching \"%s\"."), qry);
366 idx = fopen (index_file, "r");
368 mutt_perror (index_file);
373 Table = p_new(smime_id, cert_num);
374 while (!feof (idx)) {
376 fscanf (idx, MUTT_FORMAT (STRING) " %x.%i " MUTT_FORMAT (STRING),
377 fields[0], &hash, &hash_suffix, fields[2]);
379 fscanf (idx, MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) "\n",
380 fields[3], fields[4]);
382 /* 0=email 1=name 2=nick 3=intermediate 4=trust */
386 /* Check if query matches this certificate */
387 if (!m_stristr(fields[0], qry) && !m_stristr(fields[2], qry))
390 Table[cur].hash = hash;
391 Table[cur].suffix = hash_suffix;
392 m_strcpy(Table[cur].email, sizeof(Table[cur].email), fields[0]);
393 m_strcpy(Table[cur].nick, sizeof(Table[cur].nick), fields[2]);
394 Table[cur].trust = *fields[4];
395 Table[cur].public = public;
401 /* Make Helpstring */
403 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_SMIME, OP_EXIT);
404 m_strcat(helpstr, sizeof(helpstr), buf);
405 mutt_make_help (buf, sizeof (buf), _("Select "), MENU_SMIME,
406 OP_GENERIC_SELECT_ENTRY);
407 m_strcat(helpstr, sizeof(helpstr), buf);
408 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_SMIME, OP_HELP);
409 m_strcat(helpstr, sizeof(helpstr), buf);
411 /* Create the menu */
412 menu = mutt_new_menu ();
414 menu->make_entry = smime_entry;
415 menu->menu = MENU_SMIME;
416 menu->help = helpstr;
419 /* sorting keys might be done later - TODO */
426 switch (mutt_menuLoop (menu)) {
427 case OP_GENERIC_SELECT_ENTRY:
439 fname = p_new(char, 13); /* Hash + '.' + Suffix + \0 */
440 sprintf (fname, "%.8x.%i", Table[cur].hash, Table[cur].suffix);
445 mutt_menuDestroy (&menu);
447 set_option (OPTNEEDREDRAW);
456 char *smime_get_field_from_db (char *mailbox, char *query, short public,
459 int addr_len, query_len, found = 0, ask = 0, choice = 0;
460 char cert_path[_POSIX_PATH_MAX];
461 char buf[LONG_STRING], prompt[STRING];
462 char fields[5][STRING];
466 char key_trust_level = 0;
469 if (!mailbox && !query)
472 addr_len = mailbox ? m_strlen(mailbox) : 0;
473 query_len = query ? m_strlen(query) : 0;
477 /* index-file format:
478 mailbox certfile label issuer_certfile trust_flags\n
480 certfile is a hash value generated by openssl.
481 Note that this was done according to the OpenSSL
482 specs on their CA-directory.
485 snprintf (cert_path, sizeof (cert_path), "%s/.index",
486 (public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys)));
488 if (!stat (cert_path, &info)) {
489 if ((fp = safe_fopen (cert_path, "r")) == NULL) {
490 mutt_perror (cert_path);
494 while (fgets (buf, sizeof (buf) - 1, fp) != NULL)
495 if (mailbox && !(m_strncasecmp(mailbox, buf, addr_len))) {
496 numFields = sscanf (buf,
497 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
498 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
499 MUTT_FORMAT (STRING) "\n",
500 fields[0], fields[1],
501 fields[2], fields[3], fields[4]);
504 if (mailbox && public &&
506 *fields[4] == 'i' || *fields[4] == 'e' || *fields[4] == 'r'))
510 if (public && *fields[4] == 'u')
511 snprintf (prompt, sizeof (prompt),
513 ("ID %s is unverified. Do you want to use it for %s ?"),
515 else if (public && *fields[4] == 'v')
516 snprintf (prompt, sizeof (prompt),
517 _("Use (untrusted!) ID %s for %s ?"),
520 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"),
524 if (may_ask && (choice = mutt_yesorno (prompt, M_NO)) == -1) {
530 else if (choice == M_NO) {
534 else if (choice == M_YES) {
535 m_strcpy(key, sizeof(key), fields[1]);
542 key_trust_level = *fields[4];
543 m_strcpy(key, sizeof(key), fields[1]);
548 numFields = sscanf (buf,
549 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
550 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
551 MUTT_FORMAT (STRING) "\n",
552 fields[0], fields[1],
553 fields[2], fields[3], fields[4]);
555 /* query = label: return certificate. */
556 if (numFields >= 3 &&
557 !(m_strncasecmp(query, fields[2], query_len))) {
559 m_strcpy(key, sizeof(key), fields[1]);
561 /* query = certificate: return intermediate certificate. */
562 else if (numFields >= 4 &&
563 !(m_strncasecmp(query, fields[1], query_len))) {
565 m_strcpy(key, sizeof(key), fields[3]);
572 if (public && *fields[4] == 'u')
573 snprintf (prompt, sizeof (prompt),
574 _("ID %s is unverified. Do you want to use it for %s ?"),
576 else if (public && *fields[4] == 'v')
577 snprintf (prompt, sizeof (prompt),
578 _("Use (untrusted!) ID %s for %s ?"), fields[1], mailbox);
580 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"), key,
582 choice = mutt_yesorno (prompt, M_NO);
583 if (choice == -1 || choice == M_NO)
586 else if (key_trust_level && may_ask) {
587 if (key_trust_level == 'u') {
588 snprintf (prompt, sizeof (prompt),
589 _("ID %s is unverified. Do you want to use it for %s ?"),
591 choice = mutt_yesorno (prompt, M_NO);
595 else if (key_trust_level == 'v') {
597 ("Warning: You have not yet decided to trust ID %s. (any key to continue)"),
605 /* Note: m_strdup("") returns NULL. */
606 return m_strdup(key);
610 This sets the '*ToUse' variables for an upcoming decryption, where
611 the reuquired key is different from SmimeDefaultKey.
613 static void _smime_getkeys (char *mailbox)
618 k = smime_get_field_from_db (mailbox, NULL, 0, 1);
621 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), mailbox);
622 k = smime_ask_for_key (buf, mailbox, 0);
626 /* the key used last time. */
627 if (*SmimeKeyToUse &&
628 !m_strcasecmp(k, SmimeKeyToUse + m_strlen(SmimeKeys) + 1)) {
633 smime_void_passphrase ();
635 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
636 NONULL (SmimeKeys), k);
638 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
639 NONULL (SmimeCertificates), k);
641 if (m_strcasecmp(k, SmimeDefaultKey))
642 smime_void_passphrase ();
648 if (*SmimeKeyToUse) {
649 if (!m_strcasecmp(SmimeDefaultKey,
650 SmimeKeyToUse + m_strlen(SmimeKeys) + 1))
653 smime_void_passphrase ();
656 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
657 NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
659 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
660 NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
663 void smime_getkeys (ENVELOPE * env)
668 if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey) {
669 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
670 NONULL (SmimeKeys), SmimeDefaultKey);
672 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
673 NONULL (SmimeCertificates), SmimeDefaultKey);
678 for (t = env->to; !found && t; t = t->next)
679 if (mutt_addr_is_user (t)) {
681 _smime_getkeys (t->mailbox);
683 for (t = env->cc; !found && t; t = t->next)
684 if (mutt_addr_is_user (t)) {
686 _smime_getkeys (t->mailbox);
688 if (!found && (t = mutt_default_from ())) {
689 _smime_getkeys (t->mailbox);
690 address_list_wipe(&t);
694 /* This routine attempts to find the keyids of the recipients of a message.
695 * It returns NULL if any of the keys can not be found.
698 char *smime_findKeys (address_t * to, address_t * cc, address_t * bcc)
700 char *keyID, *keylist = NULL;
701 ssize_t keylist_size = 0;
702 ssize_t keylist_used = 0;
703 address_t *tmp = NULL, *addr = NULL;
704 address_t **last = &tmp;
708 for (i = 0; i < 3; i++) {
723 *last = address_list_dup (p);
725 last = &((*last)->next);
728 rfc822_qualify(tmp, mutt_fqdn(1));
730 address_list_uniq(tmp);
732 for (p = tmp; p; p = p->next) {
733 char buf[LONG_STRING];
737 if ((keyID = smime_get_field_from_db (q->mailbox, NULL, 1, 1)) == NULL) {
738 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), q->mailbox);
739 keyID = smime_ask_for_key (buf, q->mailbox, 1);
742 mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
744 address_list_wipe(&tmp);
745 address_list_wipe(&addr);
749 keylist_size += m_strlen(keyID) + 2;
750 p_realloc(&keylist, keylist_size);
751 sprintf (keylist + keylist_used, "%s\n", keyID);
752 keylist_used = m_strlen(keylist);
754 address_list_wipe(&addr);
757 address_list_wipe(&tmp);
766 static int smime_handle_cert_email (char *certificate, char *mailbox,
767 int copy, char ***buffer, int *num)
769 FILE *fpout = NULL, *fperr = NULL;
770 char tmpfname[_POSIX_PATH_MAX];
772 int ret = -1, count = 0;
775 fperr = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
777 mutt_perror (tmpfname);
780 mutt_unlink (tmpfname);
782 fpout = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
785 mutt_perror (tmpfname);
788 mutt_unlink (tmpfname);
790 if ((thepid = smime_invoke (NULL, NULL, NULL,
791 -1, fileno (fpout), fileno (fperr),
792 certificate, NULL, NULL, NULL, NULL, NULL,
793 SmimeGetCertEmailCommand)) == -1) {
794 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
800 mutt_wait_filter (thepid);
808 while ((fgets (email, sizeof (email), fpout))) {
809 *(email + m_strlen(email) - 1) = '\0';
810 if (m_strncasecmp(email, mailbox, m_strlen(mailbox)) == 0)
813 ret = ret < 0 ? 0 : ret;
819 mutt_copy_stream (fperr, stdout);
820 mutt_any_key_to_continue (_
821 ("Error: unable to create OpenSSL subprocess!"));
829 if (copy && buffer && num) {
831 *buffer = p_new(char *, count);
835 while ((fgets (email, sizeof (email), fpout))) {
836 *(email + m_strlen(email) - 1) = '\0';
837 (*buffer)[count] = p_dupstr(email, m_strlen(email));
852 static char *smime_extract_certificate (char *infile)
854 FILE *fpout = NULL, *fperr = NULL;
855 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
856 char tmpfname[_POSIX_PATH_MAX];
861 fperr = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
863 mutt_perror (tmpfname);
866 mutt_unlink (tmpfname);
868 fpout = m_tempfile (pk7out, sizeof(tmpfname), NONULL(Tempdir), NULL);
871 mutt_perror (pk7out);
875 /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
876 extract the full set of certificates directly.
878 if ((thepid = smime_invoke (NULL, NULL, NULL,
879 -1, fileno (fpout), fileno (fperr),
880 infile, NULL, NULL, NULL, NULL, NULL,
881 SmimePk7outCommand)) == -1) {
882 mutt_any_key_to_continue (_
883 ("Error: unable to create OpenSSL subprocess!"));
886 mutt_unlink (pk7out);
890 mutt_wait_filter (thepid);
898 empty = (fgetc (fpout) == EOF);
903 mutt_perror (pk7out);
904 mutt_copy_stream (fperr, stdout);
906 mutt_unlink (pk7out);
910 fpout = m_tempfile (certfile, sizeof(certfile), NONULL(Tempdir), NULL);
913 mutt_unlink (pk7out);
914 mutt_perror (certfile);
918 /* Step 2: Extract the certificates from a PKCS#7 structure.
920 if ((thepid = smime_invoke (NULL, NULL, NULL,
921 -1, fileno (fpout), fileno (fperr),
922 pk7out, NULL, NULL, NULL, NULL, NULL,
923 SmimeGetCertCommand)) == -1) {
924 mutt_any_key_to_continue (_
925 ("Error: unable to create OpenSSL subprocess!"));
928 mutt_unlink (pk7out);
929 mutt_unlink (certfile);
933 mutt_wait_filter (thepid);
935 mutt_unlink (pk7out);
941 empty = (fgetc (fpout) == EOF);
943 mutt_copy_stream (fperr, stdout);
946 mutt_unlink (certfile);
953 return m_strdup(certfile);
956 static char *smime_extract_signer_certificate (char *infile)
958 FILE *fpout = NULL, *fperr = NULL;
959 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
960 char tmpfname[_POSIX_PATH_MAX];
964 fperr = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
966 mutt_perror (tmpfname);
969 mutt_unlink (tmpfname);
971 m_tempfile (certfile, sizeof(certfile), NONULL(Tempdir), NULL);
974 mutt_perror (certfile);
978 /* Extract signer's certificate
980 if ((thepid = smime_invoke (NULL, NULL, NULL,
981 -1, -1, fileno (fperr),
982 infile, NULL, NULL, NULL, certfile, NULL,
983 SmimeGetSignerCertCommand)) == -1) {
984 mutt_any_key_to_continue (_
985 ("Error: unable to create OpenSSL subprocess!"));
988 mutt_unlink (pk7out);
989 mutt_unlink (certfile);
993 mutt_wait_filter (thepid);
999 empty = (fgetc (fpout) == EOF);
1004 mutt_copy_stream (fperr, stdout);
1005 mutt_any_key_to_continue (NULL);
1007 mutt_unlink (certfile);
1013 return m_strdup(certfile);
1016 /* Add a certificate and update index file (externally). */
1018 void smime_invoke_import (char *infile, char *mailbox __attribute__ ((unused)))
1020 char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
1021 FILE *smimein = NULL, *fpout = NULL, *fperr = NULL;
1024 fperr = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
1026 mutt_perror (tmpfname);
1029 mutt_unlink (tmpfname);
1031 fpout = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
1034 mutt_perror (tmpfname);
1037 mutt_unlink (tmpfname);
1040 if (option (OPTASKCERTLABEL))
1041 mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1044 if ((certfile = smime_extract_certificate (infile))) {
1047 if ((thepid = smime_invoke (&smimein, NULL, NULL,
1048 -1, fileno (fpout), fileno (fperr),
1049 certfile, NULL, NULL, NULL, NULL, NULL,
1050 SmimeImportCertCommand)) == -1) {
1051 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
1054 fputs (buf, smimein);
1055 fputc ('\n', smimein);
1058 mutt_wait_filter (thepid);
1060 mutt_unlink (certfile);
1061 p_delete(&certfile);
1069 mutt_copy_stream (fpout, stdout);
1070 mutt_copy_stream (fperr, stdout);
1076 int smime_verify_sender (HEADER * h)
1078 char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
1082 fpout = m_tempfile (tempfname, sizeof(tempfname), NONULL(Tempdir), NULL);
1084 mutt_perror (_("Can't create temporary file"));
1088 if (h->security & ENCRYPT)
1089 mutt_copy_message (fpout, Context, h,
1090 M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1091 CH_MIME | CH_WEED | CH_NONEWLINE);
1093 mutt_copy_message (fpout, Context, h, 0, 0);
1099 h->env->from = mutt_expand_aliases (h->env->from);
1100 mbox = h->env->from->mailbox;
1102 else if (h->env->sender) {
1103 h->env->sender = mutt_expand_aliases (h->env->sender);
1104 mbox = h->env->sender->mailbox;
1108 if ((certfile = smime_extract_signer_certificate (tempfname))) {
1109 mutt_unlink (tempfname);
1110 if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL)) {
1112 mutt_any_key_to_continue (NULL);
1116 mutt_unlink (certfile);
1117 p_delete(&certfile);
1120 mutt_any_key_to_continue (_("no certfile"));
1123 mutt_any_key_to_continue (_("no mbox"));
1125 mutt_unlink (tempfname);
1138 * Creating S/MIME - bodies.
1145 pid_t smime_invoke_encrypt (FILE ** smimein, FILE ** smimeout,
1146 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1147 int smimeerrfd, const char *fname,
1150 return smime_invoke (smimein, smimeout, smimeerr,
1151 smimeinfd, smimeoutfd, smimeerrfd,
1152 fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
1153 SmimeEncryptCommand);
1158 pid_t smime_invoke_sign (FILE ** smimein, FILE ** smimeout, FILE ** smimeerr,
1159 int smimeinfd, int smimeoutfd, int smimeerrfd,
1162 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1163 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1164 SmimeCertToUse, SmimeIntermediateToUse,
1171 BODY *smime_build_smime_entity (BODY * a, char *certlist)
1173 char buf[LONG_STRING], certfile[LONG_STRING];
1174 char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1175 char smimeinfile[_POSIX_PATH_MAX];
1176 char *cert_start = certlist, *cert_end = certlist;
1177 FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
1182 fpout = m_tempfile (tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
1184 mutt_perror (_("Can't create temporary file"));
1188 smimeerr = m_tempfile (smimeerrfile, sizeof(smimeerrfile), NONULL(Tempdir), NULL);
1190 mutt_perror (smimeerrfile);
1192 mutt_unlink (tempfile);
1195 mutt_unlink (smimeerrfile);
1197 fptmp = m_tempfile (smimeinfile, sizeof(smimeinfile), NONULL(Tempdir), NULL);
1199 mutt_perror (smimeinfile);
1200 mutt_unlink (tempfile);
1202 m_fclose(&smimeerr);
1208 int off = m_strlen(certfile);
1210 while (*++cert_end && *cert_end != '\n');
1214 snprintf (certfile + off, sizeof (certfile) - off, " %s/%s",
1215 NONULL (SmimeCertificates), cert_start);
1217 cert_start = cert_end;
1221 /* write a MIME entity */
1222 mutt_write_mime_header (a, fptmp);
1223 fputc ('\n', fptmp);
1224 mutt_write_mime_body (a, fptmp);
1228 smime_invoke_encrypt (&smimein, NULL, NULL, -1,
1229 fileno (fpout), fileno (smimeerr),
1230 smimeinfile, certfile)) == -1) {
1231 m_fclose(&smimeerr);
1232 mutt_unlink (smimeinfile);
1233 mutt_unlink (certfile);
1239 mutt_wait_filter (thepid);
1240 mutt_unlink (smimeinfile);
1241 mutt_unlink (certfile);
1245 empty = (fgetc (fpout) == EOF);
1250 while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL) {
1252 fputs (buf, stdout);
1254 m_fclose(&smimeerr);
1256 /* pause if there is any error output from SMIME */
1258 mutt_any_key_to_continue (NULL);
1261 /* fatal error while trying to encrypt message */
1263 mutt_any_key_to_continue _("No output from OpenSSL..");
1265 mutt_unlink (tempfile);
1270 t->type = TYPEAPPLICATION;
1271 t->subtype = m_strdup("x-pkcs7-mime");
1272 parameter_setval(&t->parameter, "name", "smime.p7m");
1273 parameter_setval(&t->parameter, "smime-type", "enveloped-data");
1274 t->encoding = ENCBASE64; /* The output of OpenSSL SHOULD be binary */
1276 t->disposition = DISPATTACH;
1277 t->d_filename = m_strdup("smime.p7m");
1278 t->filename = m_strdup(tempfile);
1279 t->unlink = 1; /*delete after sending the message */
1289 BODY *smime_sign_message (BODY * a)
1292 char buffer[LONG_STRING];
1293 char signedfile[_POSIX_PATH_MAX], filetosign[_POSIX_PATH_MAX];
1294 FILE *smimein = NULL, *smimeout = NULL, *smimeerr = NULL, *sfp = NULL;
1298 char *intermediates = smime_get_field_from_db (NULL, SmimeDefaultKey, 1, 1);
1300 if (!intermediates) {
1301 mutt_message (_("Warning: Intermediate certificate not found."));
1302 intermediates = SmimeDefaultKey; /* so openssl won't complain in any case */
1305 convert_to_7bit (a); /* Signed data _must_ be in 7-bit format. */
1307 sfp = m_tempfile (filetosign, sizeof(filetosign), NONULL(Tempdir), NULL);
1309 mutt_perror (filetosign);
1313 smimeout = m_tempfile (signedfile, sizeof(signedfile), NONULL(Tempdir), NULL);
1315 mutt_perror (signedfile);
1317 mutt_unlink (filetosign);
1321 mutt_write_mime_header (a, sfp);
1323 mutt_write_mime_body (a, sfp);
1328 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
1329 NONULL (SmimeKeys), SmimeDefaultKey);
1331 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
1332 NONULL (SmimeCertificates), SmimeDefaultKey);
1334 snprintf (SmimeIntermediateToUse, sizeof (SmimeIntermediateToUse), "%s/%s",
1335 NONULL (SmimeCertificates), intermediates);
1339 if ((thepid = smime_invoke_sign (&smimein, NULL, &smimeerr,
1340 -1, fileno (smimeout), -1,
1341 filetosign)) == -1) {
1342 mutt_perror (_("Can't open OpenSSL subprocess!"));
1344 m_fclose(&smimeout);
1345 mutt_unlink (signedfile);
1346 mutt_unlink (filetosign);
1349 fputs (SmimePass, smimein);
1350 fputc ('\n', smimein);
1354 mutt_wait_filter (thepid);
1356 /* check for errors from OpenSSL */
1360 while (fgets (buffer, sizeof (buffer) - 1, smimeerr) != NULL) {
1362 fputs (buffer, stdout);
1364 m_fclose(&smimeerr);
1369 empty = (fgetc (smimeout) == EOF);
1370 m_fclose(&smimeout);
1372 mutt_unlink (filetosign);
1376 mutt_any_key_to_continue (NULL);
1379 mutt_any_key_to_continue _("No output from OpenSSL...");
1381 mutt_unlink (signedfile);
1382 return (NULL); /* fatal error while signing */
1386 t->type = TYPEMULTIPART;
1387 t->subtype = m_strdup("signed");
1388 t->encoding = ENC7BIT;
1390 t->disposition = DISPINLINE;
1392 parameter_set_boundary(&t->parameter);
1393 /* check if this can be extracted from private key somehow.... */
1394 parameter_setval(&t->parameter, "micalg", "sha1");
1395 parameter_setval(&t->parameter, "protocol",
1396 "application/x-pkcs7-signature");
1401 t->parts->next = body_new();
1403 t->type = TYPEAPPLICATION;
1404 t->subtype = m_strdup("x-pkcs7-signature");
1405 t->filename = m_strdup(signedfile);
1406 t->d_filename = m_strdup("smime.p7s");
1408 t->disposition = DISPATTACH;
1409 t->encoding = ENCBASE64;
1410 t->unlink = 1; /* ok to remove this file after sending. */
1418 * Handling S/MIME - bodies.
1423 pid_t smime_invoke_verify (FILE ** smimein, FILE ** smimeout,
1424 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1425 int smimeerrfd, const char *fname,
1426 const char *sig_fname, int opaque)
1428 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1429 smimeerrfd, fname, sig_fname, NULL, NULL, NULL, NULL,
1430 (opaque ? SmimeVerifyOpaqueCommand :
1431 SmimeVerifyCommand));
1436 pid_t smime_invoke_decrypt (FILE ** smimein, FILE ** smimeout,
1437 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1438 int smimeerrfd, const char *fname)
1440 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1441 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1442 SmimeCertToUse, NULL, SmimeDecryptCommand);
1447 int smime_verify_one (BODY * sigbdy, STATE * s, const char *tempfile)
1449 char signedfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1450 FILE *fp = NULL, *smimeout = NULL, *smimeerr = NULL;
1455 ssize_t tmplength = 0;
1456 int origType = sigbdy->type;
1457 char *savePrefix = NULL;
1460 snprintf (signedfile, sizeof (signedfile), "%s.sig", tempfile);
1462 /* decode to a tempfile, saving the original destination */
1464 if ((s->fpout = safe_fopen (signedfile, "w")) == NULL) {
1465 mutt_perror (signedfile);
1468 /* decoding the attachment changes the size and offset, so save a copy
1469 * of the "real" values now, and restore them after processing
1471 tmplength = sigbdy->length;
1472 tmpoffset = sigbdy->offset;
1474 /* if we are decoding binary bodies, we don't want to prefix each
1475 * line with the prefix or else the data will get corrupted.
1477 savePrefix = s->prefix;
1480 mutt_decode_attachment (sigbdy, s);
1482 sigbdy->length = ftello (s->fpout);
1484 m_fclose(&s->fpout);
1486 /* restore final destination and substitute the tempfile for input */
1489 s->fpin = fopen (signedfile, "r");
1491 /* restore the prefix */
1492 s->prefix = savePrefix;
1494 sigbdy->type = origType;
1496 smimeerr = m_tempfile(smimeerrfile, sizeof(smimeerrfile), NONULL(Tempdir), NULL);
1498 mutt_perror (smimeerrfile);
1499 mutt_unlink (signedfile);
1503 crypt_current_time (s, "OpenSSL");
1505 if ((thepid = smime_invoke_verify (NULL, &smimeout, NULL,
1506 -1, -1, fileno (smimeerr),
1507 tempfile, signedfile, 0)) != -1) {
1508 m_fclose(&smimeout);
1510 if (mutt_wait_filter (thepid))
1520 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1521 if (linelen && !m_strcasecmp(line, "verification successful"))
1530 mutt_copy_stream (smimeerr, s->fpout);
1531 m_fclose(&smimeerr);
1533 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1535 mutt_unlink (signedfile);
1536 mutt_unlink (smimeerrfile);
1538 sigbdy->length = tmplength;
1539 sigbdy->offset = tmpoffset;
1541 /* restore the original source stream */
1554 This handles application/pkcs7-mime which can either be a signed
1555 or an encrypted message.
1558 static BODY *smime_handle_entity (BODY * m, STATE * s, FILE * outFile)
1563 char buf[HUGE_STRING];
1564 char outfile[_POSIX_PATH_MAX], errfile[_POSIX_PATH_MAX];
1565 char tmpfname[_POSIX_PATH_MAX];
1566 char tmptmpfname[_POSIX_PATH_MAX];
1567 FILE *smimeout = NULL, *smimein = NULL, *smimeerr = NULL;
1568 FILE *tmpfp = NULL, *tmpfp_buffer = NULL, *fpout = NULL;
1572 unsigned int type = mutt_is_application_smime (m);
1574 if (!(type & APPLICATION_SMIME))
1577 smimeout = m_tempfile (outfile, sizeof(outfile), NONULL(Tempdir), NULL);
1579 mutt_perror (outfile);
1583 smimeerr = m_tempfile(errfile, sizeof(errfile), NONULL(Tempdir), NULL);
1585 mutt_perror (errfile);
1586 m_fclose(&smimeout);
1589 mutt_unlink (errfile);
1591 tmpfp = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
1593 mutt_perror (tmpfname);
1594 m_fclose(&smimeout);
1595 m_fclose(&smimeerr);
1599 fseeko (s->fpin, m->offset, 0);
1600 last_pos = m->offset;
1602 mutt_copy_bytes (s->fpin, tmpfp, m->length);
1605 if ((type & ENCRYPT) &&
1606 (thepid = smime_invoke_decrypt (&smimein, NULL, NULL, -1,
1607 fileno (smimeout), fileno (smimeerr),
1609 m_fclose(&smimeout);
1610 mutt_unlink (tmpfname);
1611 if (s->flags & M_DISPLAY)
1612 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1615 else if ((type & SIGNOPAQUE) &&
1616 (thepid = smime_invoke_verify (&smimein, NULL, NULL, -1,
1618 fileno (smimeerr), NULL, tmpfname,
1619 SIGNOPAQUE)) == -1) {
1620 m_fclose(&smimeout);
1621 mutt_unlink (tmpfname);
1622 if (s->flags & M_DISPLAY)
1623 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1628 if (type & ENCRYPT) {
1629 if (!smime_valid_passphrase ())
1630 smime_void_passphrase ();
1631 fputs (SmimePass, smimein);
1632 fputc ('\n', smimein);
1637 mutt_wait_filter (thepid);
1638 mutt_unlink (tmpfname);
1641 if (s->flags & M_DISPLAY) {
1644 if ((c = fgetc (smimeerr)) != EOF) {
1645 ungetc (c, smimeerr);
1647 crypt_current_time (s, "OpenSSL");
1648 mutt_copy_stream (smimeerr, s->fpout);
1649 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1653 state_attach_puts (_("[-- The following data is S/MIME"
1654 " encrypted --]\n"), s);
1656 state_attach_puts (_("[-- The following data is S/MIME signed --]\n"),
1667 fpout = m_tempfile (tmptmpfname, sizeof(tmptmpfname), NONULL(Tempdir), NULL);
1669 mutt_perror (tmptmpfname);
1670 m_fclose(&smimeout);
1674 while (fgets (buf, sizeof (buf) - 1, smimeout) != NULL) {
1675 len = m_strlen(buf);
1676 if (len > 1 && buf[len - 2] == '\r') {
1677 buf[len - 2] = '\n';
1678 buf[len - 1] = '\0';
1686 if ((p = mutt_read_mime_header (fpout, 0)) != NULL) {
1687 fstat (fileno (fpout), &info);
1688 p->length = info.st_size - p->offset;
1690 mutt_parse_part (fpout, p);
1693 tmpfp_buffer = s->fpin;
1695 mutt_body_handler (p, s);
1696 s->fpin = tmpfp_buffer;
1700 m_fclose(&smimeout);
1701 mutt_unlink (outfile);
1705 mutt_unlink (tmptmpfname);
1710 if (s->flags & M_DISPLAY) {
1712 state_attach_puts (_("\n[-- End of S/MIME encrypted data. --]\n"), s);
1714 state_attach_puts (_("\n[-- End of S/MIME signed data. --]\n"), s);
1717 if (type & SIGNOPAQUE) {
1724 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1725 if (linelen && !m_strcasecmp(line, "verification successful"))
1730 m->goodsig = p->goodsig;
1731 m->badsig = p->badsig;
1733 m_fclose(&smimeerr);
1742 int smime_decrypt_mime (FILE * fpin, FILE ** fpout, BODY * b, BODY ** cur)
1746 char tempfile[_POSIX_PATH_MAX];
1748 long tmpoffset = b->offset;
1749 ssize_t tmplength = b->length;
1750 int origType = b->type;
1754 if (!mutt_is_application_smime (b))
1762 fseeko (s.fpin, b->offset, 0);
1764 tmpfp = m_tempfile (tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
1766 mutt_perror (_("Can't create temporary file"));
1770 mutt_unlink (tempfile);
1772 mutt_decode_attachment (b, &s);
1774 b->length = ftello (s.fpout);
1780 *fpout = m_tempfile (tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
1782 mutt_perror (_("Can't create temporary file"));
1786 mutt_unlink (tempfile);
1788 if (!(*cur = smime_handle_entity (b, &s, *fpout))) {
1793 (*cur)->goodsig = b->goodsig;
1794 (*cur)->badsig = b->badsig;
1798 b->length = tmplength;
1799 b->offset = tmpoffset;
1808 int smime_application_smime_handler (BODY * m, STATE * s)
1810 return smime_handle_entity (m, s, NULL) ? 0 : -1;
1813 int smime_send_menu (HEADER * msg, int *redraw)
1817 switch (mutt_multi_choice
1818 (_("S/MIME (e)ncrypt, (s)ign, encrypt (w)ith, sign (a)s, (b)oth, or (c)lear? "),
1820 case 1: /* (e)ncrypt */
1821 msg->security |= ENCRYPT;
1822 msg->security &= ~SIGN;
1825 case 3: /* encrypt (w)ith */
1828 msg->security |= ENCRYPT;
1831 /* I use "dra" because "123" is recognized anyway */
1832 switch (mutt_multi_choice (_("Choose algorithm family:"
1833 " 1: DES, 2: RC2, 3: AES,"
1834 " or (c)lear? "), _("drac"))) {
1836 switch (choice = mutt_multi_choice (_("1: DES, 2: Triple-DES "),
1839 m_strreplace(&SmimeCryptAlg, "des");
1842 m_strreplace(&SmimeCryptAlg, "des3");
1848 switch (choice = mutt_multi_choice (_("1: RC2-40, 2: RC2-64, 3: RC2-128 "),
1851 m_strreplace(&SmimeCryptAlg, "rc2-40");
1854 m_strreplace(&SmimeCryptAlg, "rc2-64");
1857 m_strreplace(&SmimeCryptAlg, "rc2-128");
1863 switch (choice = mutt_multi_choice (_("1: AES128, 2: AES192, 3: AES256 "),
1866 m_strreplace(&SmimeCryptAlg, "aes128");
1869 m_strreplace(&SmimeCryptAlg, "aes192");
1872 m_strreplace(&SmimeCryptAlg, "aes256");
1877 case 4: /* (c)lear */
1878 p_delete(&SmimeCryptAlg);
1880 case -1: /* Ctrl-G or Enter */
1884 } while (choice == -1);
1888 case 2: /* (s)ign */
1890 if (!SmimeDefaultKey)
1891 mutt_message (_("Can't sign: No key specified. Use Sign As."));
1894 msg->security |= SIGN;
1895 msg->security &= ~ENCRYPT;
1899 case 4: /* sign (a)s */
1901 if ((p = smime_ask_for_key (_("Sign as: "), NULL, 0))) {
1902 m_strreplace(&SmimeDefaultKey, p);
1904 msg->security |= SIGN;
1906 /* probably need a different passphrase */
1907 crypt_smime_void_passphrase ();
1910 *redraw = REDRAW_FULL;
1913 case 5: /* (b)oth */
1914 msg->security |= (ENCRYPT | SIGN);
1917 case 6: /* (f)orget it */
1918 case 7: /* (c)lear */
1923 if (msg->security && msg->security != APPLICATION_SMIME)
1924 msg->security |= APPLICATION_SMIME;
1928 return (msg->security);