Sources/OrgCore/Crypto/OpenPGP.swift
425 lines · 19314 bytes
1import CommonCrypto
2import CryptoKit
3import Foundation
4
5/// Passphrase-encrypted OpenPGP messages (RFC 4880), as `gpg --symmetric --armor` writes and
6/// reads them: a symmetric-key session packet with a string-to-key specifier, an integrity
7/// protected data packet (MDC), and inside it literal data, compressed or not. AES ciphers
8/// only; no public keys, no AEAD packets.
9public enum OpenPGP {
10 public struct Failure: Error, Equatable, CustomStringConvertible {
11 public let description: String
12 init(_ description: String) { self.description = description }
13 }
14
15 // MARK: - Armor
16
17 /// `-----BEGIN PGP MESSAGE-----`, base64 in lines of 64, the CRC-24 checksum, the end
18 /// line, and a final newline.
19 public static func armor(_ data: Data) -> String {
20 let base64 = data.base64EncodedString()
21 var lines: [String] = []
22 var index = base64.startIndex
23 while index < base64.endIndex {
24 let end = base64.index(index, offsetBy: 64, limitedBy: base64.endIndex) ?? base64.endIndex
25 lines.append(String(base64[index..<end]))
26 index = end
27 }
28 var crc = crc24(data).bigEndian
29 let checksum = withUnsafeBytes(of: &crc) { Data($0.dropFirst()) }.base64EncodedString()
30 return "-----BEGIN PGP MESSAGE-----\n\n" + lines.joined(separator: "\n") + "\n=" + checksum + "\n-----END PGP MESSAGE-----\n"
31 }
32
33 /// The bytes of an armored message, its checksum checked when it has one.
34 public static func dearmor(_ text: String) throws -> Data {
35 var lines = text.components(separatedBy: .newlines).map { $0.trimmingCharacters(in: .whitespaces) }
36 guard let begin = lines.firstIndex(where: { $0.hasPrefix("-----BEGIN PGP MESSAGE") }) else { throw Failure("Not a PGP message") }
37 lines = Array(lines[(begin + 1)...])
38 // Header lines such as `Version:`, up to a blank line.
39 if let blank = lines.firstIndex(of: ""), lines[..<blank].allSatisfy({ $0.contains(":") }) { lines = Array(lines[(blank + 1)...]) }
40 var body = ""
41 var checksum: String?
42 for line in lines {
43 if line.hasPrefix("-----END") { break }
44 if line.hasPrefix("=") { checksum = String(line.dropFirst()); continue }
45 body += line
46 }
47 guard let data = Data(base64Encoded: body) else { throw Failure("The PGP message is damaged") }
48 if let checksum, let sum = Data(base64Encoded: checksum), sum.count == 3 {
49 let crc = crc24(data)
50 guard [UInt8((crc >> 16) & 0xff), UInt8((crc >> 8) & 0xff), UInt8(crc & 0xff)] == Array(sum) else { throw Failure("The PGP message's checksum is wrong") }
51 }
52 return data
53 }
54
55 static func crc24(_ data: Data) -> UInt32 {
56 var crc: UInt32 = 0xB704CE
57 for byte in data {
58 crc ^= UInt32(byte) << 16
59 for _ in 0..<8 {
60 crc <<= 1
61 if crc & 0x1000000 != 0 { crc ^= 0x1864CFB }
62 }
63 }
64 return crc & 0xFFFFFF
65 }
66
67 // MARK: - Packets
68
69 struct Packet {
70 let tag: Int
71 let body: Data
72 }
73
74 /// The packets in `data`, partial lengths joined.
75 static func packets(_ data: Data) throws -> [Packet] {
76 let bytes = [UInt8](data)
77 var i = 0
78 var out: [Packet] = []
79 func need(_ n: Int) throws { guard i + n <= bytes.count else { throw Failure("The PGP message is cut short") } }
80 while i < bytes.count {
81 let ctb = bytes[i]
82 guard ctb & 0x80 != 0 else { throw Failure("The PGP message is damaged") }
83 i += 1
84 var body = Data()
85 let tag: Int
86 if ctb & 0x40 != 0 {
87 tag = Int(ctb & 0x3f)
88 while true {
89 try need(1)
90 let first = Int(bytes[i])
91 i += 1
92 var length: Int
93 var partial = false
94 switch first {
95 case 0..<192: length = first
96 case 192..<224:
97 try need(1)
98 length = ((first - 192) << 8) + Int(bytes[i]) + 192
99 i += 1
100 case 255:
101 try need(4)
102 length = bytes[i..<(i + 4)].reduce(0) { $0 << 8 | Int($1) }
103 i += 4
104 default:
105 length = 1 << (first & 0x1f)
106 partial = true
107 }
108 try need(length)
109 body.append(contentsOf: bytes[i..<(i + length)])
110 i += length
111 if !partial { break }
112 }
113 } else {
114 tag = Int((ctb >> 2) & 0x0f)
115 let length: Int
116 switch ctb & 3 {
117 case 0:
118 try need(1)
119 length = Int(bytes[i]); i += 1
120 case 1:
121 try need(2)
122 length = Int(bytes[i]) << 8 | Int(bytes[i + 1]); i += 2
123 case 2:
124 try need(4)
125 length = bytes[i..<(i + 4)].reduce(0) { $0 << 8 | Int($1) }; i += 4
126 default:
127 length = bytes.count - i
128 }
129 try need(length)
130 body.append(contentsOf: bytes[i..<(i + length)])
131 i += length
132 }
133 out.append(Packet(tag: tag, body: body))
134 }
135 return out
136 }
137
138 /// A new-format packet with a definite length.
139 static func packet(_ tag: Int, _ body: Data) -> Data {
140 var out = Data([0xC0 | UInt8(tag)])
141 switch body.count {
142 case 0..<192: out.append(UInt8(body.count))
143 case 192..<8384:
144 let n = body.count - 192
145 out.append(contentsOf: [UInt8(n >> 8 + 192), UInt8(n & 0xff)])
146 default:
147 out.append(255)
148 out.append(contentsOf: (0..<4).reversed().map { UInt8((body.count >> ($0 * 8)) & 0xff) })
149 }
150 return out + body
151 }
152
153 // MARK: - Keys from passphrases
154
155 /// AES's key sizes by OpenPGP's cipher numbers.
156 static let keySizes = [7: 16, 8: 24, 9: 32]
157
158 static func hash(_ algorithm: Int, _ data: Data) throws -> Data {
159 switch algorithm {
160 case 1: return Data(Insecure.MD5.hash(data: data))
161 case 2: return Data(Insecure.SHA1.hash(data: data))
162 case 8: return Data(SHA256.hash(data: data))
163 case 9: return Data(SHA384.hash(data: data))
164 case 10: return Data(SHA512.hash(data: data))
165 case 11:
166 var digest = [UInt8](repeating: 0, count: Int(CC_SHA224_DIGEST_LENGTH))
167 data.withUnsafeBytes { _ = CC_SHA224($0.baseAddress, CC_LONG(data.count), &digest) }
168 return Data(digest)
169 default: throw Failure("Hash algorithm \(algorithm) isn't supported")
170 }
171 }
172
173 /// The string-to-key specifier: its type, hash, salt and count, and how long it is.
174 struct S2K {
175 let type: Int
176 let hash: Int
177 let salt: Data
178 let count: Int
179
180 static func parse(_ bytes: [UInt8], at i: Int) throws -> (S2K, Int) {
181 guard i + 2 <= bytes.count else { throw Failure("The PGP message is damaged") }
182 let type = Int(bytes[i]), hash = Int(bytes[i + 1])
183 switch type {
184 case 0: return (S2K(type: 0, hash: hash, salt: Data(), count: 0), 2)
185 case 1:
186 guard i + 10 <= bytes.count else { throw Failure("The PGP message is damaged") }
187 return (S2K(type: 1, hash: hash, salt: Data(bytes[(i + 2)..<(i + 10)]), count: 0), 10)
188 case 3:
189 guard i + 11 <= bytes.count else { throw Failure("The PGP message is damaged") }
190 let c = Int(bytes[i + 10])
191 return (S2K(type: 3, hash: hash, salt: Data(bytes[(i + 2)..<(i + 10)]), count: (16 + (c & 15)) << ((c >> 4) + 6)), 11)
192 default: throw Failure("String-to-key type \(type) isn't supported")
193 }
194 }
195
196 /// RFC 4880 3.7.1: as many hashes as the key needs, each preloaded with one more zero.
197 /// The iterated input is hashed as it's made, a block at a time.
198 func key(_ passphrase: String, size: Int) throws -> Data {
199 let material = salt + Data(passphrase.utf8)
200 var key = Data()
201 var round = 0
202 while key.count < size {
203 var hasher = try Hasher(hash)
204 hasher.update(Data(repeating: 0, count: round))
205 if type == 3 {
206 let total = max(count, material.count)
207 // Whole copies of the material, about 64 KB of them, then what's left.
208 var block = Data()
209 let copies = max(1, 65_536 / max(1, material.count))
210 for _ in 0..<copies { block.append(material) }
211 var left = total
212 while left >= block.count {
213 hasher.update(block)
214 left -= block.count
215 }
216 if left > 0 { hasher.update(block.prefix(left)) }
217 } else {
218 hasher.update(material)
219 }
220 key.append(hasher.finish())
221 round += 1
222 }
223 return key.prefix(size)
224 }
225 }
226
227 /// One of the hashes `hash` supports, fed in parts.
228 struct Hasher {
229 private var md5: Insecure.MD5?
230 private var sha1: Insecure.SHA1?
231 private var sha256: SHA256?
232 private var sha384: SHA384?
233 private var sha512: SHA512?
234 private var sha224: CC_SHA256_CTX?
235
236 init(_ algorithm: Int) throws {
237 switch algorithm {
238 case 1: md5 = Insecure.MD5()
239 case 2: sha1 = Insecure.SHA1()
240 case 8: sha256 = SHA256()
241 case 9: sha384 = SHA384()
242 case 10: sha512 = SHA512()
243 case 11:
244 var context = CC_SHA256_CTX()
245 CC_SHA224_Init(&context)
246 sha224 = context
247 default: throw Failure("Hash algorithm \(algorithm) isn't supported")
248 }
249 }
250
251 mutating func update(_ data: Data) {
252 if md5 != nil { md5!.update(data: data) }
253 if sha1 != nil { sha1!.update(data: data) }
254 if sha256 != nil { sha256!.update(data: data) }
255 if sha384 != nil { sha384!.update(data: data) }
256 if sha512 != nil { sha512!.update(data: data) }
257 if sha224 != nil { data.withUnsafeBytes { _ = CC_SHA224_Update(&sha224!, $0.baseAddress, CC_LONG(data.count)) } }
258 }
259
260 mutating func finish() -> Data {
261 if let md5 { return Data(md5.finalize()) }
262 if let sha1 { return Data(sha1.finalize()) }
263 if let sha256 { return Data(sha256.finalize()) }
264 if let sha384 { return Data(sha384.finalize()) }
265 if let sha512 { return Data(sha512.finalize()) }
266 var digest = [UInt8](repeating: 0, count: Int(CC_SHA224_DIGEST_LENGTH))
267 _ = CC_SHA224_Final(&digest, &sha224!)
268 return Data(digest)
269 }
270 }
271
272 // MARK: - AES in CFB
273
274 static func cfb(_ data: Data, key: Data, iv: Data = Data(repeating: 0, count: 16), encrypt: Bool) throws -> Data {
275 var cryptor: CCCryptorRef?
276 let status = key.withUnsafeBytes { k in
277 iv.withUnsafeBytes { v in
278 CCCryptorCreateWithMode(CCOperation(encrypt ? kCCEncrypt : kCCDecrypt), CCMode(kCCModeCFB), CCAlgorithm(kCCAlgorithmAES),
279 CCPadding(ccNoPadding), v.baseAddress, k.baseAddress, key.count, nil, 0, 0, CCModeOptions(0), &cryptor)
280 }
281 }
282 guard status == kCCSuccess, let cryptor else { throw Failure("The cipher couldn't start") }
283 defer { CCCryptorRelease(cryptor) }
284 var out = [UInt8](repeating: 0, count: data.count)
285 var moved = 0
286 let result = data.withUnsafeBytes { d in CCCryptorUpdate(cryptor, d.baseAddress, data.count, &out, out.count, &moved) }
287 guard result == kCCSuccess else { throw Failure("The cipher failed") }
288 return Data(out.prefix(moved))
289 }
290
291 static func random(_ count: Int) throws -> Data {
292 var bytes = [UInt8](repeating: 0, count: count)
293 guard SecRandomCopyBytes(kSecRandomDefault, count, &bytes) == errSecSuccess else { throw Failure("No random bytes for the salt") }
294 return Data(bytes)
295 }
296
297 /// The coded iteration count new messages use: 65,011,712 bytes hashed, GnuPG's most.
298 static let codedCount: UInt8 = 0xFF
299
300 /// Whether `message` (packets) is encrypted with a passphrase: its first packet is a
301 /// symmetric-key session packet, not one for a public key.
302 public static func isSymmetric(_ message: Data) -> Bool {
303 (try? packets(message))?.first?.tag == 3
304 }
305
306 // MARK: - Messages
307
308 public static let wrongPassphrase = Failure("Bad session key")
309
310 /// The literal data of a passphrase-encrypted message.
311 public static func decrypt(_ message: Data, passphrase: String) throws -> Data {
312 var sessionKey: (cipher: Int, key: Data)?
313 for packet in try packets(message) {
314 switch packet.tag {
315 case 3:
316 let b = [UInt8](packet.body)
317 guard b.count >= 2, b[0] == 4 else { throw Failure("Only version 4 passphrase packets are supported") }
318 let cipher = Int(b[1])
319 guard let size = keySizes[cipher] else { throw Failure("Cipher \(cipher) isn't supported; orgstar reads AES") }
320 let (s2k, length) = try S2K.parse(b, at: 2)
321 let key = try s2k.key(passphrase, size: size)
322 if b.count > 2 + length {
323 // An encrypted session key.
324 let esk = try cfb(Data(b[(2 + length)...]), key: key, encrypt: false)
325 guard let algorithm = esk.first, let eskSize = keySizes[Int(algorithm)], esk.count == eskSize + 1 else { throw wrongPassphrase }
326 sessionKey = (Int(algorithm), esk.dropFirst())
327 } else {
328 sessionKey = (cipher, key)
329 }
330 case 18:
331 guard let sessionKey else { throw Failure("The PGP message has no passphrase packet") }
332 guard packet.body.first == 1 else { throw Failure("Only version 1 integrity protected packets are supported") }
333 let plain = try cfb(packet.body.dropFirst(), key: sessionKey.key, encrypt: false)
334 let block = 16
335 guard plain.count >= block + 2 + 22 else { throw Failure("The PGP message is cut short") }
336 let p = [UInt8](plain)
337 guard p[block - 2] == p[block], p[block - 1] == p[block + 1] else { throw wrongPassphrase }
338 let mdc = plain.suffix(20)
339 guard p[p.count - 22] == 0xD3, p[p.count - 21] == 0x14,
340 Data(Insecure.SHA1.hash(data: plain.prefix(plain.count - 20))) == mdc else {
341 throw Failure("The PGP message was modified")
342 }
343 return try literal(Data(p[(block + 2)..<(p.count - 22)]))
344 case 9:
345 throw Failure("The message has no integrity protection, which orgstar doesn't read")
346 case 20:
347 throw Failure("AEAD encrypted messages aren't supported")
348 case 10:
349 continue
350 default:
351 throw Failure("PGP packet \(packet.tag) isn't supported")
352 }
353 }
354 throw Failure("The PGP message has no encrypted data")
355 }
356
357 /// The data of the literal packet in `data`, decompressing on the way.
358 static func literal(_ data: Data) throws -> Data {
359 for packet in try packets(data) {
360 switch packet.tag {
361 case 11:
362 let b = [UInt8](packet.body)
363 guard b.count >= 6 else { throw Failure("The PGP message is damaged") }
364 let nameLength = Int(b[1])
365 guard b.count >= 2 + nameLength + 4 else { throw Failure("The PGP message is damaged") }
366 return Data(b[(2 + nameLength + 4)...])
367 case 8:
368 guard let algorithm = packet.body.first else { throw Failure("The PGP message is damaged") }
369 let compressed = packet.body.dropFirst()
370 switch algorithm {
371 case 0: return try literal(Data(compressed))
372 case 1: return try literal(try inflate(Data(compressed)))
373 case 2: return try literal(try inflate(Data(compressed.dropFirst(2))))
374 default: throw Failure("BZip2 compressed messages aren't supported")
375 }
376 default:
377 continue
378 }
379 }
380 throw Failure("The PGP message has no literal data")
381 }
382
383 /// Raw deflate, as ZIP and ZLIB packets hold it.
384 static func inflate(_ data: Data) throws -> Data {
385 do {
386 return try (data as NSData).decompressed(using: .zlib) as Data
387 } catch {
388 throw Failure("The PGP message's compressed data is damaged")
389 }
390 }
391
392 /// `gpg --symmetric --armor`: AES-256, an iterated and salted SHA-256 key, integrity
393 /// protection, binary literal data without a name.
394 public static func encrypt(_ data: Data, passphrase: String, now: Date = Date()) throws -> String {
395 armor(try encryptedMessage(data, passphrase: passphrase, now: now))
396 }
397
398 /// Whether `data` is an armored message rather than packets.
399 public static func isArmored(_ data: Data) -> Bool {
400 let head = String(decoding: data.prefix(64), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
401 return head.hasPrefix("-----BEGIN PGP MESSAGE")
402 }
403
404 /// The literal data of a passphrase-encrypted file, armored or not, as `gpg --decrypt` reads it.
405 public static func decryptFile(_ data: Data, passphrase: String) throws -> Data {
406 try decrypt(isArmored(data) ? dearmor(String(decoding: data, as: UTF8.self)) : data, passphrase: passphrase)
407 }
408
409 /// `gpg --symmetric` without `--armor`: the packets of `encrypt`.
410 public static func encryptedMessage(_ data: Data, passphrase: String, now: Date = Date()) throws -> Data {
411 let salt = try random(8)
412 let c = Int(codedCount)
413 let s2k = S2K(type: 3, hash: 8, salt: salt, count: (16 + (c & 15)) << ((c >> 4) + 6))
414 let key = try s2k.key(passphrase, size: 32)
415 let skesk = packet(3, Data([4, 9, 3, 8]) + salt + Data([codedCount]))
416 let date = UInt32(max(0, now.timeIntervalSince1970))
417 let literal = packet(11, Data([0x62, 0]) + Data((0..<4).reversed().map { UInt8((date >> ($0 * 8)) & 0xff) }) + data)
418 var prefix = try random(16)
419 prefix.append(prefix.suffix(2))
420 var plain = prefix + literal + Data([0xD3, 0x14])
421 plain.append(Data(Insecure.SHA1.hash(data: plain)))
422 let seipd = packet(18, Data([1]) + (try cfb(plain, key: key, encrypt: true)))
423 return skesk + seipd
424 }
425}