bitwarden.el 19 KB

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