Config+TLS.swift 19 KB

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