forked from Jeffail/leaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_middleware.go
236 lines (211 loc) · 6.64 KB
/
auth_middleware.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
/*
Copyright (c) 2014 Ashley Jeffs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, sub to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package net
import (
"crypto/sha1"
"encoding/base64"
"encoding/csv"
"errors"
"fmt"
"net/http"
"os"
"strings"
"golang.org/x/net/websocket"
"github.com/jeffail/util/log"
)
/*--------------------------------------------------------------------------------------------------
*/
/*
AuthMiddlewareConfig - Holds configuration options for the AuthMiddleware
*/
type AuthMiddlewareConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
PasswdFilePath string `json:"htpasswd_path" yaml:"htpasswd_path"`
}
/*
NewAuthMiddlewareConfig - Returns an AuthMiddleware configuration with the default values
*/
func NewAuthMiddlewareConfig() AuthMiddlewareConfig {
return AuthMiddlewareConfig{
Enabled: false,
PasswdFilePath: "",
}
}
/*--------------------------------------------------------------------------------------------------
*/
/*
AuthMiddleware - A construct designed to take a LeapLocator (a structure for finding and binding to
leap documents) and bind it to http clients.
*/
type AuthMiddleware struct {
config AuthMiddlewareConfig
accounts map[string]string
logger *log.Logger
stats *log.Stats
}
/*
NewAuthMiddleware - Create a new leaps AuthMiddleware.
*/
func NewAuthMiddleware(
config AuthMiddlewareConfig,
logger *log.Logger,
stats *log.Stats,
) (*AuthMiddleware, error) {
auth := AuthMiddleware{
config: config,
accounts: map[string]string{},
logger: logger.NewModule("[basic_auth]"),
stats: stats,
}
if config.Enabled {
if 0 == len(config.PasswdFilePath) {
return nil, errors.New("HTTP Auth requires a htpasswd file path in the configuration")
}
if err := auth.accountsFromFile(config.PasswdFilePath); err != nil {
return nil, fmt.Errorf("htpasswd file read error: %v", err)
}
}
return &auth, nil
}
/*--------------------------------------------------------------------------------------------------
*/
/*
WrapHandler - Wrap an http request Handler with the AuthMiddleware authentication.
*/
func (a *AuthMiddleware) WrapHandler(handler http.Handler) http.HandlerFunc {
if !a.config.Enabled {
return func(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
}
}
return func(w http.ResponseWriter, r *http.Request) {
if !a.authenticateRequest(r) {
a.requestAuth(w, r)
} else {
handler.ServeHTTP(w, r)
}
}
}
/*
WrapHandlerFunc - Wrap an http request HandlerFunc with the AuthMiddleware authentication.
*/
func (a *AuthMiddleware) WrapHandlerFunc(handler http.HandlerFunc) http.HandlerFunc {
if !a.config.Enabled {
return handler
}
return func(w http.ResponseWriter, r *http.Request) {
if !a.authenticateRequest(r) {
a.requestAuth(w, r)
} else {
handler(w, r)
}
}
}
/*
WrapWSHandler - Wrap a websocket http request handler with the AuthMiddleware authentication.
*/
func (a *AuthMiddleware) WrapWSHandler(handler websocket.Handler) websocket.Handler {
if !a.config.Enabled {
return handler
}
return func(w *websocket.Conn) {
if !a.authenticateRequest(w.Request()) {
w.Close()
} else {
handler(w)
}
}
}
/*
requestAuth - An HTTP handler that sends back a 401 (request for authentication credentials).
*/
func (a *AuthMiddleware) requestAuth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="leaps"`)
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
}
/*--------------------------------------------------------------------------------------------------
*/
/*
accountsFromFile - Extract a map of username and password hashes from a htpasswd file. MD5 hashes
are not supported, use SHA1 instead.
*/
func (a *AuthMiddleware) accountsFromFile(path string) error {
r, err := os.Open(path)
if err != nil {
return err
}
CSVReader := csv.NewReader(r)
CSVReader.Comma = ':'
CSVReader.Comment = '#'
CSVReader.FieldsPerRecord = 2
userHashes, err := CSVReader.ReadAll()
if err != nil {
return err
}
a.accounts = map[string]string{}
for _, userHash := range userHashes {
a.accounts[userHash[0]] = userHash[1]
}
return nil
}
/*
authenticateRequest - Attempts to authenticate a request using basic HTTP auth. Returns true or
false, false indicates a failed authentication.
*/
func (a *AuthMiddleware) authenticateRequest(r *http.Request) bool {
// Expected header format: AUTH_TYPE<SPACE>B64_ENCODED_CREDENTIALS
authParts := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if 2 != len(authParts) {
a.logger.Warnf("Rejecting due to auth header part count: %v != %v\n", len(authParts), 2)
return false
}
if "Basic" != authParts[0] {
a.logger.Warnf("Rejecting due to auth type: %v != Basic\n", authParts[0])
return false
}
b64Credentials := authParts[1]
decodedCredentials, err := base64.StdEncoding.DecodeString(b64Credentials)
if err != nil {
a.logger.Errorf("Failed to decode request auth credentials: %v\n", err)
return false
}
// Expected credentials format: USERNAME:PASSWORD
credentials := strings.SplitN(string(decodedCredentials), ":", 2)
if 2 != len(credentials) {
a.logger.Warnf("Rejecting due to credential count: %v != %v\n", len(credentials), 2)
return false
}
passHash, ok := a.accounts[credentials[0]]
if !ok {
a.logger.Warnf("Rejecting due to non-existant account: %v\n", credentials[0])
return false
}
if strings.HasPrefix(passHash, "{SHA}") {
shaGen := sha1.New()
shaGen.Write([]byte(credentials[1]))
if passHash[5:] != base64.StdEncoding.EncodeToString(shaGen.Sum(nil)) {
a.logger.Warnf("Rejecting due to wrong password for account: %v\n", credentials[0])
return false
}
} // Only support SHA1 right now.
return true
}
/*--------------------------------------------------------------------------------------------------
*/