1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
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 <http://www.gnu.org/licenses/>.
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.
30 ;; See the auth.info Info documentation for details.
34 ;; - never decode the backend file unless it's necessary
35 ;; - a more generic way to match backends and search backend contents
36 ;; - absorb netrc.el and simplify it
37 ;; - protect passwords better
38 ;; - allow creating and changing netrc lines (not files) e.g. change a password
42 (require 'password-cache)
46 (eval-when-compile (require 'cl))
49 (autoload 'secrets-create-item "secrets")
50 (autoload 'secrets-delete-item "secrets")
51 (autoload 'secrets-get-alias "secrets")
52 (autoload 'secrets-get-attributes "secrets")
53 (autoload 'secrets-get-secret "secrets")
54 (autoload 'secrets-list-collections "secrets")
55 (autoload 'secrets-search-items "secrets")
57 (autoload 'rfc2104-hash "rfc2104")
59 (defvar secrets-enabled)
61 (defgroup auth-source nil
62 "Authentication sources."
63 :version "23.1" ;; No Gnus
67 (defcustom auth-source-cache-expiry 7200
68 "How many seconds passwords are cached, or nil to disable
69 expiring. Overrides `password-cache-expiry' through a
72 :type '(choice (const :tag "Never" nil)
73 (const :tag "All Day" 86400)
74 (const :tag "2 Hours" 7200)
75 (const :tag "30 Minutes" 1800)
76 (integer :tag "Seconds")))
78 (defclass auth-source-backend ()
83 :documentation "The backend type.")
84 (source :initarg :source
87 :documentation "The backend source.")
92 :documentation "The backend host.")
97 :documentation "The backend user.")
102 :documentation "The backend protocol.")
103 (create-function :initarg :create-function
107 :documentation "The create function.")
108 (search-function :initarg :search-function
112 :documentation "The search function.")))
114 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
115 (pop3 "pop3" "pop" "pop3s" "110" "995")
119 "List of authentication protocols and their names"
122 :version "23.2" ;; No Gnus
123 :type '(repeat :tag "Authentication Protocols"
124 (cons :tag "Protocol Entry"
125 (symbol :tag "Protocol")
127 (string :tag "Name")))))
129 ;;; generate all the protocols in a format Customize can use
130 ;;; TODO: generate on the fly from auth-source-protocols
131 (defconst auth-source-protocols-customize
133 (let ((p (car-safe a)))
135 :tag (upcase (symbol-name p))
137 auth-source-protocols))
139 (defvar auth-source-creation-defaults nil
140 "Defaults for creating token values. Usually let-bound.")
142 (defvar auth-source-creation-prompts nil
143 "Default prompts for token values. Usually let-bound.")
145 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
147 (defcustom auth-source-save-behavior 'ask
148 "If set, auth-source will respect it for save behavior."
150 :version "23.2" ;; No Gnus
152 :tag "auth-source new token save behavior"
153 (const :tag "Always save" t)
154 (const :tag "Never save" nil)
155 (const :tag "Ask" ask)))
157 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") never) (t gpg)))
158 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
160 (defcustom auth-source-netrc-use-gpg-tokens 'never
161 "Set this to tell auth-source when to create GPG password
162 tokens in netrc files. It's either an alist or `never'."
164 :version "23.2" ;; No Gnus
166 (const :tag "Always use GPG password tokens" (t gpg))
167 (const :tag "Never use GPG password tokens" never)
168 (repeat :tag "Use a lookup list"
170 (choice :tag "Matcher"
171 (const :tag "Match anything" t)
172 (const :tag "The EPA encrypted file extensions"
173 ,(if (boundp 'epa-file-auto-mode-alist-entry)
175 'epa-file-auto-mode-alist-entry))
177 (regexp :tag "Regular expression"))
178 (choice :tag "What to do"
179 (const :tag "Save GPG-encrypted password tokens" gpg)
180 (const :tag "Don't encrypt tokens" never))))))
182 (defvar auth-source-magic "auth-source-magic ")
184 (defcustom auth-source-do-cache t
185 "Whether auth-source should cache information with `password-cache'."
187 :version "23.2" ;; No Gnus
190 (defcustom auth-source-debug nil
191 "Whether auth-source should log debug messages.
193 If the value is nil, debug messages are not logged.
195 If the value is t, debug messages are logged with `message'. In
196 that case, your authentication data will be in the clear (except
199 If the value is a function, debug messages are logged by calling
200 that function using the same arguments as `message'."
202 :version "23.2" ;; No Gnus
204 :tag "auth-source debugging mode"
205 (const :tag "Log using `message' to the *Messages* buffer" t)
206 (const :tag "Log all trivia with `message' to the *Messages* buffer"
208 (function :tag "Function that takes arguments like `message'")
209 (const :tag "Don't log anything" nil)))
211 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
212 "List of authentication sources.
214 The default will get login and password information from
215 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
216 packages to be encrypted. If that file doesn't exist, it will
217 try the unencrypted version \"~/.authinfo\" and the famous
220 See the auth.info manual for details.
222 Each entry is the authentication type with optional properties.
224 It's best to customize this with `M-x customize-variable' because the choices
225 can get pretty complex."
227 :version "24.1" ;; No Gnus
228 :type `(repeat :tag "Authentication Sources"
230 (string :tag "Just a file")
231 (const :tag "Default Secrets API Collection" 'default)
232 (const :tag "Login Secrets API Collection" "secrets:Login")
233 (const :tag "Temp Secrets API Collection" "secrets:session")
234 (list :tag "Source definition"
235 (const :format "" :value :source)
236 (choice :tag "Authentication backend choice"
237 (string :tag "Authentication Source (file)")
239 :tag "Secret Service API/KWallet/GNOME Keyring"
240 (const :format "" :value :secrets)
241 (choice :tag "Collection to use"
242 (string :tag "Collection name")
243 (const :tag "Default" 'default)
244 (const :tag "Login" "Login")
246 :tag "Temporary" "session"))))
247 (repeat :tag "Extra Parameters" :inline t
248 (choice :tag "Extra parameter"
251 (const :format "" :value :host)
252 (choice :tag "Host (machine) choice"
255 :tag "Regular expression")))
258 (const :format "" :value :port)
262 ,@auth-source-protocols-customize))
263 (list :tag "User" :inline t
264 (const :format "" :value :user)
266 :tag "Personality/Username"
271 (defcustom auth-source-gpg-encrypt-to t
272 "List of recipient keys that `authinfo.gpg' encrypted to.
273 If the value is not a list, symmetric encryption will be used."
275 :version "24.1" ;; No Gnus
276 :type '(choice (const :tag "Symmetric encryption" t)
277 (repeat :tag "Recipient public keys"
278 (string :tag "Recipient public key"))))
280 ;; temp for debugging
281 ;; (unintern 'auth-source-protocols)
282 ;; (unintern 'auth-sources)
283 ;; (customize-variable 'auth-sources)
284 ;; (setq auth-sources nil)
285 ;; (format "%S" auth-sources)
286 ;; (customize-variable 'auth-source-protocols)
287 ;; (setq auth-source-protocols nil)
288 ;; (format "%S" auth-source-protocols)
289 ;; (auth-source-pick nil :host "a" :port 'imap)
290 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
291 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
292 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
293 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
294 ;; (auth-source-protocol-defaults 'imap)
296 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
297 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
298 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
299 (defun auth-source-do-debug (&rest msg)
300 (when auth-source-debug
301 (apply 'auth-source-do-warn msg)))
303 (defun auth-source-do-trivia (&rest msg)
304 (when (or (eq auth-source-debug 'trivia)
305 (functionp auth-source-debug))
306 (apply 'auth-source-do-warn msg)))
308 (defun auth-source-do-warn (&rest msg)
310 ;; set logger to either the function in auth-source-debug or 'message
311 ;; note that it will be 'message if auth-source-debug is nil
312 (if (functionp auth-source-debug)
318 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
319 (defun auth-source-read-char-choice (prompt choices)
320 "Read one of CHOICES by `read-char-choice', or `read-char'.
321 `dropdown-list' support is disabled because it doesn't work reliably.
322 Only one of CHOICES will be returned. The PROMPT is augmented
323 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
325 (let* ((prompt-choices
326 (apply 'concat (loop for c in choices
327 collect (format "%c/" c))))
328 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
329 (full-prompt (concat prompt prompt-choices))
332 (while (not (memq k choices))
334 ((fboundp 'read-char-choice)
335 (read-char-choice full-prompt choices))
336 (t (message "%s" full-prompt)
337 (setq k (read-char))))))
340 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
341 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
342 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
343 ;; (:source (:secrets "session") :host t :port t :user "joe")
344 ;; (:source (:secrets "Login") :host t :port t)
345 ;; (:source "~/.authinfo.gpg" :host t :port t)))
347 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
348 ;; (:source (:secrets "session") :host t :port t :user "joe")
349 ;; (:source (:secrets "Login") :host t :port t)
352 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
354 ;; (auth-source-backend-parse "myfile.gpg")
355 ;; (auth-source-backend-parse 'default)
356 ;; (auth-source-backend-parse "secrets:Login")
358 (defun auth-source-backend-parse (entry)
359 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
360 (auth-source-backend-parse-parameters
363 ;; take 'default and recurse to get it as a Secrets API default collection
364 ;; matching any user, host, and protocol
366 (auth-source-backend-parse '(:source (:secrets default))))
367 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
368 ;; matching any user, host, and protocol
369 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
370 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
371 ;; take just a file name and recurse to get it as a netrc file
372 ;; matching any user, host, and protocol
374 (auth-source-backend-parse `(:source ,entry)))
376 ;; a file name with parameters
377 ((stringp (plist-get entry :source))
379 (plist-get entry :source)
380 :source (plist-get entry :source)
382 :search-function 'auth-source-netrc-search
383 :create-function 'auth-source-netrc-create))
385 ;; the Secrets API. We require the package, in order to have a
386 ;; defined value for `secrets-enabled'.
388 (not (null (plist-get entry :source))) ; the source must not be nil
389 (listp (plist-get entry :source)) ; and it must be a list
390 (require 'secrets nil t) ; and we must load the Secrets API
391 secrets-enabled) ; and that API must be enabled
393 ;; the source is either the :secrets key in ENTRY or
394 ;; if that's missing or nil, it's "session"
395 (let ((source (or (plist-get (plist-get entry :source) :secrets)
398 ;; if the source is a symbol, we look for the alias named so,
399 ;; and if that alias is missing, we use "Login"
400 (when (symbolp source)
401 (setq source (or (secrets-get-alias (symbol-name source))
404 (if (featurep 'secrets)
406 (format "Secrets API (%s)" source)
409 :search-function 'auth-source-secrets-search
410 :create-function 'auth-source-secrets-create)
412 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
414 (format "Ignored Secrets API (%s)" source)
421 "auth-source-backend-parse: invalid backend spec: %S" entry)
427 (defun auth-source-backend-parse-parameters (entry backend)
428 "Fills in the extra auth-source-backend parameters of ENTRY.
429 Using the plist ENTRY, get the :host, :port, and :user search
431 (let ((entry (if (stringp entry)
435 (when (setq val (plist-get entry :host))
436 (oset backend host val))
437 (when (setq val (plist-get entry :user))
438 (oset backend user val))
439 (when (setq val (plist-get entry :port))
440 (oset backend port val)))
443 ;; (mapcar 'auth-source-backend-parse auth-sources)
445 (defun* auth-source-search (&rest spec
446 &key type max host user port secret
447 require create delete
449 "Search or modify authentication backends according to SPEC.
451 This function parses `auth-sources' for matches of the SPEC
452 plist. It can optionally create or update an authentication
453 token if requested. A token is just a standard Emacs property
454 list with a :secret property that can be a function; all the
455 other properties will always hold scalar values.
457 Typically the :secret property, if present, contains a password.
459 Common search keys are :max, :host, :port, and :user. In
460 addition, :create specifies how tokens will be or created.
461 Finally, :type can specify which backend types you want to check.
463 A string value is always matched literally. A symbol is matched
464 as its string value, literally. All the SPEC values can be
465 single values (symbol or string) or lists thereof (in which case
466 any of the search terms matches).
468 :create t means to create a token if possible.
470 A new token will be created if no matching tokens were found.
471 The new token will have only the keys the backend requires. For
472 the netrc backend, for instance, that's the user, host, and
477 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
478 (A . \"default A\"))))
479 (auth-source-search :host \"mine\" :type 'netrc :max 1
480 :P \"pppp\" :Q \"qqqq\"
485 \"Search for any entry matching host 'mine' in backends of type
486 'netrc', maximum one result.
488 Create a new entry if you found none. The netrc backend will
489 automatically require host, user, and port. The host will be
490 'mine'. We prompt for the user with default 'defaultUser' and
491 for the port without a default. We will not prompt for A, Q,
492 or P. The resulting token will only have keys user, host, and
495 :create '(A B C) also means to create a token if possible.
497 The behavior is like :create t but if the list contains any
498 parameter, that parameter will be required in the resulting
499 token. The value for that parameter will be obtained from the
500 search parameters or from user input. If any queries are needed,
501 the alist `auth-source-creation-defaults' will be checked for the
502 default value. If the user, host, or port are missing, the alist
503 `auth-source-creation-prompts' will be used to look up the
504 prompts IN THAT ORDER (so the 'user prompt will be queried first,
505 then 'host, then 'port, and finally 'secret). Each prompt string
506 can use %u, %h, and %p to show the user, host, and port.
510 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
511 (A . \"default A\")))
512 (auth-source-creation-prompts
513 '((password . \"Enter IMAP password for %h:%p: \"))))
514 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
515 :P \"pppp\" :Q \"qqqq\"
520 \"Search for any entry matching host 'nonesuch'
521 or 'twosuch' in backends of type 'netrc', maximum one result.
523 Create a new entry if you found none. The netrc backend will
524 automatically require host, user, and port. The host will be
525 'nonesuch' and Q will be 'qqqq'. We prompt for the password
526 with the shown prompt. We will not prompt for Q. The resulting
527 token will have keys user, host, port, A, B, and Q. It will not
528 have P with any value, even though P is used in the search to
529 find only entries that have P set to 'pppp'.\"
531 When multiple values are specified in the search parameter, the
532 user is prompted for which one. So :host (X Y Z) would ask the
533 user to choose between X, Y, and Z.
535 This creation can fail if the search was not specific enough to
536 create a new token (it's up to the backend to decide that). You
537 should `catch' the backend-specific error as usual. Some
538 backends (netrc, at least) will prompt the user rather than throw
541 :require (A B C) means that only results that contain those
542 tokens will be returned. Thus for instance requiring :secret
543 will ensure that any results will actually have a :secret
546 :delete t means to delete any found entries. nil by default.
547 Use `auth-source-delete' in ELisp code instead of calling
548 `auth-source-search' directly with this parameter.
550 :type (X Y Z) will check only those backend types. 'netrc and
551 'secrets are the only ones supported right now.
553 :max N means to try to return at most N items (defaults to 1).
554 When 0 the function will return just t or nil to indicate if any
555 matches were found. More than N items may be returned, depending
556 on the search and the backend.
558 :host (X Y Z) means to match only hosts X, Y, or Z according to
559 the match rules above. Defaults to t.
561 :user (X Y Z) means to match only users X, Y, or Z according to
562 the match rules above. Defaults to t.
564 :port (P Q R) means to match only protocols P, Q, or R.
567 :K (V1 V2 V3) for any other key K will match values V1, V2, or
568 V3 (note the match rules above).
570 The return value is a list with at most :max tokens. Each token
571 is a plist with keys :backend :host :port :user, plus any other
572 keys provided by the backend (notably :secret). But note the
573 exception for :max 0, which see above.
575 The token can hold a :save-function key. If you call that, the
576 user will be prompted to save the data to the backend. You can't
577 request that this should happen right after creation, because
578 `auth-source-search' has no way of knowing if the token is
579 actually useful. So the caller must arrange to call this function.
581 The token's :secret key can hold a function. In that case you
582 must call it to obtain the actual value."
583 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
585 (ignored-keys '(:require :create :delete :max))
586 (keys (loop for i below (length spec) by 2
587 unless (memq (nth i spec) ignored-keys)
588 collect (nth i spec)))
589 (cached (auth-source-remembered-p spec))
590 ;; note that we may have cached results but found is still nil
591 ;; (there were no results from the search)
592 (found (auth-source-recall spec))
593 filtered-backends accessor-key backend)
595 (if (and cached auth-source-do-cache)
596 (auth-source-do-debug
597 "auth-source-search: found %d CACHED results matching %S"
601 (or (eq t create) (listp create)) t
602 "Invalid auth-source :create parameter (must be t or a list): %s %s")
606 "Invalid auth-source :require parameter (must be a list): %s")
608 (setq filtered-backends (copy-sequence backends))
609 (dolist (backend backends)
611 ;; ignore invalid slots
612 (condition-case signal
613 (unless (eval `(auth-source-search-collection
615 (oref backend ,key)))
616 (setq filtered-backends (delq backend filtered-backends))
618 (invalid-slot-name))))
620 (auth-source-do-trivia
621 "auth-source-search: found %d backends matching %S"
622 (length filtered-backends) spec)
624 ;; (debug spec "filtered" filtered-backends)
625 ;; First go through all the backends without :create, so we can
627 (setq found (auth-source-search-backends filtered-backends
631 ;; create is always nil here
635 (auth-source-do-debug
636 "auth-source-search: found %d results (max %d) matching %S"
637 (length found) max spec)
639 ;; If we didn't find anything, then we allow the backend(s) to
640 ;; create the entries.
643 (setq found (auth-source-search-backends filtered-backends
649 (auth-source-do-debug
650 "auth-source-search: CREATED %d results (max %d) matching %S"
651 (length found) max spec))
653 ;; note we remember the lack of result too, if it's applicable
654 (when auth-source-do-cache
655 (auth-source-remember spec found)))
659 (defun auth-source-search-backends (backends spec max create delete require)
661 (dolist (backend backends)
662 (when (> max (length matches)) ; when we need more matches...
663 (let* ((bmatches (apply
664 (slot-value backend 'search-function)
666 ;; note we're overriding whatever the spec
667 ;; has for :require, :create, and :delete
673 (auth-source-do-trivia
674 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
675 (length bmatches) max
676 (slot-value backend :type)
677 (slot-value backend :source)
679 (setq matches (append matches bmatches))))))
682 ;;; (auth-source-search :max 1)
683 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
684 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
685 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
687 (defun* auth-source-delete (&rest spec
690 "Delete entries from the authentication backends according to SPEC.
691 Calls `auth-source-search' with the :delete property in SPEC set to t.
692 The backend may not actually delete the entries.
694 Returns the deleted entries."
695 (auth-source-search (plist-put spec :delete t)))
697 (defun auth-source-search-collection (collection value)
698 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
699 (when (and (atom collection) (not (eq t collection)))
700 (setq collection (list collection)))
702 ;; (debug :collection collection :value value)
703 (or (eq collection t)
705 (equal collection value)
706 (member value collection)))
708 (defun auth-source-forget-all-cached ()
709 "Forget all cached auth-source data."
711 (loop for sym being the symbols of password-data
712 ;; when the symbol name starts with auth-source-magic
713 when (string-match (concat "^" auth-source-magic)
716 do (password-cache-remove (symbol-name sym))))
718 (defun auth-source-remember (spec found)
719 "Remember FOUND search results for SPEC."
720 (let ((password-cache-expiry auth-source-cache-expiry))
722 (concat auth-source-magic (format "%S" spec)) found)))
724 (defun auth-source-recall (spec)
725 "Recall FOUND search results for SPEC."
726 (password-read-from-cache
727 (concat auth-source-magic (format "%S" spec))))
729 (defun auth-source-remembered-p (spec)
730 "Check if SPEC is remembered."
732 (concat auth-source-magic (format "%S" spec))))
734 (defun auth-source-forget (spec)
735 "Forget any cached data matching SPEC exactly.
737 This is the same SPEC you passed to `auth-source-search'.
738 Returns t or nil for forgotten or not found."
739 (password-cache-remove (concat auth-source-magic (format "%S" spec))))
741 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
743 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
744 ;;; (auth-source-remembered-p '(:host "wedd"))
745 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
746 ;;; (auth-source-remembered-p '(:host "xedd"))
747 ;;; (auth-source-remembered-p '(:host "zedd"))
748 ;;; (auth-source-recall '(:host "xedd"))
749 ;;; (auth-source-recall '(:host t))
750 ;;; (auth-source-forget+ :host t)
752 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
753 "Forget any cached data matching SPEC. Returns forgotten count.
755 This is not a full `auth-source-search' spec but works similarly.
756 For instance, \(:host \"myhost\" \"yourhost\") would find all the
757 cached data that was found with a search for those two hosts,
758 while \(:host t) would find all host entries."
761 (loop for sym being the symbols of password-data
762 ;; when the symbol name matches with auth-source-magic
763 when (and (setq sname (symbol-name sym))
764 (string-match (concat "^" auth-source-magic "\\(.+\\)")
766 ;; and the spec matches what was stored in the cache
767 (auth-source-specmatchp spec (read (match-string 1 sname))))
770 (password-cache-remove sname)
774 (defun auth-source-specmatchp (spec stored)
775 (let ((keys (loop for i below (length spec) by 2
776 collect (nth i spec))))
779 (unless (auth-source-search-collection (plist-get stored key)
780 (plist-get spec key))
784 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
785 ;;; (auth-source-pick-first-password :port "imap")
786 (defun auth-source-pick-first-password (&rest spec)
787 "Pick the first secret found from applying SPEC to `auth-source-search'."
788 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
789 (secret (plist-get result :secret)))
791 (if (functionp secret)
795 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
796 (defun auth-source-format-prompt (prompt alist)
797 "Format PROMPT using %x (for any character x) specifiers in ALIST."
799 (let ((c (nth 0 cell))
802 (setq prompt (replace-regexp-in-string (format "%%%c" c)
807 (defun auth-source-ensure-strings (values)
808 (unless (listp values)
809 (setq values (list values)))
810 (mapcar (lambda (value)
816 ;;; Backend specific parsing: netrc/authinfo backend
818 (defvar auth-source-netrc-cache nil)
820 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
821 (defun* auth-source-netrc-parse (&rest
823 &key file max host user port delete require
825 "Parse FILE and return a list of all entries in the file.
826 Note that the MAX parameter is used so we can exit the parse early."
828 ;; We got already parsed contents; just return it.
830 (when (file-exists-p file)
831 (setq port (auth-source-ensure-strings port))
833 (let* ((tokens '("machine" "host" "default" "login" "user"
834 "password" "account" "macdef" "force"
836 (max (or max 5000)) ; sanity check: default to stop at 5K
838 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
839 (cached-mtime (plist-get cached :mtime))
840 (cached-secrets (plist-get cached :secret))
841 alist elem result pair)
843 (if (and (functionp cached-secrets)
845 (nth 5 (file-attributes file))))
847 (auth-source-do-trivia
848 "auth-source-netrc-parse: using CACHED file data for %s"
850 (insert (funcall cached-secrets)))
851 (insert-file-contents file)
852 ;; cache all netrc files (used to be just .gpg files)
853 ;; Store the contents of the file heavily encrypted in memory.
854 ;; (note for the irony-impaired: they are just obfuscated)
855 (aput 'auth-source-netrc-cache file
856 (list :mtime (nth 5 (file-attributes file))
857 :secret (lexical-let ((v (rot13-string
858 (base64-encode-string
860 (lambda () (base64-decode-string
861 (rot13-string v)))))))
862 (goto-char (point-min))
863 ;; Go through the file, line by line.
864 (while (and (not (eobp))
867 (narrow-to-region (point) (point-at-eol))
868 ;; For each line, get the tokens and values.
870 (skip-chars-forward "\t ")
871 ;; Skip lines that begin with a "#".
872 (if (eq (char-after) ?#)
873 (goto-char (point-max))
876 (if (= (following-char) ?\")
877 (read (current-buffer))
879 (point) (progn (skip-chars-forward "^\t ")
882 ((equal elem "macdef")
883 ;; We skip past the macro definition.
885 (while (and (zerop (forward-line 1))
887 (narrow-to-region (point) (point)))
888 ((member elem tokens)
889 ;; Tokens that don't have a following value are ignored,
891 (when (and pair (or (cdr pair)
892 (equal (car pair) "default")))
894 (setq pair (list elem)))
896 ;; Values that haven't got a preceding token are ignored.
900 (setq pair nil)))))))
904 (auth-source-search-collection
907 (aget alist "machine")
910 (auth-source-search-collection
914 (aget alist "account")
917 (auth-source-search-collection
921 (aget alist "protocol")
924 ;; the required list of keys is nil, or
926 ;; every element of require is in the normalized list
927 (let ((normalized (nth 0 (auth-source-netrc-normalize
928 (list alist) file))))
929 (loop for req in require
930 always (plist-get normalized req)))))
932 (push (nreverse alist) result)
933 ;; to delete a line, we just comment it out
935 (goto-char (point-min))
944 (when auth-source-gpg-encrypt-to
945 ;; (see bug#7487) making `epa-file-encrypt-to' local to
946 ;; this buffer lets epa-file skip the key selection query
947 ;; (see the `local-variable-p' check in
948 ;; `epa-file-write-region').
949 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
950 (make-local-variable 'epa-file-encrypt-to))
951 (if (listp auth-source-gpg-encrypt-to)
952 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
954 ;; ask AFTER we've successfully opened the file
955 (when (y-or-n-p (format "Save file %s? (%d deletions)"
957 (write-region (point-min) (point-max) file nil 'silent)
958 (auth-source-do-debug
959 "auth-source-netrc-parse: modified %d lines in %s"
962 (nreverse result))))))
964 (defmacro with-auth-source-epa-overrides (&rest body)
965 `(let ((file-name-handler-alist
966 ',(if (boundp 'epa-file-handler)
967 (remove (symbol-value 'epa-file-handler)
968 file-name-handler-alist)
969 file-name-handler-alist))
970 (,(if (boundp 'find-file-hook) 'find-file-hook 'find-file-hooks)
972 'epa-file-find-file-hook
973 (if (boundp 'find-file-hook) 'find-file-hook 'find-file-hooks)))
975 ',(if (boundp 'epa-file-auto-mode-alist-entry)
976 (remove (symbol-value 'epa-file-auto-mode-alist-entry)
981 (defun auth-source-epa-make-gpg-token (secret file)
983 (unless (featurep 'epa)
984 (error "EPA could not be loaded."))
985 (let* ((base (file-name-sans-extension file))
986 (passkey (format "gpg:-%s" base))
987 (stash (concat base ".gpg"))
988 ;; temporarily disable EPA
990 (with-auth-source-epa-overrides
991 (make-temp-file "gpg-token" nil
993 (epa-file-passphrase-alist
997 "token pass for %s? "
1000 (write-region secret nil stashfile)
1001 ;; temporarily disable EPA
1003 (with-auth-source-epa-overrides
1005 (insert-file-contents stashfile)
1006 (base64-encode-region (point-min) (point-max) t)
1008 (buffer-substring-no-properties
1011 (delete-file stashfile))))
1013 (defun auth-source-netrc-normalize (alist filename)
1014 (mapcar (lambda (entry)
1016 (while (setq item (pop entry))
1017 (let ((k (car item))
1020 ;; apply key aliases
1021 (setq k (cond ((member k '("machine")) "host")
1022 ((member k '("login" "account")) "user")
1023 ((member k '("protocol")) "port")
1024 ((member k '("password")) "secret")
1027 ;; send back the secret in a function (lexical binding)
1028 (when (equal k "secret")
1029 (setq v (lexical-let ((v v)
1031 (base (file-name-nondirectory
1036 (setq stash (concat base ".gpg"))
1037 (when (string-match "gpg:\\(.+\\)" v)
1038 (require 'epa nil t)
1039 (unless (featurep 'epa)
1040 (error "EPA could not be loaded."))
1041 (setq gpgdata (base64-decode-string
1042 (match-string 1 v)))
1047 ;;; FIXME: this relies on .gpg files being handled by EPA/EPG
1048 (let* ((passkey (format "gpg:-%s" base))
1049 ;; temporarily disable EPA
1051 (with-auth-source-epa-overrides
1052 (make-temp-file "gpg-token" nil
1054 (epa-file-passphrase-alist
1058 "token pass for %s? "
1063 ;; temporarily disable EPA
1064 (with-auth-source-epa-overrides
1065 (write-region gpgdata
1071 (insert-file-contents stashfile)
1072 (buffer-substring-no-properties
1075 (delete-file stashfile)))
1076 ;; clear out the decoder at end
1077 (setq token-decoder nil
1081 (funcall token-decoder gpgdata))
1083 (setq ret (plist-put ret
1084 (intern (concat ":" k))
1089 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1090 ;;; (funcall secret)
1092 (defun* auth-source-netrc-search (&rest
1094 &key backend require create delete
1095 type max host user port
1097 "Given a property list SPEC, return search matches from the :backend.
1098 See `auth-source-search' for details on SPEC."
1099 ;; just in case, check that the type is correct (null or same as the backend)
1100 (assert (or (null type) (eq type (oref backend type)))
1101 t "Invalid netrc search: %s %s")
1103 (let ((results (auth-source-netrc-normalize
1104 (auth-source-netrc-parse
1108 :file (oref backend source)
1112 (oref backend source))))
1114 ;; if we need to create an entry AND none were found to match
1118 ;; create based on the spec and record the value
1120 ;; if the user did not want to create the entry
1121 ;; in the file, it will be returned
1122 (apply (slot-value backend 'create-function) spec)
1123 ;; if not, we do the search again without :create
1124 ;; to get the updated data.
1126 ;; the result will be returned, even if the search fails
1127 (apply 'auth-source-netrc-search
1128 (plist-put spec :create nil)))))
1131 (defun auth-source-netrc-element-or-first (v)
1136 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1137 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1139 (defun* auth-source-netrc-create (&rest spec
1141 secret host user port create
1143 (let* ((base-required '(host user port secret))
1144 ;; we know (because of an assertion in auth-source-search) that the
1145 ;; :create parameter is either t or a list (which includes nil)
1146 (create-extra (if (eq t create) nil create))
1147 (required (append base-required create-extra))
1148 (file (oref backend source))
1150 ;; `valist' is an alist
1152 ;; `artificial' will be returned if no creation is needed
1155 ;; only for base required elements (defined as function parameters):
1156 ;; fill in the valist with whatever data we may have from the search
1157 ;; we complete the first value if it's a list and use the value otherwise
1158 (dolist (br base-required)
1159 (when (symbol-value br)
1160 (let ((br-choice (cond
1161 ;; all-accepting choice (predicate is t)
1162 ((eq t (symbol-value br)) nil)
1163 ;; just the value otherwise
1164 (t (symbol-value br)))))
1166 (aput 'valist br br-choice)))))
1168 ;; for extra required elements, see if the spec includes a value for them
1169 (dolist (er create-extra)
1170 (let ((name (concat ":" (symbol-name er)))
1171 (keys (loop for i below (length spec) by 2
1172 collect (nth i spec))))
1174 (when (equal (symbol-name k) name)
1175 (aput 'valist er (plist-get spec k))))))
1177 ;; for each required element
1178 (dolist (r required)
1179 (let* ((data (aget valist r))
1180 ;; take the first element if the data is a list
1181 (data (auth-source-netrc-element-or-first data))
1182 ;; this is the default to be offered
1183 (given-default (aget auth-source-creation-defaults r))
1184 ;; the default supplementals are simple:
1185 ;; for the user, try `given-default' and then (user-login-name);
1186 ;; otherwise take `given-default'
1188 ((and (not given-default) (eq r 'user))
1191 (printable-defaults (list
1194 (auth-source-netrc-element-or-first
1195 (aget valist 'user))
1196 (plist-get artificial :user)
1200 (auth-source-netrc-element-or-first
1201 (aget valist 'host))
1202 (plist-get artificial :host)
1206 (auth-source-netrc-element-or-first
1207 (aget valist 'port))
1208 (plist-get artificial :port)
1210 (prompt (or (aget auth-source-creation-prompts r)
1212 (secret "%p password for %u@%h: ")
1213 (user "%p user name for %h: ")
1214 (host "%p host name for user %u: ")
1215 (port "%p port for %u@%h: "))
1216 (format "Enter %s (%%u@%%h:%%p): " r)))
1217 (prompt (auth-source-format-prompt
1219 `((?u ,(aget printable-defaults 'user))
1220 (?h ,(aget printable-defaults 'host))
1221 (?p ,(aget printable-defaults 'port))))))
1223 ;; Store the data, prompting for the password if needed.
1226 ((and (null data) (eq r 'secret))
1227 ;; Special case prompt for passwords.
1228 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") nil) (t gpg)))
1229 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1230 (let* ((ep (format "Use GPG password tokens in %s?" file))
1233 ((eq auth-source-netrc-use-gpg-tokens 'never)
1235 ((listp auth-source-netrc-use-gpg-tokens)
1236 (let ((check (copy-sequence
1237 auth-source-netrc-use-gpg-tokens))
1240 (setq item (pop check))
1241 (when (or (eq (car item) t)
1242 (string-match (car item) file))
1243 (setq ret (cdr item))
1244 (setq check nil)))))
1246 (plain (read-passwd prompt)))
1247 ;; ask if we don't know what to do (in which case
1248 ;; auth-source-netrc-use-gpg-tokens must be a list)
1250 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1251 ;; TODO: save the defcustom now? or ask?
1252 (setq auth-source-netrc-use-gpg-tokens
1253 (cons `(,file ,gpg-encrypt)
1254 auth-source-netrc-use-gpg-tokens)))
1255 (if (eq gpg-encrypt 'gpg)
1256 (auth-source-epa-make-gpg-token plain file)
1261 (if (string-match ": *\\'" prompt)
1262 (concat (substring prompt 0 (match-beginning 0))
1263 " (default " default "): ")
1264 (concat prompt "(default " default ") "))))
1265 (read-string prompt nil nil default))
1266 (t (or data default))))
1269 (setq artificial (plist-put artificial
1270 (intern (concat ":" (symbol-name r)))
1272 (lexical-let ((data data))
1276 ;; When r is not an empty string...
1277 (when (and (stringp data)
1278 (< 0 (length data)))
1279 ;; this function is not strictly necessary but I think it
1280 ;; makes the code clearer -tzz
1281 (let ((printer (lambda ()
1282 ;; append the key (the symbol name of r)
1283 ;; and the value in r
1286 (if (zerop (length add)) "" " ")
1287 ;; remap auth-source tokens to netrc
1292 (port "port") ; redundant but clearer
1293 (t (symbol-name r)))
1294 (if (string-match "[\" ]" data)
1297 (setq add (concat add (funcall printer)))))))
1302 (lexical-let ((file file)
1304 (lambda () (auth-source-netrc-saver file add))))
1308 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1309 (defun auth-source-netrc-saver (file add)
1310 "Save a line ADD in FILE, prompting along the way.
1311 Respects `auth-source-save-behavior'. Uses
1312 `auth-source-netrc-cache' to avoid prompting more than once."
1313 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1314 (cached (assoc key auth-source-netrc-cache)))
1317 (auth-source-do-trivia
1318 "auth-source-netrc-saver: found previous run for key %s, returning"
1321 (when (file-exists-p file)
1322 (insert-file-contents file))
1323 (when auth-source-gpg-encrypt-to
1324 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1325 ;; this buffer lets epa-file skip the key selection query
1326 ;; (see the `local-variable-p' check in
1327 ;; `epa-file-write-region').
1328 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1329 (make-local-variable 'epa-file-encrypt-to))
1330 (if (listp auth-source-gpg-encrypt-to)
1331 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1332 ;; we want the new data to be found first, so insert at beginning
1333 (goto-char (point-min))
1335 ;; Ask AFTER we've successfully opened the file.
1336 (let ((prompt (format "Save auth info to file %s? " file))
1337 (done (not (eq auth-source-save-behavior 'ask)))
1338 (bufname "*auth-source Help*")
1341 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1345 (with-output-to-temp-buffer bufname
1347 (concat "(y)es, save\n"
1348 "(n)o but use the info\n"
1349 "(N)o and don't ask to save again\n"
1351 "(?) for help as you can see.\n"))
1352 ;; Why? Doesn't with-output-to-temp-buffer already do
1353 ;; the exact same thing anyway? --Stef
1354 (set-buffer standard-output)
1360 auth-source-save-behavior nil))
1361 (?e (setq add (read-string "Line to add: " add)))
1364 (when (get-buffer-window bufname)
1365 (delete-window (get-buffer-window bufname)))
1367 ;; Make sure the info is not saved.
1368 (when (null auth-source-save-behavior)
1371 (when (< 0 (length add))
1376 (write-region (point-min) (point-max) file nil 'silent)
1377 (auth-source-do-debug
1378 "auth-source-netrc-create: wrote 1 new line to %s"
1380 (message "Saved new authentication information to %s" file)
1382 (aput 'auth-source-netrc-cache key "ran"))))
1384 ;;; Backend specific parsing: Secrets API backend
1386 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1387 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1388 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1389 ;;; (let ((auth-sources '(default))) (auth-source-search))
1390 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1391 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1393 (defun* auth-source-secrets-search (&rest
1395 &key backend create delete label
1396 type max host user port
1398 "Search the Secrets API; spec is like `auth-source'.
1400 The :label key specifies the item's label. It is the only key
1401 that can specify a substring. Any :label value besides a string
1402 will allow any label.
1404 All other search keys must match exactly. If you need substring
1405 matching, do a wider search and narrow it down yourself.
1407 You'll get back all the properties of the token as a plist.
1409 Here's an example that looks for the first item in the 'Login'
1412 \(let ((auth-sources '(\"secrets:Login\")))
1413 (auth-source-search :max 1)
1415 Here's another that looks for the first item in the 'Login'
1416 Secrets collection whose label contains 'gnus':
1418 \(let ((auth-sources '(\"secrets:Login\")))
1419 (auth-source-search :max 1 :label \"gnus\")
1421 And this one looks for the first item in the 'Login' Secrets
1422 collection that's a Google Chrome entry for the git.gnus.org site
1423 authentication tokens:
1425 \(let ((auth-sources '(\"secrets:Login\")))
1426 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1430 (assert (not create) nil
1431 "The Secrets API auth-source backend doesn't support creation yet")
1433 ;; (secrets-delete-item coll elt)
1434 (assert (not delete) nil
1435 "The Secrets API auth-source backend doesn't support deletion yet")
1437 (let* ((coll (oref backend source))
1438 (max (or max 5000)) ; sanity check: default to stop at 5K
1439 (ignored-keys '(:create :delete :max :backend :label))
1440 (search-keys (loop for i below (length spec) by 2
1441 unless (memq (nth i spec) ignored-keys)
1442 collect (nth i spec)))
1443 ;; build a search spec without the ignored keys
1444 ;; if a search key is nil or t (match anything), we skip it
1445 (search-spec (apply 'append (mapcar
1447 (if (or (null (plist-get spec k))
1448 (eq t (plist-get spec k)))
1450 (list k (plist-get spec k))))
1452 ;; needed keys (always including host, login, port, and secret)
1453 (returned-keys (mm-delete-duplicates (append
1454 '(:host :login :port :secret)
1456 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1457 unless (and (stringp label)
1458 (not (string-match label item)))
1460 ;; TODO: respect max in `secrets-search-items', not after the fact
1461 (items (butlast items (- (length items) max)))
1462 ;; convert the item name to a full plist
1463 (items (mapcar (lambda (item)
1465 ;; make an entry for the secret (password) element
1468 (lexical-let ((v (secrets-get-secret coll item)))
1470 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1472 (mapcar (lambda (entry)
1473 (list (car entry) (cdr entry)))
1474 (secrets-get-attributes coll item)))))
1476 ;; ensure each item has each key in `returned-keys'
1477 (items (mapcar (lambda (plist)
1480 (mapcar (lambda (req)
1481 (if (plist-get plist req)
1489 (defun* auth-source-secrets-create (&rest
1491 &key backend type max host user port
1494 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1499 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1501 ;; deprecate the old interface
1502 (make-obsolete 'auth-source-user-or-password
1503 'auth-source-search "Emacs 24.1")
1504 (make-obsolete 'auth-source-forget-user-or-password
1505 'auth-source-forget "Emacs 24.1")
1507 (defun auth-source-user-or-password
1508 (mode host port &optional username create-missing delete-existing)
1509 "Find MODE (string or list of strings) matching HOST and PORT.
1511 DEPRECATED in favor of `auth-source-search'!
1513 USERNAME is optional and will be used as \"login\" in a search
1514 across the Secret Service API (see secrets.el) if the resulting
1515 items don't have a username. This means that if you search for
1516 username \"joe\" and it matches an item but the item doesn't have
1517 a :user attribute, the username \"joe\" will be returned.
1519 A non nil DELETE-EXISTING means deleting any matching password
1520 entry in the respective sources. This is useful only when
1521 CREATE-MISSING is non nil as well; the intended use case is to
1522 remove wrong password entries.
1524 If no matching entry is found, and CREATE-MISSING is non nil,
1525 the password will be retrieved interactively, and it will be
1526 stored in the password database which matches best (see
1529 MODE can be \"login\" or \"password\"."
1530 (auth-source-do-debug
1531 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1532 mode host port username)
1534 (let* ((listy (listp mode))
1535 (mode (if listy mode (list mode)))
1537 (format "%s %s:%s %s" mode host port username)
1538 (format "%s %s:%s" mode host port)))
1539 (search (list :host host :port port))
1540 (search (if username (append search (list :user username)) search))
1541 (search (if create-missing
1542 (append search (list :create t))
1544 (search (if delete-existing
1545 (append search (list :delete t))
1547 ;; (found (if (not delete-existing)
1548 ;; (gethash cname auth-source-cache)
1549 ;; (remhash cname auth-source-cache)
1554 (auth-source-do-debug
1555 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1557 ;; don't show the password
1558 (if (and (member "password" mode) t)
1562 found) ; return the found data
1563 ;; else, if not found, search with a max of 1
1564 (let ((choice (nth 0 (apply 'auth-source-search
1565 (append '(:max 1) search)))))
1569 ((equal "password" m)
1570 (push (if (plist-get choice :secret)
1571 (funcall (plist-get choice :secret))
1574 (push (plist-get choice :user) found)))))
1575 (setq found (nreverse found))
1576 (setq found (if listy found (car-safe found)))))
1580 (provide 'auth-source)
1582 ;;; auth-source.el ends here