smime.el 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. ;;; smime.el --- S/MIME support library
  2. ;; Copyright (C) 2000-2012 Free Software Foundation, Inc.
  3. ;; Author: Simon Josefsson <simon@josefsson.org>
  4. ;; Keywords: SMIME X.509 PEM OpenSSL
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; This library perform S/MIME operations from within Emacs.
  18. ;;
  19. ;; Functions for fetching certificates from public repositories are
  20. ;; provided, currently from DNS and LDAP.
  21. ;;
  22. ;; It uses OpenSSL (tested with version 0.9.5a and 0.9.6) for signing,
  23. ;; encryption and decryption.
  24. ;;
  25. ;; Some general knowledge of S/MIME, X.509, PKCS#12, PEM etc is
  26. ;; probably required to use this library in any useful way.
  27. ;; Especially, don't expect this library to buy security for you. If
  28. ;; you don't understand what you are doing, you're as likely to lose
  29. ;; security than gain any by using this library.
  30. ;;
  31. ;; This library is not intended to provide a "raw" API for S/MIME,
  32. ;; PKCSx or similar, it's intended to perform common operations
  33. ;; done on messages encoded in these formats. The terminology chosen
  34. ;; reflect this.
  35. ;;
  36. ;; The home of this file is in Gnus, but also available from
  37. ;; http://josefsson.org/smime.html.
  38. ;;; Quick introduction:
  39. ;; Get your S/MIME certificate from VeriSign or someplace. I used
  40. ;; Netscape to generate the key and certificate request and stuff, and
  41. ;; Netscape can export the key into PKCS#12 format.
  42. ;;
  43. ;; Enter OpenSSL. To be able to use this library, it need to have the
  44. ;; SMIME key readable in PEM format. OpenSSL is used to convert the
  45. ;; key:
  46. ;;
  47. ;; $ openssl pkcs12 -in mykey.p12 -clcerts -nodes > mykey.pem
  48. ;; ...
  49. ;;
  50. ;; Now, use M-x customize-variable smime-keys and add mykey.pem as
  51. ;; a key.
  52. ;;
  53. ;; Now you should be able to sign messages! Create a buffer and write
  54. ;; something and run M-x smime-sign-buffer RET RET and you should see
  55. ;; your message MIME armored and a signature. Encryption, M-x
  56. ;; smime-encrypt-buffer, should also work.
  57. ;;
  58. ;; To be able to verify messages you need to build up trust with
  59. ;; someone. Perhaps you trust the CA that issued your certificate, at
  60. ;; least I did, so I export it's certificates from my PKCS#12
  61. ;; certificate with:
  62. ;;
  63. ;; $ openssl pkcs12 -in mykey.p12 -cacerts -nodes > cacert.pem
  64. ;; ...
  65. ;;
  66. ;; Now, use M-x customize-variable smime-CAs and add cacert.pem as a
  67. ;; CA certificate.
  68. ;;
  69. ;; You should now be able to sign messages, and even verify messages
  70. ;; sent by others that use the same CA as you.
  71. ;; Bugs:
  72. ;;
  73. ;; Don't complain that this package doesn't do encrypted PEM files,
  74. ;; submit a patch instead. I store my keys in a safe place, so I
  75. ;; didn't need the encryption. Also, programming was made easier by
  76. ;; that decision. One might think that this even influenced were I
  77. ;; store my keys, and one would probably be right. :-)
  78. ;;
  79. ;; Update: Mathias Herberts sent the patch. However, it uses
  80. ;; environment variables to pass the password to OpenSSL, which is
  81. ;; slightly insecure. Hence a new todo: use a better -passin method.
  82. ;;
  83. ;; Cache password for e.g. 1h
  84. ;;
  85. ;; Suggestions and comments are appreciated, mail me at simon@josefsson.org.
  86. ;; begin rant
  87. ;;
  88. ;; I would include pointers to introductory text on concepts used in
  89. ;; this library here, but the material I've read are so horrible I
  90. ;; don't want to recommend them.
  91. ;;
  92. ;; Why can't someone write a simple introduction to all this stuff?
  93. ;; Until then, much of this resemble security by obscurity.
  94. ;;
  95. ;; Also, I'm not going to mention anything about the wonders of
  96. ;; cryptopolitics. Oops, I just did.
  97. ;;
  98. ;; end rant
  99. ;;; Revision history:
  100. ;; 2000-06-05 initial version, committed to Gnus CVS contrib/
  101. ;; 2000-10-28 retrieve certificates via DNS CERT RRs
  102. ;; 2001-10-14 posted to gnu.emacs.sources
  103. ;; 2005-02-13 retrieve certificates via LDAP
  104. ;;; Code:
  105. ;; For Emacs <22.2 and XEmacs.
  106. (eval-and-compile
  107. (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
  108. (require 'dig)
  109. (if (locate-library "password-cache")
  110. (require 'password-cache)
  111. (require 'password))
  112. (eval-when-compile (require 'cl))
  113. (eval-and-compile
  114. (cond
  115. ((fboundp 'replace-in-string)
  116. (defalias 'smime-replace-in-string 'replace-in-string))
  117. ((fboundp 'replace-regexp-in-string)
  118. (defun smime-replace-in-string (string regexp newtext &optional literal)
  119. "Replace all matches for REGEXP with NEWTEXT in STRING.
  120. If LITERAL is non-nil, insert NEWTEXT literally. Return a new
  121. string containing the replacements.
  122. This is a compatibility function for different Emacsen."
  123. (replace-regexp-in-string regexp newtext string nil literal)))))
  124. (defgroup smime nil
  125. "S/MIME configuration."
  126. :group 'mime)
  127. (defcustom smime-keys nil
  128. "*Map mail addresses to a file containing Certificate (and private key).
  129. The file is assumed to be in PEM format. You can also associate additional
  130. certificates to be sent with every message to each address."
  131. :type '(repeat (list (string :tag "Mail address")
  132. (file :tag "File name")
  133. (repeat :tag "Additional certificate files"
  134. (file :tag "File name"))))
  135. :group 'smime)
  136. (defcustom smime-CA-directory nil
  137. "*Directory containing certificates for CAs you trust.
  138. Directory should contain files (in PEM format) named to the X.509
  139. hash of the certificate. This can be done using OpenSSL such as:
  140. $ ln -s ca.pem `openssl x509 -noout -hash -in ca.pem`.0
  141. where `ca.pem' is the file containing a PEM encoded X.509 CA
  142. certificate."
  143. :type '(choice (const :tag "none" nil)
  144. directory)
  145. :group 'smime)
  146. (defcustom smime-CA-file nil
  147. "*Files containing certificates for CAs you trust.
  148. File should contain certificates in PEM format."
  149. :version "22.1"
  150. :type '(choice (const :tag "none" nil)
  151. file)
  152. :group 'smime)
  153. (defcustom smime-certificate-directory "~/Mail/certs/"
  154. "*Directory containing other people's certificates.
  155. It should contain files named to the X.509 hash of the certificate,
  156. and the files themselves should be in PEM format."
  157. ;The S/MIME library provide simple functionality for fetching
  158. ;certificates into this directory, so there is no need to populate it
  159. ;manually.
  160. :type 'directory
  161. :group 'smime)
  162. (defcustom smime-openssl-program
  163. (and (condition-case ()
  164. (eq 0 (call-process "openssl" nil nil nil "version"))
  165. (error nil))
  166. "openssl")
  167. "*Name of OpenSSL binary."
  168. :type 'string
  169. :group 'smime)
  170. ;; OpenSSL option to select the encryption cipher
  171. (defcustom smime-encrypt-cipher "-des3"
  172. "*Cipher algorithm used for encryption."
  173. :version "22.1"
  174. :type '(choice (const :tag "Triple DES" "-des3")
  175. (const :tag "DES" "-des")
  176. (const :tag "RC2 40 bits" "-rc2-40")
  177. (const :tag "RC2 64 bits" "-rc2-64")
  178. (const :tag "RC2 128 bits" "-rc2-128"))
  179. :group 'smime)
  180. (defcustom smime-crl-check nil
  181. "*Check revocation status of signers certificate using CRLs.
  182. Enabling this will have OpenSSL check the signers certificate
  183. against a certificate revocation list (CRL).
  184. For this to work the CRL must be up-to-date and since they are
  185. normally updated quite often (ie. several times a day) you
  186. probably need some tool to keep them up-to-date. Unfortunately
  187. Gnus cannot do this for you.
  188. The CRL should either be appended (in PEM format) to your
  189. `smime-CA-file' or be located in a file (also in PEM format) in
  190. your `smime-certificate-directory' named to the X.509 hash of the
  191. certificate with .r0 as file name extension.
  192. At least OpenSSL version 0.9.7 is required for this to work."
  193. :type '(choice (const :tag "No check" nil)
  194. (const :tag "Check certificate" "-crl_check")
  195. (const :tag "Check certificate chain" "-crl_check_all"))
  196. :group 'smime)
  197. (defcustom smime-dns-server nil
  198. "*DNS server to query certificates from.
  199. If nil, use system defaults."
  200. :version "22.1"
  201. :type '(choice (const :tag "System defaults")
  202. string)
  203. :group 'smime)
  204. (defcustom smime-ldap-host-list nil
  205. "A list of LDAP hosts with S/MIME user certificates.
  206. If needed search base, binddn, passwd, etc. for the LDAP host
  207. must be set in `ldap-host-parameters-alist'."
  208. :type '(repeat (string :tag "Host name"))
  209. :version "23.1" ;; No Gnus
  210. :group 'smime)
  211. (defvar smime-details-buffer "*OpenSSL output*")
  212. ;; Use mm-util?
  213. (eval-and-compile
  214. (defalias 'smime-make-temp-file
  215. (if (fboundp 'make-temp-file)
  216. 'make-temp-file
  217. (lambda (prefix &optional dir-flag) ;; Simple implementation
  218. (expand-file-name
  219. (make-temp-name prefix)
  220. (if (fboundp 'temp-directory)
  221. (temp-directory)
  222. temporary-file-directory))))))
  223. ;; Password dialog function
  224. (declare-function password-read-and-add "password-cache" (prompt &optional key))
  225. (defun smime-ask-passphrase (&optional cache-key)
  226. "Asks the passphrase to unlock the secret key.
  227. If `cache-key' and `password-cache' is non-nil then cache the
  228. password under `cache-key'."
  229. (let ((passphrase
  230. (password-read-and-add
  231. "Passphrase for secret key (RET for no passphrase): " cache-key)))
  232. (if (string= passphrase "")
  233. nil
  234. passphrase)))
  235. ;; OpenSSL wrappers.
  236. (defun smime-call-openssl-region (b e buf &rest args)
  237. (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
  238. (0 t)
  239. (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
  240. (2 (message "OpenSSL: One of the input files could not be read.") nil)
  241. (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
  242. (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
  243. (t (error "Unknown OpenSSL exitcode") nil)))
  244. (defun smime-make-certfiles (certfiles)
  245. (if certfiles
  246. (append (list "-certfile" (expand-file-name (car certfiles)))
  247. (smime-make-certfiles (cdr certfiles)))))
  248. ;; Sign+encrypt region
  249. (defun smime-sign-region (b e keyfile)
  250. "Sign region with certified key in KEYFILE.
  251. If signing fails, the buffer is not modified. Region is assumed to
  252. have proper MIME tags. KEYFILE is expected to contain a PEM encoded
  253. private key and certificate as its car, and a list of additional
  254. certificates to include in its caar. If no additional certificates is
  255. included, KEYFILE may be the file containing the PEM encoded private
  256. key and certificate itself."
  257. (smime-new-details-buffer)
  258. (let* ((certfiles (and (cdr-safe keyfile) (cadr keyfile)))
  259. (keyfile (or (car-safe keyfile) keyfile))
  260. (buffer (generate-new-buffer " *smime*"))
  261. (passphrase (smime-ask-passphrase (expand-file-name keyfile)))
  262. (tmpfile (smime-make-temp-file "smime")))
  263. (if passphrase
  264. (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
  265. (prog1
  266. (when (prog1
  267. (apply 'smime-call-openssl-region b e (list buffer tmpfile)
  268. "smime" "-sign" "-signer" (expand-file-name keyfile)
  269. (append
  270. (smime-make-certfiles certfiles)
  271. (if passphrase
  272. (list "-passin" "env:GNUS_SMIME_PASSPHRASE"))))
  273. (if passphrase
  274. (setenv "GNUS_SMIME_PASSPHRASE" "" t))
  275. (with-current-buffer smime-details-buffer
  276. (insert-file-contents tmpfile)
  277. (delete-file tmpfile)))
  278. (delete-region b e)
  279. (insert-buffer-substring buffer)
  280. (goto-char b)
  281. (when (looking-at "^MIME-Version: 1.0$")
  282. (delete-region (point) (progn (forward-line 1) (point))))
  283. t)
  284. (with-current-buffer smime-details-buffer
  285. (goto-char (point-max))
  286. (insert-buffer-substring buffer))
  287. (kill-buffer buffer))))
  288. (defun smime-encrypt-region (b e certfiles)
  289. "Encrypt region for recipients specified in CERTFILES.
  290. If encryption fails, the buffer is not modified. Region is assumed to
  291. have proper MIME tags. CERTFILES is a list of filenames, each file
  292. is expected to contain of a PEM encoded certificate."
  293. (smime-new-details-buffer)
  294. (let ((buffer (generate-new-buffer " *smime*"))
  295. (tmpfile (smime-make-temp-file "smime")))
  296. (prog1
  297. (when (prog1
  298. (apply 'smime-call-openssl-region b e (list buffer tmpfile)
  299. "smime" "-encrypt" smime-encrypt-cipher
  300. (mapcar 'expand-file-name certfiles))
  301. (with-current-buffer smime-details-buffer
  302. (insert-file-contents tmpfile)
  303. (delete-file tmpfile)))
  304. (delete-region b e)
  305. (insert-buffer-substring buffer)
  306. (goto-char b)
  307. (when (looking-at "^MIME-Version: 1.0$")
  308. (delete-region (point) (progn (forward-line 1) (point))))
  309. t)
  310. (with-current-buffer smime-details-buffer
  311. (goto-char (point-max))
  312. (insert-buffer-substring buffer))
  313. (kill-buffer buffer))))
  314. ;; Sign+encrypt buffer
  315. (defun smime-sign-buffer (&optional keyfile buffer)
  316. "S/MIME sign BUFFER with key in KEYFILE.
  317. KEYFILE should contain a PEM encoded key and certificate."
  318. (interactive)
  319. (with-current-buffer (or buffer (current-buffer))
  320. (unless (smime-sign-region
  321. (point-min) (point-max)
  322. (if keyfile
  323. keyfile
  324. (smime-get-key-with-certs-by-email
  325. (gnus-completing-read
  326. "Sign using key"
  327. smime-keys nil (car-safe (car-safe smime-keys))))))
  328. (error "Signing failed"))))
  329. (defun smime-encrypt-buffer (&optional certfiles buffer)
  330. "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
  331. CERTFILES is a list of filenames, each file is expected to consist of
  332. a PEM encoded key and certificate. Uses current buffer if BUFFER is
  333. nil."
  334. (interactive)
  335. (with-current-buffer (or buffer (current-buffer))
  336. (unless (smime-encrypt-region
  337. (point-min) (point-max)
  338. (or certfiles
  339. (list (read-file-name "Recipient's S/MIME certificate: "
  340. smime-certificate-directory nil))))
  341. (error "Encryption failed"))))
  342. ;; Verify+decrypt region
  343. (defun smime-verify-region (b e)
  344. "Verify S/MIME message in region between B and E.
  345. Returns non-nil on success.
  346. Any details (stdout and stderr) are left in the buffer specified by
  347. `smime-details-buffer'."
  348. (smime-new-details-buffer)
  349. (let ((CAs (append (if smime-CA-file
  350. (list "-CAfile"
  351. (expand-file-name smime-CA-file)))
  352. (if smime-CA-directory
  353. (list "-CApath"
  354. (expand-file-name smime-CA-directory))))))
  355. (unless CAs
  356. (error "No CA configured"))
  357. (if smime-crl-check
  358. (add-to-list 'CAs smime-crl-check))
  359. (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
  360. "smime" "-verify" "-out" "/dev/null" CAs)
  361. t
  362. (insert-buffer-substring smime-details-buffer)
  363. nil)))
  364. (defun smime-noverify-region (b e)
  365. "Verify integrity of S/MIME message in region between B and E.
  366. Returns non-nil on success.
  367. Any details (stdout and stderr) are left in the buffer specified by
  368. `smime-details-buffer'."
  369. (smime-new-details-buffer)
  370. (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
  371. "smime" "-verify" "-noverify" "-out" '("/dev/null"))
  372. t
  373. (insert-buffer-substring smime-details-buffer)
  374. nil))
  375. (defun smime-decrypt-region (b e keyfile &optional from)
  376. "Decrypt S/MIME message in region between B and E with key in KEYFILE.
  377. Optional FROM specifies sender's mail address.
  378. On success, replaces region with decrypted data and return non-nil.
  379. Any details (stderr on success, stdout and stderr on error) are left
  380. in the buffer specified by `smime-details-buffer'."
  381. (smime-new-details-buffer)
  382. (let ((buffer (generate-new-buffer " *smime*"))
  383. CAs (passphrase (smime-ask-passphrase (expand-file-name keyfile)))
  384. (tmpfile (smime-make-temp-file "smime")))
  385. (if passphrase
  386. (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
  387. (if (prog1
  388. (apply 'smime-call-openssl-region b e
  389. (list buffer tmpfile)
  390. "smime" "-decrypt" "-recip" (expand-file-name keyfile)
  391. (if passphrase
  392. (list "-passin" "env:GNUS_SMIME_PASSPHRASE")))
  393. (if passphrase
  394. (setenv "GNUS_SMIME_PASSPHRASE" "" t))
  395. (with-current-buffer smime-details-buffer
  396. (insert-file-contents tmpfile)
  397. (delete-file tmpfile)))
  398. (progn
  399. (delete-region b e)
  400. (when from
  401. (insert "From: " from "\n"))
  402. (insert-buffer-substring buffer)
  403. (kill-buffer buffer)
  404. t)
  405. (with-current-buffer smime-details-buffer
  406. (insert-buffer-substring buffer))
  407. (kill-buffer buffer)
  408. (delete-region b e)
  409. (insert-buffer-substring smime-details-buffer)
  410. nil)))
  411. ;; Verify+Decrypt buffer
  412. (defun smime-verify-buffer (&optional buffer)
  413. "Verify integrity of S/MIME message in BUFFER.
  414. Uses current buffer if BUFFER is nil. Returns non-nil on success.
  415. Any details (stdout and stderr) are left in the buffer specified by
  416. `smime-details-buffer'."
  417. (interactive)
  418. (with-current-buffer (or buffer (current-buffer))
  419. (smime-verify-region (point-min) (point-max))))
  420. (defun smime-noverify-buffer (&optional buffer)
  421. "Verify integrity of S/MIME message in BUFFER.
  422. Does NOT verify validity of certificate (only message integrity).
  423. Uses current buffer if BUFFER is nil. Returns non-nil on success.
  424. Any details (stdout and stderr) are left in the buffer specified by
  425. `smime-details-buffer'."
  426. (interactive)
  427. (with-current-buffer (or buffer (current-buffer))
  428. (smime-noverify-region (point-min) (point-max))))
  429. (defun smime-decrypt-buffer (&optional buffer keyfile)
  430. "Decrypt S/MIME message in BUFFER using KEYFILE.
  431. Uses current buffer if BUFFER is nil, and query user of KEYFILE if it's nil.
  432. On success, replaces data in buffer and return non-nil.
  433. Any details (stderr on success, stdout and stderr on error) are left
  434. in the buffer specified by `smime-details-buffer'."
  435. (interactive)
  436. (with-current-buffer (or buffer (current-buffer))
  437. (smime-decrypt-region
  438. (point-min) (point-max)
  439. (expand-file-name
  440. (or keyfile
  441. (smime-get-key-by-email
  442. (gnus-completing-read
  443. "Decipher using key"
  444. smime-keys nil (car-safe (car-safe smime-keys)))))))))
  445. ;; Various operations
  446. (defun smime-new-details-buffer ()
  447. (with-current-buffer (get-buffer-create smime-details-buffer)
  448. (erase-buffer)))
  449. (defun smime-pkcs7-region (b e)
  450. "Convert S/MIME message between points B and E into a PKCS7 message."
  451. (smime-new-details-buffer)
  452. (when (smime-call-openssl-region b e smime-details-buffer "smime" "-pk7out")
  453. (delete-region b e)
  454. (insert-buffer-substring smime-details-buffer)
  455. t))
  456. (defun smime-pkcs7-certificates-region (b e)
  457. "Extract any certificates enclosed in PKCS7 message between points B and E."
  458. (smime-new-details-buffer)
  459. (when (smime-call-openssl-region
  460. b e smime-details-buffer "pkcs7" "-print_certs" "-text")
  461. (delete-region b e)
  462. (insert-buffer-substring smime-details-buffer)
  463. t))
  464. (defun smime-pkcs7-email-region (b e)
  465. "Get email addresses contained in certificate between points B and E.
  466. A string or a list of strings is returned."
  467. (smime-new-details-buffer)
  468. (when (smime-call-openssl-region
  469. b e smime-details-buffer "x509" "-email" "-noout")
  470. (delete-region b e)
  471. (insert-buffer-substring smime-details-buffer)
  472. t))
  473. ;; Utility functions
  474. (defun smime-get-certfiles (keyfile keys)
  475. (if keys
  476. (let ((curkey (car keys))
  477. (otherkeys (cdr keys)))
  478. (if (string= keyfile (cadr curkey))
  479. (caddr curkey)
  480. (smime-get-certfiles keyfile otherkeys)))))
  481. (defun smime-buffer-as-string-region (b e)
  482. "Return each line in region between B and E as a list of strings."
  483. (save-excursion
  484. (goto-char b)
  485. (let (res)
  486. (while (< (point) e)
  487. (let ((str (buffer-substring (point) (point-at-eol))))
  488. (unless (string= "" str)
  489. (push str res)))
  490. (forward-line))
  491. res)))
  492. ;; Find certificates
  493. (defun smime-mail-to-domain (mailaddr)
  494. (if (string-match "@" mailaddr)
  495. (replace-match "." 'fixedcase 'literal mailaddr)
  496. mailaddr))
  497. (defun smime-cert-by-dns (mail)
  498. "Find certificate via DNS for address MAIL."
  499. (let* ((dig-dns-server smime-dns-server)
  500. (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
  501. (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
  502. (certrr (with-current-buffer digbuf
  503. (dig-extract-rr (smime-mail-to-domain mail) "cert")))
  504. (cert (and certrr (dig-rr-get-pkix-cert certrr))))
  505. (if cert
  506. (with-current-buffer retbuf
  507. (insert "-----BEGIN CERTIFICATE-----\n")
  508. (let ((i 0) (len (length cert)))
  509. (while (> (- len 64) i)
  510. (insert (substring cert i (+ i 64)) "\n")
  511. (setq i (+ i 64)))
  512. (insert (substring cert i len) "\n"))
  513. (insert "-----END CERTIFICATE-----\n"))
  514. (kill-buffer retbuf)
  515. (setq retbuf nil))
  516. (kill-buffer digbuf)
  517. retbuf))
  518. (declare-function ldap-search "ldap"
  519. (filter &optional host attributes attrsonly withdn))
  520. (defun smime-cert-by-ldap-1 (mail host)
  521. "Get certificate for MAIL from the ldap server at HOST."
  522. (let ((ldapresult
  523. (funcall
  524. (if (featurep 'xemacs)
  525. (progn
  526. (require 'smime-ldap)
  527. 'smime-ldap-search)
  528. (progn
  529. (require 'ldap)
  530. 'ldap-search))
  531. (concat "mail=" mail)
  532. host '("userCertificate") nil))
  533. (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
  534. cert)
  535. (if (and (>= (length ldapresult) 1)
  536. (> (length (cadaar ldapresult)) 0))
  537. (with-current-buffer retbuf
  538. ;; Certificates on LDAP servers _should_ be in DER format,
  539. ;; but there are some servers out there that distributes the
  540. ;; certificates in PEM format (with or without
  541. ;; header/footer) so we try to handle them anyway.
  542. (if (or (string= (substring (cadaar ldapresult) 0 27)
  543. "-----BEGIN CERTIFICATE-----")
  544. (string= (substring (cadaar ldapresult) 0 3)
  545. "MII"))
  546. (setq cert
  547. (smime-replace-in-string
  548. (cadaar ldapresult)
  549. (concat "\\(\n\\|\r\\|-----BEGIN CERTIFICATE-----\\|"
  550. "-----END CERTIFICATE-----\\)")
  551. "" t))
  552. (setq cert (base64-encode-string (cadaar ldapresult) t)))
  553. (insert "-----BEGIN CERTIFICATE-----\n")
  554. (let ((i 0) (len (length cert)))
  555. (while (> (- len 64) i)
  556. (insert (substring cert i (+ i 64)) "\n")
  557. (setq i (+ i 64)))
  558. (insert (substring cert i len) "\n"))
  559. (insert "-----END CERTIFICATE-----\n"))
  560. (kill-buffer retbuf)
  561. (setq retbuf nil))
  562. retbuf))
  563. (defun smime-cert-by-ldap (mail)
  564. "Find certificate via LDAP for address MAIL."
  565. (if smime-ldap-host-list
  566. (catch 'certbuf
  567. (dolist (host smime-ldap-host-list)
  568. (let ((retbuf (smime-cert-by-ldap-1 mail host)))
  569. (when retbuf
  570. (throw 'certbuf retbuf)))))))
  571. ;; User interface.
  572. (defvar smime-buffer "*SMIME*")
  573. (defvar smime-mode-map
  574. (let ((map (make-sparse-keymap)))
  575. (suppress-keymap map)
  576. (define-key map "q" 'smime-exit)
  577. (define-key map "f" 'smime-certificate-info)
  578. map))
  579. (autoload 'gnus-completing-read "gnus-util")
  580. (put 'smime-mode 'mode-class 'special)
  581. (define-derived-mode smime-mode fundamental-mode ;special-mode
  582. "SMIME"
  583. "Major mode for browsing, viewing and fetching certificates.
  584. All normal editing commands are switched off.
  585. \\<smime-mode-map>
  586. The following commands are available:
  587. \\{smime-mode-map}"
  588. (setq mode-line-process nil)
  589. (buffer-disable-undo)
  590. (setq truncate-lines t)
  591. (setq buffer-read-only t))
  592. (defun smime-certificate-info (certfile)
  593. (interactive "fCertificate file: ")
  594. (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
  595. (switch-to-buffer buffer)
  596. (erase-buffer)
  597. (call-process smime-openssl-program nil buffer 'display
  598. "x509" "-in" (expand-file-name certfile) "-text")
  599. (fundamental-mode)
  600. (set-buffer-modified-p nil)
  601. (toggle-read-only t)
  602. (goto-char (point-min))))
  603. (defun smime-draw-buffer ()
  604. (with-current-buffer smime-buffer
  605. (let (buffer-read-only)
  606. (erase-buffer)
  607. (insert "\nYour keys:\n")
  608. (dolist (key smime-keys)
  609. (insert
  610. (format "\t\t%s: %s\n" (car key) (cadr key))))
  611. (insert "\nTrusted Certificate Authorities:\n")
  612. (insert "\nKnown Certificates:\n"))))
  613. (defun smime ()
  614. "Go to the SMIME buffer."
  615. (interactive)
  616. (unless (get-buffer smime-buffer)
  617. (with-current-buffer (get-buffer-create smime-buffer)
  618. (smime-mode)))
  619. (smime-draw-buffer)
  620. (switch-to-buffer smime-buffer))
  621. (defun smime-exit ()
  622. "Quit the S/MIME buffer."
  623. (interactive)
  624. (kill-buffer (current-buffer)))
  625. ;; Other functions
  626. (defun smime-get-key-by-email (email)
  627. (cadr (assoc email smime-keys)))
  628. (defun smime-get-key-with-certs-by-email (email)
  629. (cdr (assoc email smime-keys)))
  630. (provide 'smime)
  631. ;;; smime.el ends here