You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

158 lines
4.9 KiB

  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 {
  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
  46. default:
  47. errorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode)
  48. }
  49. sslClientCertificates(&tlsConf, o)
  50. sslCertificateAuthority(&tlsConf, o)
  51. sslRenegotiation(&tlsConf)
  52. return func(conn net.Conn) net.Conn {
  53. client := tls.Client(conn, &tlsConf)
  54. if verifyCaOnly {
  55. sslVerifyCertificateAuthority(client, &tlsConf)
  56. }
  57. return client
  58. }
  59. }
  60. // sslClientCertificates adds the certificate specified in the "sslcert" and
  61. // "sslkey" settings, or if they aren't set, from the .postgresql directory
  62. // in the user's home directory. The configured files must exist and have
  63. // the correct permissions.
  64. func sslClientCertificates(tlsConf *tls.Config, o values) {
  65. // user.Current() might fail when cross-compiling. We have to ignore the
  66. // error and continue without home directory defaults, since we wouldn't
  67. // know from where to load them.
  68. user, _ := user.Current()
  69. // In libpq, the client certificate is only loaded if the setting is not blank.
  70. //
  71. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1036-L1037
  72. sslcert := o["sslcert"]
  73. if len(sslcert) == 0 && user != nil {
  74. sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
  75. }
  76. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1045
  77. if len(sslcert) == 0 {
  78. return
  79. }
  80. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1050:L1054
  81. if _, err := os.Stat(sslcert); os.IsNotExist(err) {
  82. return
  83. } else if err != nil {
  84. panic(err)
  85. }
  86. // In libpq, the ssl key is only loaded if the setting is not blank.
  87. //
  88. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1123-L1222
  89. sslkey := o["sslkey"]
  90. if len(sslkey) == 0 && user != nil {
  91. sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
  92. }
  93. if len(sslkey) > 0 {
  94. if err := sslKeyPermissions(sslkey); err != nil {
  95. panic(err)
  96. }
  97. }
  98. cert, err := tls.LoadX509KeyPair(sslcert, sslkey)
  99. if err != nil {
  100. panic(err)
  101. }
  102. tlsConf.Certificates = []tls.Certificate{cert}
  103. }
  104. // sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting.
  105. func sslCertificateAuthority(tlsConf *tls.Config, o values) {
  106. // In libpq, the root certificate is only loaded if the setting is not blank.
  107. //
  108. // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L950-L951
  109. if sslrootcert := o["sslrootcert"]; len(sslrootcert) > 0 {
  110. tlsConf.RootCAs = x509.NewCertPool()
  111. cert, err := ioutil.ReadFile(sslrootcert)
  112. if err != nil {
  113. panic(err)
  114. }
  115. if !tlsConf.RootCAs.AppendCertsFromPEM(cert) {
  116. errorf("couldn't parse pem in sslrootcert")
  117. }
  118. }
  119. }
  120. // sslVerifyCertificateAuthority carries out a TLS handshake to the server and
  121. // verifies the presented certificate against the CA, i.e. the one specified in
  122. // sslrootcert or the system CA if sslrootcert was not specified.
  123. func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) {
  124. err := client.Handshake()
  125. if err != nil {
  126. panic(err)
  127. }
  128. certs := client.ConnectionState().PeerCertificates
  129. opts := x509.VerifyOptions{
  130. DNSName: client.ConnectionState().ServerName,
  131. Intermediates: x509.NewCertPool(),
  132. Roots: tlsConf.RootCAs,
  133. }
  134. for i, cert := range certs {
  135. if i == 0 {
  136. continue
  137. }
  138. opts.Intermediates.AddCert(cert)
  139. }
  140. _, err = certs[0].Verify(opts)
  141. if err != nil {
  142. panic(err)
  143. }
  144. }