ssl.go 5.1 KB

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