本站源代码
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

176 lines
5.4KB

  1. package pq
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "os/user"
  9. "path/filepath"
  10. )
  11. // ssl generates a function to upgrade a net.Conn based on the "sslmode" and
  12. // related settings. The function is nil when no upgrade should take place.
  13. func ssl(o values) (func(net.Conn) (net.Conn, error), error) {
  14. verifyCaOnly := false
  15. tlsConf := tls.Config{}
  16. switch mode := o["sslmode"]; mode {
  17. // "require" is the default.
  18. case "", "require":
  19. // We must skip TLS's own verification since it requires full
  20. // verification since Go 1.3.
  21. tlsConf.InsecureSkipVerify = true
  22. // From http://www.postgresql.org/docs/current/static/libpq-ssl.html:
  23. //
  24. // Note: For backwards compatibility with earlier versions of
  25. // PostgreSQL, if a root CA file exists, the behavior of
  26. // sslmode=require will be the same as that of verify-ca, meaning the
  27. // server certificate is validated against the CA. Relying on this
  28. // behavior is discouraged, and applications that need certificate
  29. // validation should always use verify-ca or verify-full.
  30. if sslrootcert, ok := o["sslrootcert"]; ok {
  31. if _, err := os.Stat(sslrootcert); err == nil {
  32. verifyCaOnly = true
  33. } else {
  34. delete(o, "sslrootcert")
  35. }
  36. }
  37. case "verify-ca":
  38. // We must skip TLS's own verification since it requires full
  39. // verification since Go 1.3.
  40. tlsConf.InsecureSkipVerify = true
  41. verifyCaOnly = true
  42. case "verify-full":
  43. tlsConf.ServerName = o["host"]
  44. case "disable":
  45. return nil, nil
  46. default:
  47. return nil, fmterrorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode)
  48. }
  49. err := sslClientCertificates(&tlsConf, o)
  50. if err != nil {
  51. return nil, err
  52. }
  53. err = sslCertificateAuthority(&tlsConf, o)
  54. if err != nil {
  55. return nil, err
  56. }
  57. // Accept renegotiation requests initiated by the backend.
  58. //
  59. // Renegotiation was deprecated then removed from PostgreSQL 9.5, but
  60. // the default configuration of older versions has it enabled. Redshift
  61. // also initiates renegotiations and cannot be reconfigured.
  62. tlsConf.Renegotiation = tls.RenegotiateFreelyAsClient
  63. return func(conn net.Conn) (net.Conn, error) {
  64. client := tls.Client(conn, &tlsConf)
  65. if verifyCaOnly {
  66. err := sslVerifyCertificateAuthority(client, &tlsConf)
  67. if err != nil {
  68. return nil, err
  69. }
  70. }
  71. return client, nil
  72. }, nil
  73. }
  74. // sslClientCertificates adds the certificate specified in the "sslcert" and
  75. // "sslkey" settings, or if they aren't set, from the .postgresql directory
  76. // in the user's home directory. The configured files must exist and have
  77. // the correct permissions.
  78. func sslClientCertificates(tlsConf *tls.Config, o values) error {
  79. // user.Current() might fail when cross-compiling. We have to ignore the
  80. // error and continue without home directory defaults, since we wouldn't
  81. // know from where to load them.
  82. user, _ := user.Current()
  83. // In libpq, the client certificate is only loaded if the setting is not blank.
  84. //
  85. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1036-L1037
  86. sslcert := o["sslcert"]
  87. if len(sslcert) == 0 && user != nil {
  88. sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
  89. }
  90. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1045
  91. if len(sslcert) == 0 {
  92. return nil
  93. }
  94. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1050:L1054
  95. if _, err := os.Stat(sslcert); os.IsNotExist(err) {
  96. return nil
  97. } else if err != nil {
  98. return err
  99. }
  100. // In libpq, the ssl key is only loaded if the setting is not blank.
  101. //
  102. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1123-L1222
  103. sslkey := o["sslkey"]
  104. if len(sslkey) == 0 && user != nil {
  105. sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
  106. }
  107. if len(sslkey) > 0 {
  108. if err := sslKeyPermissions(sslkey); err != nil {
  109. return err
  110. }
  111. }
  112. cert, err := tls.LoadX509KeyPair(sslcert, sslkey)
  113. if err != nil {
  114. return err
  115. }
  116. tlsConf.Certificates = []tls.Certificate{cert}
  117. return nil
  118. }
  119. // sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting.
  120. func sslCertificateAuthority(tlsConf *tls.Config, o values) error {
  121. // In libpq, the root certificate is only loaded if the setting is not blank.
  122. //
  123. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L950-L951
  124. if sslrootcert := o["sslrootcert"]; len(sslrootcert) > 0 {
  125. tlsConf.RootCAs = x509.NewCertPool()
  126. cert, err := ioutil.ReadFile(sslrootcert)
  127. if err != nil {
  128. return err
  129. }
  130. if !tlsConf.RootCAs.AppendCertsFromPEM(cert) {
  131. return fmterrorf("couldn't parse pem in sslrootcert")
  132. }
  133. }
  134. return nil
  135. }
  136. // sslVerifyCertificateAuthority carries out a TLS handshake to the server and
  137. // verifies the presented certificate against the CA, i.e. the one specified in
  138. // sslrootcert or the system CA if sslrootcert was not specified.
  139. func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) error {
  140. err := client.Handshake()
  141. if err != nil {
  142. return err
  143. }
  144. certs := client.ConnectionState().PeerCertificates
  145. opts := x509.VerifyOptions{
  146. DNSName: client.ConnectionState().ServerName,
  147. Intermediates: x509.NewCertPool(),
  148. Roots: tlsConf.RootCAs,
  149. }
  150. for i, cert := range certs {
  151. if i == 0 {
  152. continue
  153. }
  154. opts.Intermediates.AddCert(cert)
  155. }
  156. _, err = certs[0].Verify(opts)
  157. return err
  158. }
上海开阖软件有限公司 沪ICP备12045867号-1