gnus-art.el (gnus-button-alist): Also support quotes 'like this'
[gnus] / lisp / sasl-scram-rfc.el
1 ;;; sasl-scram-rfc.el --- SCRAM-SHA-1 module for the SASL client framework  -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 2014-2015 Free Software Foundation, Inc.
4
5 ;; Author: Magnus Henoch <magnus.henoch@gmail.com>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; This program is implemented from RFC 5802.  It implements the
25 ;; SCRAM-SHA-1 SASL mechanism.
26 ;;
27 ;; RFC 5802 foresees "hash agility", i.e. new mechanisms based on the
28 ;; same protocol but using a different hash function.  Likewise, this
29 ;; module attempts to separate generic and specific functions, which
30 ;; should make it easy to implement any future SCRAM-* SASL mechanism.
31 ;; It should be as simple as copying the SCRAM-SHA-1 section below and
32 ;; replacing all SHA-1 references.
33 ;;
34 ;; This module does not yet implement the variants with channel
35 ;; binding, i.e. SCRAM-*-PLUS.  That would require cooperation from
36 ;; the TLS library.
37
38 ;;; Code:
39
40 (ignore-errors (require 'cl-lib))
41
42 (require 'sasl)
43 (require 'hex-util)
44 (require 'rfc2104)
45
46 ;;; Generic for SCRAM-*
47
48 (defun sasl-scram-client-first-message (client _step)
49   (let ((c-nonce (sasl-unique-id)))
50     (sasl-client-set-property client 'c-nonce c-nonce))
51   (concat
52    ;; n = client doesn't support channel binding
53    "n,"
54    ;; TODO: where would we get authorization id from?
55    ","
56    (sasl-scram--client-first-message-bare client)))
57
58 (defun sasl-scram--client-first-message-bare (client)
59   (let ((c-nonce (sasl-client-property client 'c-nonce)))
60     (concat
61      ;; TODO: saslprep username or disallow non-ASCII characters
62      "n=" (sasl-client-name client) ","
63      "r=" c-nonce)))
64
65 (eval-and-compile
66   (declare-function sasl-cl-coerce "sasl-scram-rfc")
67   (declare-function sasl-cl-mapcar-many "sasl-scram-rfc")
68   (if (fboundp 'cl-map)
69       (defalias 'sasl-cl-map 'cl-map)
70     (defun sasl-cl-mapcar-many (func seqs)
71       (if (cdr (cdr seqs))
72           (let* ((res nil)
73                  (n (apply 'min (mapcar 'length seqs)))
74                  (i 0)
75                  (args (copy-sequence seqs))
76                  p1 p2)
77             (setq seqs (copy-sequence seqs))
78             (while (< i n)
79               (setq p1 seqs p2 args)
80               (while p1
81                 (setcar p2
82                         (if (consp (car p1))
83                             (prog1 (car (car p1))
84                               (setcar p1 (cdr (car p1))))
85                           (aref (car p1) i)))
86                 (setq p1 (cdr p1) p2 (cdr p2)))
87               (push (apply func args) res)
88               (setq i (1+ i)))
89             (nreverse res))
90         (let ((res nil)
91               (x (car seqs))
92               (y (nth 1 seqs)))
93           (let ((n (min (length x) (length y)))
94                 (i -1))
95             (while (< (setq i (1+ i)) n)
96               (push (funcall func
97                              (if (consp x) (pop x) (aref x i))
98                              (if (consp y) (pop y) (aref y i)))
99                     res)))
100           (nreverse res))))
101
102     (defun sasl-cl-coerce (x type)
103       "Coerce OBJECT to type TYPE.
104 TYPE is a Common Lisp type specifier.
105 \n(fn OBJECT TYPE)"
106       (cond ((eq type 'list) (if (listp x) x (append x nil)))
107             ((eq type 'vector) (if (vectorp x) x (vconcat x)))
108             ((eq type 'string) (if (stringp x) x (concat x)))
109             ((eq type 'array) (if (arrayp x) x (vconcat x)))
110             ((and (eq type 'character) (stringp x) (= (length x) 1)) (aref x 0))
111             ((and (eq type 'character) (symbolp x))
112              (sasl-cl-coerce (symbol-name x) type))
113             ((eq type 'float) (float x))
114             ;;((cl-typep x type) x)
115             (t (error "Can't coerce %s to type %s" x type))))
116
117     (defun sasl-cl-map (type func seq &rest rest)
118       "Map a FUNCTION across one or more SEQUENCEs, returning a sequence.
119 TYPE is the sequence type to return.
120 \n(fn TYPE FUNCTION SEQUENCE...)"
121       (let (res y)
122         (if rest
123             (if (or (cdr rest) (nlistp seq) (nlistp (car rest)))
124                 (setq res (sasl-cl-mapcar-many func (cons seq rest)))
125               (setq y (car rest))
126               (while (and seq y)
127                 (push (funcall func (pop seq) (pop y)) res))
128               (setq res (nreverse res)))
129           (setq res (mapcar func seq)))
130         (and type (sasl-cl-coerce res type)))))
131
132   (if (fboundp 'string-prefix-p)
133       (defalias 'sasl-string-prefix-p 'string-prefix-p)
134     (defun sasl-string-prefix-p (prefix string &optional ignore-case)
135       "Return non-nil if PREFIX is a prefix of STRING.
136 If IGNORE-CASE is non-nil, the comparison is done without paying attention
137 to case differences."
138       (let ((prefix-length (length prefix)))
139         (cond ((> prefix-length (length string)) nil)
140               (ignore-case
141                (string-equal (downcase prefix)
142                              (downcase (substring string 0 prefix-length))))
143               (t
144                (string-equal prefix (substring string 0 prefix-length))))))))
145
146 (defun sasl-scram--client-final-message (hash-fun block-length hash-length client step)
147   (unless (string-match
148            "^r=\\([^,]+\\),s=\\([^,]+\\),i=\\([0-9]+\\)\\(?:$\\|,\\)"
149            (sasl-step-data step))
150     (sasl-error "Unexpected server response"))
151   (let* ((hmac-fun (lambda (text key)
152                      (decode-hex-string
153                       (rfc2104-hash hash-fun block-length hash-length key text))))
154          (step-data (sasl-step-data step))
155          (nonce (match-string 1 step-data))
156          (salt-base64 (match-string 2 step-data))
157          (iteration-count (string-to-number (match-string 3 step-data)))
158
159          (c-nonce (sasl-client-property client 'c-nonce))
160          ;; no channel binding, no authorization id
161          (cbind-input "n,,"))
162     (unless (sasl-string-prefix-p c-nonce nonce)
163       (sasl-error "Invalid nonce from server"))
164     (let* ((client-final-message-without-proof
165             (concat "c=" (base64-encode-string cbind-input) ","
166                     "r=" nonce))
167            (password
168             ;; TODO: either apply saslprep or disallow non-ASCII characters
169             (sasl-read-passphrase
170              (format "%s passphrase for %s: "
171                      (sasl-mechanism-name (sasl-client-mechanism client))
172                      (sasl-client-name client))))
173            (salt (base64-decode-string salt-base64))
174            (salted-password
175             ;; Hi(str, salt, i):
176             (let ((digest (concat salt (string 0 0 0 1)))
177                   (xored nil))
178               (dotimes (_i iteration-count xored)
179                 (setq digest (funcall hmac-fun digest password))
180                 (setq xored (if (null xored)
181                                 digest
182                               (sasl-cl-map 'string 'logxor xored digest))))))
183            (client-key
184             (funcall hmac-fun "Client Key" salted-password))
185            (stored-key (decode-hex-string (funcall hash-fun client-key)))
186            (auth-message
187             (concat
188              (sasl-scram--client-first-message-bare client) ","
189              step-data ","
190              client-final-message-without-proof))
191            (client-signature (funcall hmac-fun (encode-coding-string auth-message 'utf-8) stored-key))
192            (client-proof (sasl-cl-map 'string 'logxor client-key client-signature))
193            (client-final-message
194             (concat client-final-message-without-proof ","
195                     "p=" (base64-encode-string client-proof))))
196       (sasl-client-set-property client 'auth-message auth-message)
197       (sasl-client-set-property client 'salted-password salted-password)
198       client-final-message)))
199
200 (defun sasl-scram--authenticate-server (hash-fun block-length hash-length client step)
201   (cond
202    ((string-match "^e=\\([^,]+\\)" (sasl-step-data step))
203     (sasl-error (format "Server error: %s" (match-string 1 (sasl-step-data step)))))
204    ((string-match "^v=\\([^,]+\\)" (sasl-step-data step))
205     (let* ((hmac-fun (lambda (text key)
206                        (decode-hex-string
207                         (rfc2104-hash hash-fun block-length hash-length key text))))
208            (verifier (base64-decode-string (match-string 1 (sasl-step-data step))))
209            (auth-message (sasl-client-property client 'auth-message))
210            (salted-password (sasl-client-property client 'salted-password))
211            (server-key (funcall hmac-fun "Server Key" salted-password))
212            (expected-server-signature
213             (funcall hmac-fun (encode-coding-string auth-message 'utf-8) server-key)))
214       (unless (string= expected-server-signature verifier)
215         (sasl-error "Server not authenticated"))))
216    (t
217     (sasl-error "Invalid response from server"))))
218
219 ;;; SCRAM-SHA-1
220
221 (defconst sasl-scram-sha-1-steps
222   '(sasl-scram-client-first-message
223     sasl-scram-sha-1-client-final-message
224     sasl-scram-sha-1-authenticate-server))
225
226 (defun sasl-scram-sha-1-client-final-message (client step)
227   (sasl-scram--client-final-message
228    ;; HMAC-SHA1 uses block length 64 and hash length 20; see RFC 2104.
229    'sha1 64 20 client step))
230
231 (defun sasl-scram-sha-1-authenticate-server (client step)
232   (sasl-scram--authenticate-server
233    'sha1 64 20 client step))
234
235 ;; This needs to be at the end, because of how `sasl-make-mechanism'
236 ;; handles step function names.
237 (put 'sasl-scram-sha-1 'sasl-mechanism
238      (sasl-make-mechanism "SCRAM-SHA-1" sasl-scram-sha-1-steps))
239
240 (put 'sasl-scram-rfc 'sasl-mechanism (get 'sasl-scram-sha-1 'sasl-mechanism))
241
242 (provide 'sasl-scram-sha-1)
243
244 (provide 'sasl-scram-rfc)
245 ;;; sasl-scram-rfc.el ends here