org-crypt.el (12947B)
1 ;;; org-crypt.el --- Public Key Encryption for Org Entries -*- lexical-binding: t; -*- 2 ;; 3 ;; Copyright (C) 2007-2024 Free Software Foundation, Inc. 4 5 ;; Author: John Wiegley <johnw@gnu.org> 6 7 ;; This file is part of GNU Emacs. 8 ;; 9 ;; GNU Emacs is free software: you can redistribute it and/or modify 10 ;; it under the terms of the GNU General Public License as published by 11 ;; the Free Software Foundation, either version 3 of the License, or 12 ;; (at your option) any later version. 13 14 ;; GNU Emacs 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 19 ;; You should have received a copy of the GNU General Public License 20 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. 21 22 ;;; Commentary: 23 24 ;; Right now this is just a set of functions to play with. It depends 25 ;; on the epg library. Here's how you would use it: 26 ;; 27 ;; 1. To mark an entry for encryption, tag the heading with "crypt". 28 ;; You can change the tag to any complex tag matching string by 29 ;; setting the `org-crypt-tag-matcher' variable. 30 ;; 31 ;; 2. Set the encryption key to use in the `org-crypt-key' variable, 32 ;; or use `M-x org-set-property' to set the property CRYPTKEY to 33 ;; any address in your public keyring. The text of the entry (but 34 ;; not its properties or headline) will be encrypted for this user. 35 ;; For them to read it, the corresponding secret key must be 36 ;; located in the secret key ring of the account where you try to 37 ;; decrypt it. This makes it possible to leave secure notes that 38 ;; only the intended recipient can read in a shared-org-mode-files 39 ;; scenario. 40 ;; If the key is not set, org-crypt will default to symmetric encryption. 41 ;; 42 ;; 3. To later decrypt an entry, use `org-decrypt-entries' or 43 ;; `org-decrypt-entry'. It might be useful to bind this to a key, 44 ;; like C-c C-/. 45 ;; 46 ;; 4. To automatically encrypt all necessary entries when saving a 47 ;; file, call `org-crypt-use-before-save-magic' after loading 48 ;; org-crypt.el. 49 50 ;;; Thanks: 51 52 ;; - Carsten Dominik 53 ;; - Vitaly Ostanin 54 55 ;;; Code: 56 57 (require 'org-macs) 58 (org-assert-version) 59 60 (require 'org-macs) 61 (require 'org-compat) 62 63 (declare-function epg-decrypt-string "epg" (context cipher)) 64 (declare-function epg-list-keys "epg" (context &optional name mode)) 65 (declare-function epg-make-context "epg" 66 (&optional protocol armor textmode include-certs 67 cipher-algorithm digest-algorithm 68 compress-algorithm)) 69 (declare-function epg-encrypt-string "epg" 70 (context plain recipients &optional sign always-trust)) 71 (defvar epg-context) 72 73 (declare-function org-back-over-empty-lines "org" ()) 74 (declare-function org-current-level "org" ()) 75 (declare-function org-back-to-heading "org" (&optional invisible-ok)) 76 (declare-function org-before-first-heading-p "org" ()) 77 (declare-function org-end-of-meta-data "org" (&optional full)) 78 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading element)) 79 (declare-function org-entry-get "org" (pom property &optional inherit literal-nil)) 80 (declare-function org-fold-subtree "org-fold" (flag)) 81 (declare-function org-make-tags-matcher "org" (match &optional only-local-tags)) 82 (declare-function org-previous-visible-heading "org" (arg)) 83 (declare-function org-scan-tags "org" (action matcher todo-only &optional start-level)) 84 (declare-function org-set-property "org" (property value)) 85 (declare-function org-cycle-set-startup-visibility "org-cycle" ()) 86 87 (defgroup org-crypt nil 88 "Org Crypt." 89 :tag "Org Crypt" 90 :group 'org) 91 92 (defcustom org-crypt-tag-matcher "crypt" 93 "The tag matcher used to find headings whose contents should be encrypted. 94 95 See the \"Match syntax\" section of the org manual for more details." 96 :type 'string 97 :group 'org-crypt) 98 99 (defcustom org-crypt-key "" 100 "The default key to use when encrypting the contents of a heading. 101 102 If this variable is nil, always use symmetric encryption, unconditionally. 103 104 Otherwise, The string is matched against all keys in the key ring. 105 In particular, the empty string matches no key. If no key is found, 106 look for the `epa-file-encrypt-to' local variable. Ultimately fall back 107 to symmetric encryption. 108 109 This setting can be overridden in the CRYPTKEY property." 110 :group 'org-crypt 111 :type '(choice 112 (string :tag "Public key(s) matching") 113 (const :tag "Symmetric encryption" nil))) 114 115 (defcustom org-crypt-disable-auto-save 'ask 116 "What org-decrypt should do if `auto-save-mode' is enabled. 117 118 t : Disable `auto-save-mode' for the current buffer 119 prior to decrypting an entry. 120 121 nil : Leave `auto-save-mode' enabled. 122 This may cause data to be written to disk unencrypted! 123 124 `ask' : Ask user whether or not to disable `auto-save-mode' 125 for the current buffer. 126 127 `encrypt': Leave `auto-save-mode' enabled for the current buffer, 128 but automatically re-encrypt all decrypted entries 129 *before* auto-saving. 130 NOTE: This only works for entries which have a tag 131 that matches `org-crypt-tag-matcher'." 132 :group 'org-crypt 133 :version "24.1" 134 :type '(choice (const :tag "Always" t) 135 (const :tag "Never" nil) 136 (const :tag "Ask" ask) 137 (const :tag "Encrypt" encrypt))) 138 139 (defun org-crypt--encrypted-text (beg end) 140 "Return encrypted text in between BEG and END." 141 ;; Ignore indentation. 142 (replace-regexp-in-string 143 "^[ \t]*" "" 144 (buffer-substring-no-properties beg end))) 145 146 (defun org-at-encrypted-entry-p () 147 "Is the current entry encrypted? 148 When the entry is encrypted, return a pair (BEG . END) where BEG 149 and END are buffer positions delimiting the encrypted area." 150 (org-with-wide-buffer 151 (unless (org-before-first-heading-p) 152 (org-back-to-heading t) 153 (org-end-of-meta-data 'standard) 154 (let ((case-fold-search nil) 155 (banner-start (rx (seq bol 156 (zero-or-more (any "\t ")) 157 "-----BEGIN PGP MESSAGE-----" 158 eol)))) 159 (when (looking-at banner-start) 160 (let ((start (point)) 161 (banner-end (rx (seq bol 162 (or (group (zero-or-more (any "\t ")) 163 "-----END PGP MESSAGE-----" 164 eol) 165 (seq (one-or-more "*") " ")))))) 166 (when (and (re-search-forward banner-end nil t) (match-string 1)) 167 (cons start (line-beginning-position 2))))))))) 168 169 (defun org-crypt-check-auto-save () 170 "Check whether `auto-save-mode' is enabled for the current buffer. 171 172 `auto-save-mode' may cause leakage when decrypting entries, so 173 check whether it's enabled, and decide what to do about it. 174 175 See `org-crypt-disable-auto-save'." 176 (when buffer-auto-save-file-name 177 (cond 178 ((or 179 (eq org-crypt-disable-auto-save t) 180 (and 181 (eq org-crypt-disable-auto-save 'ask) 182 (y-or-n-p "`org-decrypt': auto-save-mode may cause leakage. Disable it for current buffer? "))) 183 (message "org-decrypt: Disabling auto-save-mode for %s" 184 (or (buffer-file-name) (current-buffer))) 185 ;; The argument to auto-save-mode has to be "-1", since 186 ;; giving a "nil" argument toggles instead of disabling. 187 (auto-save-mode -1)) 188 ((eq org-crypt-disable-auto-save nil) 189 (message "org-decrypt: Decrypting entry with auto-save-mode enabled. This may cause leakage.")) 190 ((eq org-crypt-disable-auto-save 'encrypt) 191 (message "org-decrypt: Enabling re-encryption on auto-save.") 192 (add-hook 'auto-save-hook 193 (lambda () 194 (message "org-crypt: Re-encrypting all decrypted entries due to auto-save.") 195 (org-encrypt-entries)) 196 nil t)) 197 (t nil)))) 198 199 (defun org-crypt-key-for-heading () 200 "Return the encryption key(s) for the current heading. 201 Assume `epg-context' is set." 202 (and org-crypt-key 203 (or (epg-list-keys epg-context 204 (pcase (org-entry-get nil "CRYPTKEY" 'selective 'literal-nil) 205 ("nil" "") 206 (key (or key org-crypt-key "")))) 207 (bound-and-true-p epa-file-encrypt-to) 208 (progn 209 (message "No crypt key set, using symmetric encryption.") 210 nil)))) 211 212 ;;;###autoload 213 (defun org-encrypt-entry () 214 "Encrypt the content of the current headline." 215 (interactive) 216 (unless (org-at-encrypted-entry-p) 217 (require 'epg) 218 (setq-local epg-context (epg-make-context nil t t)) 219 (org-with-wide-buffer 220 (org-back-to-heading t) 221 (let ((start-heading (point)) 222 (crypt-key (org-crypt-key-for-heading)) 223 (folded? (org-invisible-p (line-beginning-position)))) 224 (org-end-of-meta-data 'standard) 225 (let ((beg (point)) 226 (folded-heading 227 (and folded? 228 (save-excursion 229 (org-previous-visible-heading 1) 230 (point))))) 231 (goto-char start-heading) 232 (org-end-of-subtree t t) 233 (org-back-over-empty-lines) 234 (let* ((contents (delete-and-extract-region beg (point))) 235 (key (get-text-property 0 'org-crypt-key contents)) 236 (checksum (get-text-property 0 'org-crypt-checksum contents))) 237 (condition-case err 238 (insert 239 ;; Text and key have to be identical, otherwise we 240 ;; re-crypt. 241 (if (and (equal crypt-key key) 242 (string= checksum (sha1 contents))) 243 (get-text-property 0 'org-crypt-text contents) 244 (epg-encrypt-string epg-context contents crypt-key))) 245 ;; If encryption failed, make sure to insert back entry 246 ;; contents in the buffer. 247 (error 248 (insert contents) 249 (error "%s" (error-message-string err))))) 250 (when folded-heading 251 (goto-char folded-heading) 252 (org-fold-subtree t)) 253 nil))))) 254 255 (defvar org-outline-regexp-bol) 256 ;;;###autoload 257 (defun org-decrypt-entry () 258 "Decrypt the content of the current headline." 259 (interactive) 260 (pcase (org-at-encrypted-entry-p) 261 (`(,beg . ,end) 262 (require 'epg) 263 (setq-local epg-context (epg-make-context nil t t)) 264 (org-with-point-at beg 265 (org-crypt-check-auto-save) 266 (let* ((folded-heading 267 (and (org-invisible-p) 268 (save-excursion 269 (org-previous-visible-heading 1) 270 (point)))) 271 (level (org-current-level)) 272 (encrypted-text (org-crypt--encrypted-text beg end)) 273 (decrypted-text 274 (decode-coding-string 275 (epg-decrypt-string epg-context encrypted-text) 276 'utf-8)) 277 origin-marker) 278 ;; Delete region starting just before point, because the 279 ;; outline property starts at the \n of the heading. 280 (delete-region (1- (point)) end) 281 (setq origin-marker (point-marker)) 282 (if (string-match (org-headline-re level) decrypted-text) 283 ;; If decrypted text contains other headings with levels 284 ;; below LEVEL, adjust the subtree. 285 (let ((start 0) (min-level level)) 286 (while (string-match (org-headline-re level) decrypted-text start) 287 (setq min-level (min min-level (1- (length (match-string 0 decrypted-text)))) 288 start (match-end 0))) 289 (insert "\n" 290 (replace-regexp-in-string 291 org-outline-regexp-bol 292 (concat (make-string (1+ (- level min-level)) ?*) "\\&") 293 decrypted-text))) 294 ;; Store a checksum of the decrypted and the encrypted text 295 ;; value. This allows reusing the same encrypted text if the 296 ;; text does not change, and therefore avoid a re-encryption 297 ;; process. 298 (insert "\n" 299 (propertize decrypted-text 300 'org-crypt-checksum (sha1 decrypted-text) 301 'org-crypt-key (org-crypt-key-for-heading) 302 'org-crypt-text encrypted-text))) 303 ;; Apply initial visibility. 304 (save-restriction 305 (narrow-to-region origin-marker (point)) 306 (set-marker origin-marker nil) 307 (org-cycle-set-startup-visibility)) 308 ;; ... but keep the previous folded state. 309 (when folded-heading 310 (goto-char folded-heading) 311 (org-fold-subtree t)) 312 nil))) 313 (_ nil))) 314 315 (defvar org--matcher-tags-todo-only) 316 317 ;;;###autoload 318 (defun org-encrypt-entries () 319 "Encrypt all top-level entries in the current buffer." 320 (interactive) 321 (let ((org--matcher-tags-todo-only nil)) 322 (org-scan-tags 323 'org-encrypt-entry 324 (cdr (org-make-tags-matcher org-crypt-tag-matcher)) 325 org--matcher-tags-todo-only))) 326 327 ;;;###autoload 328 (defun org-decrypt-entries () 329 "Decrypt all entries in the current buffer." 330 (interactive) 331 (let ((org--matcher-tags-todo-only nil)) 332 (org-scan-tags 333 'org-decrypt-entry 334 (cdr (org-make-tags-matcher org-crypt-tag-matcher)) 335 org--matcher-tags-todo-only))) 336 337 ;;;###autoload 338 (defun org-crypt-use-before-save-magic () 339 "Add a hook to automatically encrypt entries before a file is saved to disk." 340 (add-hook 341 'org-mode-hook 342 (lambda () (add-hook 'before-save-hook 'org-encrypt-entries nil t)))) 343 344 (add-hook 'org-fold-reveal-start-hook 'org-decrypt-entry) 345 346 (provide 'org-crypt) 347 348 ;;; org-crypt.el ends here