Config+TLS.swift 18 KB

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