1 ;;; url-http-ntlm.el --- NTLM authentication for the url library
3 ;; Copyright (C) 2008, 2015 Free Software Foundation, Inc.
5 ;; Author: Tom Schutzer-Weissmann <tom.weissmann@gmail.com>
6 ;; Maintainer: Thomas Fitzsimmons <fitzsim@fitzsim.org>
8 ;; Keywords: comm, data, processes, hypermedia
9 ;; Homepage: https://code.google.com/p/url-http-ntlm/
10 ;; Package-Requires: ((cl-lib "0.5") (ntlm "2.0.0"))
12 ;; This program is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; This package provides a NTLM handler for the URL package.
31 ;; M-x package-install RET url-http-ntlm RET
35 ;; Taro Kawagishi <tarok@transpulse.org> wrote ntlm.el and md4.el,
36 ;; which are parts of FLIM (Faithful Library about Internet Message).
38 ;; http://stuff.mit.edu/afs/sipb/contrib/emacs/packages/flim-1.14.7/ntlm.el
39 ;; http://stuff.mit.edu/afs/sipb/contrib/emacs/packages/flim-1.14.7/md4.el
49 ;; Remove authorization after redirect.
50 (when (and (boundp 'emacs-major-version)
51 (< emacs-major-version 25))
52 (require (intern (format "url-http-ntlm-parse-headers-%d.%d"
54 emacs-minor-version))))
57 ;;; Private variables.
58 (defvar url-http-ntlm--auth-storage nil
59 "Authentication storage.
60 An alist that maps a server name to a pair of \(<username> <ntlm
63 The hashes are built using `ntlm-get-password-hashes'.")
65 (defvar url-http-ntlm--last-args nil
66 "The last `url-http-ntlm--get-stage' arguments and result.
67 This is used to detect multiple calls.")
68 (make-variable-buffer-local 'url-http-ntlm--last-args)
70 (defvar url-http-ntlm--loop-timer-counter nil
71 "A hash table used to detect NTLM negotiation errors.
72 Keys are urls, entries are (START-TIME . COUNTER).")
74 (defvar url-http-ntlm--default-users nil
75 "An alist that stores one default username per server.")
78 ;;; Private functions.
79 (defun url-http-ntlm--detect-loop (url)
80 "Detect potential infinite loop when NTLM fails on URL."
81 (when (not url-http-ntlm--loop-timer-counter)
82 (setq url-http-ntlm--loop-timer-counter (make-hash-table :test 'equal)))
83 (let* ((url-string (url-recreate-url url))
84 (last-entry (gethash url-string url-http-ntlm--loop-timer-counter))
85 (start-time (car last-entry))
86 (counter (cdr last-entry)))
89 (if (< (- (float-time) start-time) 10.0)
91 ;; Still within time window, so increment count.
92 (puthash url-string (cons start-time (1+ counter))
93 url-http-ntlm--loop-timer-counter)
94 ;; Error detected, so remove entry and clear.
95 (url-http-ntlm--authorization url-string :clear)
96 (remhash url-string url-http-ntlm--loop-timer-counter)
98 (format (concat "Access rate to %s is too high,"
99 " indicating an NTLM failure;"
100 " to debug, re-run with url-debug set to 1")
102 ;; Timeout expired, so reset counter.
103 (puthash url-string (cons (float-time) 0)
104 url-http-ntlm--loop-timer-counter)))
105 ;; New access, so initialize counter to 0.
106 (puthash url-string (cons (float-time) 0)
107 url-http-ntlm--loop-timer-counter))))
109 (defun url-http-ntlm--ensure-user (url)
110 "Return URL with its user slot set.
111 If URL's user slot is nil, set it to the last user that made a
112 request to the host in URL's server slot."
114 (if (url-user new-url)
116 (setf (url-user new-url)
117 (cdr (assoc (url-host new-url) url-http-ntlm--default-users)))
120 (defun url-http-ntlm--ensure-keepalive ()
121 "Report an error if `url-http-attempt-keepalives' is not set."
122 (cl-assert url-http-attempt-keepalives
124 (concat "NTLM authentication won't work unless"
125 " `url-http-attempt-keepalives' is set!")))
127 (defun url-http-ntlm--clean-headers ()
128 "Remove Authorization element from `url-http-extra-headers' alist."
129 (cl-declare (special url-http-extra-headers))
130 (setq url-http-extra-headers
131 (url-http-ntlm--rmssoc "Authorization" url-http-extra-headers)))
133 (defun url-http-ntlm--get-stage (args)
134 "Determine what stage of the NTLM handshake we are at.
135 PROMPT and ARGS come from `url-ntlm-auth''s caller,
136 `url-get-authentication'. Their meaning depends on the current
137 implementation - this function is well and truly coupled.
139 url-get-authentication' calls `url-ntlm-auth' once when checking
140 what authentication schemes are supported (PROMPT and ARGS are
141 nil), and then twice for every stage of the handshake: the first
142 time PROMPT is nil, the second, t; ARGS contains the server
143 response's \"WWW-Authenticate\" header, munged by
145 (cl-declare (special url-http-extra-headers))
146 (let* ((response-rxp "^NTLM TlRMTVNTUAADAAA")
147 (challenge-rxp "^TLRMTVNTUAACAAA")
148 (auth-header (assoc "Authorization" url-http-extra-headers))
151 (url-debug 'url-http-ntlm "Buffer: %s" (current-buffer))
152 (url-debug 'url-http-ntlm "Arguments: %s" args)
153 (url-debug 'url-http-ntlm "Previous arguments: %s" url-http-ntlm--last-args)
154 (if (eq args (car url-http-ntlm--last-args))
155 ;; multiple calls, return the same argument we returned last time
157 (url-debug 'url-http-ntlm "Returning previous result: %s"
158 (cdr url-http-ntlm--last-args))
159 (cdr url-http-ntlm--last-args))
161 (cond ((and auth-header (string-match response-rxp
164 ((and (= (length args) 2)
165 (cl-destructuring-bind (challenge ntlm) args
166 (and (string-equal "ntlm" (car ntlm))
167 (string-match challenge-rxp
172 (url-http-ntlm--clean-headers)
173 (setq url-http-ntlm--last-args (cons args stage))
176 (defun url-http-ntlm--authorization (url &optional clear realm)
177 "Get or clear NTLM authentication details for URL.
178 If CLEAR is non-nil, clear any saved credentials for server.
179 Otherwise, return the credentials, prompting the user if
180 necessary. REALM appears in the prompt.
182 If URL contains a username and a password, they are used and
183 stored credentials are not affected."
184 (let* ((href (if (stringp url)
185 (url-generic-parse-url url)
187 (type (url-type href))
188 (user (url-user href))
189 (server (url-host href))
190 (port (url-portspec href))
191 (pass (url-password href))
192 (stored (assoc (list type user server port)
193 url-http-ntlm--auth-storage))
194 (both (and user pass)))
198 (setq url-http-ntlm--default-users
199 (url-http-ntlm--rmssoc server url-http-ntlm--default-users))
200 (setq url-http-ntlm--auth-storage
201 (url-http-ntlm--rmssoc '(type user* server port)
202 url-http-ntlm--auth-storage))
206 (and stored user (not (equal user (cl-second (car stored)))))
208 (let* ((user* (or user
209 (url-do-auth-source-search server type :user)
210 (read-string (url-auth-user-prompt url realm)
211 (or user (user-real-login-name)))))
214 (or (url-do-auth-source-search server type :secret)
215 (read-passwd (format "Password [for %s]: "
216 (url-recreate-url url))))))
217 (key (list type user* server port))
218 (entry `(,key . (,(ntlm-get-password-hashes pass*)))))
220 (setq url-http-ntlm--default-users
223 (url-http-ntlm--rmssoc server
224 url-http-ntlm--default-users)))
225 (setq url-http-ntlm--auth-storage
227 (url-http-ntlm--rmssoc
229 url-http-ntlm--auth-storage))))
233 (defun url-http-ntlm--get-challenge ()
234 "Return the NTLM Type-2 message in the WWW-Authenticate header.
235 Return nil if the NTLM Type-2 message is not present."
237 (mail-narrow-to-head)
238 (let ((www-authenticate (mail-fetch-field "www-authenticate")))
239 (when (string-match "NTLM\\s-+\\(\\S-+\\)"
241 (base64-decode-string (match-string 1 www-authenticate))))))
243 (defun url-http-ntlm--rmssoc (key alist)
244 "Remove all elements whose `car' match KEY from ALIST."
245 (cl-remove key alist :key 'car :test 'equal))
247 (defun url-http-ntlm--string (data)
248 "Return DATA encoded as an NTLM string."
249 (concat "NTLM " (base64-encode-string data :nobreak)))
252 ;;; Public function called by `url-get-authentication'.
254 (defun url-ntlm-auth (url &optional prompt overwrite realm args)
255 "Return an NTLM HTTP authorization header.
256 Get the contents of the Authorization header for a HTTP response
257 using NTLM authentication, to access URL. Because NTLM is a
258 two-step process, this function expects to be called twice, first
259 to generate the NTLM type 1 message (request), then to respond to
260 the server's type 2 message (challenge) with a suitable response.
262 PROMPT, OVERWRITE, and REALM are ignored.
264 ARGS is expected to contain the WWW-Authentication header from
265 the server's last response. These are used by
266 `url-http-get-stage' to determine what stage we are at."
267 (url-http-ntlm--ensure-keepalive)
268 (let* ((user-url (url-http-ntlm--ensure-user url))
269 (stage (url-http-ntlm--get-stage args)))
270 (url-debug 'url-http-ntlm "Stage: %s" stage)
272 ;; NTLM Type 1 message: the request
274 (url-http-ntlm--detect-loop user-url)
275 (cl-destructuring-bind (&optional key hash)
276 (url-http-ntlm--authorization user-url nil realm)
278 (url-http-ntlm--string
279 (ntlm-build-auth-request (cl-second key) (cl-third key))))))
280 ;; NTLM Type 3 message: the response
282 (url-http-ntlm--detect-loop user-url)
283 (let ((challenge (url-http-ntlm--get-challenge)))
284 (cl-destructuring-bind (key hash)
285 (url-http-ntlm--authorization user-url nil realm)
286 (url-http-ntlm--string
287 (ntlm-build-auth-response challenge
291 (url-http-ntlm--authorization user-url :clear)))))
294 ;;; Register `url-ntlm-auth' HTTP authentication method.
296 (url-register-auth-scheme "ntlm" nil 8)
298 (provide 'url-http-ntlm)
300 ;;; url-http-ntlm.el ends here