bitwarden.el 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. ;;; bitwarden.el --- Bitwarden command wrapper -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2018 Sean Farley
  3. ;; Author: Sean Farley
  4. ;; URL: https://github.com/seanfarley/emacs-bitwarden
  5. ;; Version: 0.1.0
  6. ;; Created: 2018-09-04
  7. ;; Package-Requires: ((emacs "24.4"))
  8. ;; Keywords: extensions processes bw bitwarden
  9. ;;; License
  10. ;; This program is free software: you can redistribute it and/or modify
  11. ;; it under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation, either version 3 of the License, or
  13. ;; (at your option) any later version.
  14. ;; This program is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;; GNU General Public License for more details.
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. ;;; Commentary:
  21. ;; This package wraps the bitwarden command-line program.
  22. ;;; Code:
  23. (require 'json)
  24. ;=============================== custom variables ==============================
  25. (defcustom bitwarden-bw-executable (executable-find "bw")
  26. "The bw cli executable used by Bitwarden."
  27. :group 'bitwarden
  28. :type 'string)
  29. (defcustom bitwarden-data-file
  30. (expand-file-name "~/Library/Application Support/Bitwarden CLI/data.json")
  31. "The bw cli executable used by Bitwarden."
  32. :group 'bitwarden
  33. :type 'string)
  34. (defcustom bitwarden-user nil
  35. "Bitwarden user e-mail."
  36. :group 'bitwarden
  37. :type 'string)
  38. (defcustom bitwarden-automatic-unlock nil
  39. "Optional function to be called to attempt to unlock the vault.
  40. Set this to a lamdba that will evaluate to a password. For
  41. example, this can be the :secret plist from
  42. `auth-source-search'."
  43. :group 'bitwarden
  44. :type 'function)
  45. (defconst bitwarden--err-logged-in "you are not logged in")
  46. (defconst bitwarden--err-multiple "more than one result found")
  47. (defconst bitwarden--err-locked "vault is locked")
  48. ;===================================== util ====================================
  49. (defun bitwarden-logged-in-p ()
  50. "Check if `bitwarden-user' is logged in.
  51. Returns nil if not logged in."
  52. (let* ((json-object-type 'hash-table)
  53. (json-key-type 'string)
  54. (json (json-read-file bitwarden-data-file)))
  55. (gethash "__PROTECTED__key" json)))
  56. (defun bitwarden-unlocked-p ()
  57. "Check if we have already set the 'BW_SESSION' environment variable."
  58. (and (bitwarden-logged-in-p) (getenv "BW_SESSION")))
  59. (defun bitwarden--raw-runcmd (cmd &rest args)
  60. "Run bw command CMD with ARGS.
  61. Returns a list with the first element being the exit code and the
  62. second element being the output."
  63. (with-temp-buffer
  64. (list (apply 'call-process
  65. bitwarden-bw-executable
  66. nil (current-buffer) nil
  67. (cons cmd args))
  68. (replace-regexp-in-string "\n$" ""
  69. (buffer-string)))))
  70. (defun bitwarden-runcmd (cmd &rest args)
  71. "Run bw command CMD with ARGS.
  72. This is a wrapper for `bitwarden--raw-runcmd' that also checks
  73. for common errors."
  74. (if (bitwarden-logged-in-p)
  75. (if (bitwarden-unlocked-p)
  76. (let* ((ret (apply #'bitwarden--raw-runcmd cmd args))
  77. (exit-code (nth 0 ret))
  78. (output (nth 1 ret)))
  79. (if (eq exit-code 0)
  80. output
  81. (cond ((string-match "^More than one result was found." output)
  82. bitwarden--err-multiple)
  83. (t nil))))
  84. bitwarden--err-locked)
  85. bitwarden--err-logged-in))
  86. (defun bitwarden--login-proc-filter (proc string)
  87. "Interacts with PROC by sending line-by-line STRING."
  88. ;; read username if not defined
  89. (when (string-match "^? Email address:" string)
  90. (let ((user (read-string "Bitwarden email: ")))
  91. ;; if we are here then the user forgot to fill in this field so let's do
  92. ;; that now
  93. (setq bitwarden-user user)
  94. (process-send-string proc (concat bitwarden-user "\n"))))
  95. ;; read master password
  96. (when (string-match "^? Master password:" string)
  97. (process-send-string
  98. proc (concat (read-passwd "Bitwarden master password: ") "\n")))
  99. ;; check for bad password
  100. (when (string-match "^Username or password is incorrect" string)
  101. (message "Bitwarden: incorrect master password"))
  102. ;; if trying to unlock, check if logged in
  103. (when (string-match "^You are not logged in" string)
  104. (message "Bitwarden: cannot unlock: not logged in"))
  105. ;; read the 2fa code
  106. (when (string-match "^? Two-step login code:" string)
  107. (process-send-string
  108. proc (concat (read-passwd "Bitwarden two-step login code: ") "\n")))
  109. ;; check for bad code
  110. (when (string-match "^Login failed" string)
  111. (message "Bitwarden: incorrect two-step code"))
  112. ;; check for already logged in
  113. (when (string-match "^You are already logged in" string)
  114. (string-match "You are already logged in as \\(.*\\)\\." string)
  115. (message "Bitwarden: already logged in as %s" (match-string 1 string)))
  116. ;; success! now save the BW_SESSION into the environment so spawned processes
  117. ;; inherit it
  118. (when (string-match "^\\(You are logged in\\|Your vault is now unlocked\\)"
  119. string)
  120. ;; set the session env variable so spawned processes inherit
  121. (string-match "export BW_SESSION=\"\\(.*\\)\"" string)
  122. (setenv "BW_SESSION" (match-string 1 string))
  123. (message
  124. (concat "Bitwarden: successfully logged in as " bitwarden-user))))
  125. (defun bitwarden--raw-unlock (cmd)
  126. "Raw CMD to either unlock a vault or login.
  127. The only difference between unlock and login is just the name of
  128. the command and whether to pass the user."
  129. (when (get-process "bitwarden")
  130. (delete-process "bitwarden"))
  131. (let ((process (start-process-shell-command
  132. "bitwarden"
  133. nil ; don't use a buffer
  134. (concat bitwarden-bw-executable " " cmd))))
  135. (set-process-filter process #'bitwarden--login-proc-filter)))
  136. ;================================= interactive =================================
  137. (defun bitwarden-unlock ()
  138. "Unlock bitwarden vault.
  139. It is not sufficient to check the env variable for BW_SESSION
  140. since that could be set yet could be expired or incorrect."
  141. (interactive "M")
  142. (let ((pass (when bitwarden-automatic-unlock
  143. (concat " " (funcall bitwarden-automatic-unlock)))))
  144. (bitwarden--raw-unlock (concat "unlock" pass))))
  145. (defun bitwarden-login ()
  146. "Prompts user for password if not logged in."
  147. (interactive "M")
  148. (unless bitwarden-user
  149. (setq bitwarden-user (read-string "Bitwarden email: ")))
  150. (let ((pass (when bitwarden-automatic-unlock
  151. (concat " " (funcall bitwarden-automatic-unlock)))))
  152. (bitwarden--raw-unlock (concat "login " bitwarden-user pass))))
  153. (defun bitwarden-lock ()
  154. "Lock the bw vault. Does not ask for confirmation."
  155. (interactive)
  156. (when (bitwarden-unlocked-p)
  157. (setenv "BW_SESSION" nil)))
  158. ;;;###autoload
  159. (defun bitwarden-logout ()
  160. "Log out bw. Does not ask for confirmation."
  161. (interactive)
  162. (when (bitwarden-logged-in-p)
  163. (bitwarden-runcmd "logout")
  164. (bitwarden-lock)))
  165. (defun bitwarden--message (msg args &optional print-message)
  166. "Print MSG using `message' and `format' with ARGS if non-nil.
  167. PRINT-MESSAGE is an optional parameter to control whether this
  168. method should print at all. If nil then nothing will be printed
  169. at all.
  170. This method will prepend 'Bitwarden: ' before each MSG as a
  171. convenience. Also, return a value of nil so that no strings
  172. are mistaken as a password (e.g. accidentally interpreting
  173. 'Bitwarden: error' as the password when in fact, it was an error
  174. message but happens to be last on the method stack)."
  175. (when print-message
  176. (let ((msg (if args (format msg args) msg)))
  177. (message (concat "Bitwarden: " msg))))
  178. nil)
  179. ;;;###autoload
  180. (defun bitwarden-getpass (account &optional print-message recursive-pass)
  181. "Get password associated with ACCOUNT.
  182. If run interactively PRINT-MESSAGE gets set and password is
  183. printed to minibuffer.
  184. If RECURSIVE-PASS is set, then treat this call as an attempt to auto-unlock."
  185. (interactive "MBitwarden account name: \np")
  186. (let* ((pass (or recursive-pass
  187. (bitwarden-runcmd "get" "password" account))))
  188. (cond
  189. ((string-match bitwarden--err-locked pass)
  190. ;; try to unlock automatically, if possible
  191. (if (not bitwarden-automatic-unlock)
  192. (bitwarden--message "error: %s" pass print-message)
  193. ;; only attempt a retry once; to prevent infinite recursion
  194. (when (not recursive-pass)
  195. ;; because I don't understand how emacs is asyncronous here nor
  196. ;; how to tell it to wait until the process is done, we do so here
  197. ;; manually
  198. (bitwarden-unlock)
  199. (while (get-process "bitwarden")
  200. (sleep-for 0.1))
  201. (bitwarden-getpass account print-message
  202. (bitwarden-runcmd "get" "password" account)))))
  203. ((or (string-match bitwarden--err-logged-in pass)
  204. (string-match bitwarden--err-multiple pass))
  205. (bitwarden--message "error: %s" pass print-message))
  206. (t pass))))
  207. (provide 'bitwarden)
  208. ;;; bitwarden.el ends here