Sources/OrgCore/Crypto/OpenPGP.swift

345 lines · 15645 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        func key(_ passphrase: String, size: Int) throws -> Data {
198            let material = salt + Data(passphrase.utf8)
199            var key = Data()
200            var round = 0
201            while key.count < size {
202                var input = Data(repeating: 0, count: round)
203                if type == 3 {
204                    let total = max(count, material.count)
205                    var stream = Data(capacity: total)
206                    while stream.count < total { stream.append(material.prefix(total - stream.count)) }
207                    input.append(stream)
208                } else {
209                    input.append(material)
210                }
211                key.append(try OpenPGP.hash(hash, input))
212                round += 1
213            }
214            return key.prefix(size)
215        }
216    }
217
218    // MARK: - AES in CFB
219
220    static func cfb(_ data: Data, key: Data, iv: Data = Data(repeating: 0, count: 16), encrypt: Bool) throws -> Data {
221        var cryptor: CCCryptorRef?
222        let status = key.withUnsafeBytes { k in
223            iv.withUnsafeBytes { v in
224                CCCryptorCreateWithMode(CCOperation(encrypt ? kCCEncrypt : kCCDecrypt), CCMode(kCCModeCFB), CCAlgorithm(kCCAlgorithmAES),
225                                        CCPadding(ccNoPadding), v.baseAddress, k.baseAddress, key.count, nil, 0, 0, CCModeOptions(0), &cryptor)
226            }
227        }
228        guard status == kCCSuccess, let cryptor else { throw Failure("The cipher couldn't start") }
229        defer { CCCryptorRelease(cryptor) }
230        var out = [UInt8](repeating: 0, count: data.count)
231        var moved = 0
232        let result = data.withUnsafeBytes { d in CCCryptorUpdate(cryptor, d.baseAddress, data.count, &out, out.count, &moved) }
233        guard result == kCCSuccess else { throw Failure("The cipher failed") }
234        return Data(out.prefix(moved))
235    }
236
237    static func random(_ count: Int) -> Data {
238        var bytes = [UInt8](repeating: 0, count: count)
239        _ = SecRandomCopyBytes(kSecRandomDefault, count, &bytes)
240        return Data(bytes)
241    }
242
243    // MARK: - Messages
244
245    public static let wrongPassphrase = Failure("Bad session key")
246
247    /// The literal data of a passphrase-encrypted message.
248    public static func decrypt(_ message: Data, passphrase: String) throws -> Data {
249        var sessionKey: (cipher: Int, key: Data)?
250        for packet in try packets(message) {
251            switch packet.tag {
252            case 3:
253                let b = [UInt8](packet.body)
254                guard b.count >= 2, b[0] == 4 else { throw Failure("Only version 4 passphrase packets are supported") }
255                let cipher = Int(b[1])
256                guard let size = keySizes[cipher] else { throw Failure("Cipher \(cipher) isn't supported; orgstar reads AES") }
257                let (s2k, length) = try S2K.parse(b, at: 2)
258                let key = try s2k.key(passphrase, size: size)
259                if b.count > 2 + length {
260                    // An encrypted session key.
261                    let esk = try cfb(Data(b[(2 + length)...]), key: key, encrypt: false)
262                    guard let algorithm = esk.first, let eskSize = keySizes[Int(algorithm)], esk.count == eskSize + 1 else { throw wrongPassphrase }
263                    sessionKey = (Int(algorithm), esk.dropFirst())
264                } else {
265                    sessionKey = (cipher, key)
266                }
267            case 18:
268                guard let sessionKey else { throw Failure("The PGP message has no passphrase packet") }
269                guard packet.body.first == 1 else { throw Failure("Only version 1 integrity protected packets are supported") }
270                let plain = try cfb(packet.body.dropFirst(), key: sessionKey.key, encrypt: false)
271                let block = 16
272                guard plain.count >= block + 2 + 22 else { throw Failure("The PGP message is cut short") }
273                let p = [UInt8](plain)
274                guard p[block - 2] == p[block], p[block - 1] == p[block + 1] else { throw wrongPassphrase }
275                let mdc = plain.suffix(20)
276                guard p[p.count - 22] == 0xD3, p[p.count - 21] == 0x14,
277                      Data(Insecure.SHA1.hash(data: plain.prefix(plain.count - 20))) == mdc else {
278                    throw Failure("The PGP message was modified")
279                }
280                return try literal(Data(p[(block + 2)..<(p.count - 22)]))
281            case 9:
282                throw Failure("The message has no integrity protection, which orgstar doesn't read")
283            case 20:
284                throw Failure("AEAD encrypted messages aren't supported")
285            case 10:
286                continue
287            default:
288                throw Failure("PGP packet \(packet.tag) isn't supported")
289            }
290        }
291        throw Failure("The PGP message has no encrypted data")
292    }
293
294    /// The data of the literal packet in `data`, decompressing on the way.
295    static func literal(_ data: Data) throws -> Data {
296        for packet in try packets(data) {
297            switch packet.tag {
298            case 11:
299                let b = [UInt8](packet.body)
300                guard b.count >= 6 else { throw Failure("The PGP message is damaged") }
301                let nameLength = Int(b[1])
302                guard b.count >= 2 + nameLength + 4 else { throw Failure("The PGP message is damaged") }
303                return Data(b[(2 + nameLength + 4)...])
304            case 8:
305                guard let algorithm = packet.body.first else { throw Failure("The PGP message is damaged") }
306                let compressed = packet.body.dropFirst()
307                switch algorithm {
308                case 0: return try literal(Data(compressed))
309                case 1: return try literal(try inflate(Data(compressed)))
310                case 2: return try literal(try inflate(Data(compressed.dropFirst(2))))
311                default: throw Failure("BZip2 compressed messages aren't supported")
312                }
313            default:
314                continue
315            }
316        }
317        throw Failure("The PGP message has no literal data")
318    }
319
320    /// Raw deflate, as ZIP and ZLIB packets hold it.
321    static func inflate(_ data: Data) throws -> Data {
322        do {
323            return try (data as NSData).decompressed(using: .zlib) as Data
324        } catch {
325            throw Failure("The PGP message's compressed data is damaged")
326        }
327    }
328
329    /// `gpg --symmetric --armor`: AES-256, an iterated and salted SHA-256 key, integrity
330    /// protection, binary literal data without a name.
331    public static func encrypt(_ data: Data, passphrase: String, now: Date = Date()) throws -> String {
332        let salt = random(8)
333        let s2k = S2K(type: 3, hash: 8, salt: salt, count: (16 + (96 & 15)) << ((96 >> 4) + 6))
334        let key = try s2k.key(passphrase, size: 32)
335        let skesk = packet(3, Data([4, 9, 3, 8]) + salt + Data([96]))
336        let date = UInt32(max(0, now.timeIntervalSince1970))
337        let literal = packet(11, Data([0x62, 0]) + Data((0..<4).reversed().map { UInt8((date >> ($0 * 8)) & 0xff) }) + data)
338        var prefix = random(16)
339        prefix.append(prefix.suffix(2))
340        var plain = prefix + literal + Data([0xD3, 0x14])
341        plain.append(Data(Insecure.SHA1.hash(data: plain)))
342        let seipd = packet(18, Data([1]) + (try cfb(plain, key: key, encrypt: true)))
343        return armor(skesk + seipd)
344    }
345}