-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
hba.go
244 lines (221 loc) · 6.46 KB
/
hba.go
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
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
// Package hba implements an hba.conf parser.
package hba
// conf.rl is a ragel v6.10 file containing a parser for pg_hba.conf
// files. "make" should be executed in this directory when conf.rl is
// changed. Since it is changed so rarely it is not hooked up to the top-level
// Makefile since that would require ragel being a dev dependency, which is
// an annoying burden since it's written in C and we can't auto install it
// on all systems.
import (
"fmt"
"net"
"strings"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/errors"
"github.com/olekukonko/tablewriter"
)
// Conf is a parsed configuration.
type Conf struct {
Entries []Entry
}
func (c Conf) String() string {
if len(c.Entries) == 0 {
return "# (empty configuration)\n"
}
var sb strings.Builder
table := tablewriter.NewWriter(&sb)
table.SetAutoWrapText(false)
table.SetReflowDuringAutoWrap(false)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetBorder(false)
table.SetNoWhiteSpace(true)
table.SetTrimWhiteSpaceAtEOL(true)
table.SetTablePadding(" ")
row := []string{"# TYPE", "DATABASE", "USER", "ADDRESS", "METHOD", "OPTIONS"}
table.Append(row)
for _, e := range c.Entries {
row[0] = e.Type
row[1] = e.DatabaseString()
row[2] = e.UserString()
row[3] = e.AddressString()
row[4] = e.Method
row[5] = e.OptionsString()
table.Append(row)
}
table.Render()
return sb.String()
}
// Entry is a single line of a configuration.
type Entry struct {
Type string
Database tree.NameList
AnyDatabase bool
User tree.NameList
AnyUser bool
// Address is either AnyAddr, *net.IPNet or (unsupported) tree.Name.
Address interface{}
Method string
// MethodFn is populated during name resolution of Method.
MethodFn interface{}
Options [][2]string
}
// AnyAddr represents "any address" and is used when parsing "all" for
// the "Address" field.
type AnyAddr struct{}
// String implements the fmt.Formatter interface.
func (AnyAddr) String() string { return "all" }
// GetOption returns the value of option name if there is exactly one
// occurrence of name in the options list, otherwise the empty string.
func (h Entry) GetOption(name string) string {
var val string
for _, opt := range h.Options {
if opt[0] == name {
// If there is more than one entry, return empty string.
if val != "" {
return ""
}
val = opt[1]
}
}
return val
}
// GetOptions returns all values of option name.
func (h Entry) GetOptions(name string) []string {
var val []string
for _, opt := range h.Options {
if opt[0] == name {
val = append(val, opt[1])
}
}
return val
}
// UserMatches returns true iff the provided username matches the
// first entry in the User list or if the entry matches all.
// The provided username must be normalized already.
// The function assumes the entry was normalized to contain only
// one user and its username normalized. See ParseAndNormalize().
func (h Entry) UserMatches(userName string) bool {
return h.AnyUser || userName == string(h.User[0])
}
// AddressMatches returns true iff the provided address matches the
// entry. The function assumes the entry was normalized already.
// See ParseAndNormalize.
func (h Entry) AddressMatches(addr net.IP) (bool, error) {
switch a := h.Address.(type) {
case AnyAddr:
return true, nil
case *net.IPNet:
return a.Contains(addr), nil
default:
// This is where name-based validation can occur later.
return false, errors.Newf("unknown address type: %T", addr)
}
}
// DatabaseString returns a string that describes the database field.
func (h Entry) DatabaseString() string {
if h.AnyDatabase {
return "all"
}
var sb strings.Builder
comma := ""
for _, s := range h.Database {
sb.WriteString(comma)
if s == "all" {
// Escape manually so that we don't produce the special
// HBA keyword "all".
sb.WriteString(`"all"`)
} else {
sb.WriteString(s.String())
}
comma = ","
}
return sb.String()
}
// UserString returns a string that describes the username field.
func (h Entry) UserString() string {
if h.AnyUser {
return "all"
}
var sb strings.Builder
comma := ""
for _, s := range h.User {
sb.WriteString(comma)
if s == "all" {
// Escape manually so that we don't produce the special
// HBA keyword "all".
sb.WriteString(`"all"`)
} else {
sb.WriteString(s.String())
}
comma = ","
}
return sb.String()
}
// AddressString returns a string that describes the address field.
func (h Entry) AddressString() string {
return fmt.Sprintf("%s", h.Address)
}
// OptionsString returns a string that describes the option field.
func (h Entry) OptionsString() string {
var sb strings.Builder
sp := ""
for _, opt := range h.Options {
fmt.Fprintf(&sb, "%s%s=%s", sp, opt[0], opt[1])
sp = " "
}
return sb.String()
}
// ParseAndNormalize parses the HBA configuration from the provided
// string and performs two tasks:
//
// - it unicode-normalizes the usernames. Since usernames are
// initialized during pgwire session initialization, this
// ensures that string comparisons can be used to match usernames.
//
// - it ensures there is one entry per username. This simplifies
// the code in the authentication logic.
//
func ParseAndNormalize(val string) (*Conf, error) {
conf, err := Parse(val)
if err != nil {
return nil, err
}
entries := conf.Entries[:0]
entriesCopied := false
for i := range conf.Entries {
entry := conf.Entries[i]
// The database field is not supported yet in CockroachDB.
entry.Database = nil
entry.AnyDatabase = true
// If we're observing an "any" entry, just keep that and move
// along.
if entry.AnyUser {
entries = append(entries, entry)
continue
}
// If we're about to change the size of the slice, first copy the
// result entries.
if len(entry.User) != 1 && !entriesCopied {
entries = append([]Entry(nil), conf.Entries[:len(entries)]...)
entriesCopied = true
}
// Expand and normalize the usernames.
allUsers := entry.User
for userIdx, iu := range allUsers {
entry.User = allUsers[userIdx : userIdx+1]
entry.User[0] = tree.Name(iu.Normalize())
entries = append(entries, entry)
}
}
conf.Entries = entries
return conf, nil
}