Config+TLS.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. private import GRPCCore
  17. public import NIOCertificateReloading
  18. public import NIOCore
  19. public import NIOSSL
  20. @available(gRPCSwiftNIOTransport 2.0, *)
  21. extension HTTP2ServerTransport.Posix {
  22. /// The security configuration for this connection.
  23. public struct TransportSecurity: Sendable {
  24. package enum Wrapped: Sendable {
  25. case plaintext
  26. case tls(TLS)
  27. }
  28. package let wrapped: Wrapped
  29. /// This connection is plaintext: no encryption will take place.
  30. public static let plaintext = Self(wrapped: .plaintext)
  31. /// Secure connections with the given TLS configuration.
  32. public static func tls(_ tls: TLS) -> Self {
  33. Self(wrapped: .tls(tls))
  34. }
  35. /// Secure connections with TLS.
  36. ///
  37. /// - Parameters:
  38. /// - certificateChain: The certificates the server will offer during negotiation.
  39. /// - privateKey: The private key associated with the leaf certificate.
  40. /// - configure: A closure which allows you to modify the defaults before returning them.
  41. public static func tls(
  42. certificateChain: [TLSConfig.CertificateSource],
  43. privateKey: TLSConfig.PrivateKeySource,
  44. configure: (_ config: inout TLS) -> Void = { _ in }
  45. ) -> Self {
  46. let tlsConfig: TLS = .defaults(
  47. certificateChain: certificateChain,
  48. privateKey: privateKey,
  49. configure: configure
  50. )
  51. return .tls(tlsConfig)
  52. }
  53. /// Create a new TLS config using a certificate reloader to provide the certificate chain
  54. /// and private key.
  55. ///
  56. /// The reloader must provide an initial certificate chain and private key. If you already
  57. /// have an initial certificate chain and private key you can use
  58. /// ``tls(certificateChain:privateKey:configure:)`` and set the certificate reloader via
  59. /// the `configure` callback.
  60. ///
  61. /// The defaults include setting:
  62. /// - `clientCertificateVerificationMode` to `doNotVerify`,
  63. /// - `trustRoots` to `systemDefault`, and
  64. /// - `requireALPN` to `false`.
  65. ///
  66. /// - Parameters:
  67. /// - reloader: A certificate reloader which has been primed with an initial certificate chain
  68. /// and private key.
  69. /// - configure: A closure which allows you to modify the defaults before returning them.
  70. /// - Throws: If the reloader doesn't provide an initial certificate chain or private key.
  71. /// - Returns: A new HTTP2 NIO Posix transport TLS config.
  72. public static func tls(
  73. certificateReloader reloader: any CertificateReloader,
  74. configure: (_ config: inout TLS) -> Void = { _ in }
  75. ) throws -> Self {
  76. let (certificateChain, privateKey) = try reloader.checkPrimed()
  77. return .tls(
  78. certificateChain: certificateChain.map { source in .nioSSLCertificateSource(source) },
  79. privateKey: .nioSSLSpecific(.privateKey(privateKey))
  80. ) { config in
  81. config.certificateReloader = reloader
  82. configure(&config)
  83. }
  84. }
  85. /// Secure the connection with mutual TLS.
  86. ///
  87. /// - Parameters:
  88. /// - certificateChain: The certificates the client will offer during negotiation.
  89. /// - privateKey: The private key associated with the leaf certificate.
  90. /// - configure: A closure which allows you to modify the defaults before returning them.
  91. public static func mTLS(
  92. certificateChain: [TLSConfig.CertificateSource],
  93. privateKey: TLSConfig.PrivateKeySource,
  94. configure: (_ config: inout TLS) -> Void = { _ in }
  95. ) -> Self {
  96. let tlsConfig: TLS = .mTLS(
  97. certificateChain: certificateChain,
  98. privateKey: privateKey,
  99. configure: configure
  100. )
  101. return .tls(tlsConfig)
  102. }
  103. /// Create a new TLS config suitable for mTLS using a certificate reloader to provide the
  104. /// certificate chain and private key.
  105. ///
  106. /// The reloader must provide an initial certificate chain and private key. If you already
  107. /// have an initial certificate chain and private key you can use
  108. /// ``mTLS(certificateChain:privateKey:configure:)`` and set the certificate reloader via
  109. /// the `configure` callback.
  110. ///
  111. /// The defaults include setting:
  112. /// - `clientCertificateVerificationMode` to `noHostnameVerification`,
  113. /// - `trustRoots` to `systemDefault`, and
  114. /// - `requireALPN` to `false`.
  115. ///
  116. /// - Parameters:
  117. /// - reloader: A certificate reloader which has been primed with an initial certificate chain
  118. /// and private key.
  119. /// - configure: A closure which allows you to modify the defaults before returning them.
  120. /// - Throws: If the reloader doesn't provide an initial certificate chain or private key.
  121. /// - Returns: A new HTTP2 NIO Posix transport TLS config.
  122. public static func mTLS(
  123. certificateReloader reloader: any CertificateReloader,
  124. configure: (_ config: inout TLS) -> Void = { _ in }
  125. ) throws -> Self {
  126. let (certificateChain, privateKey) = try reloader.checkPrimed()
  127. return .mTLS(
  128. certificateChain: certificateChain.map { source in .nioSSLCertificateSource(source) },
  129. privateKey: .nioSSLSpecific(.privateKey(privateKey))
  130. ) { config in
  131. config.certificateReloader = reloader
  132. configure(&config)
  133. }
  134. }
  135. }
  136. }
  137. @available(gRPCSwiftNIOTransport 2.0, *)
  138. extension HTTP2ServerTransport.Posix.TransportSecurity {
  139. public struct TLS: Sendable {
  140. /// The certificates the server will offer during negotiation.
  141. public var certificateChain: [TLSConfig.CertificateSource]
  142. /// The private key associated with the leaf certificate.
  143. public var privateKey: TLSConfig.PrivateKeySource
  144. /// How to verify the client certificate, if one is presented.
  145. public var clientCertificateVerification: TLSConfig.CertificateVerification
  146. /// The trust roots to be used when verifying client certificates.
  147. public var trustRoots: TLSConfig.TrustRootsSource
  148. /// Whether ALPN is required.
  149. ///
  150. /// If this is set to `true` but the client does not support ALPN, then the connection will be rejected.
  151. public var requireALPN: Bool
  152. /// A certificate reloader providing the current certificate chain and private key to
  153. /// use at that point in time.
  154. public var certificateReloader: (any CertificateReloader)?
  155. /// Override the certificate verification with a custom callback that must return the verified certificate chain on success.
  156. /// Note: The callback is only used when `clientCertificateVerification` is *not* set to `noVerification`!
  157. @available(gRPCSwiftNIOTransport 2.2, *)
  158. public var customVerificationCallback:
  159. (
  160. @Sendable (
  161. _ certificates: [NIOSSLCertificate],
  162. _ promise: EventLoopPromise<NIOSSLVerificationResultWithMetadata>
  163. ) -> Void
  164. )?
  165. /// Create a new HTTP2 NIO Posix server transport TLS config.
  166. /// - Parameters:
  167. /// - certificateChain: The certificates the server will offer during negotiation.
  168. /// - privateKey: The private key associated with the leaf certificate.
  169. /// - clientCertificateVerification: How to verify the client certificate, if one is presented.
  170. /// - trustRoots: The trust roots to be used when verifying client certificates.
  171. /// - requireALPN: Whether ALPN is required.
  172. public init(
  173. certificateChain: [TLSConfig.CertificateSource],
  174. privateKey: TLSConfig.PrivateKeySource,
  175. clientCertificateVerification: TLSConfig.CertificateVerification,
  176. trustRoots: TLSConfig.TrustRootsSource,
  177. requireALPN: Bool
  178. ) {
  179. self.certificateChain = certificateChain
  180. self.privateKey = privateKey
  181. self.clientCertificateVerification = clientCertificateVerification
  182. self.trustRoots = trustRoots
  183. self.requireALPN = requireALPN
  184. }
  185. /// Create a new HTTP2 NIO Posix transport TLS config, with some values defaulted:
  186. /// - `clientCertificateVerificationMode` equals `doNotVerify`
  187. /// - `trustRoots` equals `systemDefault`
  188. /// - `requireALPN` equals `false`
  189. ///
  190. /// - Parameters:
  191. /// - certificateChain: The certificates the server will offer during negotiation.
  192. /// - privateKey: The private key associated with the leaf certificate.
  193. /// - configure: A closure which allows you to modify the defaults before returning them.
  194. /// - Returns: A new HTTP2 NIO Posix transport TLS config.
  195. public static func defaults(
  196. certificateChain: [TLSConfig.CertificateSource],
  197. privateKey: TLSConfig.PrivateKeySource,
  198. configure: (_ config: inout Self) -> Void = { _ in }
  199. ) -> Self {
  200. var config = Self(
  201. certificateChain: certificateChain,
  202. privateKey: privateKey,
  203. clientCertificateVerification: .noVerification,
  204. trustRoots: .systemDefault,
  205. requireALPN: false
  206. )
  207. configure(&config)
  208. return config
  209. }
  210. /// Create a new HTTP2 NIO Posix transport TLS config, with some values defaulted to match
  211. /// the requirements of mTLS:
  212. /// - `clientCertificateVerificationMode` equals `noHostnameVerification`
  213. /// - `trustRoots` equals `systemDefault`
  214. /// - `requireALPN` equals `false`
  215. ///
  216. /// - Parameters:
  217. /// - certificateChain: The certificates the server will offer during negotiation.
  218. /// - privateKey: The private key associated with the leaf certificate.
  219. /// - configure: A closure which allows you to modify the defaults before returning them.
  220. /// - Returns: A new HTTP2 NIO Posix transport TLS config.
  221. public static func mTLS(
  222. certificateChain: [TLSConfig.CertificateSource],
  223. privateKey: TLSConfig.PrivateKeySource,
  224. configure: (_ config: inout Self) -> Void = { _ in }
  225. ) -> Self {
  226. var config = Self(
  227. certificateChain: certificateChain,
  228. privateKey: privateKey,
  229. clientCertificateVerification: .noHostnameVerification,
  230. trustRoots: .systemDefault,
  231. requireALPN: false
  232. )
  233. configure(&config)
  234. return config
  235. }
  236. }
  237. }
  238. @available(gRPCSwiftNIOTransport 2.0, *)
  239. extension HTTP2ClientTransport.Posix {
  240. /// The security configuration for this connection.
  241. public struct TransportSecurity: Sendable {
  242. package enum Wrapped: Sendable {
  243. case plaintext
  244. case tls(TLS)
  245. }
  246. package let wrapped: Wrapped
  247. /// This connection is plaintext: no encryption will take place.
  248. public static let plaintext = Self(wrapped: .plaintext)
  249. /// Secure the connection with the given TLS configuration.
  250. public static func tls(_ tls: TLS) -> Self {
  251. Self(wrapped: .tls(tls))
  252. }
  253. /// Secure the connection with TLS using the default configuration.
  254. ///
  255. /// - Parameters:
  256. /// - configure: A closure which allows you to modify the defaults before returning them.
  257. public static func tls(
  258. configure: (_ config: inout TLS) -> Void = { _ in }
  259. ) -> Self {
  260. Self.tls(.defaults(configure: configure))
  261. }
  262. /// Secure the connection with TLS using the default configuration.
  263. public static var tls: Self {
  264. Self.tls(.defaults())
  265. }
  266. /// Secure the connection with mutual TLS.
  267. ///
  268. /// - Parameters:
  269. /// - certificateChain: The certificates the client will offer during negotiation.
  270. /// - privateKey: The private key associated with the leaf certificate.
  271. /// - configure: A closure which allows you to modify the defaults before returning them.
  272. public static func mTLS(
  273. certificateChain: [TLSConfig.CertificateSource],
  274. privateKey: TLSConfig.PrivateKeySource,
  275. configure: (_ config: inout TLS) -> Void = { _ in }
  276. ) -> Self {
  277. let tlsConfig: TLS = .mTLS(
  278. certificateChain: certificateChain,
  279. privateKey: privateKey,
  280. configure: configure
  281. )
  282. return .tls(tlsConfig)
  283. }
  284. /// Create a new TLS config suitable for mTLS using a certificate reloader to provide the
  285. /// certificate chain and private key.
  286. ///
  287. /// The reloader must provide an initial certificate chain and private key. If you have already
  288. /// have an initial certificate chain and private key you can use
  289. /// ``mTLS(certificateChain:privateKey:configure:)`` and set the certificate reloader via
  290. /// the `configure` callback.
  291. ///
  292. /// The defaults include setting:
  293. /// - `trustRoots` to `systemDefault`, and
  294. /// - `serverCertificateVerification` to `fullVerification`.
  295. ///
  296. /// - Parameters:
  297. /// - reloader: A certificate reloader which has been primed with an initial certificate chain
  298. /// and private key.
  299. /// - configure: A closure which allows you to modify the defaults before returning them.
  300. /// - Throws: If the reloader doesn't provide an initial certificate chain or private key.
  301. /// - Returns: A new HTTP2 NIO Posix transport TLS config.
  302. public static func mTLS(
  303. certificateReloader reloader: any CertificateReloader,
  304. configure: (_ config: inout TLS) -> Void = { _ in }
  305. ) throws -> Self {
  306. let (certificateChain, privateKey) = try reloader.checkPrimed()
  307. return .mTLS(
  308. certificateChain: certificateChain.map { source in .nioSSLCertificateSource(source) },
  309. privateKey: .nioSSLSpecific(.privateKey(privateKey))
  310. ) { config in
  311. config.certificateReloader = reloader
  312. configure(&config)
  313. }
  314. }
  315. }
  316. }
  317. @available(gRPCSwiftNIOTransport 2.0, *)
  318. extension HTTP2ClientTransport.Posix.TransportSecurity {
  319. public struct TLS: Sendable {
  320. /// The certificates the client will offer during negotiation.
  321. public var certificateChain: [TLSConfig.CertificateSource]
  322. /// The private key associated with the leaf certificate.
  323. public var privateKey: TLSConfig.PrivateKeySource?
  324. /// How to verify the server certificate, if one is presented.
  325. public var serverCertificateVerification: TLSConfig.CertificateVerification
  326. /// Override the certificate verification with a custom callback that must return the verified certificate chain on success.
  327. /// Note: The callback is only used when `serverCertificateVerification` is *not* set to `noVerification`!
  328. @available(gRPCSwiftNIOTransport 2.3, *)
  329. public var customVerificationCallback:
  330. (
  331. @Sendable (
  332. _ certificates: [NIOSSLCertificate],
  333. _ promise: EventLoopPromise<NIOSSLVerificationResultWithMetadata>
  334. ) -> Void
  335. )?
  336. /// The trust roots to be used when verifying server certificates.
  337. public var trustRoots: TLSConfig.TrustRootsSource
  338. /// A certificate reloader providing the current certificate chain and private key to
  339. /// use at that point in time.
  340. public var certificateReloader: (any CertificateReloader)?
  341. /// Create a new HTTP2 NIO Posix client transport TLS config.
  342. /// - Parameters:
  343. /// - certificateChain: The certificates the client will offer during negotiation.
  344. /// - privateKey: The private key associated with the leaf certificate.
  345. /// - serverCertificateVerification: How to verify the server certificate, if one is presented.
  346. /// - trustRoots: The trust roots to be used when verifying server certificates.
  347. public init(
  348. certificateChain: [TLSConfig.CertificateSource],
  349. privateKey: TLSConfig.PrivateKeySource?,
  350. serverCertificateVerification: TLSConfig.CertificateVerification,
  351. trustRoots: TLSConfig.TrustRootsSource
  352. ) {
  353. self.certificateChain = certificateChain
  354. self.privateKey = privateKey
  355. self.serverCertificateVerification = serverCertificateVerification
  356. self.trustRoots = trustRoots
  357. }
  358. /// Create a new HTTP2 NIO Posix transport TLS config, with some values defaulted:
  359. /// - `certificateChain` equals `[]`
  360. /// - `privateKey` equals `nil`
  361. /// - `serverCertificateVerification` equals `fullVerification`
  362. /// - `trustRoots` equals `systemDefault`
  363. ///
  364. /// - Parameters:
  365. /// - configure: A closure which allows you to modify the defaults before returning them.
  366. /// - Returns: A new HTTP2 NIO Posix transport TLS config.
  367. public static func defaults(
  368. configure: (_ config: inout Self) -> Void = { _ in }
  369. ) -> Self {
  370. var config = Self(
  371. certificateChain: [],
  372. privateKey: nil,
  373. serverCertificateVerification: .fullVerification,
  374. trustRoots: .systemDefault
  375. )
  376. configure(&config)
  377. return config
  378. }
  379. /// Create a new HTTP2 NIO Posix transport TLS config, with some values defaulted:
  380. /// - `certificateChain` equals `[]`
  381. /// - `privateKey` equals `nil`
  382. /// - `serverCertificateVerification` equals `fullVerification`
  383. /// - `trustRoots` equals `systemDefault`
  384. public static var defaults: Self { .defaults() }
  385. /// Create a new HTTP2 NIO Posix transport TLS config, with some values defaulted to match
  386. /// the requirements of mTLS:
  387. /// - `trustRoots` equals `systemDefault`
  388. /// - `serverCertificateVerification` equals `fullVerification`
  389. ///
  390. /// - Parameters:
  391. /// - certificateChain: The certificates the client will offer during negotiation.
  392. /// - privateKey: The private key associated with the leaf certificate.
  393. /// - configure: A closure which allows you to modify the defaults before returning them.
  394. /// - Returns: A new HTTP2 NIO Posix transport TLS config.
  395. public static func mTLS(
  396. certificateChain: [TLSConfig.CertificateSource],
  397. privateKey: TLSConfig.PrivateKeySource,
  398. configure: (_ config: inout Self) -> Void = { _ in }
  399. ) -> Self {
  400. var config = Self(
  401. certificateChain: certificateChain,
  402. privateKey: privateKey,
  403. serverCertificateVerification: .fullVerification,
  404. trustRoots: .systemDefault
  405. )
  406. configure(&config)
  407. return config
  408. }
  409. }
  410. }
  411. @available(gRPCSwiftNIOTransport 2.0, *)
  412. extension TLSConfig.PrivateKeySource {
  413. /// Creates a key source from a `NIOSSLCustomPrivateKey`.
  414. ///
  415. /// This private key source is only applicable to the NIOPosix based transports. Using one
  416. /// with a NIOTransportServices based transport is a programmer error.
  417. ///
  418. /// - Parameter key: The custom private key.
  419. /// - Returns: A private key source wrapping the custom private key.
  420. public static func customPrivateKey(_ key: any (NIOSSLCustomPrivateKey & Hashable)) -> Self {
  421. .nioSSLSpecific(.customPrivateKey(key))
  422. }
  423. }
  424. @available(gRPCSwiftNIOTransport 2.0, *)
  425. extension TLSConfig.CertificateSource {
  426. internal static func nioSSLCertificateSource(_ wrapped: NIOSSLCertificateSource) -> Self {
  427. return .transportSpecific(TransportSpecific(wrapped))
  428. }
  429. }
  430. @available(gRPCSwiftNIOTransport 2.0, *)
  431. extension CertificateReloader {
  432. fileprivate func checkPrimed() throws -> ([NIOSSLCertificateSource], NIOSSLPrivateKeySource) {
  433. func explain(missingItem item: String) -> String {
  434. return """
  435. No \(item) available. The reloader must provide a certificate chain and private key when \
  436. creating a TLS config from a reloader. Ensure the reloader is ready or create a config \
  437. with a certificate chain and private key manually and set the certificate reloader \
  438. separately.
  439. """
  440. }
  441. let override = self.sslContextConfigurationOverride
  442. guard let certificateChain = override.certificateChain else {
  443. throw RPCError(code: .invalidArgument, message: explain(missingItem: "certificate chain"))
  444. }
  445. guard let privateKey = override.privateKey else {
  446. throw RPCError(code: .invalidArgument, message: explain(missingItem: "private key"))
  447. }
  448. return (certificateChain, privateKey)
  449. }
  450. }