File: KeyUsage.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (374 lines) | stat: -rw-r--r-- 13,202 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCertificates open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import SwiftASN1

/// Defines the purpose of the key contained in the certificate.
///
/// This usage restriction may be employed when a key that could conceptually be used
/// for more than one operation (such as an RSA key) is to be restricted.
public struct KeyUsage {
    // KeyUsage is only actually 9-bits wide, so we store it in a UInt16 in bits 0 through 8.
    // To avoid the need to do bit swaps, we treat this as though the bits were encoded in ASN.1:
    // bit zero is the highest bit, bit 16 is the lowest.
    @usableFromInline
    internal var rawValue: UInt16

    /// Construct a ``KeyUsage`` extension with no usages set.
    @inlinable
    public init() {
        self.rawValue = 0
    }

    /// Construct a ``KeyUsage`` extension with some usages set.
    ///
    /// - Parameters:
    ///   - digitalSignature: This is true when the subject public key is used for verifying digital signatures,
    ///       other than signatures used in certificates (covered by `keyCertSign`) or in
    ///       CRLs (covered by `cRLSign`).
    ///   - nonRepudiation: This is true when the subject public key is used to verify digital signatures used
    ///       to provide a non-repudiation service that protects against the signing entity denying
    ///       some action. This does not cover signatures used in certificates (covered by `keyCertSign`)
    ///       or in CRLs (`cRLSign`).
    ///   - keyEncipherment: This is true when the subject public key is used to encrypt private or secret keys, e.g.
    ///       for key transport.
    ///   - dataEncipherment: This is true when the subject public key is used to encrypt raw data directly, without the use
    ///       of an intervening symmetric cipher.
    ///   - keyAgreement: This is true when the subject public key is used for key agreement.
    ///   - keyCertSign: This is true when the subject public key is used for verifying signatures on
    ///       certificates.
    ///   - cRLSign: This is true when the subject public key is used for verifying signatures on
    ///       certificate revocation lists.
    ///   - encipherOnly: This only has meaning when the `keyAgreement` field is also `true`. When `true` in that
    ///       case, the subject public key may only be used for encrypting data while performing key
    ///       agreement.
    ///   - decipherOnly: This only has meaning when the `keyAgreement` field is also `true`. When `true` in that
    ///       case, the subject public key may only be used for decrypting data while performing key
    ///       agreement.
    @inlinable
    public init(
        digitalSignature: Bool = false,
        nonRepudiation: Bool = false,
        keyEncipherment: Bool = false,
        dataEncipherment: Bool = false,
        keyAgreement: Bool = false,
        keyCertSign: Bool = false,
        cRLSign: Bool = false,
        encipherOnly: Bool = false,
        decipherOnly: Bool = false
    ) {
        self = Self()
        self.digitalSignature = digitalSignature
        self.nonRepudiation = nonRepudiation
        self.keyEncipherment = keyEncipherment
        self.dataEncipherment = dataEncipherment
        self.keyAgreement = keyAgreement
        self.keyCertSign = keyCertSign
        self.cRLSign = cRLSign
        self.encipherOnly = encipherOnly
        self.decipherOnly = decipherOnly
    }

    /// Create a new ``KeyUsage`` object
    /// by unwrapping a ``Certificate/Extension``.
    ///
    /// - Parameter ext: The ``Certificate/Extension`` to unwrap
    /// - Throws: if the ``Certificate/Extension/oid`` is not equal to
    ///     `ASN1ObjectIdentifier.X509ExtensionID.keyUsage`.
    @inlinable
    public init(_ ext: Certificate.Extension) throws {
        guard ext.oid == .X509ExtensionID.keyUsage else {
            throw CertificateError.incorrectOIDForExtension(
                reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.keyUsage), got \(ext.oid)"
            )
        }

        let keyUsageValue = try ASN1BitString(derEncoded: ext.value)
        try Self.validateBitString(keyUsageValue)
        self.rawValue = UInt16(keyUsageValue)
    }

    /// This is true when the subject public key is used for verifying digital signatures,
    /// other than signatures used in certificates (covered by ``keyCertSign``) or in
    /// CRLs (covered by ``cRLSign``).
    @inlinable
    public var digitalSignature: Bool {
        get {
            return (self.rawValue & 0x8000) == 0x8000
        }
        set {
            if newValue {
                self.rawValue |= 0x8000
            } else {
                self.rawValue &= (~0x8000)
            }
        }
    }

    /// This is true when the subject public key is used to verify digital signatures used
    /// to provide a non-repudiation service that protects against the signing entity denying
    /// some action. This does not cover signatures used in certificates (covered by ``keyCertSign``)
    /// or in CRLs (``cRLSign``).
    @inlinable
    public var nonRepudiation: Bool {
        get {
            return (self.rawValue & 0x4000) == 0x4000
        }
        set {
            if newValue {
                self.rawValue |= 0x4000
            } else {
                self.rawValue &= (~0x4000)
            }
        }
    }

    /// This is true when the subject public key is used to encrypt private or secret keys, e.g.
    /// for key transport.
    @inlinable
    public var keyEncipherment: Bool {
        get {
            return (self.rawValue & 0x2000) == 0x2000
        }
        set {
            if newValue {
                self.rawValue |= 0x2000
            } else {
                self.rawValue &= (~0x2000)
            }
        }
    }

    /// This is true when the subject public key is used to encrypt raw data directly, without the use
    /// of an intervening symmetric cipher.
    @inlinable
    public var dataEncipherment: Bool {
        get {
            return (self.rawValue & 0x1000) == 0x1000
        }
        set {
            if newValue {
                self.rawValue |= 0x1000
            } else {
                self.rawValue &= (~0x1000)
            }
        }
    }

    /// This is true when the subject public key is used for key agreement.
    @inlinable
    public var keyAgreement: Bool {
        get {
            return (self.rawValue & 0x0800) == 0x0800
        }
        set {
            if newValue {
                self.rawValue |= 0x0800
            } else {
                self.rawValue &= (~0x0800)
            }
        }
    }

    /// This is true when the subject public key is used for verifying signatures on
    /// certificates.
    @inlinable
    public var keyCertSign: Bool {
        get {
            return (self.rawValue & 0x0400) == 0x0400
        }
        set {
            if newValue {
                self.rawValue |= 0x0400
            } else {
                self.rawValue &= (~0x0400)
            }
        }
    }

    /// This is true when the subject public key is used for verifying signatures on
    /// certificate revocation lists.
    @inlinable
    public var cRLSign: Bool {
        get {
            return (self.rawValue & 0x0200) == 0x0200
        }
        set {
            if newValue {
                self.rawValue |= 0x0200
            } else {
                self.rawValue &= (~0x0200)
            }
        }
    }

    /// This only has meaning when the ``keyAgreement`` field is also `true`. When `true` in that
    /// case, the subject public key may only be used for encrypting data while performing key
    /// agreement.
    @inlinable
    public var encipherOnly: Bool {
        get {
            return (self.rawValue & 0x0100) == 0x0100
        }
        set {
            if newValue {
                self.rawValue |= 0x0100
            } else {
                self.rawValue &= (~0x0100)
            }
        }
    }

    /// This only has meaning when the ``keyAgreement`` field is also `true`. When `true` in that
    /// case, the subject public key may only be used for decrypting data while performing key
    /// agreement.
    @inlinable
    public var decipherOnly: Bool {
        get {
            return (self.rawValue & 0x0080) == 0x0080
        }
        set {
            if newValue {
                self.rawValue |= 0x0080
            } else {
                self.rawValue &= (~0x0080)
            }
        }
    }

    @inlinable
    internal static func validateBitString(_ bitstring: ASN1BitString) throws {
        switch bitstring.bytes.count {
        case 0:
            // This is fine, no bits are set.
            precondition(bitstring.paddingBits == 0)
        case 1:
            // This is fine, no more than 8 bits.
            // We want to confirm that the bit _before_ the first padding bit isn't 0.
            // We cannot have 8 padding bits.
            precondition(bitstring.paddingBits < 8)
            let bitMask = UInt8(0x01) << bitstring.paddingBits
            if (bitstring.bytes[bitstring.bytes.startIndex] & bitMask) == 0 {
                throw ASN1Error.invalidASN1Object(reason: "Invalid leading padding bit")
            }
        case 2 where bitstring.paddingBits == 7:
            // This is fine, there are 9 valid bits: 8 from the prior byte and 1 here.
            if (bitstring.bytes[bitstring.bytes.startIndex &+ 1] & 0x80) == 0 {
                throw ASN1Error.invalidASN1Object(reason: "Invalid padding bit")
            }
        default:
            // Too many bits!
            throw ASN1Error.invalidASN1Object(reason: "Too many bits for Key Usage")
        }
    }
}

extension KeyUsage: Hashable {}

extension KeyUsage: Sendable {}

extension KeyUsage: CustomStringConvertible {
    public var description: String {
        var enabledUsages: [String] = []

        if self.digitalSignature {
            enabledUsages.append("digitalSignature")
        }
        if self.nonRepudiation {
            enabledUsages.append("nonRepudiation")
        }
        if self.keyEncipherment {
            enabledUsages.append("keyEncipherment")
        }
        if self.dataEncipherment {
            enabledUsages.append("dataEncipherment")
        }
        if self.keyAgreement {
            enabledUsages.append("keyAgreement")
        }
        if self.keyCertSign {
            enabledUsages.append("keyCertSign")
        }
        if self.cRLSign {
            enabledUsages.append("cRLSign")
        }
        if self.encipherOnly {
            enabledUsages.append("encipherOnly")
        }
        if self.decipherOnly {
            enabledUsages.append("decipherOnly")
        }

        return enabledUsages.joined(separator: ", ")
    }
}

extension KeyUsage: CustomDebugStringConvertible {
    public var debugDescription: String {
        "KeyUsage(\(String(describing: self)))"
    }
}

extension Certificate.Extension {
    /// Construct an opaque ``Certificate/Extension`` from this Key Usage extension.
    ///
    /// - Parameters:
    ///   - keyUsage: The extension to wrap
    ///   - critical: Whether this extension should have the critical bit set.
    @inlinable
    public init(_ keyUsage: KeyUsage, critical: Bool) throws {
        let asn1Representation = ASN1BitString(keyUsage)
        var serializer = DER.Serializer()
        try serializer.serialize(asn1Representation)
        self.init(oid: .X509ExtensionID.keyUsage, critical: critical, value: serializer.serializedBytes[...])
    }
}

extension KeyUsage: CertificateExtensionConvertible {
    public func makeCertificateExtension() throws -> Certificate.Extension {
        return try .init(self, critical: false)
    }
}

extension UInt16 {
    @inlinable
    init(_ bitString: ASN1BitString) {
        switch bitString.bytes.count {
        case 0:
            self = 0
        case 1:
            self = UInt16(bitString.bytes[bitString.bytes.startIndex]) << 8
        case 2:
            self = UInt16(bitString.bytes[bitString.bytes.startIndex]) << 8
            self |= UInt16(bitString.bytes[bitString.bytes.startIndex + 1])
        default:
            preconditionFailure()
        }
    }
}

extension ASN1BitString {
    @inlinable
    init(_ ext: KeyUsage) {
        if ext.decipherOnly {
            // We need two bytes here.
            let bytes = [UInt8(truncatingIfNeeded: ext.rawValue >> 8), UInt8(truncatingIfNeeded: ext.rawValue)]
            self = .init(bytes: bytes[...], paddingBits: 7)
        } else {
            // We only need one byte here.
            let byte = UInt8(truncatingIfNeeded: ext.rawValue >> 8)
            self = .init(bytes: [byte], paddingBits: byte.trailingZeroBitCount)
        }
    }
}