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.
17 #include "mutt_curses.h"
18 #include "mutt_menu.h"
35 #ifdef HAVE_SYS_TIME_H
36 # include <sys/time.h>
39 #ifdef HAVE_SYS_RESOURCE_H
40 # include <sys/resource.h>
43 #ifdef CRYPT_BACKEND_CLASSIC_SMIME
45 #include "mutt_crypt.h"
47 struct smime_command_context {
48 const char *key; /* %k */
49 const char *cryptalg; /* %a */
50 const char *fname; /* %f */
51 const char *sig_fname; /* %s */
52 const char *certificates; /* %c */
53 const char *intermediates; /* %i */
62 char trust; /* i=Invalid r=revoked e=expired u=unverified v=verified t=trusted */
63 short public; /* 1=public 0=private */
67 char SmimePass[STRING];
68 time_t SmimeExptime = 0; /* when does the cached passphrase expire? */
71 static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
72 static char SmimeCertToUse[_POSIX_PATH_MAX];
73 static char SmimeIntermediateToUse[_POSIX_PATH_MAX];
77 * Queries and passphrase handling.
83 /* these are copies from pgp.c */
86 void smime_void_passphrase (void)
88 memset (SmimePass, 0, sizeof (SmimePass));
92 int smime_valid_passphrase (void)
94 time_t now = time (NULL);
96 if (now < SmimeExptime)
97 /* Use cached copy. */
100 smime_void_passphrase ();
102 if (mutt_get_password
103 (_("Enter SMIME passphrase:"), SmimePass, sizeof (SmimePass)) == 0) {
104 SmimeExptime = time (NULL) + SmimeTimeout;
115 * The OpenSSL interface
118 /* This is almost identical to ppgp's invoking interface. */
120 static const char *_mutt_fmt_smime_command (char *dest,
125 const char *ifstring,
126 const char *elsestring,
131 struct smime_command_context *cctx = (struct smime_command_context *) data;
132 int optional = (flags & M_FORMAT_OPTIONAL);
138 char path[_POSIX_PATH_MAX];
139 char buf1[LONG_STRING], buf2[LONG_STRING];
142 strfcpy (path, NONULL (SmimeCALocation), sizeof (path));
143 mutt_expand_path (path, sizeof (path));
144 mutt_quote_filename (buf1, sizeof (buf1), path);
146 if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
147 snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
149 snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
151 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
152 snprintf (dest, destlen, fmt, buf2);
154 else if (!SmimeCALocation)
160 { /* certificate (list) */
162 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
163 snprintf (dest, destlen, fmt, NONULL (cctx->certificates));
165 else if (!cctx->certificates)
171 { /* intermediate certificates */
173 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
174 snprintf (dest, destlen, fmt, NONULL (cctx->intermediates));
176 else if (!cctx->intermediates)
182 { /* detached signature */
184 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
185 snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
187 else if (!cctx->sig_fname)
195 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
196 snprintf (dest, destlen, fmt, NONULL (cctx->key));
204 { /* algorithm for encryption */
206 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
207 snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
215 { /* file to process */
217 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
218 snprintf (dest, destlen, fmt, NONULL (cctx->fname));
220 else if (!cctx->fname)
231 mutt_FormatString (dest, destlen, ifstring, _mutt_fmt_smime_command,
233 else if (flags & M_FORMAT_OPTIONAL)
234 mutt_FormatString (dest, destlen, elsestring, _mutt_fmt_smime_command,
242 static void mutt_smime_command (char *d, size_t dlen,
243 struct smime_command_context *cctx,
246 mutt_FormatString (d, dlen, NONULL (fmt), _mutt_fmt_smime_command,
247 (unsigned long) cctx, 0);
248 dprint (2, (debugfile, "mutt_smime_command: %s\n", d));
254 static pid_t smime_invoke (FILE ** smimein, FILE ** smimeout,
255 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
256 int smimeerrfd, const char *fname,
257 const char *sig_fname, const char *cryptalg,
258 const char *key, const char *certificates,
259 const char *intermediates, const char *format)
261 struct smime_command_context cctx;
262 char cmd[HUGE_STRING];
264 memset (&cctx, 0, sizeof (cctx));
266 if (!format || !*format)
270 cctx.sig_fname = sig_fname;
272 cctx.cryptalg = cryptalg;
273 cctx.certificates = certificates;
274 cctx.intermediates = intermediates;
276 mutt_smime_command (cmd, sizeof (cmd), &cctx, format);
278 return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
279 smimeinfd, smimeoutfd, smimeerrfd);
288 * Key and certificate handling.
294 Search the certificate index for given mailbox.
295 return certificate file name.
298 static void smime_entry (char *s, size_t l, MUTTMENU * menu, int num)
300 smime_id *Table = (smime_id *) menu->data;
301 smime_id this = Table[num];
304 switch (this.trust) {
306 truststate = N_("Trusted ");
309 truststate = N_("Verified ");
312 truststate = N_("Unverified");
315 truststate = N_("Expired ");
318 truststate = N_("Revoked ");
321 truststate = N_("Invalid ");
324 truststate = N_("Unknown ");
327 snprintf (s, l, " 0x%.8X.%i %s %-35.35s %s", this.hash, this.suffix,
328 truststate, this.email, this.nick);
330 snprintf (s, l, " 0x%.8X.%i %-35.35s %s", this.hash, this.suffix,
331 this.email, this.nick);
338 char *smime_ask_for_key (char *prompt, char *mailbox, short public)
342 long cert_num; /* Will contain the number of certificates.
343 * To be able to get it, the .index file will be read twice... */
344 char index_file[_POSIX_PATH_MAX];
346 char buf[LONG_STRING];
347 char fields[5][STRING];
348 int numFields, hash_suffix, done, cur; /* The current entry */
351 char helpstr[HUGE_STRING * 3];
356 prompt = _("Enter keyID: ");
357 snprintf (index_file, sizeof (index_file), "%s/.index",
358 public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys));
360 index = fopen (index_file, "r");
362 mutt_perror (index_file);
367 while (!feof (index)) {
368 if (fgets (buf, sizeof (buf), index))
375 if (mutt_get_field (prompt, qry, sizeof (qry), 0))
377 snprintf (title, sizeof (title),
378 _("S/MIME certificates matching \"%s\"."), qry);
381 index = fopen (index_file, "r");
383 mutt_perror (index_file);
388 Table = safe_calloc (cert_num, sizeof (smime_id));
389 while (!feof (index)) {
391 fscanf (index, MUTT_FORMAT (STRING) " %x.%i " MUTT_FORMAT (STRING),
392 fields[0], &hash, &hash_suffix, fields[2]);
394 fscanf (index, MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) "\n",
395 fields[3], fields[4]);
397 /* 0=email 1=name 2=nick 3=intermediate 4=trust */
401 /* Check if query matches this certificate */
402 if (!mutt_stristr (fields[0], qry) && !mutt_stristr (fields[2], qry))
405 Table[cur].hash = hash;
406 Table[cur].suffix = hash_suffix;
407 strncpy (Table[cur].email, fields[0], sizeof (Table[cur].email));
408 strncpy (Table[cur].nick, fields[2], sizeof (Table[cur].nick));
409 Table[cur].trust = *fields[4];
410 Table[cur].public = public;
416 /* Make Helpstring */
418 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_SMIME, OP_EXIT);
419 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
420 mutt_make_help (buf, sizeof (buf), _("Select "), MENU_SMIME,
421 OP_GENERIC_SELECT_ENTRY);
422 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
423 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_SMIME, OP_HELP);
424 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
426 /* Create the menu */
427 menu = mutt_new_menu ();
429 menu->make_entry = smime_entry;
430 menu->menu = MENU_SMIME;
431 menu->help = helpstr;
434 /* sorting keys might be done later - TODO */
441 switch (mutt_menuLoop (menu)) {
442 case OP_GENERIC_SELECT_ENTRY:
454 fname = safe_malloc (13); /* Hash + '.' + Suffix + \0 */
455 sprintf (fname, "%.8x.%i", Table[cur].hash, Table[cur].suffix);
460 mutt_menuDestroy (&menu);
462 set_option (OPTNEEDREDRAW);
471 char *smime_get_field_from_db (char *mailbox, char *query, short public,
474 int addr_len, query_len, found = 0, ask = 0, choice = 0;
475 char cert_path[_POSIX_PATH_MAX];
476 char buf[LONG_STRING], prompt[STRING];
477 char fields[5][STRING];
481 char key_trust_level = 0;
484 if (!mailbox && !query)
487 addr_len = mailbox ? mutt_strlen (mailbox) : 0;
488 query_len = query ? mutt_strlen (query) : 0;
492 /* index-file format:
493 mailbox certfile label issuer_certfile trust_flags\n
495 certfile is a hash value generated by openssl.
496 Note that this was done according to the OpenSSL
497 specs on their CA-directory.
500 snprintf (cert_path, sizeof (cert_path), "%s/.index",
501 (public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys)));
503 if (!stat (cert_path, &info)) {
504 if ((fp = safe_fopen (cert_path, "r")) == NULL) {
505 mutt_perror (cert_path);
509 while (fgets (buf, sizeof (buf) - 1, fp) != NULL)
510 if (mailbox && !(mutt_strncasecmp (mailbox, buf, addr_len))) {
511 numFields = sscanf (buf,
512 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
513 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
514 MUTT_FORMAT (STRING) "\n",
515 fields[0], fields[1],
516 fields[2], fields[3], fields[4]);
519 if (mailbox && public &&
521 *fields[4] == 'i' || *fields[4] == 'e' || *fields[4] == 'r'))
525 if (public && *fields[4] == 'u')
526 snprintf (prompt, sizeof (prompt),
528 ("ID %s is unverified. Do you want to use it for %s ?"),
530 else if (public && *fields[4] == 'v')
531 snprintf (prompt, sizeof (prompt),
532 _("Use (untrusted!) ID %s for %s ?"),
535 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"),
539 if (may_ask && (choice = mutt_yesorno (prompt, M_NO)) == -1) {
545 else if (choice == M_NO) {
549 else if (choice == M_YES) {
550 strfcpy (key, fields[1], sizeof (key));
557 key_trust_level = *fields[4];
558 strfcpy (key, fields[1], sizeof (key));
563 numFields = sscanf (buf,
564 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
565 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
566 MUTT_FORMAT (STRING) "\n",
567 fields[0], fields[1],
568 fields[2], fields[3], fields[4]);
570 /* query = label: return certificate. */
571 if (numFields >= 3 &&
572 !(mutt_strncasecmp (query, fields[2], query_len))) {
574 strfcpy (key, fields[1], sizeof (key));
576 /* query = certificate: return intermediate certificate. */
577 else if (numFields >= 4 &&
578 !(mutt_strncasecmp (query, fields[1], query_len))) {
580 strfcpy (key, fields[3], sizeof (key));
587 if (public && *fields[4] == 'u')
588 snprintf (prompt, sizeof (prompt),
589 _("ID %s is unverified. Do you want to use it for %s ?"),
591 else if (public && *fields[4] == 'v')
592 snprintf (prompt, sizeof (prompt),
593 _("Use (untrusted!) ID %s for %s ?"), fields[1], mailbox);
595 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"), key,
597 choice = mutt_yesorno (prompt, M_NO);
598 if (choice == -1 || choice == M_NO)
601 else if (key_trust_level && may_ask) {
602 if (key_trust_level == 'u') {
603 snprintf (prompt, sizeof (prompt),
604 _("ID %s is unverified. Do you want to use it for %s ?"),
606 choice = mutt_yesorno (prompt, M_NO);
610 else if (key_trust_level == 'v') {
612 ("Warning: You have not yet decided to trust ID %s. (any key to continue)"),
620 /* Note: safe_strdup ("") returns NULL. */
621 return safe_strdup (key);
628 This sets the '*ToUse' variables for an upcoming decryption, where
629 the reuquired key is different from SmimeDefaultKey.
632 void _smime_getkeys (char *mailbox)
637 k = smime_get_field_from_db (mailbox, NULL, 0, 1);
640 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), mailbox);
641 k = smime_ask_for_key (buf, mailbox, 0);
645 /* the key used last time. */
646 if (*SmimeKeyToUse &&
647 !mutt_strcasecmp (k, SmimeKeyToUse + mutt_strlen (SmimeKeys) + 1)) {
652 smime_void_passphrase ();
654 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
655 NONULL (SmimeKeys), k);
657 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
658 NONULL (SmimeCertificates), k);
660 if (mutt_strcasecmp (k, SmimeDefaultKey))
661 smime_void_passphrase ();
667 if (*SmimeKeyToUse) {
668 if (!mutt_strcasecmp (SmimeDefaultKey,
669 SmimeKeyToUse + mutt_strlen (SmimeKeys) + 1))
672 smime_void_passphrase ();
675 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
676 NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
678 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
679 NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
682 void smime_getkeys (ENVELOPE * env)
687 if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey) {
688 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
689 NONULL (SmimeKeys), SmimeDefaultKey);
691 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
692 NONULL (SmimeCertificates), SmimeDefaultKey);
697 for (t = env->to; !found && t; t = t->next)
698 if (mutt_addr_is_user (t)) {
700 _smime_getkeys (t->mailbox);
702 for (t = env->cc; !found && t; t = t->next)
703 if (mutt_addr_is_user (t)) {
705 _smime_getkeys (t->mailbox);
707 if (!found && (t = mutt_default_from ())) {
708 _smime_getkeys (t->mailbox);
709 rfc822_free_address (&t);
713 /* This routine attempts to find the keyids of the recipients of a message.
714 * It returns NULL if any of the keys can not be found.
717 char *smime_findKeys (ADDRESS * to, ADDRESS * cc, ADDRESS * bcc)
719 char *keyID, *keylist = NULL;
720 size_t keylist_size = 0;
721 size_t keylist_used = 0;
722 ADDRESS *tmp = NULL, *addr = NULL;
723 ADDRESS **last = &tmp;
727 const char *fqdn = mutt_fqdn (1);
729 for (i = 0; i < 3; i++) {
744 *last = rfc822_cpy_adr (p);
746 last = &((*last)->next);
750 rfc822_qualify (tmp, fqdn);
752 tmp = mutt_remove_duplicates (tmp);
754 for (p = tmp; p; p = p->next) {
755 char buf[LONG_STRING];
759 if ((keyID = smime_get_field_from_db (q->mailbox, NULL, 1, 1)) == NULL) {
760 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), q->mailbox);
761 keyID = smime_ask_for_key (buf, q->mailbox, 1);
764 mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
766 rfc822_free_address (&tmp);
767 rfc822_free_address (&addr);
771 keylist_size += mutt_strlen (keyID) + 2;
772 safe_realloc (&keylist, keylist_size);
773 sprintf (keylist + keylist_used, "%s\n", keyID); /* __SPRINTF_CHECKED__ */
774 keylist_used = mutt_strlen (keylist);
776 rfc822_free_address (&addr);
779 rfc822_free_address (&tmp);
788 static int smime_handle_cert_email (char *certificate, char *mailbox,
789 int copy, char ***buffer, int *num)
791 FILE *fpout = NULL, *fperr = NULL;
792 char tmpfname[_POSIX_PATH_MAX];
794 int ret = -1, count = 0;
797 mutt_mktemp (tmpfname);
798 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
799 mutt_perror (tmpfname);
802 mutt_unlink (tmpfname);
804 mutt_mktemp (tmpfname);
805 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
807 mutt_perror (tmpfname);
810 mutt_unlink (tmpfname);
812 if ((thepid = smime_invoke (NULL, NULL, NULL,
813 -1, fileno (fpout), fileno (fperr),
814 certificate, NULL, NULL, NULL, NULL, NULL,
815 SmimeGetCertEmailCommand)) == -1) {
816 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
822 mutt_wait_filter (thepid);
830 while ((fgets (email, sizeof (email), fpout))) {
831 *(email + mutt_strlen (email) - 1) = '\0';
832 if (mutt_strncasecmp (email, mailbox, mutt_strlen (mailbox)) == 0)
835 ret = ret < 0 ? 0 : ret;
841 mutt_copy_stream (fperr, stdout);
842 mutt_any_key_to_continue (_
843 ("Error: unable to create OpenSSL subprocess!"));
851 if (copy && buffer && num) {
853 *buffer = safe_calloc (sizeof (char *), count);
857 while ((fgets (email, sizeof (email), fpout))) {
858 *(email + mutt_strlen (email) - 1) = '\0';
859 (*buffer)[count] = safe_calloc (1, mutt_strlen (email) + 1);
860 strncpy ((*buffer)[count], email, mutt_strlen (email));
875 static char *smime_extract_certificate (char *infile)
877 FILE *fpout = NULL, *fperr = NULL;
878 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
879 char tmpfname[_POSIX_PATH_MAX];
884 mutt_mktemp (tmpfname);
885 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
886 mutt_perror (tmpfname);
889 mutt_unlink (tmpfname);
891 mutt_mktemp (pk7out);
892 if ((fpout = safe_fopen (pk7out, "w+")) == NULL) {
894 mutt_perror (pk7out);
898 /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
899 extract the full set of certificates directly.
901 if ((thepid = smime_invoke (NULL, NULL, NULL,
902 -1, fileno (fpout), fileno (fperr),
903 infile, NULL, NULL, NULL, NULL, NULL,
904 SmimePk7outCommand)) == -1) {
905 mutt_any_key_to_continue (_
906 ("Error: unable to create OpenSSL subprocess!"));
909 mutt_unlink (pk7out);
913 mutt_wait_filter (thepid);
920 empty = (fgetc (fpout) == EOF);
922 mutt_perror (pk7out);
923 mutt_copy_stream (fperr, stdout);
926 mutt_unlink (pk7out);
933 mutt_mktemp (certfile);
934 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
936 mutt_unlink (pk7out);
937 mutt_perror (certfile);
941 /* Step 2: Extract the certificates from a PKCS#7 structure.
943 if ((thepid = smime_invoke (NULL, NULL, NULL,
944 -1, fileno (fpout), fileno (fperr),
945 pk7out, NULL, NULL, NULL, NULL, NULL,
946 SmimeGetCertCommand)) == -1) {
947 mutt_any_key_to_continue (_
948 ("Error: unable to create OpenSSL subprocess!"));
951 mutt_unlink (pk7out);
952 mutt_unlink (certfile);
956 mutt_wait_filter (thepid);
958 mutt_unlink (pk7out);
964 empty = (fgetc (fpout) == EOF);
966 mutt_copy_stream (fperr, stdout);
969 mutt_unlink (certfile);
976 return safe_strdup (certfile);
979 static char *smime_extract_signer_certificate (char *infile)
981 FILE *fpout = NULL, *fperr = NULL;
982 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
983 char tmpfname[_POSIX_PATH_MAX];
988 mutt_mktemp (tmpfname);
989 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
990 mutt_perror (tmpfname);
993 mutt_unlink (tmpfname);
996 mutt_mktemp (certfile);
997 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
999 mutt_perror (certfile);
1003 /* Extract signer's certificate
1005 if ((thepid = smime_invoke (NULL, NULL, NULL,
1006 -1, -1, fileno (fperr),
1007 infile, NULL, NULL, NULL, certfile, NULL,
1008 SmimeGetSignerCertCommand)) == -1) {
1009 mutt_any_key_to_continue (_
1010 ("Error: unable to create OpenSSL subprocess!"));
1013 mutt_unlink (pk7out);
1014 mutt_unlink (certfile);
1018 mutt_wait_filter (thepid);
1024 empty = (fgetc (fpout) == EOF);
1027 mutt_copy_stream (fperr, stdout);
1028 mutt_any_key_to_continue (NULL);
1031 mutt_unlink (certfile);
1038 return safe_strdup (certfile);
1044 /* Add a certificate and update index file (externally). */
1046 void smime_invoke_import (char *infile, char *mailbox)
1048 char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
1049 FILE *smimein = NULL, *fpout = NULL, *fperr = NULL;
1052 mutt_mktemp (tmpfname);
1053 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
1054 mutt_perror (tmpfname);
1057 mutt_unlink (tmpfname);
1059 mutt_mktemp (tmpfname);
1060 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
1062 mutt_perror (tmpfname);
1065 mutt_unlink (tmpfname);
1069 if (option (OPTASKCERTLABEL))
1070 mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1073 if ((certfile = smime_extract_certificate (infile))) {
1076 if ((thepid = smime_invoke (&smimein, NULL, NULL,
1077 -1, fileno (fpout), fileno (fperr),
1078 certfile, NULL, NULL, NULL, NULL, NULL,
1079 SmimeImportCertCommand)) == -1) {
1080 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
1083 fputs (buf, smimein);
1084 fputc ('\n', smimein);
1087 mutt_wait_filter (thepid);
1089 mutt_unlink (certfile);
1098 mutt_copy_stream (fpout, stdout);
1099 mutt_copy_stream (fperr, stdout);
1108 int smime_verify_sender (HEADER * h)
1110 char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
1114 mutt_mktemp (tempfname);
1115 if (!(fpout = safe_fopen (tempfname, "w"))) {
1116 mutt_perror (tempfname);
1120 if (h->security & ENCRYPT)
1121 mutt_copy_message (fpout, Context, h,
1122 M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1123 CH_MIME | CH_WEED | CH_NONEWLINE);
1125 mutt_copy_message (fpout, Context, h, 0, 0);
1131 h->env->from = mutt_expand_aliases (h->env->from);
1132 mbox = h->env->from->mailbox;
1134 else if (h->env->sender) {
1135 h->env->sender = mutt_expand_aliases (h->env->sender);
1136 mbox = h->env->sender->mailbox;
1140 if ((certfile = smime_extract_signer_certificate (tempfname))) {
1141 mutt_unlink (tempfname);
1142 if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL)) {
1144 mutt_any_key_to_continue (NULL);
1148 mutt_unlink (certfile);
1152 mutt_any_key_to_continue (_("no certfile"));
1155 mutt_any_key_to_continue (_("no mbox"));
1157 mutt_unlink (tempfname);
1170 * Creating S/MIME - bodies.
1177 pid_t smime_invoke_encrypt (FILE ** smimein, FILE ** smimeout,
1178 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1179 int smimeerrfd, const char *fname,
1182 return smime_invoke (smimein, smimeout, smimeerr,
1183 smimeinfd, smimeoutfd, smimeerrfd,
1184 fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
1185 SmimeEncryptCommand);
1190 pid_t smime_invoke_sign (FILE ** smimein, FILE ** smimeout, FILE ** smimeerr,
1191 int smimeinfd, int smimeoutfd, int smimeerrfd,
1194 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1195 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1196 SmimeCertToUse, SmimeIntermediateToUse,
1203 BODY *smime_build_smime_entity (BODY * a, char *certlist)
1205 char buf[LONG_STRING], certfile[LONG_STRING];
1206 char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1207 char smimeinfile[_POSIX_PATH_MAX];
1208 char *cert_start = certlist, *cert_end = certlist;
1209 FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
1214 mutt_mktemp (tempfile);
1215 if ((fpout = safe_fopen (tempfile, "w+")) == NULL) {
1216 mutt_perror (tempfile);
1220 mutt_mktemp (smimeerrfile);
1221 if ((smimeerr = safe_fopen (smimeerrfile, "w+")) == NULL) {
1222 mutt_perror (smimeerrfile);
1224 mutt_unlink (tempfile);
1227 mutt_unlink (smimeerrfile);
1229 mutt_mktemp (smimeinfile);
1230 if ((fptmp = safe_fopen (smimeinfile, "w+")) == NULL) {
1231 mutt_perror (smimeinfile);
1232 mutt_unlink (tempfile);
1240 int off = mutt_strlen (certfile);
1242 while (*++cert_end && *cert_end != '\n');
1246 snprintf (certfile + off, sizeof (certfile) - off, " %s/%s",
1247 NONULL (SmimeCertificates), cert_start);
1249 cert_start = cert_end;
1253 /* write a MIME entity */
1254 mutt_write_mime_header (a, fptmp);
1255 fputc ('\n', fptmp);
1256 mutt_write_mime_body (a, fptmp);
1260 smime_invoke_encrypt (&smimein, NULL, NULL, -1,
1261 fileno (fpout), fileno (smimeerr),
1262 smimeinfile, certfile)) == -1) {
1264 mutt_unlink (smimeinfile);
1265 mutt_unlink (certfile);
1271 mutt_wait_filter (thepid);
1272 mutt_unlink (smimeinfile);
1273 mutt_unlink (certfile);
1277 empty = (fgetc (fpout) == EOF);
1282 while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL) {
1284 fputs (buf, stdout);
1288 /* pause if there is any error output from SMIME */
1290 mutt_any_key_to_continue (NULL);
1293 /* fatal error while trying to encrypt message */
1295 mutt_any_key_to_continue _("No output from OpenSSL..");
1297 mutt_unlink (tempfile);
1301 t = mutt_new_body ();
1302 t->type = TYPEAPPLICATION;
1303 t->subtype = safe_strdup ("x-pkcs7-mime");
1304 mutt_set_parameter ("name", "smime.p7m", &t->parameter);
1305 mutt_set_parameter ("smime-type", "enveloped-data", &t->parameter);
1306 t->encoding = ENCBASE64; /* The output of OpenSSL SHOULD be binary */
1308 t->disposition = DISPATTACH;
1309 t->d_filename = safe_strdup ("smime.p7m");
1310 t->filename = safe_strdup (tempfile);
1311 t->unlink = 1; /*delete after sending the message */
1321 BODY *smime_sign_message (BODY * a)
1324 char buffer[LONG_STRING];
1325 char signedfile[_POSIX_PATH_MAX], filetosign[_POSIX_PATH_MAX];
1326 FILE *smimein = NULL, *smimeout = NULL, *smimeerr = NULL, *sfp = NULL;
1330 char *intermediates = smime_get_field_from_db (NULL, SmimeDefaultKey, 1, 1);
1332 if (!intermediates) {
1333 mutt_message (_("Warning: Intermediate certificate not found."));
1334 intermediates = SmimeDefaultKey; /* so openssl won't complain in any case */
1337 convert_to_7bit (a); /* Signed data _must_ be in 7-bit format. */
1339 mutt_mktemp (filetosign);
1340 if ((sfp = safe_fopen (filetosign, "w+")) == NULL) {
1341 mutt_perror (filetosign);
1345 mutt_mktemp (signedfile);
1346 if ((smimeout = safe_fopen (signedfile, "w+")) == NULL) {
1347 mutt_perror (signedfile);
1349 mutt_unlink (filetosign);
1353 mutt_write_mime_header (a, sfp);
1355 mutt_write_mime_body (a, sfp);
1360 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
1361 NONULL (SmimeKeys), SmimeDefaultKey);
1363 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
1364 NONULL (SmimeCertificates), SmimeDefaultKey);
1366 snprintf (SmimeIntermediateToUse, sizeof (SmimeIntermediateToUse), "%s/%s",
1367 NONULL (SmimeCertificates), intermediates);
1371 if ((thepid = smime_invoke_sign (&smimein, NULL, &smimeerr,
1372 -1, fileno (smimeout), -1,
1373 filetosign)) == -1) {
1374 mutt_perror _("Can't open OpenSSL subprocess!");
1377 mutt_unlink (signedfile);
1378 mutt_unlink (filetosign);
1381 fputs (SmimePass, smimein);
1382 fputc ('\n', smimein);
1386 mutt_wait_filter (thepid);
1388 /* check for errors from OpenSSL */
1392 while (fgets (buffer, sizeof (buffer) - 1, smimeerr) != NULL) {
1394 fputs (buffer, stdout);
1401 empty = (fgetc (smimeout) == EOF);
1404 mutt_unlink (filetosign);
1408 mutt_any_key_to_continue (NULL);
1411 mutt_any_key_to_continue _("No output from OpenSSL...");
1413 mutt_unlink (signedfile);
1414 return (NULL); /* fatal error while signing */
1417 t = mutt_new_body ();
1418 t->type = TYPEMULTIPART;
1419 t->subtype = safe_strdup ("signed");
1420 t->encoding = ENC7BIT;
1422 t->disposition = DISPINLINE;
1424 mutt_generate_boundary (&t->parameter);
1425 /* check if this can be extracted from private key somehow.... */
1426 mutt_set_parameter ("micalg", "sha1", &t->parameter);
1427 mutt_set_parameter ("protocol", "application/x-pkcs7-signature",
1433 t->parts->next = mutt_new_body ();
1435 t->type = TYPEAPPLICATION;
1436 t->subtype = safe_strdup ("x-pkcs7-signature");
1437 t->filename = safe_strdup (signedfile);
1438 t->d_filename = safe_strdup ("smime.p7s");
1440 t->disposition = DISPATTACH;
1441 t->encoding = ENCBASE64;
1442 t->unlink = 1; /* ok to remove this file after sending. */
1454 * Handling S/MIME - bodies.
1463 pid_t smime_invoke_verify (FILE ** smimein, FILE ** smimeout,
1464 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1465 int smimeerrfd, const char *fname,
1466 const char *sig_fname, int opaque)
1468 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1469 smimeerrfd, fname, sig_fname, NULL, NULL, NULL, NULL,
1470 (opaque ? SmimeVerifyOpaqueCommand :
1471 SmimeVerifyCommand));
1476 pid_t smime_invoke_decrypt (FILE ** smimein, FILE ** smimeout,
1477 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1478 int smimeerrfd, const char *fname)
1480 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1481 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1482 SmimeCertToUse, NULL, SmimeDecryptCommand);
1487 int smime_verify_one (BODY * sigbdy, STATE * s, const char *tempfile)
1489 char signedfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1490 FILE *fp = NULL, *smimeout = NULL, *smimeerr = NULL;
1495 size_t tmplength = 0;
1496 int origType = sigbdy->type;
1497 char *savePrefix = NULL;
1500 snprintf (signedfile, sizeof (signedfile), "%s.sig", tempfile);
1502 /* decode to a tempfile, saving the original destination */
1504 if ((s->fpout = safe_fopen (signedfile, "w")) == NULL) {
1505 mutt_perror (signedfile);
1508 /* decoding the attachment changes the size and offset, so save a copy
1509 * of the "real" values now, and restore them after processing
1511 tmplength = sigbdy->length;
1512 tmpoffset = sigbdy->offset;
1514 /* if we are decoding binary bodies, we don't want to prefix each
1515 * line with the prefix or else the data will get corrupted.
1517 savePrefix = s->prefix;
1520 mutt_decode_attachment (sigbdy, s);
1522 sigbdy->length = ftell (s->fpout);
1526 /* restore final destination and substitute the tempfile for input */
1529 s->fpin = fopen (signedfile, "r");
1531 /* restore the prefix */
1532 s->prefix = savePrefix;
1534 sigbdy->type = origType;
1537 mutt_mktemp (smimeerrfile);
1538 if (!(smimeerr = safe_fopen (smimeerrfile, "w+"))) {
1539 mutt_perror (smimeerrfile);
1540 mutt_unlink (signedfile);
1544 crypt_current_time (s, "OpenSSL");
1546 if ((thepid = smime_invoke_verify (NULL, &smimeout, NULL,
1547 -1, -1, fileno (smimeerr),
1548 tempfile, signedfile, 0)) != -1) {
1552 if (mutt_wait_filter (thepid))
1562 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1563 if (linelen && !mutt_strcasecmp (line, "verification successful"))
1572 mutt_copy_stream (smimeerr, s->fpout);
1575 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1577 mutt_unlink (signedfile);
1578 mutt_unlink (smimeerrfile);
1580 sigbdy->length = tmplength;
1581 sigbdy->offset = tmpoffset;
1583 /* restore the original source stream */
1596 This handles application/pkcs7-mime which can either be a signed
1597 or an encrypted message.
1600 static BODY *smime_handle_entity (BODY * m, STATE * s, FILE * outFile)
1605 char buf[HUGE_STRING];
1606 char outfile[_POSIX_PATH_MAX], errfile[_POSIX_PATH_MAX];
1607 char tmpfname[_POSIX_PATH_MAX];
1608 char tmptmpfname[_POSIX_PATH_MAX];
1609 FILE *smimeout = NULL, *smimein = NULL, *smimeerr = NULL;
1610 FILE *tmpfp = NULL, *tmpfp_buffer = NULL, *fpout = NULL;
1614 unsigned int type = mutt_is_application_smime (m);
1616 if (!(type & APPLICATION_SMIME))
1619 mutt_mktemp (outfile);
1620 if ((smimeout = safe_fopen (outfile, "w+")) == NULL) {
1621 mutt_perror (outfile);
1625 mutt_mktemp (errfile);
1626 if ((smimeerr = safe_fopen (errfile, "w+")) == NULL) {
1627 mutt_perror (errfile);
1632 mutt_unlink (errfile);
1635 mutt_mktemp (tmpfname);
1636 if ((tmpfp = safe_fopen (tmpfname, "w+")) == NULL) {
1637 mutt_perror (tmpfname);
1645 fseek (s->fpin, m->offset, 0);
1646 last_pos = m->offset;
1648 mutt_copy_bytes (s->fpin, tmpfp, m->length);
1653 if ((type & ENCRYPT) &&
1654 (thepid = smime_invoke_decrypt (&smimein, NULL, NULL, -1,
1655 fileno (smimeout), fileno (smimeerr),
1659 mutt_unlink (tmpfname);
1660 state_attach_puts (_
1661 ("[-- Error: unable to create OpenSSL subprocess! --]\n"),
1665 else if ((type & SIGNOPAQUE) &&
1666 (thepid = smime_invoke_verify (&smimein, NULL, NULL, -1,
1668 fileno (smimeerr), NULL, tmpfname,
1669 SIGNOPAQUE)) == -1) {
1672 mutt_unlink (tmpfname);
1673 state_attach_puts (_
1674 ("[-- Error: unable to create OpenSSL subprocess! --]\n"),
1680 if (type & ENCRYPT) {
1681 if (!smime_valid_passphrase ())
1682 smime_void_passphrase ();
1683 fputs (SmimePass, smimein);
1684 fputc ('\n', smimein);
1689 mutt_wait_filter (thepid);
1690 mutt_unlink (tmpfname);
1693 if (s->flags & M_DISPLAY) {
1696 if ((c = fgetc (smimeerr)) != EOF) {
1697 ungetc (c, smimeerr);
1699 crypt_current_time (s, "OpenSSL");
1700 mutt_copy_stream (smimeerr, s->fpout);
1701 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1705 state_attach_puts (_("[-- The following data is S/MIME"
1706 " encrypted --]\n"), s);
1708 state_attach_puts (_("[-- The following data is S/MIME signed --]\n"),
1719 mutt_mktemp (tmptmpfname);
1720 if ((fpout = safe_fopen (tmptmpfname, "w+")) == NULL) {
1721 mutt_perror (tmptmpfname);
1727 while (fgets (buf, sizeof (buf) - 1, smimeout) != NULL) {
1728 len = mutt_strlen (buf);
1729 if (len > 1 && buf[len - 2] == '\r') {
1730 buf[len - 2] = '\n';
1731 buf[len - 1] = '\0';
1739 if ((p = mutt_read_mime_header (fpout, 0)) != NULL) {
1740 fstat (fileno (fpout), &info);
1741 p->length = info.st_size - p->offset;
1743 mutt_parse_part (fpout, p);
1746 tmpfp_buffer = s->fpin;
1748 mutt_body_handler (p, s);
1749 s->fpin = tmpfp_buffer;
1755 mutt_unlink (outfile);
1759 mutt_unlink (tmptmpfname);
1764 if (s->flags & M_DISPLAY) {
1766 state_attach_puts (_("\n[-- End of S/MIME encrypted data. --]\n"), s);
1768 state_attach_puts (_("\n[-- End of S/MIME signed data. --]\n"), s);
1771 if (type & SIGNOPAQUE) {
1778 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1779 if (linelen && !mutt_strcasecmp (line, "verification successful"))
1784 m->goodsig = p->goodsig;
1785 m->badsig = p->badsig;
1796 int smime_decrypt_mime (FILE * fpin, FILE ** fpout, BODY * b, BODY ** cur)
1800 char tempfile[_POSIX_PATH_MAX];
1802 long tmpoffset = b->offset;
1803 size_t tmplength = b->length;
1804 int origType = b->type;
1807 if (!mutt_is_application_smime (b))
1813 memset (&s, 0, sizeof (s));
1815 fseek (s.fpin, b->offset, 0);
1817 mutt_mktemp (tempfile);
1818 if ((tmpfp = safe_fopen (tempfile, "w+")) == NULL) {
1819 mutt_perror (tempfile);
1823 mutt_unlink (tempfile);
1825 mutt_decode_attachment (b, &s);
1827 b->length = ftell (s.fpout);
1833 mutt_mktemp (tempfile);
1834 if ((*fpout = safe_fopen (tempfile, "w+")) == NULL) {
1835 mutt_perror (tempfile);
1838 mutt_unlink (tempfile);
1840 *cur = smime_handle_entity (b, &s, *fpout);
1841 (*cur)->goodsig = b->goodsig;
1842 (*cur)->badsig = b->badsig;
1844 b->length = tmplength;
1845 b->offset = tmpoffset;
1854 void smime_application_smime_handler (BODY * m, STATE * s)
1857 smime_handle_entity (m, s, NULL);
1861 int smime_send_menu (HEADER * msg, int *redraw)
1865 if (!(WithCrypto & APPLICATION_SMIME))
1866 return msg->security;
1868 switch (mutt_multi_choice
1870 ("S/MIME (e)ncrypt, (s)ign, encrypt (w)ith, sign (a)s, (b)oth, or (c)lear? "),
1872 case 1: /* (e)ncrypt */
1873 msg->security |= ENCRYPT;
1874 msg->security &= ~SIGN;
1877 case 3: /* encrypt (w)ith */
1878 msg->security |= ENCRYPT;
1879 switch (mutt_multi_choice (_("1: DES, 2: Triple-DES, 3: RC2-40,"
1880 " 4: RC2-64, 5: RC2-128, or (f)orget it? "),
1883 mutt_str_replace (&SmimeCryptAlg, "des");
1886 mutt_str_replace (&SmimeCryptAlg, "des3");
1889 mutt_str_replace (&SmimeCryptAlg, "rc2-40");
1892 mutt_str_replace (&SmimeCryptAlg, "rc2-64");
1895 mutt_str_replace (&SmimeCryptAlg, "rc2-128");
1897 case 6: /* forget it */
1902 case 2: /* (s)ign */
1904 if (!SmimeDefaultKey)
1905 mutt_message (_("Can't sign: No key specified. Use Sign As."));
1908 msg->security |= SIGN;
1909 msg->security &= ~ENCRYPT;
1913 case 4: /* sign (a)s */
1915 if ((p = smime_ask_for_key (_("Sign as: "), NULL, 0))) {
1916 p[mutt_strlen (p) - 1] = '\0';
1917 mutt_str_replace (&SmimeDefaultKey, p);
1919 msg->security |= SIGN;
1921 /* probably need a different passphrase */
1922 crypt_smime_void_passphrase ();
1926 msg->security &= ~SIGN;
1929 *redraw = REDRAW_FULL;
1932 case 5: /* (b)oth */
1933 msg->security |= (ENCRYPT | SIGN);
1936 case 6: /* (f)orget it */
1937 case 7: /* (c)lear */
1942 if (msg->security && msg->security != APPLICATION_SMIME)
1943 msg->security |= APPLICATION_SMIME;
1947 return (msg->security);
1951 #endif /* CRYPT_BACKEND_CLASSIC_SMIME */