Debian Codegraph @

modules/caddyhttp/caddyauth/basicauth.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddyauth
16
17 import (
18 "encoding/base64"
19 "encoding/hex"
20 "encoding/json"
21 "fmt"
22 weakrand "math/rand/v2"
23 "net/http"
24 "strings"
25 "sync"
26
27 "golang.org/x/sync/singleflight"
28
29 "github.com/caddyserver/caddy/v2"
30 )
31
32 func init() {
33 caddy.RegisterModule(HTTPBasicAuth{})
34 }
35
36 // HTTPBasicAuth facilitates HTTP basic authentication.
37 type HTTPBasicAuth struct {
38 // The algorithm with which the passwords are hashed. Default: bcrypt
39 HashRaw json.RawMessage `json:"hash,omitempty" caddy:"namespace=http.authentication.hashes inline_key=algorithm"`
40
41 // The list of accounts to authenticate.
42 AccountList []Account `json:"accounts,omitempty"`
43
44 // The name of the realm. Default: restricted
45 Realm string `json:"realm,omitempty"`
46
47 // If non-nil, a mapping of plaintext passwords to their
48 // hashes will be cached in memory (with random eviction).
49 // This can greatly improve the performance of traffic-heavy
50 // servers that use secure password hashing algorithms, with
51 // the downside that plaintext passwords will be stored in
52 // memory for a longer time (this should not be a problem
53 // as long as your machine is not compromised, at which point
54 // all bets are off, since basicauth necessitates plaintext
55 // passwords being received over the wire anyway). Note that
56 // a cache hit does not mean it is a valid password.
57 HashCache *Cache `json:"hash_cache,omitempty"`
58
59 Accounts map[string]Account `json:"-"`
60 Hash Comparer `json:"-"`
61
62 // fakePassword is used when a given user is not found,
63 // so that timing side-channels can be mitigated: it gives
64 // us something to hash and compare even if the user does
65 // not exist, which should have similar timing as a user
66 // account that does exist.
67 fakePassword []byte
68 }
69
70 // CaddyModule returns the Caddy module information.
71 func (HTTPBasicAuth) CaddyModule() caddy.ModuleInfo {
72 return caddy.ModuleInfo{
73 ID: "http.authentication.providers.http_basic",
74 New: func() caddy.Module { return new(HTTPBasicAuth) },
75 }
76 }
77
78 // Provision provisions the HTTP basic auth provider.
79 func (hba *HTTPBasicAuth) Provision(ctx caddy.Context) error {
80 if hba.HashRaw == nil {
81 hba.HashRaw = json.RawMessage(`{"algorithm": "bcrypt"}`)
82 }
83
84 // load password hasher
85 hasherIface, err := ctx.LoadModule(hba, "HashRaw")
86 if err != nil {
87 return fmt.Errorf("loading password hasher module: %v", err)
88 }
89 hba.Hash = hasherIface.(Comparer)
90
91 if hba.Hash == nil {
92 return fmt.Errorf("hash is required")
93 }
94
95 // if supported, generate a fake password we can compare against if needed
96 if hasher, ok := hba.Hash.(Hasher); ok {
97 hba.fakePassword = hasher.FakeHash()
98 }
99
100 repl := caddy.NewReplacer()
101
102 // load account list
103 hba.Accounts = make(map[string]Account)
104 for i, acct := range hba.AccountList {
105 if _, ok := hba.Accounts[acct.Username]; ok {
106 return fmt.Errorf("account %d: username is not unique: %s", i, acct.Username)
107 }
108
109 acct.Username = repl.ReplaceAll(acct.Username, "")
110 acct.Password = repl.ReplaceAll(acct.Password, "")
111
112 if acct.Username == "" || acct.Password == "" {
113 return fmt.Errorf("account %d: username and password are required", i)
114 }
115
116 // TODO: Remove support for redundantly-encoded b64-encoded hashes
117 // Passwords starting with '$' are likely in Modular Crypt Format,
118 // so we don't need to base64 decode them. But historically, we
119 // required redundant base64, so we try to decode it otherwise.
120 if strings.HasPrefix(acct.Password, "$") {
121 acct.password = []byte(acct.Password)
122 } else {
123 acct.password, err = base64.StdEncoding.DecodeString(acct.Password)
124 if err != nil {
125 return fmt.Errorf("base64-decoding password: %v", err)
126 }
127 }
128
129 hba.Accounts[acct.Username] = acct
130 }
131 hba.AccountList = nil // allow GC to deallocate
132
133 if hba.HashCache != nil {
134 hba.HashCache.cache = make(map[string]bool)
135 hba.HashCache.mu = new(sync.RWMutex)
136 hba.HashCache.g = new(singleflight.Group)
137 }
138
139 return nil
140 }
141
142 // Authenticate validates the user credentials in req and returns the user, if valid.
143 func (hba HTTPBasicAuth) Authenticate(w http.ResponseWriter, req *http.Request) (User, bool, error) {
144 username, plaintextPasswordStr, ok := req.BasicAuth()
145 if !ok {
146 return hba.promptForCredentials(w, nil)
147 }
148
149 account, accountExists := hba.Accounts[username]
150 if !accountExists {
151 // don't return early if account does not exist; we want
152 // to try to avoid side-channels that leak existence, so
153 // we use a fake password to simulate realistic CPU cycles
154 account.password = hba.fakePassword
155 }
156
157 same, err := hba.correctPassword(account, []byte(plaintextPasswordStr))
158 if err != nil || !same || !accountExists {
159 return hba.promptForCredentials(w, err)
160 }
161
162 return User{ID: username}, true, nil
163 }
164
165 func (hba HTTPBasicAuth) correctPassword(account Account, plaintextPassword []byte) (bool, error) {
166 compare := func() (bool, error) {
167 return hba.Hash.Compare(account.password, plaintextPassword)
168 }
169
170 // if no caching is enabled, simply return the result of hashing + comparing
171 if hba.HashCache == nil {
172 return compare()
173 }
174
175 // compute a cache key that is unique for these input parameters
176 cacheKey := hex.EncodeToString(append(account.password, plaintextPassword...))
177
178 // fast track: if the result of the input is already cached, use it
179 hba.HashCache.mu.RLock()
180 same, ok := hba.HashCache.cache[cacheKey]
181 hba.HashCache.mu.RUnlock()
182 if ok {
183 return same, nil
184 }
185 // slow track: do the expensive op, then add it to the cache
186 // but perform it in a singleflight group so that multiple
187 // parallel requests using the same password don't cause a
188 // thundering herd problem by all performing the same hashing
189 // operation before the first one finishes and caches it.
190 v, err, _ := hba.HashCache.g.Do(cacheKey, func() (any, error) {
191 return compare()
192 })
193 if err != nil {
194 return false, err
195 }
196 same = v.(bool)
197 hba.HashCache.mu.Lock()
198 if len(hba.HashCache.cache) >= 1000 {
199 hba.HashCache.makeRoom() // keep cache size under control
200 }
201 hba.HashCache.cache[cacheKey] = same
202 hba.HashCache.mu.Unlock()
203
204 return same, nil
205 }
206
207 func (hba HTTPBasicAuth) promptForCredentials(w http.ResponseWriter, err error) (User, bool, error) {
208 // browsers show a message that says something like:
209 // "The website says: <realm>"
210 // which is kinda dumb, but whatever.
211 realm := hba.Realm
212 if realm == "" {
213 realm = "restricted"
214 }
215 w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
216 return User{}, false, err
217 }
218
219 // Cache enables caching of basic auth results. This is especially
220 // helpful for secure password hashes which can be expensive to
221 // compute on every HTTP request.
222 type Cache struct {
223 mu *sync.RWMutex
224 g *singleflight.Group
225
226 // map of concatenated hashed password + plaintext password, to result
227 cache map[string]bool
228 }
229
230 // makeRoom deletes about 1/10 of the items in the cache
231 // in order to keep its size under control. It must not be
232 // called without a lock on c.mu.
233 func (c *Cache) makeRoom() {
234 // we delete more than just 1 entry so that we don't have
235 // to do this on every request; assuming the capacity of
236 // the cache is on a long tail, we can save a lot of CPU
237 // time by doing a whole bunch of deletions now and then
238 // we won't have to do them again for a while
239 numToDelete := max(len(c.cache)/10, 1)
240 for deleted := 0; deleted <= numToDelete; deleted++ {
241 // Go maps are "nondeterministic" not actually random,
242 // so although we could just chop off the "front" of the
243 // map with less code, this is a heavily skewed eviction
244 // strategy; generating random numbers is cheap and
245 // ensures a much better distribution.
246 //nolint:gosec
247 rnd := weakrand.IntN(len(c.cache))
248 i := 0
249 for key := range c.cache {
250 if i == rnd {
251 delete(c.cache, key)
252 break
253 }
254 i++
255 }
256 }
257 }
258
259 // Comparer is a type that can securely compare
260 // a plaintext password with a hashed password
261 // in constant-time. Comparers should hash the
262 // plaintext password and then use constant-time
263 // comparison.
264 type Comparer interface {
265 // Compare returns true if the result of hashing
266 // plaintextPassword is hashedPassword, false
267 // otherwise. An error is returned only if
268 // there is a technical/configuration error.
269 Compare(hashedPassword, plaintextPassword []byte) (bool, error)
270 }
271
272 // Hasher is a type that can generate a secure hash
273 // given a plaintext. Hashing modules which implement
274 // this interface can be used with the hash-password
275 // subcommand as well as benefitting from anti-timing
276 // features. A hasher also returns a fake hash which
277 // can be used for timing side-channel mitigation.
278 type Hasher interface {
279 Hash(plaintext []byte) ([]byte, error)
280 FakeHash() []byte
281 }
282
283 // Account contains a username and password.
284 type Account struct {
285 // A user's username.
286 Username string `json:"username"`
287
288 // The user's hashed password, in Modular Crypt Format (with `$` prefix)
289 // or base64-encoded.
290 Password string `json:"password"` //nolint:gosec // false positive, this is a hashed password
291
292 password []byte
293 }
294
295 // Interface guards
296 var (
297 _ caddy.Provisioner = (*HTTPBasicAuth)(nil)
298 _ Authenticator = (*HTTPBasicAuth)(nil)
299 )