1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2014 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 (autoload 'plstore-open
"plstore")
60 (autoload 'plstore-find
"plstore")
61 (autoload 'plstore-put
"plstore")
62 (autoload 'plstore-delete
"plstore")
63 (autoload 'plstore-save
"plstore")
64 (autoload 'plstore-get-file
"plstore")
66 (autoload 'epg-make-context
"epg")
67 (autoload 'epg-context-set-passphrase-callback
"epg")
68 (autoload 'epg-decrypt-string
"epg")
69 (autoload 'epg-context-set-armor
"epg")
70 (autoload 'epg-encrypt-string
"epg")
72 (autoload 'help-mode
"help-mode" nil t
)
74 (defvar secrets-enabled
)
76 (defgroup auth-source nil
77 "Authentication sources."
78 :version
"23.1" ;; No Gnus
82 (defcustom auth-source-cache-expiry
7200
83 "How many seconds passwords are cached, or nil to disable
84 expiring. Overrides `password-cache-expiry' through a
88 :type
'(choice (const :tag
"Never" nil
)
89 (const :tag
"All Day" 86400)
90 (const :tag
"2 Hours" 7200)
91 (const :tag
"30 Minutes" 1800)
92 (integer :tag
"Seconds")))
94 ;; The slots below correspond with the `auth-source-search' spec,
95 ;; so a backend with :host set, for instance, would match only
96 ;; searches for that host. Normally they are nil.
97 (defclass auth-source-backend
()
102 :documentation
"The backend type.")
103 (source :initarg
:source
106 :documentation
"The backend source.")
111 :documentation
"The backend host.")
116 :documentation
"The backend user.")
121 :documentation
"The backend protocol.")
124 :documentation
"Internal backend data.")
125 (create-function :initarg
:create-function
129 :documentation
"The create function.")
130 (search-function :initarg
:search-function
134 :documentation
"The search function.")))
136 (defcustom auth-source-protocols
'((imap "imap" "imaps" "143" "993")
137 (pop3 "pop3" "pop" "pop3s" "110" "995")
141 "List of authentication protocols and their names"
144 :version
"23.2" ;; No Gnus
145 :type
'(repeat :tag
"Authentication Protocols"
146 (cons :tag
"Protocol Entry"
147 (symbol :tag
"Protocol")
149 (string :tag
"Name")))))
151 ;; Generate all the protocols in a format Customize can use.
152 ;; TODO: generate on the fly from auth-source-protocols
153 (defconst auth-source-protocols-customize
155 (let ((p (car-safe a
)))
157 :tag
(upcase (symbol-name p
))
159 auth-source-protocols
))
161 (defvar auth-source-creation-defaults nil
162 "Defaults for creating token values. Usually let-bound.")
164 (defvar auth-source-creation-prompts nil
165 "Default prompts for token values. Usually let-bound.")
167 (make-obsolete 'auth-source-hide-passwords nil
"Emacs 24.1")
169 (defcustom auth-source-save-behavior
'ask
170 "If set, auth-source will respect it for save behavior."
172 :version
"23.2" ;; No Gnus
174 :tag
"auth-source new token save behavior"
175 (const :tag
"Always save" t
)
176 (const :tag
"Never save" nil
)
177 (const :tag
"Ask" ask
)))
179 ;; 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)))
180 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
182 (defcustom auth-source-netrc-use-gpg-tokens
'never
183 "Set this to tell auth-source when to create GPG password
184 tokens in netrc files. It's either an alist or `never'.
185 Note that if EPA/EPG is not available, this should NOT be used."
187 :version
"23.2" ;; No Gnus
189 (const :tag
"Always use GPG password tokens" (t gpg
))
190 (const :tag
"Never use GPG password tokens" never
)
191 (repeat :tag
"Use a lookup list"
193 (choice :tag
"Matcher"
194 (const :tag
"Match anything" t
)
195 (const :tag
"The EPA encrypted file extensions"
196 ,(if (boundp 'epa-file-auto-mode-alist-entry
)
198 'epa-file-auto-mode-alist-entry
))
200 (regexp :tag
"Regular expression"))
201 (choice :tag
"What to do"
202 (const :tag
"Save GPG-encrypted password tokens" gpg
)
203 (const :tag
"Don't encrypt tokens" never
))))))
205 (defvar auth-source-magic
"auth-source-magic ")
207 (defcustom auth-source-do-cache t
208 "Whether auth-source should cache information with `password-cache'."
210 :version
"23.2" ;; No Gnus
213 (defcustom auth-source-debug nil
214 "Whether auth-source should log debug messages.
216 If the value is nil, debug messages are not logged.
218 If the value is t, debug messages are logged with `message'. In
219 that case, your authentication data will be in the clear (except
222 If the value is a function, debug messages are logged by calling
223 that function using the same arguments as `message'."
225 :version
"23.2" ;; No Gnus
227 :tag
"auth-source debugging mode"
228 (const :tag
"Log using `message' to the *Messages* buffer" t
)
229 (const :tag
"Log all trivia with `message' to the *Messages* buffer"
231 (function :tag
"Function that takes arguments like `message'")
232 (const :tag
"Don't log anything" nil
)))
234 (defcustom auth-sources
'("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
235 "List of authentication sources.
236 Each entry is the authentication type with optional properties.
237 Entries are tried in the order in which they appear.
238 See Info node `(auth)Help for users' for details.
240 If an entry names a file with the \".gpg\" extension and you have
241 EPA/EPG set up, the file will be encrypted and decrypted
242 automatically. See Info node `(epa)Encrypting/decrypting gpg files'
245 It's best to customize this with `M-x customize-variable' because the choices
246 can get pretty complex."
248 :version
"24.1" ;; No Gnus
249 :type
`(repeat :tag
"Authentication Sources"
251 (string :tag
"Just a file")
252 (const :tag
"Default Secrets API Collection" default
)
253 (const :tag
"Login Secrets API Collection" "secrets:Login")
254 (const :tag
"Temp Secrets API Collection" "secrets:session")
256 (const :tag
"Default internet Mac OS Keychain"
257 macos-keychain-internet
)
259 (const :tag
"Default generic Mac OS Keychain"
260 macos-keychain-generic
)
262 (list :tag
"Source definition"
263 (const :format
"" :value
:source
)
264 (choice :tag
"Authentication backend choice"
265 (string :tag
"Authentication Source (file)")
267 :tag
"Secret Service API/KWallet/GNOME Keyring"
268 (const :format
"" :value
:secrets
)
269 (choice :tag
"Collection to use"
270 (string :tag
"Collection name")
271 (const :tag
"Default" default
)
272 (const :tag
"Login" "Login")
274 :tag
"Temporary" "session")))
276 :tag
"Mac OS internet Keychain"
278 :value
:macos-keychain-internet
)
279 (choice :tag
"Collection to use"
280 (string :tag
"internet Keychain path")
281 (const :tag
"default" default
)))
283 :tag
"Mac OS generic Keychain"
285 :value
:macos-keychain-generic
)
286 (choice :tag
"Collection to use"
287 (string :tag
"generic Keychain path")
288 (const :tag
"default" default
))))
289 (repeat :tag
"Extra Parameters" :inline t
290 (choice :tag
"Extra parameter"
293 (const :format
"" :value
:host
)
294 (choice :tag
"Host (machine) choice"
297 :tag
"Regular expression")))
300 (const :format
"" :value
:port
)
304 ,@auth-source-protocols-customize
))
305 (list :tag
"User" :inline t
306 (const :format
"" :value
:user
)
308 :tag
"Personality/Username"
313 (defcustom auth-source-gpg-encrypt-to t
314 "List of recipient keys that `authinfo.gpg' encrypted to.
315 If the value is not a list, symmetric encryption will be used."
317 :version
"24.1" ;; No Gnus
318 :type
'(choice (const :tag
"Symmetric encryption" t
)
319 (repeat :tag
"Recipient public keys"
320 (string :tag
"Recipient public key"))))
322 ;; temp for debugging
323 ;; (unintern 'auth-source-protocols)
324 ;; (unintern 'auth-sources)
325 ;; (customize-variable 'auth-sources)
326 ;; (setq auth-sources nil)
327 ;; (format "%S" auth-sources)
328 ;; (customize-variable 'auth-source-protocols)
329 ;; (setq auth-source-protocols nil)
330 ;; (format "%S" auth-source-protocols)
331 ;; (auth-source-pick nil :host "a" :port 'imap)
332 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
333 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
334 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
335 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
336 ;; (auth-source-protocol-defaults 'imap)
338 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
339 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
340 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
341 (defun auth-source-do-debug (&rest msg
)
342 (when auth-source-debug
343 (apply 'auth-source-do-warn msg
)))
345 (defun auth-source-do-trivia (&rest msg
)
346 (when (or (eq auth-source-debug
'trivia
)
347 (functionp auth-source-debug
))
348 (apply 'auth-source-do-warn msg
)))
350 (defun auth-source-do-warn (&rest msg
)
352 ;; set logger to either the function in auth-source-debug or 'message
353 ;; note that it will be 'message if auth-source-debug is nil
354 (if (functionp auth-source-debug
)
360 ;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
361 (defun auth-source-read-char-choice (prompt choices
)
362 "Read one of CHOICES by `read-char-choice', or `read-char'.
363 `dropdown-list' support is disabled because it doesn't work reliably.
364 Only one of CHOICES will be returned. The PROMPT is augmented
365 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
367 (let* ((prompt-choices
368 (apply 'concat
(loop for c in choices
369 collect
(format "%c/" c
))))
370 (prompt-choices (concat "[" (substring prompt-choices
0 -
1) "] "))
371 (full-prompt (concat prompt prompt-choices
))
374 (while (not (memq k choices
))
376 ((fboundp 'read-char-choice
)
377 (read-char-choice full-prompt choices
))
378 (t (message "%s" full-prompt
)
379 (setq k
(read-char))))))
382 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
383 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
384 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
385 ;; (:source (:secrets "session") :host t :port t :user "joe")
386 ;; (:source (:secrets "Login") :host t :port t)
387 ;; (:source "~/.authinfo.gpg" :host t :port t)))
389 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
390 ;; (:source (:secrets "session") :host t :port t :user "joe")
391 ;; (:source (:secrets "Login") :host t :port t)
394 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
396 ;; (auth-source-backend-parse "myfile.gpg")
397 ;; (auth-source-backend-parse 'default)
398 ;; (auth-source-backend-parse "secrets:Login")
399 ;; (auth-source-backend-parse 'macos-keychain-internet)
400 ;; (auth-source-backend-parse 'macos-keychain-generic)
401 ;; (auth-source-backend-parse "macos-keychain-internet:/path/here.keychain")
402 ;; (auth-source-backend-parse "macos-keychain-generic:/path/here.keychain")
404 (defun auth-source-backend-parse (entry)
405 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
406 (auth-source-backend-parse-parameters
409 ;; take 'default and recurse to get it as a Secrets API default collection
410 ;; matching any user, host, and protocol
412 (auth-source-backend-parse '(:source
(:secrets default
))))
413 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
414 ;; matching any user, host, and protocol
415 ((and (stringp entry
) (string-match "^secrets:\\(.+\\)" entry
))
416 (auth-source-backend-parse `(:source
(:secrets
,(match-string 1 entry
)))))
418 ;; take 'macos-keychain-internet and recurse to get it as a Mac OS
419 ;; Keychain collection matching any user, host, and protocol
420 ((eq entry
'macos-keychain-internet
)
421 (auth-source-backend-parse '(:source
(:macos-keychain-internet default
))))
422 ;; take 'macos-keychain-generic and recurse to get it as a Mac OS
423 ;; Keychain collection matching any user, host, and protocol
424 ((eq entry
'macos-keychain-generic
)
425 (auth-source-backend-parse '(:source
(:macos-keychain-generic default
))))
426 ;; take macos-keychain-internet:XYZ and recurse to get it as MacOS
427 ;; Keychain "XYZ" matching any user, host, and protocol
428 ((and (stringp entry
) (string-match "^macos-keychain-internet:\\(.+\\)"
430 (auth-source-backend-parse `(:source
(:macos-keychain-internet
431 ,(match-string 1 entry
)))))
432 ;; take macos-keychain-generic:XYZ and recurse to get it as MacOS
433 ;; Keychain "XYZ" matching any user, host, and protocol
434 ((and (stringp entry
) (string-match "^macos-keychain-generic:\\(.+\\)"
436 (auth-source-backend-parse `(:source
(:macos-keychain-generic
437 ,(match-string 1 entry
)))))
439 ;; take just a file name and recurse to get it as a netrc file
440 ;; matching any user, host, and protocol
442 (auth-source-backend-parse `(:source
,entry
)))
444 ;; a file name with parameters
445 ((stringp (plist-get entry
:source
))
446 (if (equal (file-name-extension (plist-get entry
:source
)) "plist")
448 (plist-get entry
:source
)
449 :source
(plist-get entry
:source
)
451 :search-function
'auth-source-plstore-search
452 :create-function
'auth-source-plstore-create
453 :data
(plstore-open (plist-get entry
:source
)))
455 (plist-get entry
:source
)
456 :source
(plist-get entry
:source
)
458 :search-function
'auth-source-netrc-search
459 :create-function
'auth-source-netrc-create
)))
461 ;; the MacOS Keychain
463 (not (null (plist-get entry
:source
))) ; the source must not be nil
464 (listp (plist-get entry
:source
)) ; and it must be a list
466 (plist-get (plist-get entry
:source
) :macos-keychain-generic
)
467 (plist-get (plist-get entry
:source
) :macos-keychain-internet
)))
469 (let* ((source-spec (plist-get entry
:source
))
470 (keychain-generic (plist-get source-spec
:macos-keychain-generic
))
471 (keychain-type (if keychain-generic
472 'macos-keychain-generic
473 'macos-keychain-internet
))
474 (source (plist-get source-spec
(if keychain-generic
475 :macos-keychain-generic
476 :macos-keychain-internet
))))
478 (when (symbolp source
)
479 (setq source
(symbol-name source
)))
482 (format "Mac OS Keychain (%s)" source
)
485 :search-function
'auth-source-macos-keychain-search
486 :create-function
'auth-source-macos-keychain-create
)))
488 ;; the Secrets API. We require the package, in order to have a
489 ;; defined value for `secrets-enabled'.
491 (not (null (plist-get entry
:source
))) ; the source must not be nil
492 (listp (plist-get entry
:source
)) ; and it must be a list
493 (require 'secrets nil t
) ; and we must load the Secrets API
494 secrets-enabled
) ; and that API must be enabled
496 ;; the source is either the :secrets key in ENTRY or
497 ;; if that's missing or nil, it's "session"
498 (let ((source (or (plist-get (plist-get entry
:source
) :secrets
)
501 ;; if the source is a symbol, we look for the alias named so,
502 ;; and if that alias is missing, we use "Login"
503 (when (symbolp source
)
504 (setq source
(or (secrets-get-alias (symbol-name source
))
507 (if (featurep 'secrets
)
509 (format "Secrets API (%s)" source
)
512 :search-function
'auth-source-secrets-search
513 :create-function
'auth-source-secrets-create
)
515 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry
)
517 (format "Ignored Secrets API (%s)" source
)
524 "auth-source-backend-parse: invalid backend spec: %S" entry
)
530 (defun auth-source-backend-parse-parameters (entry backend
)
531 "Fills in the extra auth-source-backend parameters of ENTRY.
532 Using the plist ENTRY, get the :host, :port, and :user search
534 (let ((entry (if (stringp entry
)
538 (when (setq val
(plist-get entry
:host
))
539 (oset backend host val
))
540 (when (setq val
(plist-get entry
:user
))
541 (oset backend user val
))
542 (when (setq val
(plist-get entry
:port
))
543 (oset backend port val
)))
546 ;; (mapcar 'auth-source-backend-parse auth-sources)
548 (defun* auth-source-search
(&rest spec
549 &key type max host user port secret
550 require create delete
552 "Search or modify authentication backends according to SPEC.
554 This function parses `auth-sources' for matches of the SPEC
555 plist. It can optionally create or update an authentication
556 token if requested. A token is just a standard Emacs property
557 list with a :secret property that can be a function; all the
558 other properties will always hold scalar values.
560 Typically the :secret property, if present, contains a password.
562 Common search keys are :max, :host, :port, and :user. In
563 addition, :create specifies how tokens will be or created.
564 Finally, :type can specify which backend types you want to check.
566 A string value is always matched literally. A symbol is matched
567 as its string value, literally. All the SPEC values can be
568 single values (symbol or string) or lists thereof (in which case
569 any of the search terms matches).
571 :create t means to create a token if possible.
573 A new token will be created if no matching tokens were found.
574 The new token will have only the keys the backend requires. For
575 the netrc backend, for instance, that's the user, host, and
580 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
581 (A . \"default A\"))))
582 (auth-source-search :host \"mine\" :type 'netrc :max 1
583 :P \"pppp\" :Q \"qqqq\"
588 \"Search for any entry matching host 'mine' in backends of type
589 'netrc', maximum one result.
591 Create a new entry if you found none. The netrc backend will
592 automatically require host, user, and port. The host will be
593 'mine'. We prompt for the user with default 'defaultUser' and
594 for the port without a default. We will not prompt for A, Q,
595 or P. The resulting token will only have keys user, host, and
598 :create '(A B C) also means to create a token if possible.
600 The behavior is like :create t but if the list contains any
601 parameter, that parameter will be required in the resulting
602 token. The value for that parameter will be obtained from the
603 search parameters or from user input. If any queries are needed,
604 the alist `auth-source-creation-defaults' will be checked for the
605 default value. If the user, host, or port are missing, the alist
606 `auth-source-creation-prompts' will be used to look up the
607 prompts IN THAT ORDER (so the 'user prompt will be queried first,
608 then 'host, then 'port, and finally 'secret). Each prompt string
609 can use %u, %h, and %p to show the user, host, and port.
613 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
614 (A . \"default A\")))
615 (auth-source-creation-prompts
616 '((password . \"Enter IMAP password for %h:%p: \"))))
617 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
618 :P \"pppp\" :Q \"qqqq\"
623 \"Search for any entry matching host 'nonesuch'
624 or 'twosuch' in backends of type 'netrc', maximum one result.
626 Create a new entry if you found none. The netrc backend will
627 automatically require host, user, and port. The host will be
628 'nonesuch' and Q will be 'qqqq'. We prompt for the password
629 with the shown prompt. We will not prompt for Q. The resulting
630 token will have keys user, host, port, A, B, and Q. It will not
631 have P with any value, even though P is used in the search to
632 find only entries that have P set to 'pppp'.\"
634 When multiple values are specified in the search parameter, the
635 user is prompted for which one. So :host (X Y Z) would ask the
636 user to choose between X, Y, and Z.
638 This creation can fail if the search was not specific enough to
639 create a new token (it's up to the backend to decide that). You
640 should `catch' the backend-specific error as usual. Some
641 backends (netrc, at least) will prompt the user rather than throw
644 :require (A B C) means that only results that contain those
645 tokens will be returned. Thus for instance requiring :secret
646 will ensure that any results will actually have a :secret
649 :delete t means to delete any found entries. nil by default.
650 Use `auth-source-delete' in ELisp code instead of calling
651 `auth-source-search' directly with this parameter.
653 :type (X Y Z) will check only those backend types. 'netrc and
654 'secrets are the only ones supported right now.
656 :max N means to try to return at most N items (defaults to 1).
657 When 0 the function will return just t or nil to indicate if any
658 matches were found. More than N items may be returned, depending
659 on the search and the backend.
661 :host (X Y Z) means to match only hosts X, Y, or Z according to
662 the match rules above. Defaults to t.
664 :user (X Y Z) means to match only users X, Y, or Z according to
665 the match rules above. Defaults to t.
667 :port (P Q R) means to match only protocols P, Q, or R.
670 :K (V1 V2 V3) for any other key K will match values V1, V2, or
671 V3 (note the match rules above).
673 The return value is a list with at most :max tokens. Each token
674 is a plist with keys :backend :host :port :user, plus any other
675 keys provided by the backend (notably :secret). But note the
676 exception for :max 0, which see above.
678 The token can hold a :save-function key. If you call that, the
679 user will be prompted to save the data to the backend. You can't
680 request that this should happen right after creation, because
681 `auth-source-search' has no way of knowing if the token is
682 actually useful. So the caller must arrange to call this function.
684 The token's :secret key can hold a function. In that case you
685 must call it to obtain the actual value."
686 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources
))
688 (ignored-keys '(:require
:create
:delete
:max
))
689 (keys (loop for i below
(length spec
) by
2
690 unless
(memq (nth i spec
) ignored-keys
)
691 collect
(nth i spec
)))
692 (cached (auth-source-remembered-p spec
))
693 ;; note that we may have cached results but found is still nil
694 ;; (there were no results from the search)
695 (found (auth-source-recall spec
))
696 filtered-backends accessor-key backend
)
698 (if (and cached auth-source-do-cache
)
699 (auth-source-do-debug
700 "auth-source-search: found %d CACHED results matching %S"
704 (or (eq t create
) (listp create
)) t
705 "Invalid auth-source :create parameter (must be t or a list): %s %s")
709 "Invalid auth-source :require parameter (must be a list): %s")
711 (setq filtered-backends
(copy-sequence backends
))
712 (dolist (backend backends
)
714 ;; ignore invalid slots
715 (condition-case signal
716 (unless (eval `(auth-source-search-collection
718 (oref backend
,key
)))
719 (setq filtered-backends
(delq backend filtered-backends
))
721 (invalid-slot-name))))
723 (auth-source-do-trivia
724 "auth-source-search: found %d backends matching %S"
725 (length filtered-backends
) spec
)
727 ;; (debug spec "filtered" filtered-backends)
728 ;; First go through all the backends without :create, so we can
730 (setq found
(auth-source-search-backends filtered-backends
734 ;; create is always nil here
738 (auth-source-do-debug
739 "auth-source-search: found %d results (max %d) matching %S"
740 (length found
) max spec
)
742 ;; If we didn't find anything, then we allow the backend(s) to
743 ;; create the entries.
746 (setq found
(auth-source-search-backends filtered-backends
752 (auth-source-do-debug
753 "auth-source-search: CREATED %d results (max %d) matching %S"
754 (length found
) max spec
))
756 ;; note we remember the lack of result too, if it's applicable
757 (when auth-source-do-cache
758 (auth-source-remember spec found
)))
762 (defun auth-source-search-backends (backends spec max create delete require
)
764 (dolist (backend backends
)
765 (when (> max
(length matches
)) ; when we need more matches...
766 (let* ((bmatches (apply
767 (slot-value backend
'search-function
)
769 :type
(slot-value backend
:type
)
770 ;; note we're overriding whatever the spec
771 ;; has for :require, :create, and :delete
777 (auth-source-do-trivia
778 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
779 (length bmatches
) max
780 (slot-value backend
:type
)
781 (slot-value backend
:source
)
783 (setq matches
(append matches bmatches
))))))
786 ;; (auth-source-search :max 1)
787 ;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
788 ;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
789 ;; (auth-source-search :host "nonesuch" :type 'secrets)
791 (defun* auth-source-delete
(&rest spec
794 "Delete entries from the authentication backends according to SPEC.
795 Calls `auth-source-search' with the :delete property in SPEC set to t.
796 The backend may not actually delete the entries.
798 Returns the deleted entries."
799 (auth-source-search (plist-put spec
:delete t
)))
801 (defun auth-source-search-collection (collection value
)
802 "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
803 (when (and (atom collection
) (not (eq t collection
)))
804 (setq collection
(list collection
)))
806 ;; (debug :collection collection :value value)
807 (or (eq collection t
)
809 (equal collection value
)
810 (member value collection
)))
812 (defvar auth-source-netrc-cache nil
)
814 (defun auth-source-forget-all-cached ()
815 "Forget all cached auth-source data."
817 (loop for sym being the symbols of password-data
818 ;; when the symbol name starts with auth-source-magic
819 when
(string-match (concat "^" auth-source-magic
)
822 do
(password-cache-remove (symbol-name sym
)))
823 (setq auth-source-netrc-cache nil
))
825 (defun auth-source-format-cache-entry (spec)
826 "Format SPEC entry to put it in the password cache."
827 (concat auth-source-magic
(format "%S" spec
)))
829 (defun auth-source-remember (spec found
)
830 "Remember FOUND search results for SPEC."
831 (let ((password-cache-expiry auth-source-cache-expiry
))
833 (auth-source-format-cache-entry spec
) found
)))
835 (defun auth-source-recall (spec)
836 "Recall FOUND search results for SPEC."
837 (password-read-from-cache (auth-source-format-cache-entry spec
)))
839 (defun auth-source-remembered-p (spec)
840 "Check if SPEC is remembered."
842 (auth-source-format-cache-entry spec
)))
844 (defun auth-source-forget (spec)
845 "Forget any cached data matching SPEC exactly.
847 This is the same SPEC you passed to `auth-source-search'.
848 Returns t or nil for forgotten or not found."
849 (password-cache-remove (auth-source-format-cache-entry spec
)))
851 ;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
853 ;; (auth-source-remember '(:host "wedd") '(4 5 6))
854 ;; (auth-source-remembered-p '(:host "wedd"))
855 ;; (auth-source-remember '(:host "xedd") '(1 2 3))
856 ;; (auth-source-remembered-p '(:host "xedd"))
857 ;; (auth-source-remembered-p '(:host "zedd"))
858 ;; (auth-source-recall '(:host "xedd"))
859 ;; (auth-source-recall '(:host t))
860 ;; (auth-source-forget+ :host t)
862 (defun* auth-source-forget
+ (&rest spec
&allow-other-keys
)
863 "Forget any cached data matching SPEC. Returns forgotten count.
865 This is not a full `auth-source-search' spec but works similarly.
866 For instance, \(:host \"myhost\" \"yourhost\") would find all the
867 cached data that was found with a search for those two hosts,
868 while \(:host t) would find all host entries."
871 (loop for sym being the symbols of password-data
872 ;; when the symbol name matches with auth-source-magic
873 when
(and (setq sname
(symbol-name sym
))
874 (string-match (concat "^" auth-source-magic
"\\(.+\\)")
876 ;; and the spec matches what was stored in the cache
877 (auth-source-specmatchp spec
(read (match-string 1 sname
))))
880 (password-cache-remove sname
)
884 (defun auth-source-specmatchp (spec stored
)
885 (let ((keys (loop for i below
(length spec
) by
2
886 collect
(nth i spec
))))
889 (unless (auth-source-search-collection (plist-get stored key
)
890 (plist-get spec key
))
894 ;; (auth-source-pick-first-password :host "z.lifelogs.com")
895 ;; (auth-source-pick-first-password :port "imap")
896 (defun auth-source-pick-first-password (&rest spec
)
897 "Pick the first secret found from applying SPEC to `auth-source-search'."
898 (let* ((result (nth 0 (apply 'auth-source-search
(plist-put spec
:max
1))))
899 (secret (plist-get result
:secret
)))
901 (if (functionp secret
)
905 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
906 (defun auth-source-format-prompt (prompt alist
)
907 "Format PROMPT using %x (for any character x) specifiers in ALIST."
909 (let ((c (nth 0 cell
))
912 (setq prompt
(replace-regexp-in-string (format "%%%c" c
)
917 (defun auth-source-ensure-strings (values)
918 (unless (listp values
)
919 (setq values
(list values
)))
920 (mapcar (lambda (value)
926 ;;; Backend specific parsing: netrc/authinfo backend
928 (defun auth-source--aput-1 (alist key val
)
931 (while (and (consp rest
) (not (equal key
(caar rest
))))
932 (push (pop rest
) seen
))
934 (if (null rest
) alist
935 (nconc (nreverse seen
)
936 (if (equal key
(caar rest
)) (cdr rest
) rest
))))))
937 (defmacro auth-source--aput
(var key val
)
938 `(setq ,var
(auth-source--aput-1 ,var
,key
,val
)))
940 (defun auth-source--aget (alist key
)
941 (cdr (assoc key alist
)))
943 ;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
944 (defun* auth-source-netrc-parse
(&rest
946 &key file max host user port delete require
948 "Parse FILE and return a list of all entries in the file.
949 Note that the MAX parameter is used so we can exit the parse early."
951 ;; We got already parsed contents; just return it.
953 (when (file-exists-p file
)
954 (setq port
(auth-source-ensure-strings port
))
956 (let* ((max (or max
5000)) ; sanity check: default to stop at 5K
958 (cached (cdr-safe (assoc file auth-source-netrc-cache
)))
959 (cached-mtime (plist-get cached
:mtime
))
960 (cached-secrets (plist-get cached
:secret
))
961 (check (lambda(alist)
963 (auth-source-search-collection
966 (auth-source--aget alist
"machine")
967 (auth-source--aget alist
"host")
969 (auth-source-search-collection
972 (auth-source--aget alist
"login")
973 (auth-source--aget alist
"account")
974 (auth-source--aget alist
"user")
976 (auth-source-search-collection
979 (auth-source--aget alist
"port")
980 (auth-source--aget alist
"protocol")
983 ;; the required list of keys is nil, or
985 ;; every element of require is in n(ormalized)
986 (let ((n (nth 0 (auth-source-netrc-normalize
987 (list alist
) file
))))
988 (loop for req in require
989 always
(plist-get n req
)))))))
992 (if (and (functionp cached-secrets
)
994 (nth 5 (file-attributes file
))))
996 (auth-source-do-trivia
997 "auth-source-netrc-parse: using CACHED file data for %s"
999 (insert (funcall cached-secrets
)))
1000 (insert-file-contents file
)
1001 ;; cache all netrc files (used to be just .gpg files)
1002 ;; Store the contents of the file heavily encrypted in memory.
1003 ;; (note for the irony-impaired: they are just obfuscated)
1005 auth-source-netrc-cache file
1006 (list :mtime
(nth 5 (file-attributes file
))
1007 :secret
(lexical-let ((v (mapcar '1+ (buffer-string))))
1008 (lambda () (apply 'string
(mapcar '1- v
)))))))
1009 (goto-char (point-min))
1010 (let ((entries (auth-source-netrc-parse-entries check max
))
1012 (while (setq alist
(pop entries
))
1013 (push (nreverse alist
) result
)))
1015 (when (< 0 modified
)
1016 (when auth-source-gpg-encrypt-to
1017 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1018 ;; this buffer lets epa-file skip the key selection query
1019 ;; (see the `local-variable-p' check in
1020 ;; `epa-file-write-region').
1021 (unless (local-variable-p 'epa-file-encrypt-to
(current-buffer))
1022 (make-local-variable 'epa-file-encrypt-to
))
1023 (if (listp auth-source-gpg-encrypt-to
)
1024 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to
)))
1026 ;; ask AFTER we've successfully opened the file
1027 (when (y-or-n-p (format "Save file %s? (%d deletions)"
1029 (write-region (point-min) (point-max) file nil
'silent
)
1030 (auth-source-do-debug
1031 "auth-source-netrc-parse: modified %d lines in %s"
1034 (nreverse result
))))))
1036 (defun auth-source-netrc-parse-next-interesting ()
1037 "Advance to the next interesting position in the current buffer."
1038 ;; If we're looking at a comment or are at the end of the line, move forward
1039 (while (or (looking-at "#")
1043 (skip-chars-forward "\t "))
1045 (defun auth-source-netrc-parse-one ()
1046 "Read one thing from the current buffer."
1047 (auth-source-netrc-parse-next-interesting)
1049 (when (or (looking-at "'\\([^']*\\)'")
1050 (looking-at "\"\\([^\"]*\\)\"")
1051 (looking-at "\\([^ \t\n]+\\)"))
1052 (forward-char (length (match-string 0)))
1053 (auth-source-netrc-parse-next-interesting)
1054 (match-string-no-properties 1)))
1056 ;; with thanks to org-mode
1057 (defsubst auth-source-current-line
(&optional pos
)
1059 (and pos
(goto-char pos
))
1060 ;; works also in narrowed buffer, because we start at 1, not point-min
1061 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1063 (defun auth-source-netrc-parse-entries(check max
)
1064 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1065 (let ((adder (lambda(check alist all
)
1068 (> max
(length all
))
1069 (funcall check alist
))
1072 item item2 all alist default
)
1073 (while (setq item
(auth-source-netrc-parse-one))
1074 (setq default
(equal item
"default"))
1075 ;; We're starting a new machine. Save the old one.
1078 (equal item
"machine")))
1079 ;; (auth-source-do-trivia
1080 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
1081 (setq all
(funcall adder check alist all
)
1083 ;; In default entries, we don't have a next token.
1084 ;; We store them as ("machine" . t)
1086 (push (cons "machine" t
) alist
)
1087 ;; Not a default entry. Grab the next item.
1088 (when (setq item2
(auth-source-netrc-parse-one))
1089 ;; Did we get a "machine" value?
1090 (if (equal item2
"machine")
1093 "%s: Unexpected 'machine' token at line %d"
1094 "auth-source-netrc-parse-entries"
1095 (auth-source-current-line))
1097 (push (cons item item2
) alist
)))))
1099 ;; Clean up: if there's an entry left over, use it.
1101 (setq all
(funcall adder check alist all
))
1102 ;; (auth-source-do-trivia
1103 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1107 (defvar auth-source-passphrase-alist nil
)
1109 (defun auth-source-token-passphrase-callback-function (context key-id file
)
1110 (let* ((file (file-truename file
))
1111 (entry (assoc file auth-source-passphrase-alist
))
1113 ;; return the saved passphrase, calling a function if needed
1114 (or (copy-sequence (if (functionp (cdr entry
))
1115 (funcall (cdr entry
))
1119 (setq entry
(list file
))
1120 (push entry auth-source-passphrase-alist
))
1123 (format "Passphrase for %s tokens: " file
)
1125 (setcdr entry
(lexical-let ((p (copy-sequence passphrase
)))
1129 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1130 (defun auth-source-epa-extract-gpg-token (secret file
)
1131 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1132 FILE is the file from which we obtained this token."
1133 (when (string-match "^gpg:\\(.+\\)" secret
)
1134 (setq secret
(base64-decode-string (match-string 1 secret
))))
1135 (let ((context (epg-make-context 'OpenPGP
))
1137 (epg-context-set-passphrase-callback
1139 (cons #'auth-source-token-passphrase-callback-function
1141 (epg-decrypt-string context secret
)))
1143 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1144 (defun auth-source-epa-make-gpg-token (secret file
)
1145 (let ((context (epg-make-context 'OpenPGP
))
1146 (pp-escape-newlines nil
)
1148 (epg-context-set-armor context t
)
1149 (epg-context-set-passphrase-callback
1151 (cons #'auth-source-token-passphrase-callback-function
1153 (setq cipher
(epg-encrypt-string context secret nil
))
1156 (base64-encode-region (point-min) (point-max) t
)
1157 (concat "gpg:" (buffer-substring-no-properties
1161 (defun auth-source-netrc-normalize (alist filename
)
1162 (mapcar (lambda (entry)
1164 (while (setq item
(pop entry
))
1165 (let ((k (car item
))
1168 ;; apply key aliases
1169 (setq k
(cond ((member k
'("machine")) "host")
1170 ((member k
'("login" "account")) "user")
1171 ((member k
'("protocol")) "port")
1172 ((member k
'("password")) "secret")
1175 ;; send back the secret in a function (lexical binding)
1176 (when (equal k
"secret")
1177 (setq v
(lexical-let ((lexv v
)
1178 (token-decoder nil
))
1179 (when (string-match "^gpg:" lexv
)
1180 ;; it's a GPG token: create a token decoder
1181 ;; which unsets itself once
1185 (auth-source-epa-extract-gpg-token
1188 (setq token-decoder nil
)))))
1191 (setq lexv
(funcall token-decoder lexv
)))
1193 (setq ret
(plist-put ret
1194 (intern (concat ":" k
))
1199 ;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1202 (defun* auth-source-netrc-search
(&rest
1204 &key backend require create delete
1205 type max host user port
1207 "Given a property list SPEC, return search matches from the :backend.
1208 See `auth-source-search' for details on SPEC."
1209 ;; just in case, check that the type is correct (null or same as the backend)
1210 (assert (or (null type
) (eq type
(oref backend type
)))
1211 t
"Invalid netrc search: %s %s")
1213 (let ((results (auth-source-netrc-normalize
1214 (auth-source-netrc-parse
1218 :file
(oref backend source
)
1222 (oref backend source
))))
1224 ;; if we need to create an entry AND none were found to match
1228 ;; create based on the spec and record the value
1230 ;; if the user did not want to create the entry
1231 ;; in the file, it will be returned
1232 (apply (slot-value backend
'create-function
) spec
)
1233 ;; if not, we do the search again without :create
1234 ;; to get the updated data.
1236 ;; the result will be returned, even if the search fails
1237 (apply 'auth-source-netrc-search
1238 (plist-put spec
:create nil
)))))
1241 (defun auth-source-netrc-element-or-first (v)
1246 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1247 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1249 (defun* auth-source-netrc-create
(&rest spec
1251 secret host user port create
1253 (let* ((base-required '(host user port secret
))
1254 ;; we know (because of an assertion in auth-source-search) that the
1255 ;; :create parameter is either t or a list (which includes nil)
1256 (create-extra (if (eq t create
) nil create
))
1257 (current-data (car (auth-source-search :max
1
1260 (required (append base-required create-extra
))
1261 (file (oref backend source
))
1263 ;; `valist' is an alist
1265 ;; `artificial' will be returned if no creation is needed
1268 ;; only for base required elements (defined as function parameters):
1269 ;; fill in the valist with whatever data we may have from the search
1270 ;; we complete the first value if it's a list and use the value otherwise
1271 (dolist (br base-required
)
1272 (when (symbol-value br
)
1273 (let ((br-choice (cond
1274 ;; all-accepting choice (predicate is t)
1275 ((eq t
(symbol-value br
)) nil
)
1276 ;; just the value otherwise
1277 (t (symbol-value br
)))))
1279 (auth-source--aput valist br br-choice
)))))
1281 ;; for extra required elements, see if the spec includes a value for them
1282 (dolist (er create-extra
)
1283 (let ((name (concat ":" (symbol-name er
)))
1284 (keys (loop for i below
(length spec
) by
2
1285 collect
(nth i spec
))))
1287 (when (equal (symbol-name k
) name
)
1288 (auth-source--aput valist er
(plist-get spec k
))))))
1290 ;; for each required element
1291 (dolist (r required
)
1292 (let* ((data (auth-source--aget valist r
))
1293 ;; take the first element if the data is a list
1294 (data (or (auth-source-netrc-element-or-first data
)
1295 (plist-get current-data
1296 (intern (format ":%s" r
) obarray
))))
1297 ;; this is the default to be offered
1298 (given-default (auth-source--aget
1299 auth-source-creation-defaults r
))
1300 ;; the default supplementals are simple:
1301 ;; for the user, try `given-default' and then (user-login-name);
1302 ;; otherwise take `given-default'
1304 ((and (not given-default
) (eq r
'user
))
1307 (printable-defaults (list
1310 (auth-source-netrc-element-or-first
1311 (auth-source--aget valist
'user
))
1312 (plist-get artificial
:user
)
1316 (auth-source-netrc-element-or-first
1317 (auth-source--aget valist
'host
))
1318 (plist-get artificial
:host
)
1322 (auth-source-netrc-element-or-first
1323 (auth-source--aget valist
'port
))
1324 (plist-get artificial
:port
)
1326 (prompt (or (auth-source--aget auth-source-creation-prompts r
)
1328 (secret "%p password for %u@%h: ")
1329 (user "%p user name for %h: ")
1330 (host "%p host name for user %u: ")
1331 (port "%p port for %u@%h: "))
1332 (format "Enter %s (%%u@%%h:%%p): " r
)))
1333 (prompt (auth-source-format-prompt
1335 `((?u
,(auth-source--aget printable-defaults
'user
))
1336 (?h
,(auth-source--aget printable-defaults
'host
))
1337 (?p
,(auth-source--aget printable-defaults
'port
))))))
1339 ;; Store the data, prompting for the password if needed.
1342 ;; Special case prompt for passwords.
1343 ;; 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)))
1344 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1345 (let* ((ep (format "Use GPG password tokens in %s?" file
))
1348 ((eq auth-source-netrc-use-gpg-tokens
'never
)
1350 ((listp auth-source-netrc-use-gpg-tokens
)
1351 (let ((check (copy-sequence
1352 auth-source-netrc-use-gpg-tokens
))
1355 (setq item
(pop check
))
1356 (when (or (eq (car item
) t
)
1357 (string-match (car item
) file
))
1358 (setq ret
(cdr item
))
1359 (setq check nil
)))))
1361 (plain (or (eval default
) (read-passwd prompt
))))
1362 ;; ask if we don't know what to do (in which case
1363 ;; auth-source-netrc-use-gpg-tokens must be a list)
1365 (setq gpg-encrypt
(if (y-or-n-p ep
) 'gpg
'never
))
1366 ;; TODO: save the defcustom now? or ask?
1367 (setq auth-source-netrc-use-gpg-tokens
1368 (cons `(,file
,gpg-encrypt
)
1369 auth-source-netrc-use-gpg-tokens
)))
1370 (if (eq gpg-encrypt
'gpg
)
1371 (auth-source-epa-make-gpg-token plain file
)
1373 (if (stringp default
)
1374 (read-string (if (string-match ": *\\'" prompt
)
1375 (concat (substring prompt
0 (match-beginning 0))
1376 " (default " default
"): ")
1377 (concat prompt
"(default " default
") "))
1382 (setq artificial
(plist-put artificial
1383 (intern (concat ":" (symbol-name r
)))
1385 (lexical-let ((data data
))
1389 ;; When r is not an empty string...
1390 (when (and (stringp data
)
1391 (< 0 (length data
)))
1392 ;; this function is not strictly necessary but I think it
1393 ;; makes the code clearer -tzz
1394 (let ((printer (lambda ()
1395 ;; append the key (the symbol name of r)
1396 ;; and the value in r
1399 (if (zerop (length add
)) "" " ")
1400 ;; remap auth-source tokens to netrc
1405 (port "port") ; redundant but clearer
1406 (t (symbol-name r
)))
1407 (if (string-match "[\"# ]" data
)
1410 (setq add
(concat add
(funcall printer
)))))))
1415 (lexical-let ((file file
)
1417 (lambda () (auth-source-netrc-saver file add
))))
1421 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1422 (defun auth-source-netrc-saver (file add
)
1423 "Save a line ADD in FILE, prompting along the way.
1424 Respects `auth-source-save-behavior'. Uses
1425 `auth-source-netrc-cache' to avoid prompting more than once."
1426 (let* ((key (format "%s %s" file
(rfc2104-hash 'md5
64 16 file add
)))
1427 (cached (assoc key auth-source-netrc-cache
)))
1430 (auth-source-do-trivia
1431 "auth-source-netrc-saver: found previous run for key %s, returning"
1434 (when (file-exists-p file
)
1435 (insert-file-contents file
))
1436 (when auth-source-gpg-encrypt-to
1437 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1438 ;; this buffer lets epa-file skip the key selection query
1439 ;; (see the `local-variable-p' check in
1440 ;; `epa-file-write-region').
1441 (unless (local-variable-p 'epa-file-encrypt-to
(current-buffer))
1442 (make-local-variable 'epa-file-encrypt-to
))
1443 (if (listp auth-source-gpg-encrypt-to
)
1444 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to
)))
1445 ;; we want the new data to be found first, so insert at beginning
1446 (goto-char (point-min))
1448 ;; Ask AFTER we've successfully opened the file.
1449 (let ((prompt (format "Save auth info to file %s? " file
))
1450 (done (not (eq auth-source-save-behavior
'ask
)))
1451 (bufname "*auth-source Help*")
1454 (setq k
(auth-source-read-char-choice prompt
'(?y ?n ?N ?e ??
)))
1458 (with-output-to-temp-buffer bufname
1460 (concat "(y)es, save\n"
1461 "(n)o but use the info\n"
1462 "(N)o and don't ask to save again\n"
1464 "(?) for help as you can see.\n"))
1465 ;; Why? Doesn't with-output-to-temp-buffer already do
1466 ;; the exact same thing anyway? --Stef
1467 (set-buffer standard-output
)
1474 (customize-save-variable 'auth-source-save-behavior nil
))
1475 (?e
(setq add
(read-string "Line to add: " add
)))
1478 (when (get-buffer-window bufname
)
1479 (delete-window (get-buffer-window bufname
)))
1481 ;; Make sure the info is not saved.
1482 (when (null auth-source-save-behavior
)
1485 (when (< 0 (length add
))
1490 (write-region (point-min) (point-max) file nil
'silent
)
1491 ;; Make the .authinfo file non-world-readable.
1492 (set-file-modes file
#o600
)
1493 (auth-source-do-debug
1494 "auth-source-netrc-create: wrote 1 new line to %s"
1496 (message "Saved new authentication information to %s" file
)
1498 (auth-source--aput auth-source-netrc-cache key
"ran"))))
1500 ;;; Backend specific parsing: Secrets API backend
1502 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1503 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1504 ;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1505 ;; (let ((auth-sources '(default))) (auth-source-search))
1506 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1507 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1509 (defun auth-source-secrets-listify-pattern (pattern)
1510 "Convert a pattern with lists to a list of string patterns.
1512 auth-source patterns can have values of the form :foo (\"bar\"
1513 \"qux\"), which means to match any secret with :foo equal to
1514 \"bar\" or :foo equal to \"qux\". The secrets backend supports
1515 only string values for patterns, so this routine returns a list
1516 of patterns that is equivalent to the single original pattern
1517 when interpreted such that if a secret matches any pattern in the
1518 list, it matches the original pattern."
1521 (let* ((key (pop pattern
))
1522 (value (pop pattern
))
1523 (tails (auth-source-secrets-listify-pattern pattern
))
1524 (heads (if (stringp value
)
1525 (list (list key value
))
1526 (mapcar (lambda (v) (list key v
)) value
))))
1532 collect
(append h tl
))))))
1534 (defun* auth-source-secrets-search
(&rest
1536 &key backend create delete label
1537 type max host user port
1539 "Search the Secrets API; spec is like `auth-source'.
1541 The :label key specifies the item's label. It is the only key
1542 that can specify a substring. Any :label value besides a string
1543 will allow any label.
1545 All other search keys must match exactly. If you need substring
1546 matching, do a wider search and narrow it down yourself.
1548 You'll get back all the properties of the token as a plist.
1550 Here's an example that looks for the first item in the 'Login'
1553 \(let ((auth-sources '(\"secrets:Login\")))
1554 (auth-source-search :max 1)
1556 Here's another that looks for the first item in the 'Login'
1557 Secrets collection whose label contains 'gnus':
1559 \(let ((auth-sources '(\"secrets:Login\")))
1560 (auth-source-search :max 1 :label \"gnus\")
1562 And this one looks for the first item in the 'Login' Secrets
1563 collection that's a Google Chrome entry for the git.gnus.org site
1564 authentication tokens:
1566 \(let ((auth-sources '(\"secrets:Login\")))
1567 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1571 (assert (not create
) nil
1572 "The Secrets API auth-source backend doesn't support creation yet")
1574 ;; (secrets-delete-item coll elt)
1575 (assert (not delete
) nil
1576 "The Secrets API auth-source backend doesn't support deletion yet")
1578 (let* ((coll (oref backend source
))
1579 (max (or max
5000)) ; sanity check: default to stop at 5K
1580 (ignored-keys '(:create
:delete
:max
:backend
:label
:require
:type
))
1581 (search-keys (loop for i below
(length spec
) by
2
1582 unless
(memq (nth i spec
) ignored-keys
)
1583 collect
(nth i spec
)))
1584 ;; build a search spec without the ignored keys
1585 ;; if a search key is nil or t (match anything), we skip it
1586 (search-specs (auth-source-secrets-listify-pattern
1587 (apply 'append
(mapcar
1589 (if (or (null (plist-get spec k
))
1590 (eq t
(plist-get spec k
)))
1592 (list k
(plist-get spec k
))))
1594 ;; needed keys (always including host, login, port, and secret)
1595 (returned-keys (mm-delete-duplicates (append
1596 '(:host
:login
:port
:secret
)
1599 (loop for search-spec in search-specs
1601 (loop for item in
(apply 'secrets-search-items coll search-spec
)
1602 unless
(and (stringp label
)
1603 (not (string-match label item
)))
1605 ;; TODO: respect max in `secrets-search-items', not after the fact
1606 (items (butlast items
(- (length items
) max
)))
1607 ;; convert the item name to a full plist
1608 (items (mapcar (lambda (item)
1610 ;; make an entry for the secret (password) element
1613 (lexical-let ((v (secrets-get-secret coll item
)))
1615 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1617 (mapcar (lambda (entry)
1618 (list (car entry
) (cdr entry
)))
1619 (secrets-get-attributes coll item
)))))
1621 ;; ensure each item has each key in `returned-keys'
1622 (items (mapcar (lambda (plist)
1625 (mapcar (lambda (req)
1626 (if (plist-get plist req
)
1634 (defun* auth-source-secrets-create
(&rest
1636 &key backend type max host user port
1639 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1642 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1644 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :create t))
1645 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :delete t))
1646 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1))
1647 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search))
1649 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :create t))
1650 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :delete t))
1651 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1))
1652 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search))
1654 ;; (let ((auth-sources '("macos-keychain-internet:/Users/tzz/Library/Keychains/login.keychain"))) (auth-source-search :max 1))
1655 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1 :host "git.gnus.org"))
1657 (defun* auth-source-macos-keychain-search
(&rest
1659 &key backend create delete label
1660 type max host user port
1662 "Search the MacOS Keychain; spec is like `auth-source'.
1664 All search keys must match exactly. If you need substring
1665 matching, do a wider search and narrow it down yourself.
1667 You'll get back all the properties of the token as a plist.
1669 The :type key is either 'macos-keychain-internet or
1670 'macos-keychain-generic.
1672 For the internet keychain type, the :label key searches the
1673 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1674 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1675 and :port maps to \"-P PORT\" or \"-r PROT\"
1676 (note PROT has to be a 4-character string).
1678 For the generic keychain type, the :label key searches the item's
1679 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1680 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1681 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1683 Here's an example that looks for the first item in the default
1684 generic MacOS Keychain:
1686 \(let ((auth-sources '(macos-keychain-generic)))
1687 (auth-source-search :max 1)
1689 Here's another that looks for the first item in the internet
1690 MacOS Keychain collection whose label is 'gnus':
1692 \(let ((auth-sources '(macos-keychain-internet)))
1693 (auth-source-search :max 1 :label \"gnus\")
1695 And this one looks for the first item in the internet keychain
1696 entries for git.gnus.org:
1698 \(let ((auth-sources '(macos-keychain-internet\")))
1699 (auth-source-search :max 1 :host \"git.gnus.org\"))
1702 (assert (not create
) nil
1703 "The MacOS Keychain auth-source backend doesn't support creation yet")
1705 ;; (macos-keychain-delete-item coll elt)
1706 (assert (not delete
) nil
1707 "The MacOS Keychain auth-source backend doesn't support deletion yet")
1709 (let* ((coll (oref backend source
))
1710 (max (or max
5000)) ; sanity check: default to stop at 5K
1711 (ignored-keys '(:create
:delete
:max
:backend
:label
))
1712 (search-keys (loop for i below
(length spec
) by
2
1713 unless
(memq (nth i spec
) ignored-keys
)
1714 collect
(nth i spec
)))
1715 ;; build a search spec without the ignored keys
1716 ;; if a search key is nil or t (match anything), we skip it
1717 (search-spec (apply 'append
(mapcar
1719 (if (or (null (plist-get spec k
))
1720 (eq t
(plist-get spec k
)))
1722 (list k
(plist-get spec k
))))
1724 ;; needed keys (always including host, login, port, and secret)
1725 (returned-keys (mm-delete-duplicates (append
1726 '(:host
:login
:port
:secret
)
1728 (items (apply 'auth-source-macos-keychain-search-items
1734 ;; ensure each item has each key in `returned-keys'
1735 (items (mapcar (lambda (plist)
1738 (mapcar (lambda (req)
1739 (if (plist-get plist req
)
1747 (defun* auth-source-macos-keychain-search-items
(coll type max
1753 (let* ((keychain-generic (eq type
'macos-keychain-generic
))
1754 (args `(,(if keychain-generic
1755 "find-generic-password"
1756 "find-internet-password")
1758 (ret (list :type type
)))
1760 (setq args
(append args
(list "-l" label
))))
1762 (setq args
(append args
(list (if keychain-generic
"-c" "-s") host
))))
1764 (setq args
(append args
(list "-a" user
))))
1767 (if keychain-generic
1768 (setq args
(append args
(list "-s" port
)))
1769 (setq args
(append args
(list
1770 (if (string-match "[0-9]+" port
) "-P" "-r")
1773 (unless (equal coll
"default")
1774 (setq args
(append args
(list coll
))))
1777 (apply 'call-process
"/usr/bin/security" nil t nil args
)
1778 (goto-char (point-min))
1781 ((looking-at "^password: \"\\(.+\\)\"$")
1782 (setq ret
(auth-source-macos-keychain-result-append
1786 (lexical-let ((v (match-string 1)))
1788 ;; TODO: check if this is really the label
1789 ;; match 0x00000007 <blob>="AppleID"
1790 ((looking-at "^[ ]+0x00000007 <blob>=\"\\(.+\\)\"")
1791 (setq ret
(auth-source-macos-keychain-result-append
1796 ;; match "crtr"<uint32>="aapl"
1797 ;; match "svce"<blob>="AppleID"
1798 ((looking-at "^[ ]+\"\\([a-z]+\\)\"[^=]+=\"\\(.+\\)\"")
1799 (setq ret
(auth-source-macos-keychain-result-append
1803 (match-string 2)))))
1805 ;; return `ret' iff it has the :secret key
1806 (and (plist-get ret
:secret
) (list ret
))))
1808 (defun auth-source-macos-keychain-result-append (result generic k v
)
1811 ((equal k
"acct") "user")
1812 ;; for generic keychains, creator is host, service is port
1813 ((and generic
(equal k
"crtr")) "host")
1814 ((and generic
(equal k
"svce")) "port")
1815 ;; for internet keychains, protocol is port, server is host
1816 ((and (not generic
) (equal k
"ptcl")) "port")
1817 ((and (not generic
) (equal k
"srvr")) "host")
1820 (push (intern (format ":%s" k
)) result
))
1822 (defun* auth-source-macos-keychain-create
(&rest
1824 &key backend type max host user port
1829 ;;; Backend specific parsing: PLSTORE backend
1831 (defun* auth-source-plstore-search
(&rest
1833 &key backend create delete label
1834 type max host user port
1836 "Search the PLSTORE; spec is like `auth-source'."
1837 (let* ((store (oref backend data
))
1838 (max (or max
5000)) ; sanity check: default to stop at 5K
1839 (ignored-keys '(:create
:delete
:max
:backend
:label
:require
:type
))
1840 (search-keys (loop for i below
(length spec
) by
2
1841 unless
(memq (nth i spec
) ignored-keys
)
1842 collect
(nth i spec
)))
1843 ;; build a search spec without the ignored keys
1844 ;; if a search key is nil or t (match anything), we skip it
1845 (search-spec (apply 'append
(mapcar
1847 (let ((v (plist-get spec k
)))
1855 ;; needed keys (always including host, login, port, and secret)
1856 (returned-keys (mm-delete-duplicates (append
1857 '(:host
:login
:port
:secret
)
1859 (items (plstore-find store search-spec
))
1860 (item-names (mapcar #'car items
))
1861 (items (butlast items
(- (length items
) max
)))
1862 ;; convert the item to a full plist
1863 (items (mapcar (lambda (item)
1864 (let* ((plist (copy-tree (cdr item
)))
1865 (secret (plist-member plist
:secret
)))
1869 (lexical-let ((v (car (cdr secret
))))
1873 ;; ensure each item has each key in `returned-keys'
1874 (items (mapcar (lambda (plist)
1877 (mapcar (lambda (req)
1878 (if (plist-get plist req
)
1885 ;; if we need to create an entry AND none were found to match
1889 ;; create based on the spec and record the value
1891 ;; if the user did not want to create the entry
1892 ;; in the file, it will be returned
1893 (apply (slot-value backend
'create-function
) spec
)
1894 ;; if not, we do the search again without :create
1895 ;; to get the updated data.
1897 ;; the result will be returned, even if the search fails
1898 (apply 'auth-source-plstore-search
1899 (plist-put spec
:create nil
)))))
1902 (dolist (item-name item-names
)
1903 (plstore-delete store item-name
))
1904 (plstore-save store
)))
1907 (defun* auth-source-plstore-create
(&rest spec
1909 secret host user port create
1911 (let* ((base-required '(host user port secret
))
1912 (base-secret '(secret))
1913 ;; we know (because of an assertion in auth-source-search) that the
1914 ;; :create parameter is either t or a list (which includes nil)
1915 (create-extra (if (eq t create
) nil create
))
1916 (current-data (car (auth-source-search :max
1
1919 (required (append base-required create-extra
))
1920 (file (oref backend source
))
1922 ;; `valist' is an alist
1924 ;; `artificial' will be returned if no creation is needed
1928 ;; only for base required elements (defined as function parameters):
1929 ;; fill in the valist with whatever data we may have from the search
1930 ;; we complete the first value if it's a list and use the value otherwise
1931 (dolist (br base-required
)
1932 (when (symbol-value br
)
1933 (let ((br-choice (cond
1934 ;; all-accepting choice (predicate is t)
1935 ((eq t
(symbol-value br
)) nil
)
1936 ;; just the value otherwise
1937 (t (symbol-value br
)))))
1939 (auth-source--aput valist br br-choice
)))))
1941 ;; for extra required elements, see if the spec includes a value for them
1942 (dolist (er create-extra
)
1943 (let ((name (concat ":" (symbol-name er
)))
1944 (keys (loop for i below
(length spec
) by
2
1945 collect
(nth i spec
))))
1947 (when (equal (symbol-name k
) name
)
1948 (auth-source--aput valist er
(plist-get spec k
))))))
1950 ;; for each required element
1951 (dolist (r required
)
1952 (let* ((data (auth-source--aget valist r
))
1953 ;; take the first element if the data is a list
1954 (data (or (auth-source-netrc-element-or-first data
)
1955 (plist-get current-data
1956 (intern (format ":%s" r
) obarray
))))
1957 ;; this is the default to be offered
1958 (given-default (auth-source--aget
1959 auth-source-creation-defaults r
))
1960 ;; the default supplementals are simple:
1961 ;; for the user, try `given-default' and then (user-login-name);
1962 ;; otherwise take `given-default'
1964 ((and (not given-default
) (eq r
'user
))
1967 (printable-defaults (list
1970 (auth-source-netrc-element-or-first
1971 (auth-source--aget valist
'user
))
1972 (plist-get artificial
:user
)
1976 (auth-source-netrc-element-or-first
1977 (auth-source--aget valist
'host
))
1978 (plist-get artificial
:host
)
1982 (auth-source-netrc-element-or-first
1983 (auth-source--aget valist
'port
))
1984 (plist-get artificial
:port
)
1986 (prompt (or (auth-source--aget auth-source-creation-prompts r
)
1988 (secret "%p password for %u@%h: ")
1989 (user "%p user name for %h: ")
1990 (host "%p host name for user %u: ")
1991 (port "%p port for %u@%h: "))
1992 (format "Enter %s (%%u@%%h:%%p): " r
)))
1993 (prompt (auth-source-format-prompt
1995 `((?u
,(auth-source--aget printable-defaults
'user
))
1996 (?h
,(auth-source--aget printable-defaults
'host
))
1997 (?p
,(auth-source--aget printable-defaults
'port
))))))
1999 ;; Store the data, prompting for the password if needed.
2002 (or (eval default
) (read-passwd prompt
))
2003 (if (stringp default
)
2005 (if (string-match ": *\\'" prompt
)
2006 (concat (substring prompt
0 (match-beginning 0))
2007 " (default " default
"): ")
2008 (concat prompt
"(default " default
") "))
2013 (if (member r base-secret
)
2014 (setq secret-artificial
2015 (plist-put secret-artificial
2016 (intern (concat ":" (symbol-name r
)))
2018 (setq artificial
(plist-put artificial
2019 (intern (concat ":" (symbol-name r
)))
2021 (plstore-put (oref backend data
)
2022 (sha1 (format "%s@%s:%s"
2023 (plist-get artificial
:user
)
2024 (plist-get artificial
:host
)
2025 (plist-get artificial
:port
)))
2026 artificial secret-artificial
)
2027 (if (y-or-n-p (format "Save auth info to file %s? "
2028 (plstore-get-file (oref backend data
))))
2029 (plstore-save (oref backend data
)))))
2033 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
2035 ;; deprecate the old interface
2036 (make-obsolete 'auth-source-user-or-password
2037 'auth-source-search
"Emacs 24.1")
2038 (make-obsolete 'auth-source-forget-user-or-password
2039 'auth-source-forget
"Emacs 24.1")
2041 (defun auth-source-user-or-password
2042 (mode host port
&optional username create-missing delete-existing
)
2043 "Find MODE (string or list of strings) matching HOST and PORT.
2045 DEPRECATED in favor of `auth-source-search'!
2047 USERNAME is optional and will be used as \"login\" in a search
2048 across the Secret Service API (see secrets.el) if the resulting
2049 items don't have a username. This means that if you search for
2050 username \"joe\" and it matches an item but the item doesn't have
2051 a :user attribute, the username \"joe\" will be returned.
2053 A non nil DELETE-EXISTING means deleting any matching password
2054 entry in the respective sources. This is useful only when
2055 CREATE-MISSING is non nil as well; the intended use case is to
2056 remove wrong password entries.
2058 If no matching entry is found, and CREATE-MISSING is non nil,
2059 the password will be retrieved interactively, and it will be
2060 stored in the password database which matches best (see
2063 MODE can be \"login\" or \"password\"."
2064 (auth-source-do-debug
2065 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2066 mode host port username
)
2068 (let* ((listy (listp mode
))
2069 (mode (if listy mode
(list mode
)))
2071 (format "%s %s:%s %s" mode host port username
)
2072 (format "%s %s:%s" mode host port
)))
2073 (search (list :host host
:port port
))
2074 (search (if username
(append search
(list :user username
)) search
))
2075 (search (if create-missing
2076 (append search
(list :create t
))
2078 (search (if delete-existing
2079 (append search
(list :delete t
))
2081 ;; (found (if (not delete-existing)
2082 ;; (gethash cname auth-source-cache)
2083 ;; (remhash cname auth-source-cache)
2088 (auth-source-do-debug
2089 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2091 ;; don't show the password
2092 (if (and (member "password" mode
) t
)
2096 found
) ; return the found data
2097 ;; else, if not found, search with a max of 1
2098 (let ((choice (nth 0 (apply 'auth-source-search
2099 (append '(:max
1) search
)))))
2103 ((equal "password" m
)
2104 (push (if (plist-get choice
:secret
)
2105 (funcall (plist-get choice
:secret
))
2108 (push (plist-get choice
:user
) found
)))))
2109 (setq found
(nreverse found
))
2110 (setq found
(if listy found
(car-safe found
)))))
2114 (defun auth-source-user-and-password (host &optional user
)
2115 (let* ((auth-info (car
2119 :user
"yourusername"
2121 :require
'(:user
:secret
)
2126 :require
'(:user
:secret
)
2128 (user (plist-get auth-info
:user
))
2129 (password (plist-get auth-info
:secret
)))
2130 (when (functionp password
)
2131 (setq password
(funcall password
)))
2132 (list user password auth-info
)))
2134 (provide 'auth-source
)
2136 ;;; auth-source.el ends here