bitwarden.el 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. (require 'subr-x)
  25. (require 'tree-widget)
  26. ;=============================== custom variables ==============================
  27. (defcustom bitwarden-bw-executable (executable-find "bw")
  28. "The bw cli executable used by Bitwarden."
  29. :group 'bitwarden
  30. :type 'string)
  31. (defcustom bitwarden-data-file
  32. (expand-file-name "~/Library/Application Support/Bitwarden CLI/data.json")
  33. "The bw cli executable used by Bitwarden."
  34. :group 'bitwarden
  35. :type 'string)
  36. (defcustom bitwarden-user nil
  37. "Bitwarden user e-mail."
  38. :group 'bitwarden
  39. :type 'string)
  40. (defcustom bitwarden-automatic-unlock nil
  41. "Optional function to be called to attempt to unlock the vault.
  42. Set this to a lamdba that will evaluate to a password. For
  43. example, this can be the :secret plist from
  44. `auth-source-search'."
  45. :group 'bitwarden
  46. :type 'function)
  47. (defconst bitwarden--err-logged-in "you are not logged in")
  48. (defconst bitwarden--err-multiple "more than one result found")
  49. (defconst bitwarden--err-locked "vault is locked")
  50. ;===================================== util ====================================
  51. (defun bitwarden-logged-in-p ()
  52. "Check if `bitwarden-user' is logged in.
  53. Returns nil if not logged in."
  54. (let* ((json-object-type 'hash-table)
  55. (json-key-type 'string)
  56. (json (json-read-file bitwarden-data-file)))
  57. (gethash "__PROTECTED__key" json)))
  58. (defun bitwarden-unlocked-p ()
  59. "Check if we have already set the 'BW_SESSION' environment variable."
  60. (and (bitwarden-logged-in-p) (getenv "BW_SESSION")))
  61. (defun bitwarden--raw-runcmd (cmd &rest args)
  62. "Run bw command CMD with ARGS.
  63. Returns a list with the first element being the exit code and the
  64. second element being the output."
  65. (with-temp-buffer
  66. (list (apply 'call-process
  67. bitwarden-bw-executable
  68. nil (current-buffer) nil
  69. (cons cmd args))
  70. (replace-regexp-in-string "\n$" ""
  71. (buffer-string)))))
  72. (defun bitwarden-runcmd (cmd &rest args)
  73. "Run bw command CMD with ARGS.
  74. This is a wrapper for `bitwarden--raw-runcmd' that also checks
  75. for common errors."
  76. (if (bitwarden-logged-in-p)
  77. (if (bitwarden-unlocked-p)
  78. (let* ((ret (apply #'bitwarden--raw-runcmd cmd args))
  79. (exit-code (nth 0 ret))
  80. (output (nth 1 ret)))
  81. (if (eq exit-code 0)
  82. output
  83. (cond ((string-match "^More than one result was found." output)
  84. bitwarden--err-multiple)
  85. (t nil))))
  86. bitwarden--err-locked)
  87. bitwarden--err-logged-in))
  88. (defun bitwarden--login-proc-filter (proc string print-message)
  89. "Interacts with PROC by sending line-by-line STRING.
  90. If PRINT-MESSAGE is set then messages are printed to minibuffer."
  91. ;; read username if not defined
  92. (when (string-match "^? Email address:" string)
  93. (let ((user (read-string "Bitwarden email: ")))
  94. ;; if we are here then the user forgot to fill in this field so let's do
  95. ;; that now
  96. (setq bitwarden-user user)
  97. (process-send-string proc (concat bitwarden-user "\n"))))
  98. ;; read master password
  99. (when (string-match "^? Master password:" string)
  100. (process-send-string
  101. proc (concat (read-passwd "Bitwarden master password: ") "\n")))
  102. ;; check for bad password
  103. (when (string-match "^Username or password is incorrect" string)
  104. (bitwarden--message "incorrect master password" nil print-message))
  105. ;; if trying to unlock, check if logged in
  106. (when (string-match "^You are not logged in" string)
  107. (bitwarden--message "cannot unlock: not logged in" nil print-message))
  108. ;; read the 2fa code
  109. (when (string-match "^? Two-step login code:" string)
  110. (process-send-string
  111. proc (concat (read-passwd "Bitwarden two-step login code: ") "\n")))
  112. ;; check for bad code
  113. (when (string-match "^Login failed" string)
  114. (bitwarden--message "incorrect two-step code" nil print-message))
  115. ;; check for already logged in
  116. (when (string-match "^You are already logged in" string)
  117. (string-match "You are already logged in as \\(.*\\)\\." string)
  118. (bitwarden--message
  119. "already logged in as %s" (match-string 1 string) print-message))
  120. ;; success! now save the BW_SESSION into the environment so spawned processes
  121. ;; inherit it
  122. (when (string-match "^\\(You are logged in\\|Your vault is now unlocked\\)"
  123. string)
  124. ;; set the session env variable so spawned processes inherit
  125. (string-match "export BW_SESSION=\"\\(.*\\)\"" string)
  126. (setenv "BW_SESSION" (match-string 1 string))
  127. (bitwarden--message
  128. "successfully logged in as %s" bitwarden-user print-message)))
  129. (defun bitwarden--raw-unlock (cmd print-message)
  130. "Raw CMD to either unlock a vault or login.
  131. The only difference between unlock and login is just the name of
  132. the command and whether to pass the user.
  133. If PRINT-MESSAGE is set then messages are printed to minibuffer."
  134. (when (get-process "bitwarden")
  135. (delete-process "bitwarden"))
  136. (let ((process (start-process-shell-command
  137. "bitwarden"
  138. nil ; don't use a buffer
  139. (concat bitwarden-bw-executable " " cmd))))
  140. (set-process-filter process (lambda (proc string)
  141. (bitwarden--login-proc-filter
  142. proc string print-message)))
  143. ;; suppress output to the minibuffer when running this programatically
  144. nil))
  145. ;================================= interactive =================================
  146. (defun bitwarden-unlock (&optional print-message)
  147. "Unlock bitwarden vault.
  148. It is not sufficient to check the env variable for BW_SESSION
  149. since that could be set yet could be expired or incorrect.
  150. If run interactively PRINT-MESSAGE gets set and messages are
  151. printed to minibuffer."
  152. (interactive "p")
  153. (let ((pass (when bitwarden-automatic-unlock
  154. (concat " " (funcall bitwarden-automatic-unlock)))))
  155. (bitwarden--raw-unlock (concat "unlock " pass) print-message)))
  156. (defun bitwarden-login (&optional print-message)
  157. "Prompts user for password if not logged in.
  158. If run interactively PRINT-MESSAGE gets set and messages are
  159. printed to minibuffer."
  160. (interactive "p")
  161. (unless bitwarden-user
  162. (setq bitwarden-user (read-string "Bitwarden email: ")))
  163. (let ((pass (when bitwarden-automatic-unlock
  164. (concat " " (funcall bitwarden-automatic-unlock)))))
  165. (bitwarden--raw-unlock (concat "login " bitwarden-user pass) print-message)))
  166. (defun bitwarden-lock ()
  167. "Lock the bw vault. Does not ask for confirmation."
  168. (interactive)
  169. (when (bitwarden-unlocked-p)
  170. (setenv "BW_SESSION" nil)))
  171. ;;;###autoload
  172. (defun bitwarden-logout ()
  173. "Log out bw. Does not ask for confirmation."
  174. (interactive)
  175. (when (bitwarden-logged-in-p)
  176. (bitwarden-runcmd "logout")
  177. (bitwarden-lock)))
  178. (defun bitwarden--message (msg args &optional print-message)
  179. "Print MSG using `message' and `format' with ARGS if non-nil.
  180. PRINT-MESSAGE is an optional parameter to control whether this
  181. method should print at all. If nil then nothing will be printed
  182. at all.
  183. This method will prepend 'Bitwarden: ' before each MSG as a
  184. convenience. Also, return a value of nil so that no strings
  185. are mistaken as a password (e.g. accidentally interpreting
  186. 'Bitwarden: error' as the password when in fact, it was an error
  187. message but happens to be last on the method stack)."
  188. (when print-message
  189. (let ((msg (if args (format msg args) msg)))
  190. (message (concat "Bitwarden: " msg))))
  191. nil)
  192. (defun bitwarden--handle-message (msg &optional print-message)
  193. "Handle return MSG of `bitwarden--auto-cmd'.
  194. Since `bitwarden--auto-cmd' returns a list of (err-code message),
  195. this function exists to handle that. Printing the error message
  196. is entirely dependent on PRINT-MESSAGE (see below for more info
  197. on PRINT-MESSAGE).
  198. If the error code is 0, then print the password based on
  199. PRINT-MESSAGE or just return it.
  200. If the error code is non-zero, then print the message based on
  201. PRINT-MESSAGE and return nil.
  202. PRINT-MESSAGE is an optional parameter to control whether this
  203. method should print at all. If nil then nothing will be printed
  204. at all but password will be returned (e.g. when run
  205. non-interactively)."
  206. (let* ((err (nth 0 msg))
  207. (pass (nth 1 msg)))
  208. (cond
  209. ((eq err 0)
  210. (if print-message
  211. (message "%s" pass)
  212. pass))
  213. (t
  214. (bitwarden--message "%s" pass print-message)
  215. nil))))
  216. (defun bitwarden--auto-cmd (cmd &optional recursive-pass)
  217. "Run Bitwarden CMD and attempt to auto unlock.
  218. If RECURSIVE-PASS is set, then treat this call as a second
  219. attempt after trying to auto-unlock.
  220. Returns a tuple of the error code and the error message or
  221. password if successful."
  222. (let* ((res (or recursive-pass (apply 'bitwarden-runcmd cmd))))
  223. (cond
  224. ((string-match bitwarden--err-locked res)
  225. ;; try to unlock automatically, if possible
  226. (if (not bitwarden-automatic-unlock)
  227. (list 1 (format "error: %s" res))
  228. ;; only attempt a retry once; to prevent infinite recursion
  229. (when (not recursive-pass)
  230. ;; because I don't understand how emacs is asyncronous here nor
  231. ;; how to tell it to wait until the process is done, we do so here
  232. ;; manually
  233. (bitwarden-unlock)
  234. (while (get-process "bitwarden")
  235. (sleep-for 0.1))
  236. (bitwarden--auto-cmd cmd (apply 'bitwarden-runcmd cmd)))))
  237. ((or (string-match bitwarden--err-logged-in res)
  238. (string-match bitwarden--err-multiple res))
  239. (list 2 (format "error: %s" res)))
  240. (t (list 0 res)))))
  241. ;;;###autoload
  242. (defun bitwarden-getpass (account &optional print-message)
  243. "Get password associated with ACCOUNT.
  244. If run interactively PRINT-MESSAGE gets set and password is
  245. printed to minibuffer."
  246. (interactive "MBitwarden account name: \np")
  247. (bitwarden--handle-message
  248. (bitwarden--auto-cmd (list "get" "password" account))
  249. print-message))
  250. ;;;###autoload
  251. (defun bitwarden-search (&optional search-str)
  252. "Search for vault for items containing SEARCH-STR.
  253. If run interactively PRINT-MESSAGE gets set and password is
  254. printed to minibuffer.
  255. Returns a vector of hashtables of the results."
  256. (let* ((args (and search-str (list "--search" search-str)))
  257. (ret (bitwarden--auto-cmd (append (list "list" "items") args)))
  258. (result (bitwarden--handle-message ret)))
  259. (when result
  260. (let* ((json-object-type 'hash-table)
  261. (json-key-type 'string)
  262. (json (json-read-from-string result)))
  263. json))))
  264. ;;;###autoload
  265. (defun bitwarden-folders ()
  266. "List bitwarden folders."
  267. (let* ((ret (bitwarden--auto-cmd (list "list" "folders")))
  268. (result (bitwarden--handle-message ret)))
  269. (when result
  270. (let* ((json-object-type 'hash-table)
  271. (json-key-type 'string)
  272. (json (json-read-from-string result)))
  273. json))))
  274. ;================================= widget utils ================================
  275. (defun bitwarden-list-next ()
  276. "Move to the next item."
  277. (interactive)
  278. (forward-line)
  279. (beginning-of-line)
  280. (widget-forward 1))
  281. (defun bitwarden-list-prev ()
  282. "Move to the previous item."
  283. (interactive)
  284. (widget-backward 2)
  285. (beginning-of-line)
  286. (widget-forward 1))
  287. ;; bitwarden-list-dialog-mode
  288. (defvar bitwarden-list-dialog-mode-map
  289. (let ((map (make-sparse-keymap)))
  290. (set-keymap-parent map widget-keymap)
  291. (define-key map "n" 'bitwarden-list-next)
  292. (define-key map "p" 'bitwarden-list-prev)
  293. (define-key map "q" 'bitwarden-list-cancel-dialog)
  294. map)
  295. "Keymap used in recentf dialogs.")
  296. (define-derived-mode bitwarden-list-dialog-mode nil "bitwarden-list-dialog"
  297. "Major mode of recentf dialogs.
  298. \\{bitwarden-list-dialog-mode-map}"
  299. :syntax-table nil
  300. :abbrev-table nil
  301. (setq truncate-lines t))
  302. (defsubst bitwarden-list-all-get-item-at-pos ()
  303. "Get hashtable from widget at current pos in dialog widget."
  304. (let ((widget (get-char-property (point) 'button)))
  305. (widget-value widget)))
  306. (defsubst bitwarden-list-all-make-spaces (spaces)
  307. "Create a string with SPACES number of whitespaces."
  308. (mapconcat 'identity (make-list spaces " ") ""))
  309. (defsubst bitwarden-pad-to-width (item width)
  310. "Create a string with ITEM padded to WIDTH."
  311. (if (= (length item) width)
  312. item
  313. (if (>= (length item) width)
  314. (concat (substring item 0 (- width 1)) "…")
  315. (concat item (bitwarden-list-all-make-spaces (- width (length item)))))))
  316. ;================================ widget actions ===============================
  317. ;; Dialog settings and actions
  318. (defun bitwarden-list-cancel-dialog (&rest _ignore)
  319. "Cancel the current dialog.
  320. IGNORE arguments."
  321. (interactive)
  322. (kill-buffer (current-buffer))
  323. (bitwarden--message "dialog canceled" nil t))
  324. (defun bitwarden-list-all-kill-ring-save (&optional widget-item)
  325. "Bitwarden `kill-ring-save', insert password to kill ring.
  326. If WIDGET-ITEM is not supplied then look for the widget at the
  327. current point."
  328. (interactive)
  329. (let* ((item (or widget-item
  330. (bitwarden-list-all-get-item-at-pos)))
  331. (type (gethash "type" item))
  332. (login (gethash "login" item)))
  333. (if (not (eq type 1))
  334. (bitwarden--message "error: not a login item" nil t)
  335. (kill-new (gethash "password" login))
  336. (message "Password added to kill ring"))))
  337. (defun bitwarden-list-all-item-action (widget &rest _ignore)
  338. "Do action to element associated with WIDGET's value.
  339. IGNORE other arguments."
  340. (bitwarden-list-all-kill-ring-save (widget-value widget))
  341. (kill-buffer (current-buffer)))
  342. ;=================================== widgets ===================================
  343. (defmacro bitwarden-list-dialog (name &rest forms)
  344. "Show a dialog buffer with NAME, setup with FORMS."
  345. (declare (indent 1) (debug t))
  346. `(with-current-buffer (get-buffer-create ,name)
  347. ;; Cleanup buffer
  348. (let ((inhibit-read-only t)
  349. (ol (overlay-lists)))
  350. (mapc 'delete-overlay (car ol))
  351. (mapc 'delete-overlay (cdr ol))
  352. (erase-buffer))
  353. (bitwarden-list-dialog-mode)
  354. ,@forms
  355. (widget-setup)
  356. (switch-to-buffer (current-buffer))))
  357. (defsubst bitwarden-list-all-make-element (item)
  358. "Create a new cons list from ITEM."
  359. (let* ((folder-id (gethash "folderId" item))
  360. (login-item (gethash "login" item)))
  361. (cons folder-id
  362. (list (cons (concat
  363. (bitwarden-pad-to-width (gethash "name" item) 40)
  364. (bitwarden-pad-to-width
  365. (if login-item (gethash "username" login-item) "")
  366. 32)
  367. (format-time-string
  368. "%Y-%m-%d %T"
  369. (date-to-time (bitwarden-pad-to-width
  370. (gethash "revisionDate" item) 24))))
  371. item)))))
  372. (defun bitwarden-list-all-tree (key val)
  373. "Return a `tree-widget' of folders.
  374. Creates a widget with text KEY and items VAL."
  375. ;; Represent a sub-menu with a tree widget
  376. `(tree-widget
  377. :open t
  378. :match ignore
  379. :node (item :tag ,key
  380. :sample-face bold
  381. :format "%{%t%}\n")
  382. ,@(mapcar 'bitwarden-list-all-item val)))
  383. (defun bitwarden-list-all-item (pass-element)
  384. "Return a widget to display PASS-ELEMENT in a dialog buffer."
  385. ;; Represent a single file with a link widget
  386. `(link :tag ,(car pass-element)
  387. :button-prefix ""
  388. :button-suffix ""
  389. :button-face default
  390. :format "%[%t\n%]"
  391. :help-echo ,(concat "Viewing item " (gethash "id" (cdr pass-element)))
  392. :action bitwarden-list-all-item-action
  393. ,(cdr pass-element)))
  394. (defun bitwarden-list-all-items (items)
  395. "Return a list of widgets to display ITEMS in a dialog buffer."
  396. (let* ((folders (mapcar (lambda (e)
  397. (cons
  398. (gethash "id" e)
  399. (gethash "name" e)))
  400. (bitwarden-folders)))
  401. (hash (make-hash-table :test 'equal)))
  402. ;; create hash table where the keys are the folders and each value is a list
  403. ;; of the password items
  404. (dolist (x (mapcar 'bitwarden-list-all-make-element items))
  405. (let* ((folder-id (car x))
  406. (key (cdr (assoc folder-id folders)))
  407. (val (cdr x))
  408. (klist (gethash key hash)))
  409. (puthash key (append klist val) hash)))
  410. (mapcar (lambda (key)
  411. (bitwarden-list-all-tree key (gethash key hash)))
  412. (sort (hash-table-keys hash) #'string<))))
  413. ;;;###autoload
  414. (defun bitwarden-list-all ()
  415. "Show a dialog, listing all entries associated with `bitwarden-user'.
  416. If optional argument GROUP is given, only entries in GROUP will be listed."
  417. (interactive)
  418. (bitwarden-list-dialog "*bitwarden-list*"
  419. ;; Use a L&F that looks like the recentf menu.
  420. (tree-widget-set-theme "folder")
  421. (apply 'widget-create
  422. `(group
  423. :indent 0
  424. :format "%v\n"
  425. ,@(bitwarden-list-all-items
  426. (bitwarden-search))))
  427. (widget-create
  428. 'push-button
  429. :notify 'bitwarden-list-cancel-dialog
  430. "Cancel")
  431. (goto-char (point-min))))
  432. (provide 'bitwarden)
  433. ;;; bitwarden.el ends here