config.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers.
  2. //
  3. // As a reminder from https://golang.org/pkg/crypto/tls/#Config:
  4. //
  5. // A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified.
  6. // A Config may be reused; the tls package will also not modify it.
  7. package tlsconfig
  8. import (
  9. "crypto/tls"
  10. "crypto/x509"
  11. "encoding/pem"
  12. "errors"
  13. "fmt"
  14. "os"
  15. )
  16. // Options represents the information needed to create client and server TLS configurations.
  17. type Options struct {
  18. CAFile string
  19. // If either CertFile or KeyFile is empty, Client() will not load them
  20. // preventing the client from authenticating to the server.
  21. // However, Server() requires them and will error out if they are empty.
  22. CertFile string
  23. KeyFile string
  24. // client-only option
  25. InsecureSkipVerify bool
  26. // server-only option
  27. ClientAuth tls.ClientAuthType
  28. // If ExclusiveRootPools is set, then if a CA file is provided, the root pool used for TLS
  29. // creds will include exclusively the roots in that CA file. If no CA file is provided,
  30. // the system pool will be used.
  31. ExclusiveRootPools bool
  32. MinVersion uint16
  33. // If Passphrase is set, it will be used to decrypt a TLS private key
  34. // if the key is encrypted.
  35. //
  36. // Deprecated: Use of encrypted TLS private keys has been deprecated, and
  37. // will be removed in a future release. Golang has deprecated support for
  38. // legacy PEM encryption (as specified in RFC 1423), as it is insecure by
  39. // design (see https://go-review.googlesource.com/c/go/+/264159).
  40. Passphrase string
  41. }
  42. // Extra (server-side) accepted CBC cipher suites - will phase out in the future
  43. var acceptedCBCCiphers = []uint16{
  44. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  45. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  46. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  47. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  48. }
  49. // DefaultServerAcceptedCiphers should be uses by code which already has a crypto/tls
  50. // options struct but wants to use a commonly accepted set of TLS cipher suites, with
  51. // known weak algorithms removed.
  52. var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...)
  53. // ServerDefault returns a secure-enough TLS configuration for the server TLS configuration.
  54. func ServerDefault(ops ...func(*tls.Config)) *tls.Config {
  55. tlsConfig := &tls.Config{
  56. // Avoid fallback by default to SSL protocols < TLS1.2
  57. MinVersion: tls.VersionTLS12,
  58. PreferServerCipherSuites: true,
  59. CipherSuites: DefaultServerAcceptedCiphers,
  60. }
  61. for _, op := range ops {
  62. op(tlsConfig)
  63. }
  64. return tlsConfig
  65. }
  66. // ClientDefault returns a secure-enough TLS configuration for the client TLS configuration.
  67. func ClientDefault(ops ...func(*tls.Config)) *tls.Config {
  68. tlsConfig := &tls.Config{
  69. // Prefer TLS1.2 as the client minimum
  70. MinVersion: tls.VersionTLS12,
  71. CipherSuites: clientCipherSuites,
  72. }
  73. for _, op := range ops {
  74. op(tlsConfig)
  75. }
  76. return tlsConfig
  77. }
  78. // certPool returns an X.509 certificate pool from `caFile`, the certificate file.
  79. func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) {
  80. // If we should verify the server, we need to load a trusted ca
  81. var (
  82. certPool *x509.CertPool
  83. err error
  84. )
  85. if exclusivePool {
  86. certPool = x509.NewCertPool()
  87. } else {
  88. certPool, err = SystemCertPool()
  89. if err != nil {
  90. return nil, fmt.Errorf("failed to read system certificates: %v", err)
  91. }
  92. }
  93. pemData, err := os.ReadFile(caFile)
  94. if err != nil {
  95. return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err)
  96. }
  97. if !certPool.AppendCertsFromPEM(pemData) {
  98. return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile)
  99. }
  100. return certPool, nil
  101. }
  102. // allTLSVersions lists all the TLS versions and is used by the code that validates
  103. // a uint16 value as a TLS version.
  104. var allTLSVersions = map[uint16]struct{}{
  105. tls.VersionTLS10: {},
  106. tls.VersionTLS11: {},
  107. tls.VersionTLS12: {},
  108. tls.VersionTLS13: {},
  109. }
  110. // isValidMinVersion checks that the input value is a valid tls minimum version
  111. func isValidMinVersion(version uint16) bool {
  112. _, ok := allTLSVersions[version]
  113. return ok
  114. }
  115. // adjustMinVersion sets the MinVersion on `config`, the input configuration.
  116. // It assumes the current MinVersion on the `config` is the lowest allowed.
  117. func adjustMinVersion(options Options, config *tls.Config) error {
  118. if options.MinVersion > 0 {
  119. if !isValidMinVersion(options.MinVersion) {
  120. return fmt.Errorf("invalid minimum TLS version: %x", options.MinVersion)
  121. }
  122. if options.MinVersion < config.MinVersion {
  123. return fmt.Errorf("requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion)
  124. }
  125. config.MinVersion = options.MinVersion
  126. }
  127. return nil
  128. }
  129. // IsErrEncryptedKey returns true if the 'err' is an error of incorrect
  130. // password when trying to decrypt a TLS private key.
  131. //
  132. // Deprecated: Use of encrypted TLS private keys has been deprecated, and
  133. // will be removed in a future release. Golang has deprecated support for
  134. // legacy PEM encryption (as specified in RFC 1423), as it is insecure by
  135. // design (see https://go-review.googlesource.com/c/go/+/264159).
  136. func IsErrEncryptedKey(err error) bool {
  137. return errors.Is(err, x509.IncorrectPasswordError)
  138. }
  139. // getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format.
  140. // If the private key is encrypted, 'passphrase' is used to decrypted the
  141. // private key.
  142. func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) {
  143. // this section makes some small changes to code from notary/tuf/utils/x509.go
  144. pemBlock, _ := pem.Decode(keyBytes)
  145. if pemBlock == nil {
  146. return nil, fmt.Errorf("no valid private key found")
  147. }
  148. var err error
  149. if x509.IsEncryptedPEMBlock(pemBlock) { //nolint:staticcheck // Ignore SA1019 (IsEncryptedPEMBlock is deprecated)
  150. keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) //nolint:staticcheck // Ignore SA1019 (DecryptPEMBlock is deprecated)
  151. if err != nil {
  152. return nil, fmt.Errorf("private key is encrypted, but could not decrypt it: %w", err)
  153. }
  154. keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes})
  155. }
  156. return keyBytes, nil
  157. }
  158. // getCert returns a Certificate from the CertFile and KeyFile in 'options',
  159. // if the key is encrypted, the Passphrase in 'options' will be used to
  160. // decrypt it.
  161. func getCert(options Options) ([]tls.Certificate, error) {
  162. if options.CertFile == "" && options.KeyFile == "" {
  163. return nil, nil
  164. }
  165. cert, err := os.ReadFile(options.CertFile)
  166. if err != nil {
  167. return nil, err
  168. }
  169. prKeyBytes, err := os.ReadFile(options.KeyFile)
  170. if err != nil {
  171. return nil, err
  172. }
  173. prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase)
  174. if err != nil {
  175. return nil, err
  176. }
  177. tlsCert, err := tls.X509KeyPair(cert, prKeyBytes)
  178. if err != nil {
  179. return nil, err
  180. }
  181. return []tls.Certificate{tlsCert}, nil
  182. }
  183. // Client returns a TLS configuration meant to be used by a client.
  184. func Client(options Options) (*tls.Config, error) {
  185. tlsConfig := ClientDefault()
  186. tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify
  187. if !options.InsecureSkipVerify && options.CAFile != "" {
  188. CAs, err := certPool(options.CAFile, options.ExclusiveRootPools)
  189. if err != nil {
  190. return nil, err
  191. }
  192. tlsConfig.RootCAs = CAs
  193. }
  194. tlsCerts, err := getCert(options)
  195. if err != nil {
  196. return nil, fmt.Errorf("could not load X509 key pair: %w", err)
  197. }
  198. tlsConfig.Certificates = tlsCerts
  199. if err := adjustMinVersion(options, tlsConfig); err != nil {
  200. return nil, err
  201. }
  202. return tlsConfig, nil
  203. }
  204. // Server returns a TLS configuration meant to be used by a server.
  205. func Server(options Options) (*tls.Config, error) {
  206. tlsConfig := ServerDefault()
  207. tlsConfig.ClientAuth = options.ClientAuth
  208. tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile)
  209. if err != nil {
  210. if os.IsNotExist(err) {
  211. return nil, fmt.Errorf("could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err)
  212. }
  213. return nil, fmt.Errorf("error reading X509 key pair - make sure the key is not encrypted (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err)
  214. }
  215. tlsConfig.Certificates = []tls.Certificate{tlsCert}
  216. if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" {
  217. CAs, err := certPool(options.CAFile, options.ExclusiveRootPools)
  218. if err != nil {
  219. return nil, err
  220. }
  221. tlsConfig.ClientCAs = CAs
  222. }
  223. if err := adjustMinVersion(options, tlsConfig); err != nil {
  224. return nil, err
  225. }
  226. return tlsConfig, nil
  227. }