tls.el (tls-format-message): Eval-and-compile
[gnus] / lisp / tls.el
1 ;;; tls.el --- TLS/SSL support via wrapper around GnuTLS
2
3 ;; Copyright (C) 1996-1999, 2002-2015 Free Software Foundation, Inc.
4
5 ;; Author: Simon Josefsson <simon@josefsson.org>
6 ;; Keywords: comm, tls, gnutls, ssl
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This package implements a simple wrapper around "gnutls-cli" to
26 ;; make Emacs support TLS/SSL.
27 ;;
28 ;; Usage is the same as `open-network-stream', i.e.:
29 ;;
30 ;; (setq tmp (open-tls-stream "test" (current-buffer) "news.mozilla.org" 563))
31 ;; ...
32 ;; #<process test>
33 ;; (process-send-string tmp "mode reader\n")
34 ;; 200 secnews.netscape.com Netscape-Collabra/3.52 03615 NNRP ready ...
35 ;; nil
36 ;; (process-send-string tmp "quit\n")
37 ;; 205
38 ;; nil
39
40 ;; To use this package as a replacement for ssl.el by William M. Perry
41 ;; <wmperry@cs.indiana.edu>, you need to evaluate the following:
42 ;;
43 ;; (defalias 'open-ssl-stream 'open-tls-stream)
44
45 ;;; Code:
46
47 (autoload 'format-spec "format-spec")
48 (autoload 'format-spec-make "format-spec")
49
50 (defgroup tls nil
51   "Transport Layer Security (TLS) parameters."
52   :group 'comm)
53
54 (defcustom tls-end-of-info
55   (concat
56    "\\("
57    ;; `openssl s_client' regexp.  See ssl/ssl_txt.c lines 219-220.
58    ;; According to apps/s_client.c line 1515 `---' is always the last
59    ;; line that is printed by s_client before the real data.
60    "^    Verify return code: .+\n---\n\\|"
61    ;; `gnutls' regexp. See src/cli.c lines 721-.
62    "^- Simple Client Mode:\n"
63    "\\(\n\\|"                           ; ignore blank lines
64    ;; According to GnuTLS v2.1.5 src/cli.c lines 640-650 and 705-715
65    ;; in `main' the handshake will start after this message.  If the
66    ;; handshake fails, the programs will abort.
67    "^\\*\\*\\* Starting TLS handshake\n\\)*"
68    "\\)")
69   "Regexp matching end of TLS client informational messages.
70 Client data stream begins after the last character matched by
71 this.  The default matches `openssl s_client' (version 0.9.8c)
72 and `gnutls-cli' (version 2.0.1) output."
73   :version "22.2"
74   :type 'regexp
75   :group 'tls)
76
77 (defcustom tls-program '("gnutls-cli --insecure -p %p %h"
78                          "gnutls-cli --insecure -p %p %h --protocols ssl3"
79                          "openssl s_client -connect %h:%p -no_ssl2 -ign_eof")
80   "List of strings containing commands to start TLS stream to a host.
81 Each entry in the list is tried until a connection is successful.
82 %h is replaced with server hostname, %p with port to connect to.
83 The program should read input on stdin and write output to stdout.
84
85 See `tls-checktrust' on how to check trusted root certs.
86
87 Also see `tls-success' for what the program should output after
88 successful negotiation."
89   :type
90   '(choice
91     (const :tag "Default list of commands"
92            ("gnutls-cli --insecure -p %p %h"
93             "gnutls-cli --insecure -p %p %h --protocols ssl3"
94             "openssl s_client -connect %h:%p -no_ssl2 -ign_eof"))
95     (list :tag "Choose commands"
96           :value
97           ("gnutls-cli --insecure -p %p %h"
98            "gnutls-cli --insecure -p %p %h --protocols ssl3"
99            "openssl s_client -connect %h:%p -no_ssl2 -ign_eof")
100           (set :inline t
101                ;; FIXME: add brief `:tag "..."' descriptions.
102                ;; (repeat :inline t :tag "Other" (string))
103                ;; See `tls-checktrust':
104                (const "gnutls-cli --x509cafile /etc/ssl/certs/ca-certificates.crt -p %p %h")
105                (const "gnutls-cli --x509cafile /etc/ssl/certs/ca-certificates.crt -p %p %h --protocols ssl3")
106                (const "openssl s_client -connect %h:%p -CAfile /etc/ssl/certs/ca-certificates.crt -no_ssl2 -ign_eof")
107                ;; No trust check:
108                (const "gnutls-cli --insecure -p %p %h")
109                (const "gnutls-cli --insecure -p %p %h --protocols ssl3")
110                (const "openssl s_client -connect %h:%p -no_ssl2 -ign_eof"))
111           (repeat :inline t :tag "Other" (string)))
112     (list :tag "List of commands"
113           (repeat :tag "Command" (string))))
114   :version "22.1"
115   :group 'tls)
116
117 (defcustom tls-process-connection-type nil
118   "Value for `process-connection-type' to use when starting TLS process."
119   :version "22.1"
120   :type 'boolean
121   :group 'tls)
122
123 (defcustom tls-success "- Handshake was completed\\|SSL handshake has read "
124   "Regular expression indicating completed TLS handshakes.
125 The default is what GnuTLS's \"gnutls-cli\" or OpenSSL's
126 \"openssl s_client\" outputs."
127   :version "22.1"
128   :type 'regexp
129   :group 'tls)
130
131 (defcustom tls-checktrust nil
132   "Indicate if certificates should be checked against trusted root certs.
133 If this is `ask', the user can decide whether to accept an
134 untrusted certificate.  You may have to adapt `tls-program' in
135 order to make this feature work properly, i.e., to ensure that
136 the external program knows about the root certificates you
137 consider trustworthy, e.g.:
138
139 \(setq tls-program
140       '(\"gnutls-cli --x509cafile /etc/ssl/certs/ca-certificates.crt -p %p %h\"
141         \"gnutls-cli --x509cafile /etc/ssl/certs/ca-certificates.crt -p %p %h --protocols ssl3\"
142         \"openssl s_client -connect %h:%p -CAfile /etc/ssl/certs/ca-certificates.crt -no_ssl2 -ign_eof\"))"
143   :type '(choice (const :tag "Always" t)
144                  (const :tag "Never" nil)
145                  (const :tag "Ask" ask))
146   :version "23.1" ;; No Gnus
147   :group 'tls)
148
149 (defcustom tls-untrusted
150   "- Peer's certificate is NOT trusted\\|Verify return code: \\([^0] \\|.[^ ]\\)"
151   "Regular expression indicating failure of TLS certificate verification.
152 The default is what GnuTLS's \"gnutls-cli\" or OpenSSL's
153 \"openssl s_client\" return in the event of unsuccessful
154 verification."
155   :type 'regexp
156   :version "23.1" ;; No Gnus
157   :group 'tls)
158
159 (defcustom tls-hostmismatch
160   "# The hostname in the certificate does NOT match"
161   "Regular expression indicating a host name mismatch in certificate.
162 When the host name specified in the certificate doesn't match the
163 name of the host you are connecting to, gnutls-cli issues a
164 warning to this effect.  There is no such feature in openssl.  Set
165 this to nil if you want to ignore host name mismatches."
166   :type 'regexp
167   :version "23.1" ;; No Gnus
168   :group 'tls)
169
170 (defcustom tls-certtool-program "certtool"
171   "Name of GnuTLS certtool.
172 Used by `tls-certificate-information'."
173   :version "22.1"
174   :type 'string
175   :group 'tls)
176
177 (eval-and-compile
178   (if (fboundp 'format-message)
179       (defalias 'tls-format-message 'format-message)
180     ;; for Emacs < 25, and XEmacs, don't worry about quote translation.
181     (defalias 'tls-format-message 'format)))
182
183 (defun tls-certificate-information (der)
184   "Parse X.509 certificate in DER format into an assoc list."
185   (let ((certificate (concat "-----BEGIN CERTIFICATE-----\n"
186                              (base64-encode-string der)
187                              "\n-----END CERTIFICATE-----\n"))
188         (exit-code 0))
189     (with-current-buffer (get-buffer-create " *certtool*")
190       (erase-buffer)
191       (insert certificate)
192       (setq exit-code (condition-case ()
193                           (call-process-region (point-min) (point-max)
194                                                tls-certtool-program
195                                                t (list (current-buffer) nil) t
196                                                "--certificate-info")
197                         (error -1)))
198       (if (/= exit-code 0)
199           nil
200         (let ((vals nil))
201           (goto-char (point-min))
202           (while (re-search-forward "^\\([^:]+\\): \\(.*\\)" nil t)
203             (push (cons (match-string 1) (match-string 2)) vals))
204           (nreverse vals))))))
205
206 (defun open-tls-stream (name buffer host port)
207   "Open a TLS connection for a port to a host.
208 Returns a subprocess-object to represent the connection.
209 Input and output work as for subprocesses; `delete-process' closes it.
210 Args are NAME BUFFER HOST PORT.
211 NAME is name for process.  It is modified if necessary to make it unique.
212 BUFFER is the buffer (or buffer name) to associate with the process.
213  Process output goes at end of that buffer, unless you specify
214  an output stream or filter function to handle the output.
215  BUFFER may be also nil, meaning that this process is not associated
216  with any buffer
217 Third arg is name of the host to connect to, or its IP address.
218 Fourth arg PORT is an integer specifying a port to connect to."
219   (let ((cmds tls-program)
220         (use-temp-buffer (null buffer))
221         process cmd done)
222     (if use-temp-buffer
223         (setq buffer (generate-new-buffer " TLS"))
224       ;; BUFFER is a string but does not exist as a buffer object.
225       (unless (and (get-buffer buffer)
226                    (buffer-name (get-buffer buffer)))
227         (generate-new-buffer buffer)))
228     (with-current-buffer buffer
229       (message "Opening TLS connection to `%s'..." host)
230       (while (and (not done) (setq cmd (pop cmds)))
231         (let ((process-connection-type tls-process-connection-type)
232               (formatted-cmd
233                (format-spec
234                 cmd
235                 (format-spec-make
236                  ?h host
237                  ?p (if (integerp port)
238                         (int-to-string port)
239                       port)))))
240           (message "Opening TLS connection with `%s'..." formatted-cmd)
241           (setq process (start-process
242                          name buffer shell-file-name shell-command-switch
243                          formatted-cmd))
244           (while (and process
245                       (memq (process-status process) '(open run))
246                       (progn
247                         (goto-char (point-min))
248                         (not (setq done (re-search-forward
249                                          tls-success nil t)))))
250             (unless (accept-process-output process 1)
251               (sit-for 1)))
252           (message "Opening TLS connection with `%s'...%s" formatted-cmd
253                    (if done "done" "failed"))
254           (if (not done)
255               (delete-process process)
256             ;; advance point to after all informational messages that
257             ;; `openssl s_client' and `gnutls' print
258             (let ((start-of-data nil))
259               (while
260                   (not (setq start-of-data
261                              ;; the string matching `tls-end-of-info'
262                              ;; might come in separate chunks from
263                              ;; `accept-process-output', so start the
264                              ;; search where `tls-success' ended
265                              (save-excursion
266                                (if (re-search-forward tls-end-of-info nil t)
267                                    (match-end 0)))))
268                 (accept-process-output process 1))
269               (if start-of-data
270                   ;; move point to start of client data
271                   (goto-char start-of-data)))
272             (setq done process))))
273       (when (and done
274                  (or
275                   (and tls-checktrust
276                        (save-excursion
277                          (goto-char (point-min))
278                          (re-search-forward tls-untrusted nil t))
279                        (or
280                         (and (not (eq tls-checktrust 'ask))
281                              (message "The certificate presented by `%s' is \
282 NOT trusted." host))
283                         (not (yes-or-no-p
284                               (tls-format-message "\
285 The certificate presented by `%s' is NOT trusted. Accept anyway? " host)))))
286                   (and tls-hostmismatch
287                        (save-excursion
288                          (goto-char (point-min))
289                          (re-search-forward tls-hostmismatch nil t))
290                        (not (yes-or-no-p
291                              (format "Host name in certificate doesn't \
292 match `%s'. Connect anyway? " host))))))
293         (setq done nil)
294         (delete-process process))
295       ;; Delete all the informational messages that could confuse
296       ;; future uses of `buffer'.
297       (delete-region (point-min) (point)))
298     (message "Opening TLS connection to `%s'...%s"
299              host (if done "done" "failed"))
300     (when use-temp-buffer
301       (if done (set-process-buffer process nil))
302       (kill-buffer buffer))
303     done))
304
305 (provide 'tls)
306
307 ;;; tls.el ends here