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