Skip to content

Commit 1a976f7

Browse files
sean-jackc
andcommitted
pgconn: add require_auth to restrict accepted server auth methods
The auth dispatch loop in connectOne unconditionally honored whatever Authentication* message the server sent, including AuthenticationCleartextPassword and AuthenticationMD5Password. Combined with the default sslmode=prefer (silent plaintext fallback), an active MITM could intercept SSLRequest, reply N, request cleartext, and capture the user's password. Add a RequireAuth config field with libpq-compatible semantics: a comma-separated list of method names (password, md5, gss, sspi, scram-sha-256, oauth, none), optionally each "!"-prefixed to negate. Negated and non-negated entries cannot be mixed; duplicates are rejected. Wire up PGREQUIREAUTH and PGCHANNELBINDING env vars. Enforcement happens in the connectOne auth loop: each Authentication{Cleartext,MD5Password,SASL,GSS} message is checked before any reply is sent, and AuthenticationOk is rejected when authRequired && !clientFinishedAuth. SASL distinguishes the OAUTHBEARER and SCRAM paths so require_auth=scram-sha-256 does not permit OAuth and vice versa. Parsing happens both at ParseConfig time (to fail fast on bad values) and at connect time, so callers who mutate Config.RequireAuth after ParseConfig see their change take effect — the parser is pure and cheap. Reported by CrowdStrike (F02). Mirrors libpq's require_auth (PG16+). Co-Authored-By: Jack Christensen <[email protected]>
1 parent 39a7fab commit 1a976f7

4 files changed

Lines changed: 272 additions & 0 deletions

File tree

‎pgconn/config.go‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,13 @@ type Config struct {
9999
// Valid values: "disable", "prefer", "require". Defaults to "prefer".
100100
ChannelBinding string
101101

102+
// RequireAuth restricts which authentication methods the client will accept from the server,
103+
// matching libpq's require_auth parameter. It is a comma-separated list of method names
104+
// (password, md5, gss, sspi, scram-sha-256, oauth, none). A leading "!" on every entry negates
105+
// the list (forbid these methods, allow all others). Empty (the default) means all methods are
106+
// accepted.
107+
RequireAuth string
108+
102109
createdByParseConfig bool // Used to enforce created by ParseConfig rule.
103110
}
104111

@@ -357,6 +364,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
357364
"min_protocol_version": {},
358365
"max_protocol_version": {},
359366
"channel_binding": {},
367+
"require_auth": {},
360368
}
361369

362370
// Adding kerberos configuration
@@ -495,6 +503,11 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
495503
return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("unknown channel_binding value: %v", channelBinding)}
496504
}
497505

506+
config.RequireAuth = settings["require_auth"]
507+
if _, err := parseRequireAuth(config.RequireAuth); err != nil {
508+
return nil, &ParseConfigError{ConnString: connString, msg: "invalid require_auth", err: err}
509+
}
510+
498511
return config, nil
499512
}
500513

@@ -534,6 +547,8 @@ func parseEnvSettings() map[string]string {
534547
"PGOPTIONS": "options",
535548
"PGMINPROTOCOLVERSION": "min_protocol_version",
536549
"PGMAXPROTOCOLVERSION": "max_protocol_version",
550+
"PGCHANNELBINDING": "channel_binding",
551+
"PGREQUIREAUTH": "require_auth",
537552
}
538553

539554
for envname, realname := range nameMap {

‎pgconn/pgconn.go‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,21 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
412412
return nil, newPerDialConnectError("failed to write startup message", err)
413413
}
414414

415+
// Parse require_auth on each connect so that callers who mutate
416+
// Config.RequireAuth after ParseConfig see their change take effect.
417+
// The parser is pure and cheap; ParseConfigWithOptions validates the
418+
// value up front so any parse error here indicates post-parse mutation.
419+
requireAuthPolicy, err := parseRequireAuth(config.RequireAuth)
420+
if err != nil {
421+
pgConn.conn.Close()
422+
return nil, newPerDialConnectError("invalid require_auth", err)
423+
}
424+
requireAuthFail := func(err error) (*PgConn, error) {
425+
pgConn.conn.Close()
426+
return nil, newPerDialConnectError("require_auth check failed", err)
427+
}
428+
clientFinishedAuth := false
429+
415430
for {
416431
msg, err := pgConn.receiveMessage()
417432
if err != nil {
@@ -428,19 +443,30 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
428443
pgConn.secretKey = msg.SecretKey
429444

430445
case *pgproto3.AuthenticationOk:
446+
if requireAuthPolicy.authRequired && !clientFinishedAuth {
447+
return requireAuthFail(requireAuthPolicy.check(authMethodNone))
448+
}
431449
case *pgproto3.AuthenticationCleartextPassword:
450+
if err := requireAuthPolicy.check(authMethodPassword); err != nil {
451+
return requireAuthFail(err)
452+
}
432453
err = pgConn.txPasswordMessage(pgConn.config.Password)
433454
if err != nil {
434455
pgConn.conn.Close()
435456
return nil, newPerDialConnectError("failed to write password message", err)
436457
}
458+
clientFinishedAuth = true
437459
case *pgproto3.AuthenticationMD5Password:
460+
if err := requireAuthPolicy.check(authMethodMD5); err != nil {
461+
return requireAuthFail(err)
462+
}
438463
digestedPassword := "md5" + hexMD5(hexMD5(pgConn.config.Password+pgConn.config.User)+string(msg.Salt[:]))
439464
err = pgConn.txPasswordMessage(digestedPassword)
440465
if err != nil {
441466
pgConn.conn.Close()
442467
return nil, newPerDialConnectError("failed to write password message", err)
443468
}
469+
clientFinishedAuth = true
444470
case *pgproto3.AuthenticationSASL:
445471
// Check if OAUTHBEARER is supported
446472
serverSupportsOAuthBearer := false
@@ -452,20 +478,31 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
452478
}
453479

454480
if serverSupportsOAuthBearer && pgConn.config.OAuthTokenProvider != nil {
481+
if err := requireAuthPolicy.check(authMethodOAuth); err != nil {
482+
return requireAuthFail(err)
483+
}
455484
err = pgConn.oauthAuth(ctx)
456485
} else {
486+
if err := requireAuthPolicy.check(authMethodSCRAMSHA256); err != nil {
487+
return requireAuthFail(err)
488+
}
457489
err = pgConn.scramAuth(msg.AuthMechanisms)
458490
}
459491
if err != nil {
460492
pgConn.conn.Close()
461493
return nil, newPerDialConnectError("failed SASL auth", err)
462494
}
495+
clientFinishedAuth = true
463496
case *pgproto3.AuthenticationGSS:
497+
if err := requireAuthPolicy.check(authMethodGSS); err != nil {
498+
return requireAuthFail(err)
499+
}
464500
err = pgConn.gssAuth()
465501
if err != nil {
466502
pgConn.conn.Close()
467503
return nil, newPerDialConnectError("failed GSS auth", err)
468504
}
505+
clientFinishedAuth = true
469506
case *pgproto3.ReadyForQuery:
470507
pgConn.status = connStatusIdle
471508
// The connect-phase deadline-only watcher is no longer needed; replace

‎pgconn/require_auth.go‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
package pgconn
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
)
7+
8+
// authMethod is one of the method keywords accepted by libpq's require_auth.
9+
type authMethod uint8
10+
11+
const (
12+
authMethodPassword authMethod = iota
13+
authMethodMD5
14+
authMethodGSS
15+
authMethodSSPI
16+
authMethodSCRAMSHA256
17+
authMethodOAuth
18+
authMethodNone
19+
authMethodCount
20+
)
21+
22+
var authMethodNames = [authMethodCount]string{
23+
authMethodPassword: "password",
24+
authMethodMD5: "md5",
25+
authMethodGSS: "gss",
26+
authMethodSSPI: "sspi",
27+
authMethodSCRAMSHA256: "scram-sha-256",
28+
authMethodOAuth: "oauth",
29+
authMethodNone: "none",
30+
}
31+
32+
// requireAuth is the parsed form of the require_auth connection parameter. It mirrors libpq's
33+
// auth_required / allowed_auth_methods bookkeeping (see fe-connect.c, conn->allowed_auth_methods).
34+
type requireAuth struct {
35+
// raw is the original parameter value, used in error messages.
36+
raw string
37+
38+
// authRequired is true when the server must complete an authentication exchange before sending
39+
// AuthenticationOk. It is false when the parameter is unset, fully negated, or "none" is in the
40+
// allowed set.
41+
authRequired bool
42+
43+
// allowed is a bitmask of permitted authMethod values.
44+
allowed uint8
45+
}
46+
47+
func (ra requireAuth) allows(m authMethod) bool {
48+
return ra.allowed&(1<<m) != 0
49+
}
50+
51+
// check returns an error if method m is not permitted by the policy. The reason is phrased to
52+
// follow libpq's "authentication method requirement \"%s\" failed: %s" form so users migrating
53+
// from libpq see familiar diagnostics.
54+
func (ra requireAuth) check(m authMethod) error {
55+
if ra.allows(m) {
56+
return nil
57+
}
58+
var reason string
59+
if m == authMethodNone {
60+
reason = "server did not complete authentication"
61+
} else {
62+
reason = fmt.Sprintf("server requested %s authentication", authMethodNames[m])
63+
}
64+
return fmt.Errorf("authentication method requirement %q failed: %s", ra.raw, reason)
65+
}
66+
67+
// parseRequireAuth parses the require_auth connection parameter with libpq-compatible semantics:
68+
// a comma-separated list of method names, optionally each prefixed with "!" to negate. Negated and
69+
// non-negated entries cannot be mixed; duplicate entries are rejected. An empty string yields a
70+
// permissive policy (all methods allowed, no authentication required).
71+
func parseRequireAuth(s string) (requireAuth, error) {
72+
ra := requireAuth{raw: s}
73+
74+
if s == "" {
75+
ra.allowed = 1<<authMethodCount - 1
76+
return ra, nil
77+
}
78+
79+
first := true
80+
negated := false
81+
for part := range strings.SplitSeq(s, ",") {
82+
method := strings.TrimSpace(part)
83+
84+
neg := strings.HasPrefix(method, "!")
85+
if neg {
86+
method = method[1:]
87+
}
88+
if first {
89+
negated = neg
90+
if negated {
91+
// A negated list starts from "everything allowed, auth not required" and removes
92+
// methods; "!none" below flips authRequired back on.
93+
ra.allowed = 1<<authMethodCount - 1
94+
} else {
95+
ra.authRequired = true
96+
}
97+
first = false
98+
} else if neg != negated {
99+
if neg {
100+
return requireAuth{}, fmt.Errorf("negative require_auth method %q cannot be mixed with non-negative methods", method)
101+
}
102+
return requireAuth{}, fmt.Errorf("require_auth method %q cannot be mixed with negative methods", method)
103+
}
104+
105+
var m authMethod
106+
switch method {
107+
case "password":
108+
m = authMethodPassword
109+
case "md5":
110+
m = authMethodMD5
111+
case "gss":
112+
m = authMethodGSS
113+
case "sspi":
114+
m = authMethodSSPI
115+
case "scram-sha-256":
116+
m = authMethodSCRAMSHA256
117+
case "oauth":
118+
m = authMethodOAuth
119+
case "none":
120+
m = authMethodNone
121+
default:
122+
return requireAuth{}, fmt.Errorf("invalid require_auth method: %q", method)
123+
}
124+
125+
bit := uint8(1) << m
126+
if negated {
127+
if ra.allowed&bit == 0 {
128+
return requireAuth{}, fmt.Errorf("require_auth method %q is specified more than once", part)
129+
}
130+
ra.allowed &^= bit
131+
if m == authMethodNone {
132+
ra.authRequired = true
133+
}
134+
} else {
135+
if ra.allowed&bit != 0 {
136+
return requireAuth{}, fmt.Errorf("require_auth method %q is specified more than once", part)
137+
}
138+
ra.allowed |= bit
139+
if m == authMethodNone {
140+
ra.authRequired = false
141+
}
142+
}
143+
}
144+
145+
return ra, nil
146+
}

‎pgconn/require_auth_test.go‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package pgconn
2+
3+
import (
4+
"strings"
5+
"testing"
6+
)
7+
8+
func TestParseRequireAuth(t *testing.T) {
9+
type want struct {
10+
authRequired bool
11+
allow []authMethod
12+
forbid []authMethod
13+
}
14+
for _, tc := range []struct {
15+
in string
16+
want want
17+
err string
18+
}{
19+
{in: "", want: want{authRequired: false, allow: []authMethod{authMethodPassword, authMethodMD5, authMethodGSS, authMethodSSPI, authMethodSCRAMSHA256, authMethodOAuth, authMethodNone}}},
20+
{in: "scram-sha-256", want: want{authRequired: true, allow: []authMethod{authMethodSCRAMSHA256}, forbid: []authMethod{authMethodPassword, authMethodMD5, authMethodNone}}},
21+
{in: "md5,scram-sha-256", want: want{authRequired: true, allow: []authMethod{authMethodMD5, authMethodSCRAMSHA256}, forbid: []authMethod{authMethodPassword, authMethodNone}}},
22+
{in: "none", want: want{authRequired: false, allow: []authMethod{authMethodNone}, forbid: []authMethod{authMethodPassword, authMethodSCRAMSHA256}}},
23+
{in: "scram-sha-256,none", want: want{authRequired: false, allow: []authMethod{authMethodSCRAMSHA256, authMethodNone}, forbid: []authMethod{authMethodPassword}}},
24+
{in: "!password", want: want{authRequired: false, allow: []authMethod{authMethodMD5, authMethodSCRAMSHA256, authMethodNone}, forbid: []authMethod{authMethodPassword}}},
25+
{in: "!password,!md5", want: want{authRequired: false, allow: []authMethod{authMethodSCRAMSHA256, authMethodGSS, authMethodNone}, forbid: []authMethod{authMethodPassword, authMethodMD5}}},
26+
{in: "!none", want: want{authRequired: true, allow: []authMethod{authMethodPassword, authMethodMD5, authMethodSCRAMSHA256}, forbid: []authMethod{authMethodNone}}},
27+
{in: " scram-sha-256 , md5 ", want: want{authRequired: true, allow: []authMethod{authMethodSCRAMSHA256, authMethodMD5}, forbid: []authMethod{authMethodPassword}}},
28+
29+
{in: "bogus", err: "invalid require_auth method"},
30+
{in: "md5,md5", err: "specified more than once"},
31+
{in: "!md5,!md5", err: "specified more than once"},
32+
{in: "md5,!password", err: "cannot be mixed"},
33+
{in: "!md5,password", err: "cannot be mixed"},
34+
} {
35+
t.Run(tc.in, func(t *testing.T) {
36+
ra, err := parseRequireAuth(tc.in)
37+
if tc.err != "" {
38+
if err == nil || !strings.Contains(err.Error(), tc.err) {
39+
t.Fatalf("expected error containing %q, got %v", tc.err, err)
40+
}
41+
return
42+
}
43+
if err != nil {
44+
t.Fatalf("unexpected error: %v", err)
45+
}
46+
if ra.authRequired != tc.want.authRequired {
47+
t.Errorf("authRequired = %v, want %v", ra.authRequired, tc.want.authRequired)
48+
}
49+
for _, m := range tc.want.allow {
50+
if !ra.allows(m) {
51+
t.Errorf("expected %s allowed", authMethodNames[m])
52+
}
53+
}
54+
for _, m := range tc.want.forbid {
55+
if ra.allows(m) {
56+
t.Errorf("expected %s forbidden", authMethodNames[m])
57+
}
58+
}
59+
})
60+
}
61+
}
62+
63+
func TestRequireAuthCheckMessages(t *testing.T) {
64+
ra, _ := parseRequireAuth("scram-sha-256")
65+
if err := ra.check(authMethodSCRAMSHA256); err != nil {
66+
t.Fatalf("scram-sha-256 should be allowed: %v", err)
67+
}
68+
if err := ra.check(authMethodPassword); err == nil || !strings.Contains(err.Error(), `requirement "scram-sha-256" failed: server requested password`) {
69+
t.Fatalf("wrong error for password: %v", err)
70+
}
71+
if err := ra.check(authMethodNone); err == nil || !strings.Contains(err.Error(), "server did not complete authentication") {
72+
t.Fatalf("wrong error for none: %v", err)
73+
}
74+
}

0 commit comments

Comments
 (0)