; doc/emacs/misc.texi (Network Security): Fix typo.
[emacs.git] / lisp / net / network-stream.el
bloba0589e25a44cf6677f669067d9488d5213940e26
1 ;;; network-stream.el --- open network processes, possibly with encryption -*- lexical-binding: t -*-
3 ;; Copyright (C) 2010-2018 Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: network
8 ;; This file is part of GNU Emacs.
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.
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.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This library provides the function `open-network-stream', which provides a
26 ;; higher-level interface for opening TCP network processes than the built-in
27 ;; function `make-network-process'. In addition to plain connections, it
28 ;; supports TLS/SSL and STARTTLS connections.
30 ;; Usage example:
32 ;; (open-network-stream
33 ;; "*nnimap*" buffer address port
34 ;; :type 'network
35 ;; :capability-command "1 CAPABILITY\r\n"
36 ;; :success " OK "
37 ;; :starttls-function
38 ;; (lambda (capabilities)
39 ;; (if (not (string-match "STARTTLS" capabilities))
40 ;; nil
41 ;; "1 STARTTLS\r\n")))
43 ;;; Code:
45 (require 'auth-source)
46 (require 'nsm)
47 (require 'puny)
49 (declare-function starttls-available-p "starttls" ())
50 (declare-function starttls-negotiate "starttls" (process))
52 (autoload 'gnutls-negotiate "gnutls")
53 (autoload 'open-gnutls-stream "gnutls")
54 (defvar starttls-extra-arguments)
55 (defvar starttls-extra-args)
56 (defvar starttls-use-gnutls)
57 (defvar starttls-gnutls-program)
58 (defvar starttls-program)
60 ;;;###autoload
61 (defun open-network-stream (name buffer host service &rest parameters)
62 "Open a TCP connection to HOST, optionally with encryption.
63 Normally, return a network process object; with a non-nil
64 :return-list parameter, return a list instead (see below).
65 Input and output work as for subprocesses; `delete-process'
66 closes it.
68 NAME is the name for the process. It is modified if necessary to
69 make it unique.
70 BUFFER is a buffer or buffer name to associate with the process.
71 Process output goes at end of that buffer. BUFFER may be nil,
72 meaning that the process is not associated with any buffer.
73 HOST is the name or IP address of the host to connect to.
74 SERVICE is the name of the service desired, or an integer or
75 integer string specifying a port number to connect to.
77 The remaining PARAMETERS should be a sequence of keywords and
78 values:
80 :type specifies the connection type, one of the following:
81 nil or `network'
82 -- Begin with an ordinary network connection, and if
83 the parameters :success and :capability-command
84 are also supplied, try to upgrade to an encrypted
85 connection via STARTTLS. Even if that
86 fails (e.g. if HOST does not support TLS), retain
87 an unencrypted connection.
88 `plain' -- An ordinary, unencrypted network connection.
89 `starttls' -- Begin with an ordinary connection, and try
90 upgrading via STARTTLS. If that fails for any
91 reason, drop the connection; in that case the
92 returned object is a killed process.
93 `tls' -- A TLS connection.
94 `ssl' -- Equivalent to `tls'.
95 `shell' -- A shell connection.
97 :return-list specifies this function's return value.
98 If omitted or nil, return a process object. A non-nil means to
99 return (PROC . PROPS), where PROC is a process object and PROPS
100 is a plist of connection properties, with these keywords:
101 :greeting -- the greeting returned by HOST (a string), or nil.
102 :capabilities -- a string representing HOST's capabilities,
103 or nil if none could be found.
104 :type -- the resulting connection type; `plain' (unencrypted)
105 or `tls' (TLS-encrypted).
107 :end-of-command specifies a regexp matching the end of a command.
109 :end-of-capability specifies a regexp matching the end of the
110 response to the command specified for :capability-command.
111 It defaults to the regexp specified for :end-of-command.
113 :success specifies a regexp matching a message indicating a
114 successful STARTTLS negotiation. For instance, the default
115 should be \"^3\" for an NNTP connection.
117 :capability-command specifies a command used to query the HOST
118 for its capabilities. For instance, for IMAP this should be
119 \"1 CAPABILITY\\r\\n\".
121 :starttls-function specifies a function for handling STARTTLS.
122 This function should take one parameter, the response to the
123 capability command, and should return the command to switch on
124 STARTTLS if the server supports STARTTLS, and nil otherwise.
126 :always-query-capabilities says whether to query the server for
127 capabilities, even if we're doing a `plain' network connection.
129 :client-certificate should either be a list where the first
130 element is the certificate key file name, and the second
131 element is the certificate file name itself, or t, which
132 means that `auth-source' will be queried for the key and the
133 certificate. This parameter will only be used when doing TLS
134 or STARTTLS connections.
136 :use-starttls-if-possible is a boolean that says to do opportunistic
137 STARTTLS upgrades even if Emacs doesn't have built-in TLS functionality.
139 :warn-unless-encrypted is a boolean which, if :return-list is
140 non-nil, is used warn the user if the connection isn't encrypted.
142 :nogreeting is a boolean that can be used to inhibit waiting for
143 a greeting from the server.
145 :nowait, if non-nil, says the connection should be made
146 asynchronously, if possible.
148 :shell-command is a format-spec string that can be used if :type
149 is `shell'. It has two specs, %s for host and %p for port
150 number. Example: \"ssh gateway nc %s %p\".
152 :tls-parameters is a list that should be supplied if you're
153 opening a TLS connection. The first element is the TLS
154 type (either `gnutls-x509pki' or `gnutls-anon'), and the
155 remaining elements should be a keyword list accepted by
156 gnutls-boot (as returned by `gnutls-boot-parameters')."
157 (unless (featurep 'make-network-process)
158 (error "Emacs was compiled without networking support"))
159 (let ((type (plist-get parameters :type))
160 (return-list (plist-get parameters :return-list)))
161 (if (and (not return-list)
162 (or (eq type 'plain)
163 (and (memq type '(nil network))
164 (not (and (plist-get parameters :success)
165 (plist-get parameters :capability-command))))))
166 ;; The simplest case: wrapper around `make-network-process'.
167 (make-network-process :name name :buffer buffer
168 :host (puny-encode-domain host) :service service
169 :nowait (plist-get parameters :nowait)
170 :tls-parameters
171 (plist-get parameters :tls-parameters))
172 (let ((work-buffer (or buffer
173 (generate-new-buffer " *stream buffer*")))
174 (fun (cond ((and (eq type 'plain)
175 (not (plist-get parameters
176 :always-query-capabilities)))
177 'network-stream-open-plain)
178 ((memq type '(nil network starttls plain))
179 'network-stream-open-starttls)
180 ((memq type '(tls ssl)) 'network-stream-open-tls)
181 ((eq type 'shell) 'network-stream-open-shell)
182 (t (error "Invalid connection type %s" type))))
183 result)
184 (unwind-protect
185 (setq result (funcall fun name work-buffer host service parameters))
186 (unless buffer
187 (and (processp (car result))
188 (set-process-buffer (car result) nil))
189 (kill-buffer work-buffer)))
190 (if return-list
191 (list (car result)
192 :greeting (nth 1 result)
193 :capabilities (nth 2 result)
194 :type (nth 3 result)
195 :error (nth 4 result))
196 (car result))))))
198 (defun network-stream-certificate (host service parameters)
199 (let ((spec (plist-get :client-certificate parameters)))
200 (cond
201 ((listp spec)
202 ;; Either nil or a list with a key/certificate pair.
203 spec)
204 ((eq spec t)
205 (let* ((auth-info
206 (car (auth-source-search :max 1
207 :host host
208 :port service)))
209 (key (plist-get auth-info :key))
210 (cert (plist-get auth-info :cert)))
211 (and key cert
212 (list key cert)))))))
214 ;;;###autoload
215 (defalias 'open-protocol-stream 'open-network-stream)
216 (define-obsolete-function-alias 'open-protocol-stream 'open-network-stream
217 "26.1")
219 (defun network-stream-open-plain (name buffer host service parameters)
220 (let ((start (with-current-buffer buffer (point)))
221 (stream (make-network-process :name name :buffer buffer
222 :host (puny-encode-domain host)
223 :service service
224 :nowait (plist-get parameters :nowait))))
225 (when (plist-get parameters :warn-unless-encrypted)
226 (setq stream (nsm-verify-connection stream host service nil t)))
227 (list stream
228 (network-stream-get-response stream start
229 (plist-get parameters :end-of-command))
231 'plain)))
233 (defun network-stream-open-starttls (name buffer host service parameters)
234 (let* ((start (with-current-buffer buffer (point)))
235 (require-tls (eq (plist-get parameters :type) 'starttls))
236 (starttls-function (plist-get parameters :starttls-function))
237 (success-string (plist-get parameters :success))
238 (capability-command (plist-get parameters :capability-command))
239 (eoc (plist-get parameters :end-of-command))
240 (eo-capa (or (plist-get parameters :end-of-capability)
241 eoc))
242 ;; Return (STREAM GREETING CAPABILITIES RESULTING-TYPE)
243 (stream (make-network-process :name name :buffer buffer
244 :host (puny-encode-domain host)
245 :service service))
246 (greeting (and (not (plist-get parameters :nogreeting))
247 (network-stream-get-response stream start eoc)))
248 (capabilities (network-stream-command stream capability-command
249 eo-capa))
250 (resulting-type 'plain)
251 starttls-available starttls-command error)
253 ;; First check whether the server supports STARTTLS at all.
254 (when (and capabilities success-string starttls-function)
255 (setq starttls-command
256 (funcall starttls-function capabilities)))
257 ;; If we have built-in STARTTLS support, try to upgrade the
258 ;; connection.
259 (when (and starttls-command
260 (setq starttls-available
261 (or (gnutls-available-p)
262 (and (or require-tls
263 (plist-get parameters :use-starttls-if-possible))
264 (require 'starttls)
265 (starttls-available-p))))
266 (not (eq (plist-get parameters :type) 'plain)))
267 ;; If using external STARTTLS, drop this connection and start
268 ;; anew with `starttls-open-stream'.
269 (unless (gnutls-available-p)
270 (delete-process stream)
271 (setq start (with-current-buffer buffer (point-max)))
272 (let* ((starttls-extra-arguments
273 (if (or require-tls
274 (member "--insecure" starttls-extra-arguments))
275 starttls-extra-arguments
276 ;; For opportunistic TLS upgrades, we don't really
277 ;; care about the identity of the peer.
278 (cons "--insecure" starttls-extra-arguments)))
279 (starttls-extra-args starttls-extra-args)
280 (cert (network-stream-certificate host service parameters)))
281 ;; There are client certificates requested, so add them to
282 ;; the command line.
283 (when cert
284 (setq starttls-extra-arguments
285 (nconc (list "--x509keyfile" (expand-file-name (nth 0 cert))
286 "--x509certfile" (expand-file-name (nth 1 cert)))
287 starttls-extra-arguments)
288 starttls-extra-args
289 (nconc (list "--key-file" (expand-file-name (nth 0 cert))
290 "--cert-file" (expand-file-name (nth 1 cert)))
291 starttls-extra-args)))
292 (setq stream (starttls-open-stream name buffer host service)))
293 (network-stream-get-response stream start eoc)
294 ;; Requery capabilities for protocols that require it; i.e.,
295 ;; EHLO for SMTP.
296 (when (plist-get parameters :always-query-capabilities)
297 (network-stream-command stream capability-command eo-capa)))
298 (when (let ((response
299 (network-stream-command stream starttls-command eoc)))
300 (and response (string-match success-string response)))
301 ;; The server said it was OK to begin STARTTLS negotiations.
302 (if (gnutls-available-p)
303 (let ((cert (network-stream-certificate host service parameters)))
304 (condition-case nil
305 (gnutls-negotiate :process stream
306 :hostname (puny-encode-domain host)
307 :keylist (and cert (list cert)))
308 ;; If we get a gnutls-specific error (for instance if
309 ;; the certificate the server gives us is completely
310 ;; syntactically invalid), then close the connection
311 ;; and possibly (further down) try to create a
312 ;; non-encrypted connection.
313 (gnutls-error
314 (delete-process stream))))
315 (unless (starttls-negotiate stream)
316 (delete-process stream)))
317 (if (memq (process-status stream) '(open run))
318 (setq resulting-type 'tls)
319 ;; We didn't successfully negotiate STARTTLS; if TLS
320 ;; isn't demanded, reopen an unencrypted connection.
321 (unless require-tls
322 (setq stream
323 (make-network-process :name name :buffer buffer
324 :host (puny-encode-domain host)
325 :service service))
326 (network-stream-get-response stream start eoc)))
327 (unless (process-live-p stream)
328 (error "Unable to negotiate a TLS connection with %s/%s"
329 host service))
330 ;; Re-get the capabilities, which may have now changed.
331 (setq capabilities
332 (network-stream-command stream capability-command eo-capa))))
334 ;; If TLS is mandatory, close the connection if it's unencrypted.
335 (when (and require-tls
336 ;; ... but Emacs wasn't able to -- either no built-in
337 ;; support, or no gnutls-cli installed.
338 (eq resulting-type 'plain))
339 (setq error
340 (if (or (null starttls-command)
341 starttls-available)
342 "Server does not support TLS"
343 ;; See `starttls-available-p'. If this predicate
344 ;; changes to allow running under Windows, the error
345 ;; message below should be amended.
346 (if (or (memq system-type '(windows-nt ms-dos))
347 (not (featurep 'starttls)))
348 (concat "Emacs does not support TLS")
349 (concat "Emacs does not support TLS, and no external `"
350 (if starttls-use-gnutls
351 starttls-gnutls-program
352 starttls-program)
353 "' program was found"))))
354 (delete-process stream)
355 (setq stream nil))
356 ;; Check certificate validity etc.
357 (when (gnutls-available-p)
358 (setq stream (nsm-verify-connection
359 stream host service
360 (eq resulting-type 'tls)
361 (plist-get parameters :warn-unless-encrypted))))
362 ;; Return value:
363 (list stream greeting capabilities resulting-type error)))
365 (defun network-stream-command (stream command eoc)
366 (when command
367 (let ((start (with-current-buffer (process-buffer stream) (point-max))))
368 (process-send-string stream command)
369 (network-stream-get-response stream start eoc))))
371 (defun network-stream-get-response (stream start end-of-command)
372 (when end-of-command
373 (with-current-buffer (process-buffer stream)
374 (save-excursion
375 (goto-char start)
376 (while (and (memq (process-status stream) '(open run))
377 (not (re-search-forward end-of-command nil t)))
378 (accept-process-output stream 0 50)
379 (goto-char start))
380 ;; Return the data we got back, or nil if the process died.
381 (unless (= start (point))
382 (buffer-substring start (point)))))))
384 (declare-function open-tls-stream "tls" (name buffer host port))
386 (defun network-stream-open-tls (name buffer host service parameters)
387 (with-current-buffer buffer
388 (let* ((start (point-max))
389 (stream
390 (if (gnutls-available-p)
391 (open-gnutls-stream name buffer host service
392 (plist-get parameters :nowait))
393 (require 'tls)
394 (open-tls-stream name buffer host service)))
395 (eoc (plist-get parameters :end-of-command)))
396 (if (plist-get parameters :nowait)
397 (list stream nil nil 'tls)
398 ;; Check certificate validity etc.
399 (when (and (gnutls-available-p) stream)
400 (setq stream (nsm-verify-connection stream host service)))
401 (if (null stream)
402 (list nil nil nil 'plain)
403 ;; If we're using tls.el, we have to delete the output from
404 ;; openssl/gnutls-cli.
405 (when (and (not (gnutls-available-p))
406 eoc)
407 (network-stream-get-response stream start eoc)
408 (goto-char (point-min))
409 (when (re-search-forward eoc nil t)
410 (goto-char (match-beginning 0))
411 (delete-region (point-min) (line-beginning-position))))
412 (let ((capability-command (plist-get parameters :capability-command))
413 (eo-capa (or (plist-get parameters :end-of-capability)
414 eoc)))
415 (list stream
416 (network-stream-get-response stream start eoc)
417 (network-stream-command stream capability-command eo-capa)
418 'tls)))))))
420 (declare-function format-spec "format-spec" (format spec))
421 (declare-function format-spec-make "format-spec" (&rest pairs))
423 (defun network-stream-open-shell (name buffer host service parameters)
424 (require 'format-spec)
425 (let* ((capability-command (plist-get parameters :capability-command))
426 (eoc (plist-get parameters :end-of-command))
427 (start (with-current-buffer buffer (point)))
428 (stream (let ((process-connection-type nil))
429 (start-process name buffer shell-file-name
430 shell-command-switch
431 (format-spec
432 (plist-get parameters :shell-command)
433 (format-spec-make
434 ?s host
435 ?p service))))))
436 (list stream
437 (network-stream-get-response stream start eoc)
438 (network-stream-command stream capability-command
439 (or (plist-get parameters :end-of-capability)
440 eoc))
441 'plain)))
443 (provide 'network-stream)
445 ;;; network-stream.el ends here