config.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. // 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.
  5. // A Config may be reused; the tls package will also not modify it.
  6. package tlsconfig
  7. import (
  8. "crypto/tls"
  9. "crypto/x509"
  10. "encoding/pem"
  11. "fmt"
  12. "io/ioutil"
  13. "os"
  14. "github.com/pkg/errors"
  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. Passphrase string
  36. }
  37. // Extra (server-side) accepted CBC cipher suites - will phase out in the future
  38. var acceptedCBCCiphers = []uint16{
  39. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  40. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  41. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  42. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  43. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  44. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  45. }
  46. // DefaultServerAcceptedCiphers should be uses by code which already has a crypto/tls
  47. // options struct but wants to use a commonly accepted set of TLS cipher suites, with
  48. // known weak algorithms removed.
  49. var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...)
  50. // allTLSVersions lists all the TLS versions and is used by the code that validates
  51. // a uint16 value as a TLS version.
  52. var allTLSVersions = map[uint16]struct{}{
  53. tls.VersionSSL30: {},
  54. tls.VersionTLS10: {},
  55. tls.VersionTLS11: {},
  56. tls.VersionTLS12: {},
  57. }
  58. // ServerDefault returns a secure-enough TLS configuration for the server TLS configuration.
  59. func ServerDefault() *tls.Config {
  60. return &tls.Config{
  61. // Avoid fallback to SSL protocols < TLS1.0
  62. MinVersion: tls.VersionTLS10,
  63. PreferServerCipherSuites: true,
  64. CipherSuites: DefaultServerAcceptedCiphers,
  65. }
  66. }
  67. // ClientDefault returns a secure-enough TLS configuration for the client TLS configuration.
  68. func ClientDefault() *tls.Config {
  69. return &tls.Config{
  70. // Prefer TLS1.2 as the client minimum
  71. MinVersion: tls.VersionTLS12,
  72. CipherSuites: clientCipherSuites,
  73. }
  74. }
  75. // certPool returns an X.509 certificate pool from `caFile`, the certificate file.
  76. func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) {
  77. // If we should verify the server, we need to load a trusted ca
  78. var (
  79. certPool *x509.CertPool
  80. err error
  81. )
  82. if exclusivePool {
  83. certPool = x509.NewCertPool()
  84. } else {
  85. certPool, err = SystemCertPool()
  86. if err != nil {
  87. return nil, fmt.Errorf("failed to read system certificates: %v", err)
  88. }
  89. }
  90. pem, err := ioutil.ReadFile(caFile)
  91. if err != nil {
  92. return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err)
  93. }
  94. if !certPool.AppendCertsFromPEM(pem) {
  95. return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile)
  96. }
  97. return certPool, nil
  98. }
  99. // isValidMinVersion checks that the input value is a valid tls minimum version
  100. func isValidMinVersion(version uint16) bool {
  101. _, ok := allTLSVersions[version]
  102. return ok
  103. }
  104. // adjustMinVersion sets the MinVersion on `config`, the input configuration.
  105. // It assumes the current MinVersion on the `config` is the lowest allowed.
  106. func adjustMinVersion(options Options, config *tls.Config) error {
  107. if options.MinVersion > 0 {
  108. if !isValidMinVersion(options.MinVersion) {
  109. return fmt.Errorf("Invalid minimum TLS version: %x", options.MinVersion)
  110. }
  111. if options.MinVersion < config.MinVersion {
  112. return fmt.Errorf("Requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion)
  113. }
  114. config.MinVersion = options.MinVersion
  115. }
  116. return nil
  117. }
  118. // IsErrEncryptedKey returns true if the 'err' is an error of incorrect
  119. // password when tryin to decrypt a TLS private key
  120. func IsErrEncryptedKey(err error) bool {
  121. return errors.Cause(err) == x509.IncorrectPasswordError
  122. }
  123. // getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format.
  124. // If the private key is encrypted, 'passphrase' is used to decrypted the
  125. // private key.
  126. func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) {
  127. // this section makes some small changes to code from notary/tuf/utils/x509.go
  128. pemBlock, _ := pem.Decode(keyBytes)
  129. if pemBlock == nil {
  130. return nil, fmt.Errorf("no valid private key found")
  131. }
  132. var err error
  133. if x509.IsEncryptedPEMBlock(pemBlock) {
  134. keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase))
  135. if err != nil {
  136. return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it")
  137. }
  138. keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes})
  139. }
  140. return keyBytes, nil
  141. }
  142. // getCert returns a Certificate from the CertFile and KeyFile in 'options',
  143. // if the key is encrypted, the Passphrase in 'options' will be used to
  144. // decrypt it.
  145. func getCert(options Options) ([]tls.Certificate, error) {
  146. if options.CertFile == "" && options.KeyFile == "" {
  147. return nil, nil
  148. }
  149. errMessage := "Could not load X509 key pair"
  150. cert, err := ioutil.ReadFile(options.CertFile)
  151. if err != nil {
  152. return nil, errors.Wrap(err, errMessage)
  153. }
  154. prKeyBytes, err := ioutil.ReadFile(options.KeyFile)
  155. if err != nil {
  156. return nil, errors.Wrap(err, errMessage)
  157. }
  158. prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase)
  159. if err != nil {
  160. return nil, errors.Wrap(err, errMessage)
  161. }
  162. tlsCert, err := tls.X509KeyPair(cert, prKeyBytes)
  163. if err != nil {
  164. return nil, errors.Wrap(err, errMessage)
  165. }
  166. return []tls.Certificate{tlsCert}, nil
  167. }
  168. // Client returns a TLS configuration meant to be used by a client.
  169. func Client(options Options) (*tls.Config, error) {
  170. tlsConfig := ClientDefault()
  171. tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify
  172. if !options.InsecureSkipVerify && options.CAFile != "" {
  173. CAs, err := certPool(options.CAFile, options.ExclusiveRootPools)
  174. if err != nil {
  175. return nil, err
  176. }
  177. tlsConfig.RootCAs = CAs
  178. }
  179. tlsCerts, err := getCert(options)
  180. if err != nil {
  181. return nil, err
  182. }
  183. tlsConfig.Certificates = tlsCerts
  184. if err := adjustMinVersion(options, tlsConfig); err != nil {
  185. return nil, err
  186. }
  187. return tlsConfig, nil
  188. }
  189. // Server returns a TLS configuration meant to be used by a server.
  190. func Server(options Options) (*tls.Config, error) {
  191. tlsConfig := ServerDefault()
  192. tlsConfig.ClientAuth = options.ClientAuth
  193. tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile)
  194. if err != nil {
  195. if os.IsNotExist(err) {
  196. return nil, fmt.Errorf("Could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err)
  197. }
  198. return nil, fmt.Errorf("Error reading X509 key pair (cert: %q, key: %q): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err)
  199. }
  200. tlsConfig.Certificates = []tls.Certificate{tlsCert}
  201. if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" {
  202. CAs, err := certPool(options.CAFile, options.ExclusiveRootPools)
  203. if err != nil {
  204. return nil, err
  205. }
  206. tlsConfig.ClientCAs = CAs
  207. }
  208. if err := adjustMinVersion(options, tlsConfig); err != nil {
  209. return nil, err
  210. }
  211. return tlsConfig, nil
  212. }