config.go 7.8 KB

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