sasl-scram-rfc.el (sasl-cl-coerce, sasl-cl-mapcar-many, sasl-cl-map, sasl-string...
[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
44 ;;; SCRAM-SHA-1
45
46 (require 'hex-util)
47 (require 'rfc2104)
48
49 (defconst sasl-scram-sha-1-steps
50   '(sasl-scram-client-first-message
51     sasl-scram-sha-1-client-final-message
52     sasl-scram-sha-1-authenticate-server))
53
54 (defun sasl-scram-sha-1-client-final-message (client step)
55   (sasl-scram--client-final-message
56    ;; HMAC-SHA1 uses block length 64 and hash length 20; see RFC 2104.
57    'sha1 64 20 client step))
58
59 (defun sasl-scram-sha-1-authenticate-server (client step)
60   (sasl-scram--authenticate-server
61    'sha1 64 20 client step))
62
63 (put 'sasl-scram-sha-1 'sasl-mechanism
64      (sasl-make-mechanism "SCRAM-SHA-1" sasl-scram-sha-1-steps))
65
66 (provide 'sasl-scram-sha-1)
67
68 ;;; Generic for SCRAM-*
69
70 (defun sasl-scram-client-first-message (client _step)
71   (let ((c-nonce (sasl-unique-id)))
72     (sasl-client-set-property client 'c-nonce c-nonce))
73   (concat
74    ;; n = client doesn't support channel binding
75    "n,"
76    ;; TODO: where would we get authorization id from?
77    ","
78    (sasl-scram--client-first-message-bare client)))
79
80 (defun sasl-scram--client-first-message-bare (client)
81   (let ((c-nonce (sasl-client-property client 'c-nonce)))
82     (concat
83      ;; TODO: saslprep username or disallow non-ASCII characters
84      "n=" (sasl-client-name client) ","
85      "r=" c-nonce)))
86
87 (eval-and-compile
88   (declare-function sasl-cl-coerce "sasl-scram-rfc")
89   (declare-function sasl-cl-mapcar-many "sasl-scram-rfc")
90   (if (fboundp 'cl-map)
91       (defalias 'sasl-cl-map 'cl-map)
92     (defun sasl-cl-mapcar-many (func seqs)
93       (if (cdr (cdr seqs))
94           (let* ((res nil)
95                  (n (apply 'min (mapcar 'length seqs)))
96                  (i 0)
97                  (args (copy-sequence seqs))
98                  p1 p2)
99             (setq seqs (copy-sequence seqs))
100             (while (< i n)
101               (setq p1 seqs p2 args)
102               (while p1
103                 (setcar p2
104                         (if (consp (car p1))
105                             (prog1 (car (car p1))
106                               (setcar p1 (cdr (car p1))))
107                           (aref (car p1) i)))
108                 (setq p1 (cdr p1) p2 (cdr p2)))
109               (push (apply func args) res)
110               (setq i (1+ i)))
111             (nreverse res))
112         (let ((res nil)
113               (x (car seqs))
114               (y (nth 1 seqs)))
115           (let ((n (min (length x) (length y)))
116                 (i -1))
117             (while (< (setq i (1+ i)) n)
118               (push (funcall func
119                              (if (consp x) (pop x) (aref x i))
120                              (if (consp y) (pop y) (aref y i)))
121                     res)))
122           (nreverse res))))
123
124     (defun sasl-cl-coerce (x type)
125       "Coerce OBJECT to type TYPE.
126 TYPE is a Common Lisp type specifier.
127 \n(fn OBJECT TYPE)"
128       (cond ((eq type 'list) (if (listp x) x (append x nil)))
129             ((eq type 'vector) (if (vectorp x) x (vconcat x)))
130             ((eq type 'string) (if (stringp x) x (concat x)))
131             ((eq type 'array) (if (arrayp x) x (vconcat x)))
132             ((and (eq type 'character) (stringp x) (= (length x) 1)) (aref x 0))
133             ((and (eq type 'character) (symbolp x))
134              (sasl-cl-coerce (symbol-name x) type))
135             ((eq type 'float) (float x))
136             ;;((cl-typep x type) x)
137             (t (error "Can't coerce %s to type %s" x type))))
138
139     (defun sasl-cl-map (type func seq &rest rest)
140       "Map a FUNCTION across one or more SEQUENCEs, returning a sequence.
141 TYPE is the sequence type to return.
142 \n(fn TYPE FUNCTION SEQUENCE...)"
143       (let (res y)
144         (if rest
145             (if (or (cdr rest) (nlistp seq) (nlistp (car rest)))
146                 (setq res (sasl-cl-mapcar-many func (cons seq rest)))
147               (setq y (car rest))
148               (while (and seq y)
149                 (push (funcall func (pop seq) (pop y)) res))
150               (setq res (nreverse res)))
151           (setq res (mapcar func seq)))
152         (and type (sasl-cl-coerce res type)))))
153
154   (if (fboundp 'string-prefix-p)
155       (defalias 'sasl-string-prefix-p 'string-prefix-p)
156     (defun sasl-string-prefix-p (prefix string &optional ignore-case)
157       "Return non-nil if PREFIX is a prefix of STRING.
158 If IGNORE-CASE is non-nil, the comparison is done without paying attention
159 to case differences."
160       (let ((prefix-length (length prefix)))
161         (cond ((> prefix-length (length string)) nil)
162               (ignore-case
163                (string-equal (downcase prefix)
164                              (downcase (substring string 0 prefix-length))))
165               (t
166                (string-equal prefix (substring string 0 prefix-length))))))))
167
168 (defun sasl-scram--client-final-message (hash-fun block-length hash-length client step)
169   (unless (string-match
170            "^r=\\([^,]+\\),s=\\([^,]+\\),i=\\([0-9]+\\)\\(?:$\\|,\\)"
171            (sasl-step-data step))
172     (sasl-error "Unexpected server response"))
173   (let* ((hmac-fun (lambda (text key)
174                      (decode-hex-string
175                       (rfc2104-hash hash-fun block-length hash-length key text))))
176          (step-data (sasl-step-data step))
177          (nonce (match-string 1 step-data))
178          (salt-base64 (match-string 2 step-data))
179          (iteration-count (string-to-number (match-string 3 step-data)))
180
181          (c-nonce (sasl-client-property client 'c-nonce))
182          ;; no channel binding, no authorization id
183          (cbind-input "n,,"))
184     (unless (sasl-string-prefix-p c-nonce nonce)
185       (sasl-error "Invalid nonce from server"))
186     (let* ((client-final-message-without-proof
187             (concat "c=" (base64-encode-string cbind-input) ","
188                     "r=" nonce))
189            (password
190             ;; TODO: either apply saslprep or disallow non-ASCII characters
191             (sasl-read-passphrase
192              (format "%s passphrase for %s: "
193                      (sasl-mechanism-name (sasl-client-mechanism client))
194                      (sasl-client-name client))))
195            (salt (base64-decode-string salt-base64))
196            (salted-password
197             ;; Hi(str, salt, i):
198             (let ((digest (concat salt (string 0 0 0 1)))
199                   (xored nil))
200               (dotimes (_i iteration-count xored)
201                 (setq digest (funcall hmac-fun digest password))
202                 (setq xored (if (null xored)
203                                 digest
204                               (sasl-cl-map 'string 'logxor xored digest))))))
205            (client-key
206             (funcall hmac-fun "Client Key" salted-password))
207            (stored-key (decode-hex-string (funcall hash-fun client-key)))
208            (auth-message
209             (concat
210              (sasl-scram--client-first-message-bare client) ","
211              step-data ","
212              client-final-message-without-proof))
213            (client-signature (funcall hmac-fun (encode-coding-string auth-message 'utf-8) stored-key))
214            (client-proof (sasl-cl-map 'string 'logxor client-key client-signature))
215            (client-final-message
216             (concat client-final-message-without-proof ","
217                     "p=" (base64-encode-string client-proof))))
218       (sasl-client-set-property client 'auth-message auth-message)
219       (sasl-client-set-property client 'salted-password salted-password)
220       client-final-message)))
221
222 (defun sasl-scram--authenticate-server (hash-fun block-length hash-length client step)
223   (cond
224    ((string-match "^e=\\([^,]+\\)" (sasl-step-data step))
225     (sasl-error (format "Server error: %s" (match-string 1 (sasl-step-data step)))))
226    ((string-match "^v=\\([^,]+\\)" (sasl-step-data step))
227     (let* ((hmac-fun (lambda (text key)
228                        (decode-hex-string
229                         (rfc2104-hash hash-fun block-length hash-length key text))))
230            (verifier (base64-decode-string (match-string 1 (sasl-step-data step))))
231            (auth-message (sasl-client-property client 'auth-message))
232            (salted-password (sasl-client-property client 'salted-password))
233            (server-key (funcall hmac-fun "Server Key" salted-password))
234            (expected-server-signature
235             (funcall hmac-fun (encode-coding-string auth-message 'utf-8) server-key)))
236       (unless (string= expected-server-signature verifier)
237         (sasl-error "Server not authenticated"))))
238    (t
239     (sasl-error "Invalid response from server"))))
240
241 (provide 'sasl-scram-rfc)
242 ;;; sasl-scram-rfc.el ends here