-
-
Notifications
You must be signed in to change notification settings - Fork 954
Expand file tree
/
Copy pathssl.go
More file actions
312 lines (283 loc) · 8.76 KB
/
ssl.go
File metadata and controls
312 lines (283 loc) · 8.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package pq
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/lib/pq/internal/pqutil"
)
// Registry for custom tls.Configs
var (
tlsConfs = make(map[string]*tls.Config)
tlsConfsMu sync.RWMutex
)
// RegisterTLSConfig registers a custom [tls.Config]. They are used by using
// sslmode=pqgo-«key» in the connection string.
//
// Set the config to nil to remove a configuration.
func RegisterTLSConfig(key string, config *tls.Config) error {
key = strings.TrimPrefix(key, "pqgo-")
if config == nil {
tlsConfsMu.Lock()
delete(tlsConfs, key)
tlsConfsMu.Unlock()
return nil
}
tlsConfsMu.Lock()
tlsConfs[key] = config
tlsConfsMu.Unlock()
return nil
}
func hasTLSConfig(key string) bool {
tlsConfsMu.RLock()
defer tlsConfsMu.RUnlock()
_, ok := tlsConfs[key]
return ok
}
func getTLSConfigClone(key string) *tls.Config {
tlsConfsMu.RLock()
defer tlsConfsMu.RUnlock()
if v, ok := tlsConfs[key]; ok {
return v.Clone()
}
return nil
}
// ssl generates a function to upgrade a net.Conn based on the "sslmode" and
// related settings. The function is nil when no upgrade should take place.
//
// Don't refer to Config.SSLMode here, as the mode in arguments may be different
// in case of sslmode=allow or prefer.
func ssl(cfg Config, mode SSLMode) (func(net.Conn) (net.Conn, error), error) {
var (
home = pqutil.Home(true)
// Don't set defaults here, because tlsConf may be overwritten if a
// custom one was registered. Set it after the sslmode switch.
tlsConf = &tls.Config{}
// Only verify the CA signing but not the hostname.
verifyCaOnly = false
)
if mode.useSSL() && !cfg.SSLInline && cfg.SSLRootCert == "" && home != "" {
f := filepath.Join(home, "root.crt")
if _, err := os.Stat(f); err == nil {
cfg.SSLRootCert = f
}
}
switch {
case mode == SSLModeDisable || mode == SSLModeAllow:
return nil, nil
case mode == "" || mode == SSLModeRequire || mode == SSLModePrefer:
// Skip TLS's own verification since it requires full verification.
tlsConf.InsecureSkipVerify = true
// From http://www.postgresql.org/docs/current/static/libpq-ssl.html:
//
// For backwards compatibility with earlier versions of PostgreSQL, if a
// root CA file exists, the behavior of sslmode=require will be the same
// as that of verify-ca, meaning the server certificate is validated
// against the CA. Relying on this behavior is discouraged, and
// applications that need certificate validation should always use
// verify-ca or verify-full.
if cfg.SSLRootCert != "" {
if cfg.SSLInline {
verifyCaOnly = true
} else if _, err := os.Stat(cfg.SSLRootCert); err == nil {
verifyCaOnly = true
} else if cfg.SSLRootCert != "system" {
cfg.SSLRootCert = ""
}
}
case mode == SSLModeVerifyCA:
// Skip TLS's own verification since it requires full verification.
tlsConf.InsecureSkipVerify = true
verifyCaOnly = true
case mode == SSLModeVerifyFull:
tlsConf.ServerName = cfg.Host
case strings.HasPrefix(string(mode), "pqgo-"):
tlsConf = getTLSConfigClone(string(mode[5:]))
if tlsConf == nil {
return nil, fmt.Errorf(`pq: unknown custom sslmode %q`, mode)
}
default:
panic("unreachable")
}
tlsConf.MinVersion = cfg.SSLMinProtocolVersion.tlsconf()
tlsConf.MaxVersion = cfg.SSLMaxProtocolVersion.tlsconf()
// RFC 6066 asks to not set SNI if the host is a literal IP address (IPv4 or
// IPv6). This check is coded already crypto.tls.hostnameInSNI, so just
// always set ServerName here and let crypto/tls do the filtering.
if cfg.SSLSNI {
tlsConf.ServerName = cfg.Host
}
err := sslClientCertificates(tlsConf, cfg, home)
if err != nil {
return nil, err
}
rootPem, err := sslCertificateAuthority(tlsConf, cfg)
if err != nil {
return nil, err
}
sslAppendIntermediates(tlsConf, cfg, rootPem)
// Accept renegotiation requests initiated by the backend.
//
// Renegotiation was deprecated then removed from PostgreSQL 9.5, but the
// default configuration of older versions has it enabled. Redshift also
// initiates renegotiations and cannot be reconfigured.
//
// TODO: I think this can be removed?
tlsConf.Renegotiation = tls.RenegotiateFreelyAsClient
return func(conn net.Conn) (net.Conn, error) {
client := tls.Client(conn, tlsConf)
if verifyCaOnly {
err := client.Handshake()
if err != nil {
return client, err
}
var (
certs = client.ConnectionState().PeerCertificates
opts = x509.VerifyOptions{Intermediates: x509.NewCertPool(), Roots: tlsConf.RootCAs}
)
for _, cert := range certs[1:] {
opts.Intermediates.AddCert(cert)
}
_, err = certs[0].Verify(opts)
return client, err
}
return client, nil
}, nil
}
// sslClientCertificates adds the certificate specified in the "sslcert" and
//
// "sslkey" settings, or if they aren't set, from the .postgresql directory
// in the user's home directory. The configured files must exist and have
// the correct permissions.
func sslClientCertificates(tlsConf *tls.Config, cfg Config, home string) error {
if cfg.SSLInline {
cert, err := tls.X509KeyPair([]byte(cfg.SSLCert), []byte(cfg.SSLKey))
if err != nil {
return err
}
// Use GetClientCertificate instead of the Certificates field. When
// Certificates is set, Go's TLS client only sends the cert if the
// server's CertificateRequest includes a CA that issued it. When the
// client cert was signed by an intermediate CA but the server only
// advertises the root CA, Go skips sending the cert entirely.
// GetClientCertificate bypasses this filtering.
tlsConf.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
return &cert, nil
}
return nil
}
// Only load client certificate and key if the setting is not blank, like libpq.
if cfg.SSLCert == "" && home != "" {
cfg.SSLCert = filepath.Join(home, "postgresql.crt")
}
if cfg.SSLCert == "" {
return nil
}
_, err := os.Stat(cfg.SSLCert)
if err != nil {
if pqutil.ErrNotExists(err) {
return nil
}
return err
}
// In libpq, the ssl key is only loaded if the setting is not blank.
if cfg.SSLKey == "" && home != "" {
cfg.SSLKey = filepath.Join(home, "postgresql.key")
}
if cfg.SSLKey != "" {
err := pqutil.SSLKeyPermissions(cfg.SSLKey)
if err != nil {
return err
}
}
cert, err := tls.LoadX509KeyPair(cfg.SSLCert, cfg.SSLKey)
if err != nil {
return err
}
// Using GetClientCertificate instead of Certificates per comment above.
tlsConf.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
return &cert, nil
}
return nil
}
var testSystemRoots *x509.CertPool
// sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting.
func sslCertificateAuthority(tlsConf *tls.Config, cfg Config) ([]byte, error) {
// Only load root certificate if not blank, like libpq.
if cfg.SSLRootCert == "" {
return nil, nil
}
if cfg.SSLRootCert == "system" {
// No work to do as system CAs are used by default if RootCAs is nil.
tlsConf.RootCAs = testSystemRoots
return nil, nil
}
tlsConf.RootCAs = x509.NewCertPool()
var cert []byte
if cfg.SSLInline {
cert = []byte(cfg.SSLRootCert)
} else {
var err error
cert, err = os.ReadFile(cfg.SSLRootCert)
if err != nil {
return nil, err
}
}
if !tlsConf.RootCAs.AppendCertsFromPEM(cert) {
return nil, errors.New("pq: couldn't parse pem from sslrootcert")
}
return cert, nil
}
// sslAppendIntermediates appends intermediate CA certificates from sslrootcert
// to the client certificate chain. This is needed so the server can verify the
// client cert when it was signed by an intermediate CA — without this, the TLS
// handshake only sends the leaf client cert.
func sslAppendIntermediates(tlsConf *tls.Config, cfg Config, rootPem []byte) {
if cfg.SSLRootCert == "" || tlsConf.GetClientCertificate == nil || len(rootPem) == 0 {
return
}
var (
pemData = slices.Clone(rootPem)
intermediates [][]byte
)
for {
var block *pem.Block
block, pemData = pem.Decode(pemData)
if block == nil {
break
}
if block.Type != "CERTIFICATE" {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
continue
}
// Skip self-signed root CAs; only append intermediates.
if cert.IsCA && !bytes.Equal(cert.RawIssuer, cert.RawSubject) {
intermediates = append(intermediates, block.Bytes)
}
}
if len(intermediates) == 0 {
return
}
// Wrap the existing GetClientCertificate to append intermediate certs to
// the certificate chain returned during the TLS handshake.
origGetCert := tlsConf.GetClientCertificate
tlsConf.GetClientCertificate = func(info *tls.CertificateRequestInfo) (*tls.Certificate, error) {
cert, err := origGetCert(info)
if err != nil {
return cert, err
}
cert.Certificate = append(cert.Certificate, intermediates...)
return cert, nil
}
}