e43f09e5ed1168f829f22714d0007068f62a15b7
[gnus] / lisp / auth-source.el
1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
2
3 ;; Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
4
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
6 ;; Keywords: news
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 is the auth-source.el package.  It lets users tell Gnus how to
26 ;; authenticate in a single place.  Simplicity is the goal.  Instead
27 ;; of providing 5000 options, we'll stick to simple, easy to
28 ;; understand options.
29
30 ;; See the auth.info Info documentation for details.
31
32 ;;; Code:
33
34 (require 'gnus-util)
35
36 (eval-when-compile (require 'cl))
37 (autoload 'netrc-machine-user-or-password "netrc")
38 (autoload 'secrets-create-item "secrets")
39 (autoload 'secrets-delete-item "secrets")
40 (autoload 'secrets-get-alias "secrets")
41 (autoload 'secrets-get-attribute "secrets")
42 (autoload 'secrets-get-secret "secrets")
43 (autoload 'secrets-list-collections "secrets")
44 (autoload 'secrets-search-items "secrets")
45
46 (defgroup auth-source nil
47   "Authentication sources."
48   :version "23.1" ;; No Gnus
49   :group 'gnus)
50
51 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
52                                    (pop3 "pop3" "pop" "pop3s" "110" "995")
53                                    (ssh  "ssh" "22")
54                                    (sftp "sftp" "115")
55                                    (smtp "smtp" "25"))
56   "List of authentication protocols and their names"
57
58   :group 'auth-source
59   :version "23.2" ;; No Gnus
60   :type '(repeat :tag "Authentication Protocols"
61                  (cons :tag "Protocol Entry"
62                        (symbol :tag "Protocol")
63                        (repeat :tag "Names"
64                                (string :tag "Name")))))
65
66 ;;; generate all the protocols in a format Customize can use
67 ;;; TODO: generate on the fly from auth-source-protocols
68 (defconst auth-source-protocols-customize
69   (mapcar (lambda (a)
70             (let ((p (car-safe a)))
71               (list 'const
72                     :tag (upcase (symbol-name p))
73                     p)))
74           auth-source-protocols))
75
76 (defvar auth-source-cache (make-hash-table :test 'equal)
77   "Cache for auth-source data")
78
79 (defcustom auth-source-do-cache t
80   "Whether auth-source should cache information."
81   :group 'auth-source
82   :version "23.2" ;; No Gnus
83   :type `boolean)
84
85 (defcustom auth-source-debug nil
86   "Whether auth-source should log debug messages.
87 Also see `auth-source-hide-passwords'.
88
89 If the value is nil, debug messages are not logged.
90 If the value is t, debug messages are logged with `message'.
91  In that case, your authentication data will be in the
92  clear (except for passwords, which are always stripped out).
93 If the value is a function, debug messages are logged by calling
94  that function using the same arguments as `message'."
95   :group 'auth-source
96   :version "23.2" ;; No Gnus
97   :type `(choice
98           :tag "auth-source debugging mode"
99           (const :tag "Log using `message' to the *Messages* buffer" t)
100           (function :tag "Function that takes arguments like `message'")
101           (const :tag "Don't log anything" nil)))
102
103 (defcustom auth-source-hide-passwords t
104   "Whether auth-source should hide passwords in log messages.
105 Only relevant if `auth-source-debug' is not nil."
106   :group 'auth-source
107   :version "23.2" ;; No Gnus
108   :type `boolean)
109
110 (defcustom auth-sources '((:source "~/.authinfo.gpg"))
111   "List of authentication sources.
112
113 The default will get login and password information from a .gpg
114 file, which you should set up with the EPA/EPG packages to be
115 encrypted.  See the auth.info manual for details.
116
117 Each entry is the authentication type with optional properties.
118
119 It's best to customize this with `M-x customize-variable' because the choices
120 can get pretty complex."
121   :group 'auth-source
122   :version "23.2" ;; No Gnus
123   :type `(repeat :tag "Authentication Sources"
124                  (list :tag "Source definition"
125                        (const :format "" :value :source)
126                        (choice :tag "Authentication backend choice"
127                                (string :tag "Authentication Source (file)")
128                                (list :tag "secrets.el (Secret Service API/KWallet/GNOME Keyring)"
129                                      (const :format "" :value :secrets)
130                                      (choice :tag "Collection to use"
131                                              (string :tag "Collection name")
132                                              (const :tag "Default" 'default)
133                                              (const :tag "Login" "login")
134                                              (const :tag "Temporary" "session"))))
135                        (repeat :tag "Extra Parameters" :inline t
136                                (choice :tag "Extra parameter"
137                                        (list :tag "Host (omit to match as a fallback)"
138                                              (const :format "" :value :host)
139                                              (choice :tag "Host (machine) choice"
140                                                      (const :tag "Any" t)
141                                                      (regexp :tag "Host (machine) regular expression")))
142                                        (list :tag "Protocol (omit to match as a fallback)"
143                                              (const :format "" :value :protocol)
144                                              (choice :tag "Protocol"
145                                                      (const :tag "Any" t)
146                                                      ,@auth-source-protocols-customize))
147                                        (list :tag "User  (omit to match as a fallback)" :inline t
148                                              (const :format "" :value :user)
149                                              (choice :tag "Personality or username"
150                                                      (const :tag "Any" t)
151                                                      (string :tag "Specific user name"))))))))
152
153 ;; temp for debugging
154 ;; (unintern 'auth-source-protocols)
155 ;; (unintern 'auth-sources)
156 ;; (customize-variable 'auth-sources)
157 ;; (setq auth-sources nil)
158 ;; (format "%S" auth-sources)
159 ;; (customize-variable 'auth-source-protocols)
160 ;; (setq auth-source-protocols nil)
161 ;; (format "%S" auth-source-protocols)
162 ;; (auth-source-pick nil :host "a" :port 'imap)
163 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
164 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
165 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
166 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
167 ;; (auth-source-protocol-defaults 'imap)
168
169 ;; (let ((auth-source-debug 'debug)) (auth-source-debug "hello"))
170 ;; (let ((auth-source-debug t)) (auth-source-debug "hello"))
171 ;; (let ((auth-source-debug nil)) (auth-source-debug "hello"))
172 (defun auth-source-do-debug (&rest msg)
173   ;; set logger to either the function in auth-source-debug or 'message
174   ;; note that it will be 'message if auth-source-debug is nil, so
175   ;; we also check the value
176   (when auth-source-debug
177     (let ((logger (if (functionp auth-source-debug)
178                       auth-source-debug
179                     'message)))
180       (apply logger msg))))
181
182 ;; (auth-source-pick nil :host "any" :protocol 'imap :user "joe")
183 ;; (auth-source-pick t :host "any" :protocol 'imap :user "joe")
184 ;; (setq auth-sources '((:source (:secrets default) :host t :protocol t :user "joe")
185 ;;                   (:source (:secrets "session") :host t :protocol t :user "joe")
186 ;;                   (:source (:secrets "login") :host t :protocol t)
187 ;;                   (:source "~/.authinfo.gpg" :host t :protocol t)))
188
189 ;; (setq auth-sources '((:source (:secrets default) :host t :protocol t :user "joe")
190 ;;                   (:source (:secrets "session") :host t :protocol t :user "joe")
191 ;;                   (:source (:secrets "login") :host t :protocol t)
192 ;;                   ))
193
194 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :protocol t)))
195
196 (defun auth-get-source (entry)
197   "Return the source string of ENTRY, which is one entry in `auth-sources'.
198 If it is a Secret Service API, return the collection name, otherwise
199 the file name."
200   (let ((source (plist-get entry :source)))
201     (if (stringp source)
202         source
203       ;; Secret Service API.
204       (setq source (plist-get source :secrets))
205       (when (eq source 'default)
206         (setq source (or (secrets-get-alias "default") "login")))
207       (or source "session"))))
208
209 (defun auth-source-pick (&rest spec)
210   "Parse `auth-sources' for matches of the SPEC plist.
211
212 Common keys are :host, :protocol, and :user.  A value of t in
213 SPEC means to always succeed in the match.  A string value is
214 matched as a regex."
215   (let ((keys (loop for i below (length spec) by 2 collect (nth i spec)))
216         choices)
217     (dolist (choice (copy-tree auth-sources) choices)
218       (let ((source (plist-get choice :source))
219             (match t))
220         (when
221             (and
222              ;; Check existence of source.
223              (if (consp source)
224                  ;; Secret Service API.
225                  (member (auth-get-source choice) (secrets-list-collections))
226                ;; authinfo file.
227                (file-exists-p source))
228
229              ;; Check keywords.
230              (dolist (k keys match)
231                (let* ((v (plist-get spec k))
232                       (choicev (if (plist-member choice k)
233                                    (plist-get choice k) t)))
234                  (setq match
235                        (and match
236                             (or
237                              ;; source always matches spec key
238                              (eq t choicev)
239                              ;; source key gives regex to match against spec
240                              (and (stringp choicev) (string-match choicev v))
241                              ;; source key gives symbol to match against spec
242                              (and (symbolp choicev) (eq choicev v))))))))
243
244           (add-to-list 'choices choice 'append))))))
245
246 (defun auth-source-retrieve (mode entry &rest spec)
247   "Retrieve MODE credentials according to SPEC from ENTRY."
248   (catch 'no-password
249     (let ((host (plist-get spec :host))
250           (user (plist-get spec :user))
251           (prot (plist-get spec :protocol))
252           (source (plist-get entry :source))
253           result)
254       (cond
255        ;; Secret Service API.
256        ((consp source)
257         (let ((coll (auth-get-source entry))
258               item)
259           ;; Loop over candidates with a matching host attribute.
260           (dolist (elt (secrets-search-items coll :host host) item)
261             (when (and (or (not user)
262                            (string-equal
263                             user (secrets-get-attribute coll elt :user)))
264                        (or (not prot)
265                            (string-equal
266                             prot (secrets-get-attribute coll elt :protocol))))
267               (setq item elt)
268               (return elt)))
269           ;; Compose result.
270           (when item
271             (setq result
272                   (mapcar (lambda (m)
273                             (if (string-equal "password" m)
274                                 (or (secrets-get-secret coll item)
275                                     ;; When we do not find a password,
276                                     ;; we return nil anyway.
277                                     (throw 'no-password nil))
278                               (or (secrets-get-attribute coll item :user)
279                                   user)))
280                           (if (consp mode) mode (list mode)))))
281           (if (consp mode) result (car result))))
282        ;; Anything else is netrc.
283        (t
284         (let ((search (list source (list host) (list (format "%s" prot))
285                             (auth-source-protocol-defaults prot))))
286           (setq result
287                 (mapcar (lambda (m)
288                           (if (string-equal "password" m)
289                               (or (apply
290                                    'netrc-machine-user-or-password m search)
291                                   ;; When we do not find a password, we
292                                   ;; return nil anyway.
293                                   (throw 'no-password nil))
294                             (or (apply
295                                  'netrc-machine-user-or-password m search)
296                                 user)))
297                         (if (consp mode) mode (list mode)))))
298         (if (consp mode) result (car result)))))))
299
300 (defun auth-source-create (mode entry &rest spec)
301   "Create interactively credentials according to SPEC in ENTRY.
302 Return structure as specified by MODE."
303   (let* ((host (plist-get spec :host))
304          (user (plist-get spec :user))
305          (prot (plist-get spec :protocol))
306          (source (plist-get entry :source))
307          (name (concat (if user (format "%s@" user))
308                        host
309                        (if prot (format ":%s" prot))))
310          result)
311     (setq result
312           (mapcar
313            (lambda (m)
314              (if (equal "password" m)
315                  (let ((passwd (read-passwd "Password: ")))
316                    (cond
317                     ;; Secret Service API.
318                     ((consp source)
319                      (apply
320                       'secrets-create-item
321                       (auth-get-source entry) name passwd spec))
322                     (t)) ;; netrc not implemented yes.
323                    passwd)
324                (or
325                 ;; the originally requested :user
326                 user
327                 "unknown-user")))
328            (if (consp mode) mode (list mode))))
329     (if (consp mode) result (car result))))
330
331 (defun auth-source-delete (entry &rest spec)
332   "Delete credentials according to SPEC in ENTRY."
333   (let ((host (plist-get spec :host))
334         (user (plist-get spec :user))
335         (prot (plist-get spec :protocol))
336         (source (plist-get entry :source)))
337     (cond
338      ;; Secret Service API.
339      ((consp source)
340       (let ((coll (auth-get-source entry)))
341         ;; Loop over candidates with a matching host attribute.
342         (dolist (elt (secrets-search-items coll :host host))
343           (when (and (or (not user)
344                          (string-equal
345                           user (secrets-get-attribute coll elt :user)))
346                      (or (not prot)
347                          (string-equal
348                           prot (secrets-get-attribute coll elt :protocol))))
349             (secrets-delete-item coll elt)))))
350      (t)))) ;; netrc not implemented yes.
351
352 (defun auth-source-forget-user-or-password
353   (mode host protocol &optional username)
354   "Remove cached authentication token."
355   (interactive "slogin/password: \nsHost: \nsProtocol: \n") ;for testing
356   (remhash
357    (if username
358        (format "%s %s:%s %s" mode host protocol username)
359      (format "%s %s:%s" mode host protocol))
360    auth-source-cache))
361
362 (defun auth-source-forget-all-cached ()
363   "Forget all cached auth-source authentication tokens."
364   (interactive)
365   (setq auth-source-cache (make-hash-table :test 'equal)))
366
367 ;; (progn
368 ;;   (auth-source-forget-all-cached)
369 ;;   (list
370 ;;    (auth-source-user-or-password '("login" "password") "imap.myhost.com" "other")
371 ;;    (auth-source-user-or-password '("login" "password") "imap.myhost.com" "other" "tzz")
372 ;;    (auth-source-user-or-password '("login" "password") "imap.myhost.com" "other" "joe")))
373
374 (defun auth-source-user-or-password
375   (mode host protocol &optional username create-missing delete-existing)
376   "Find MODE (string or list of strings) matching HOST and PROTOCOL.
377
378 USERNAME is optional and will be used as \"login\" in a search
379 across the Secret Service API (see secrets.el) if the resulting
380 items don't have a username.  This means that if you search for
381 username \"joe\" and it matches an item but the item doesn't have
382 a :user attribute, the username \"joe\" will be returned.
383
384 A non nil DELETE-EXISTING means deleting any matching password
385 entry in the respective sources.  This is useful only when
386 CREATE-MISSING is non nil as well; the intended use case is to
387 remove wrong password entries.
388
389 If no matching entry is found, and CREATE-MISSING is non nil,
390 the password will be retrieved interactively, and it will be
391 stored in the password database which matches best (see
392 `auth-sources').
393
394 MODE can be \"login\" or \"password\"."
395   (auth-source-do-debug
396    "auth-source-user-or-password: get %s for %s (%s) + user=%s"
397    mode host protocol username)
398   (let* ((listy (listp mode))
399          (mode (if listy mode (list mode)))
400          (cname (if username
401                     (format "%s %s:%s %s" mode host protocol username)
402                   (format "%s %s:%s" mode host protocol)))
403          (search (list :host host :protocol protocol))
404          (search (if username (append search (list :user username)) search))
405          (found (if (not delete-existing)
406                     (gethash cname auth-source-cache)
407                   (remhash cname auth-source-cache)
408                   nil)))
409     (if found
410         (progn
411           (auth-source-do-debug
412            "auth-source-user-or-password: cached %s=%s for %s (%s) + %s"
413            mode
414            ;; don't show the password
415            (if (and (member "password" mode) auth-source-hide-passwords)
416                "SECRET"
417              found)
418            host protocol username)
419           found)                        ; return the found data
420       ;; else, if not found
421       (let ((choices (apply 'auth-source-pick search)))
422         (dolist (choice choices)
423           (if delete-existing
424               (apply 'auth-source-delete choice search)
425             (setq found (apply 'auth-source-retrieve mode choice search)))
426           (and found (return found)))
427
428         ;; We haven't found something, so we will create it interactively.
429         (when (and (not found) choices create-missing)
430           (setq found (apply 'auth-source-create mode (car choices) search)))
431
432         ;; Cache the result.
433         (when found
434           (auth-source-do-debug
435            "auth-source-user-or-password: found %s=%s for %s (%s) + %s"
436            mode
437            ;; don't show the password
438            (if (and (member "password" mode) auth-source-hide-passwords)
439                "SECRET" found)
440            host protocol username)
441           (setq found (if listy found (car-safe found)))
442           (when auth-source-do-cache
443             (puthash cname found auth-source-cache)))
444
445         found))))
446
447 (defun auth-source-protocol-defaults (protocol)
448   "Return a list of default ports and names for PROTOCOL."
449   (cdr-safe (assoc protocol auth-source-protocols)))
450
451 (defun auth-source-user-or-password-imap (mode host)
452   (auth-source-user-or-password mode host 'imap))
453
454 (defun auth-source-user-or-password-pop3 (mode host)
455   (auth-source-user-or-password mode host 'pop3))
456
457 (defun auth-source-user-or-password-ssh (mode host)
458   (auth-source-user-or-password mode host 'ssh))
459
460 (defun auth-source-user-or-password-sftp (mode host)
461   (auth-source-user-or-password mode host 'sftp))
462
463 (defun auth-source-user-or-password-smtp (mode host)
464   (auth-source-user-or-password mode host 'smtp))
465
466 (provide 'auth-source)
467
468 ;; arch-tag: ff1afe78-06e9-42c2-b693-e9f922cbe4ab
469 ;;; auth-source.el ends here