Sources/OrgCore/Crypto/OrgCrypt.swift
203 lines · 11345 bytes
1import CryptoKit
2import Foundation
3
4/// org-crypt (org-crypt.el, Org 9.8.7) with symmetric encryption, as with `org-crypt-key`
5/// nil: an entry's text after its planning, properties and logbook, through the end of its
6/// subtree, replaced by an armored OpenPGP message under the heading.
7public enum OrgCrypt {
8 public struct Failure: Error, Equatable, CustomStringConvertible {
9 public let description: String
10 public init(_ description: String) { self.description = description }
11 }
12
13 /// `org-end-of-meta-data 'standard`: past planning, the property drawer, clock lines,
14 /// blank lines and logbook drawers.
15 static func metaDataEnd(_ buffer: EmacsBuffer) {
16 buffer.endOfMetaData()
17 guard !buffer.atHeading else { return }
18 let end = buffer.saveExcursion { () -> Int in buffer.outlineNextHeading(); return buffer.point }
19 while !buffer.eobp {
20 if buffer.lookingAt("[ \\t]*$|^[ \\t]*CLOCK:") != nil {
21 buffer.forwardLine(1)
22 } else if buffer.lookingAt("[ \\t]*:LOGBOOK:[ \\t]*$") != nil {
23 guard buffer.searchForward("^[ \\t]*:END:[ \\t]*$", bound: end, caseInsensitive: true) != nil else { return }
24 buffer.forwardLine(1)
25 } else {
26 return
27 }
28 }
29 }
30
31 /// The heading the entry at `offset` is under, or nil before the first.
32 public static func heading(_ text: String, at offset: Int) -> Int? {
33 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
34 return try? buffer.backToHeading()
35 }
36
37 /// `org-at-encrypted-entry-p`: the message's lines, from its begin line through the line
38 /// after its end line.
39 public static func encryptedRange(_ text: String, at offset: Int) -> Range<Int>? {
40 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
41 guard (try? buffer.backToHeading()) != nil else { return nil }
42 metaDataEnd(buffer)
43 guard buffer.lookingAt("[ \\t]*-----BEGIN PGP MESSAGE-----[ \\t]*$") != nil else { return nil }
44 let start = buffer.point
45 guard let match = buffer.searchForward("^(?:([ \\t]*-----END PGP MESSAGE-----)[ \\t]*$|\\*+ )", caseInsensitive: false),
46 match[1] != nil else { return nil }
47 let line = buffer.lineEnd(match[0]!.lowerBound)
48 return start..<min(line + 1, buffer.length)
49 }
50
51 /// What `org-encrypt-entry` encrypts: after the meta-data through the subtree's end, less
52 /// the blank lines before the next heading.
53 public static func bodyRange(_ text: String, at offset: Int) -> Range<Int>? {
54 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
55 guard let heading = try? buffer.backToHeading() else { return nil }
56 metaDataEnd(buffer)
57 let start = buffer.point
58 buffer.point = heading
59 buffer.endOfSubtree(toHeading: true)
60 buffer.backOverEmptyLines()
61 return start..<max(start, buffer.point)
62 }
63
64 /// `org-encrypt-entry`: the text with the entry at `offset` encrypted, or nil when it's
65 /// encrypted already.
66 public static func encrypt(_ text: String, at offset: Int, passphrase: String, now: Date = Date()) throws -> String? {
67 guard heading(text, at: offset) != nil else { throw Failure("Before first headline") }
68 guard encryptedRange(text, at: offset) == nil, let range = bodyRange(text, at: offset) else { return nil }
69 let ns = text as NSString
70 let contents = ns.substring(with: NSRange(range))
71 let message = try OpenPGP.encrypt(Data(contents.utf8), passphrase: passphrase, now: now)
72 return ns.replacingCharacters(in: NSRange(range), with: message)
73 }
74
75 /// The decrypted text of the entry at `offset` and where its message is.
76 public static func decrypt(_ text: String, at offset: Int, passphrase: String) throws -> (plaintext: String, range: Range<Int>) {
77 guard let range = encryptedRange(text, at: offset) else { throw Failure("Not an encrypted entry") }
78 let message = (text as NSString).substring(with: NSRange(range))
79 let data: Data
80 do {
81 data = try OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: passphrase)
82 } catch let failure as OpenPGP.Failure {
83 throw Failure(failure == OpenPGP.wrongPassphrase ? "Wrong passphrase" : failure.description)
84 }
85 var plain = String(decoding: data, as: UTF8.self)
86 // epg encrypts in text mode, with CRLF line ends, and `decode-coding-string` with
87 // `utf-8` takes them back to LF.
88 if plain.contains("\r\n"), !plain.replacingOccurrences(of: "\r\n", with: "").contains("\n") {
89 plain = plain.replacingOccurrences(of: "\r\n", with: "\n")
90 }
91 return (plain, range)
92 }
93
94 /// `org-decrypt-entry`: the text with the entry's message replaced by what it holds, its
95 /// headings moved below the entry's level when they aren't.
96 public static func decryptInPlace(_ text: String, at offset: Int, passphrase: String) throws -> String {
97 var (plain, range) = try decrypt(text, at: offset, passphrase: passphrase)
98 let ns = text as NSString
99 let headingStart = heading(text, at: offset)!
100 let level = ns.substring(from: headingStart).prefix { $0 == "*" }.count
101 let pattern = "(?m)^\\*{1,\(level)} "
102 if plain.range(of: pattern, options: .regularExpression) != nil {
103 let minLevel = plain.matches(of: try! Regex(pattern)).map { plain[$0.range].count - 1 }.min() ?? level
104 let prefix = String(repeating: "*", count: 1 + level - minLevel)
105 plain = plain.replacing(#/(?m)^\*+ /#) { prefix + $0.output }
106 }
107 return ns.replacingCharacters(in: NSRange((range.lowerBound - 1)..<range.upperBound), with: "\n" + plain)
108 }
109
110 /// The entry's message replaced by `plaintext` encrypted again.
111 public static func replacing(_ text: String, at offset: Int, with plaintext: String, passphrase: String, now: Date = Date()) throws -> String {
112 guard let range = encryptedRange(text, at: offset) else { throw Failure("Not an encrypted entry") }
113 let message = try OpenPGP.encrypt(Data(plaintext.utf8), passphrase: passphrase, now: now)
114 return (text as NSString).replacingCharacters(in: NSRange(range), with: message)
115 }
116
117 /// The headings with `tag` (`org-crypt-tag-matcher`), inherited or their own, in order.
118 public static func taggedHeadings(_ text: String, tag: String = "crypt", settings: OrgSettings = .default) -> [Int] {
119 let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings))
120 return model.headings.indices.filter { model.tags(of: $0).contains { $0.value == tag } }.map { model.headings[$0].headingRange.lowerBound }
121 }
122
123 /// `org-encrypt-entries`: every tagged entry not encrypted yet, from the top, so that an
124 /// entry's tagged children go inside its message. The text and how many were encrypted.
125 public static func encryptAll(_ text: String, passphrase: String, tag: String = "crypt", settings: OrgSettings = .default, now: Date = Date()) throws -> (String, Int) {
126 var text = text
127 var count = 0
128 var from = 0
129 while let next = taggedHeadings(text, tag: tag, settings: settings).first(where: { $0 >= from }) {
130 if let encrypted = try encrypt(text, at: next, passphrase: passphrase, now: now) {
131 text = encrypted
132 count += 1
133 }
134 from = next + 1
135 }
136 return (text, count)
137 }
138
139 /// The tagged entries `seal` encrypts whose text isn't blank: those a save can't write
140 /// without the passphrase. Their headings' offsets.
141 public static func unencrypted(_ text: String, tag: String = "crypt", settings: OrgSettings = .default) -> [Int] {
142 guard text.contains(tag) else { return [] }
143 let ns = text as NSString
144 var found: [Int] = []
145 var covered = 0
146 for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered {
147 guard encryptedRange(text, at: heading) == nil, let range = bodyRange(text, at: heading) else { continue }
148 // Tagged children go inside this entry's message.
149 covered = range.upperBound
150 if !ns.substring(with: NSRange(range)).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { found.append(heading) }
151 }
152 return found
153 }
154
155 /// `org-encrypt-entries` as `org-crypt-use-before-save-magic` runs it before a save. An
156 /// entry whose text `reuse` knows by its `checksum` gets that message again, as org-crypt
157 /// keeps an entry decrypted and left unchanged byte for byte. The text, and each message
158 /// with the text it holds.
159 public static func seal(
160 _ text: String, passphrase: String, tag: String = "crypt", settings: OrgSettings = .default,
161 reuse: (String) -> String? = { _ in nil }, now: Date = Date()
162 ) throws -> (text: String, messages: [(message: String, plaintext: String)]) {
163 guard text.contains(tag) else { return (text, []) }
164 var result = text as NSString
165 var messages: [(String, String)] = []
166 var shift = 0
167 var covered = 0
168 for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered {
169 let current = result as String
170 guard encryptedRange(current, at: heading + shift) == nil, let range = bodyRange(current, at: heading + shift) else { continue }
171 covered = range.upperBound - shift
172 let contents = result.substring(with: NSRange(range))
173 let message = try reuse(checksum(contents)) ?? OpenPGP.encrypt(Data(contents.utf8), passphrase: passphrase, now: now)
174 result = result.replacingCharacters(in: NSRange(range), with: message) as NSString
175 shift += (message as NSString).length - range.count
176 messages.append((message, contents))
177 }
178 return (result as String, messages)
179 }
180
181 /// What an entry's text is known by, as `org-crypt-checksum` is.
182 public static func checksum(_ contents: String) -> String {
183 SHA256.hash(data: Data(contents.utf8)).map { String(format: "%02x", $0) }.joined()
184 }
185
186 /// The first encrypted entry's message in `text`.
187 public static func firstMessage(_ text: String) -> String? {
188 let ns = text as NSString
189 var search = NSRange(location: 0, length: ns.length)
190 while true {
191 let begin = ns.range(of: "-----BEGIN PGP MESSAGE-----", options: [], range: search)
192 guard begin.location != NSNotFound else { return nil }
193 let lineStart = ns.lineRange(for: NSRange(location: begin.location, length: 0)).location
194 if let range = encryptedRange(text, at: lineStart), range.lowerBound == lineStart { return ns.substring(with: NSRange(range)) }
195 search = NSRange(location: NSMaxRange(begin), length: ns.length - NSMaxRange(begin))
196 }
197 }
198
199 /// Whether `passphrase` opens `message`.
200 public static func opens(_ message: String, passphrase: String) -> Bool {
201 (try? OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: passphrase)) != nil
202 }
203}