bitwarden.el 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 print-message)
  87. "Interacts with PROC by sending line-by-line STRING.
  88. If PRINT-MESSAGE is set then messages are printed to minibuffer."
  89. ;; read username if not defined
  90. (when (string-match "^? Email address:" string)
  91. (let ((user (read-string "Bitwarden email: ")))
  92. ;; if we are here then the user forgot to fill in this field so let's do
  93. ;; that now
  94. (setq bitwarden-user user)
  95. (process-send-string proc (concat bitwarden-user "\n"))))
  96. ;; read master password
  97. (when (string-match "^? Master password:" string)
  98. (process-send-string
  99. proc (concat (read-passwd "Bitwarden master password: ") "\n")))
  100. ;; check for bad password
  101. (when (string-match "^Username or password is incorrect" string)
  102. (bitwarden--message "incorrect master password" nil print-message))
  103. ;; if trying to unlock, check if logged in
  104. (when (string-match "^You are not logged in" string)
  105. (bitwarden--message "cannot unlock: not logged in" nil print-message))
  106. ;; read the 2fa code
  107. (when (string-match "^? Two-step login code:" string)
  108. (process-send-string
  109. proc (concat (read-passwd "Bitwarden two-step login code: ") "\n")))
  110. ;; check for bad code
  111. (when (string-match "^Login failed" string)
  112. (bitwarden--message "incorrect two-step code" nil print-message))
  113. ;; check for already logged in
  114. (when (string-match "^You are already logged in" string)
  115. (string-match "You are already logged in as \\(.*\\)\\." string)
  116. (bitwarden--message
  117. "already logged in as %s" (match-string 1 string) print-message))
  118. ;; success! now save the BW_SESSION into the environment so spawned processes
  119. ;; inherit it
  120. (when (string-match "^\\(You are logged in\\|Your vault is now unlocked\\)"
  121. string)
  122. ;; set the session env variable so spawned processes inherit
  123. (string-match "export BW_SESSION=\"\\(.*\\)\"" string)
  124. (setenv "BW_SESSION" (match-string 1 string))
  125. (bitwarden--message
  126. "successfully logged in as %s" bitwarden-user print-message)))
  127. (defun bitwarden--raw-unlock (cmd print-message)
  128. "Raw CMD to either unlock a vault or login.
  129. The only difference between unlock and login is just the name of
  130. the command and whether to pass the user.
  131. If PRINT-MESSAGE is set then messages are printed to minibuffer."
  132. (when (get-process "bitwarden")
  133. (delete-process "bitwarden"))
  134. (let ((process (start-process-shell-command
  135. "bitwarden"
  136. nil ; don't use a buffer
  137. (concat bitwarden-bw-executable " " cmd))))
  138. (set-process-filter process (lambda (proc string)
  139. (bitwarden--login-proc-filter
  140. proc string print-message)))
  141. ;; suppress output to the minibuffer when running this programatically
  142. nil))
  143. ;================================= interactive =================================
  144. (defun bitwarden-unlock (&optional print-message)
  145. "Unlock bitwarden vault.
  146. It is not sufficient to check the env variable for BW_SESSION
  147. since that could be set yet could be expired or incorrect.
  148. If run interactively PRINT-MESSAGE gets set and messages are
  149. printed to minibuffer."
  150. (interactive "p")
  151. (let ((pass (when bitwarden-automatic-unlock
  152. (concat " " (funcall bitwarden-automatic-unlock)))))
  153. (bitwarden--raw-unlock (concat "unlock" pass print-message) print-message)))
  154. (defun bitwarden-login (&optional print-message)
  155. "Prompts user for password if not logged in.
  156. If run interactively PRINT-MESSAGE gets set and messages are
  157. printed to minibuffer."
  158. (interactive "p")
  159. (unless bitwarden-user
  160. (setq bitwarden-user (read-string "Bitwarden email: ")))
  161. (let ((pass (when bitwarden-automatic-unlock
  162. (concat " " (funcall bitwarden-automatic-unlock)))))
  163. (bitwarden--raw-unlock (concat "login " bitwarden-user pass) print-message)))
  164. (defun bitwarden-lock ()
  165. "Lock the bw vault. Does not ask for confirmation."
  166. (interactive)
  167. (when (bitwarden-unlocked-p)
  168. (setenv "BW_SESSION" nil)))
  169. ;;;###autoload
  170. (defun bitwarden-logout ()
  171. "Log out bw. Does not ask for confirmation."
  172. (interactive)
  173. (when (bitwarden-logged-in-p)
  174. (bitwarden-runcmd "logout")
  175. (bitwarden-lock)))
  176. (defun bitwarden--message (msg args &optional print-message)
  177. "Print MSG using `message' and `format' with ARGS if non-nil.
  178. PRINT-MESSAGE is an optional parameter to control whether this
  179. method should print at all. If nil then nothing will be printed
  180. at all.
  181. This method will prepend 'Bitwarden: ' before each MSG as a
  182. convenience. Also, return a value of nil so that no strings
  183. are mistaken as a password (e.g. accidentally interpreting
  184. 'Bitwarden: error' as the password when in fact, it was an error
  185. message but happens to be last on the method stack)."
  186. (when print-message
  187. (let ((msg (if args (format msg args) msg)))
  188. (message (concat "Bitwarden: " msg))))
  189. nil)
  190. (defun bitwarden--message-pass (pass &optional print-message)
  191. "Print PASS using `message' or return PASS.
  192. PRINT-MESSAGE is an optional parameter to control whether this
  193. method should print at all. If nil then nothing will be printed
  194. at all but PASS will be returned (e.g. when run non-interactively)."
  195. (if print-message
  196. (message pass)
  197. pass))
  198. ;;;###autoload
  199. (defun bitwarden-getpass (account &optional print-message recursive-pass)
  200. "Get password associated with ACCOUNT.
  201. If run interactively PRINT-MESSAGE gets set and password is
  202. printed to minibuffer.
  203. If RECURSIVE-PASS is set, then treat this call as an attempt to auto-unlock."
  204. (interactive "MBitwarden account name: \np")
  205. (let* ((pass (or recursive-pass
  206. (bitwarden-runcmd "get" "password" account))))
  207. (cond
  208. ((string-match bitwarden--err-locked pass)
  209. ;; try to unlock automatically, if possible
  210. (if (not bitwarden-automatic-unlock)
  211. (bitwarden--message "error: %s" pass print-message)
  212. ;; only attempt a retry once; to prevent infinite recursion
  213. (when (not recursive-pass)
  214. ;; because I don't understand how emacs is asyncronous here nor
  215. ;; how to tell it to wait until the process is done, we do so here
  216. ;; manually
  217. (bitwarden-unlock)
  218. (while (get-process "bitwarden")
  219. (sleep-for 0.1))
  220. (bitwarden--message-pass
  221. (bitwarden-getpass account print-message
  222. (bitwarden-runcmd "get" "password" account))
  223. print-message))))
  224. ((or (string-match bitwarden--err-logged-in pass)
  225. (string-match bitwarden--err-multiple pass))
  226. (bitwarden--message "error: %s" pass print-message))
  227. (t (bitwarden--message-pass pass print-message)))))
  228. (provide 'bitwarden)
  229. ;;; bitwarden.el ends here