This repository has been archived by the owner on Jun 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
userauth.go
260 lines (237 loc) · 7.44 KB
/
userauth.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package main
import (
"bufio"
"crypto/x509"
"encoding/csv"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"regexp"
"github.com/dgrijalva/jwt-go"
"github.com/lestrrat/go-jwx/jwk"
"github.com/minio/minio-go/v6/pkg/s3signer"
log "github.com/sirupsen/logrus"
)
// Authenticator is an interface that takes care of authenticating users to the
// S3 proxy. It contains only one method, Authenticate.
type Authenticator interface {
// Authenticate inspects an http.Request and returns nil if the user is
// authenticated, otherwise an error is returned.
Authenticate(r *http.Request) error
}
// AlwaysAllow is an Authenticator that always authenticates
type AlwaysAllow struct{}
// NewAlwaysAllow returns a new AlwaysAllow authenticator.
func NewAlwaysAllow() *AlwaysAllow {
return &AlwaysAllow{}
}
// Authenticate authenticates everyone.
func (u *AlwaysAllow) Authenticate(r *http.Request) error {
return nil
}
// ValidateFromFile is an Authenticator that reads client ids and secret ids
// from a file.
type ValidateFromFile struct {
filename string
}
// NewValidateFromFile returns a new ValidateFromFile, reading users from the
// supplied file.
func NewValidateFromFile(filename string) *ValidateFromFile {
return &ValidateFromFile{filename}
}
// ValidateFromToken is an Authenticator that reads the public key from
// supplied file
type ValidateFromToken struct {
pubkeys map[string][]byte
}
// NewValidateFromToken returns a new ValidateFromToken, reading the key from
// the supplied file.
func NewValidateFromToken(pubkeys map[string][]byte) *ValidateFromToken {
return &ValidateFromToken{pubkeys}
}
// Authenticate checks whether the http.Request is signed by any of the users
// in the supplied file.
func (u *ValidateFromFile) Authenticate(r *http.Request) error {
re := regexp.MustCompile("Credential=([^/]+)/")
curAccessKey := ""
if tmp := re.FindStringSubmatch(r.Header.Get("Authorization")); tmp != nil {
// Check if user requested own bucket
curAccessKey = tmp[1]
re := regexp.MustCompile("/([^/]+)/")
if curAccessKey != re.FindStringSubmatch(r.URL.Path)[1] {
return fmt.Errorf("user not authorized to access location")
}
} else {
log.Debug("User not found in signature")
return fmt.Errorf("user not found in signature")
}
if curSecretKey, err := u.secretFromID(curAccessKey); err == nil {
if r.Method == http.MethodGet {
re := regexp.MustCompile("Signature=(.*)")
signature := re.FindStringSubmatch(r.Header.Get("Authorization"))
if signature == nil {
return fmt.Errorf("user signature not found")
}
// Create signing request
nr, e := http.NewRequest(r.Method, r.URL.String(), r.Body)
if e != nil {
log.Debug("error creating the new request")
log.Debug(e)
}
// Add required headers
nr.Header.Set("X-Amz-Date", r.Header.Get("X-Amz-Date"))
nr.Header.Set("X-Amz-Content-Sha256", r.Header.Get("X-Amz-Content-Sha256"))
nr.Host = r.Host
nr.URL.RawQuery = r.URL.RawQuery
// Sign the new request
s3signer.SignV4(*nr, curAccessKey, curSecretKey, "", "us-east-1")
curSignature := re.FindStringSubmatch(nr.Header.Get("Authorization"))
// Compare signatures
if curSignature[1] != signature[1] {
return fmt.Errorf("user signature not authenticated")
}
}
} else {
log.Debug("user not existing: ", curAccessKey)
return fmt.Errorf("user not existing")
}
return nil
}
func (u *ValidateFromFile) secretFromID(id string) (string, error) {
f, e := os.Open(u.filename)
if e != nil {
log.Panicf("error opening users files: %s", e)
}
defer func() {
if err := f.Close(); err != nil {
log.Debug("error on close ")
log.Debug(err)
}
}()
// TODO: Lookup whether to defer a close here?
r := csv.NewReader(bufio.NewReader(f))
for {
record, e := r.Read()
if e == io.EOF {
break
}
if record[0] == id {
return record[1], nil
}
}
return "", fmt.Errorf("cannot find id")
}
// Authenticate verifies that the token included in the http.Request
// is valid
func (u *ValidateFromToken) Authenticate(r *http.Request) error {
// Verify signature by parsing the token with the given key
tokenStr := r.Header.Get("X-Amz-Security-Token")
if tokenStr == "" {
return fmt.Errorf("user token not found")
}
token, _ := jwt.Parse(tokenStr, func(tokenStr *jwt.Token) (interface{}, error) { return nil, nil })
if claims, ok := token.Claims.(jwt.MapClaims); ok {
strIss := fmt.Sprintf("%v", claims["iss"])
re := regexp.MustCompile(`//([^/]*)`)
if token.Header["alg"] == "ES256" {
key, err := jwt.ParseECPublicKeyFromPEM(u.pubkeys[re.FindStringSubmatch(strIss)[1]])
if err != nil {
return fmt.Errorf("failed to parse public key")
}
_, err = jwt.Parse(tokenStr, func(tokenStr *jwt.Token) (interface{}, error) { return key, nil })
if err != nil {
return fmt.Errorf("user token not valid")
}
} else if token.Header["alg"] == "RS256" {
key, err := jwt.ParseRSAPublicKeyFromPEM(u.pubkeys[re.FindStringSubmatch(strIss)[1]])
if err != nil {
return fmt.Errorf("failed to parse public key")
}
_, err = jwt.Parse(tokenStr, func(tokenStr *jwt.Token) (interface{}, error) { return key, nil })
if err != nil {
return fmt.Errorf("user token not valid")
}
}
}
// Check whether token username and filepath match
re := regexp.MustCompile("/([^/]+)/")
username := re.FindStringSubmatch(r.URL.Path)[1]
if claims, ok := token.Claims.(jwt.MapClaims); ok {
if claims["sub"] != username {
return fmt.Errorf("token username different that url")
}
}
return nil
}
// Function for reading the ega key in []byte
func (u *ValidateFromToken) getjwtkey(jwtpubkeypath string) error {
re := regexp.MustCompile(`(.*)\.+`)
err := filepath.Walk(jwtpubkeypath,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.Mode().IsRegular() {
log.Debug("reading file: ", filepath.Join(filepath.Clean(jwtpubkeypath), info.Name()))
keyData, err := ioutil.ReadFile(filepath.Join(filepath.Clean(jwtpubkeypath), info.Name()))
if err != nil {
return fmt.Errorf("token file error: %s", err)
}
mapkey := re.FindStringSubmatch(info.Name())[1]
u.pubkeys[mapkey] = keyData
}
return nil
})
if err != nil {
return fmt.Errorf("failed to get public key files")
}
return nil
}
// Function for fetching the elixir key from the JWK and transform it to []byte
func (u *ValidateFromToken) getjwtpubkey(jwtpubkeyurl string) error {
re := regexp.MustCompile("/([^/]+)/")
if re.FindStringSubmatch(jwtpubkeyurl) == nil {
return fmt.Errorf("not valid link")
}
key := re.FindStringSubmatch(jwtpubkeyurl)[1]
set, err := jwk.Fetch(jwtpubkeyurl)
if err != nil {
return fmt.Errorf("failed to parse JWK")
}
keyEl, err := set.Keys[0].Materialize()
if err != nil {
return fmt.Errorf("failed to generate public key")
}
pkeyBytes, err := x509.MarshalPKIXPublicKey(keyEl)
if err != nil {
return fmt.Errorf("failed to marshal public key")
}
log.Debug("request jwt")
r, err := http.Get(jwtpubkeyurl)
if err != nil {
return fmt.Errorf("failed to get JWK")
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("failed to parse response")
}
defer r.Body.Close()
var keytype map[string][]map[string]string
err = json.Unmarshal(b, &keytype)
if err != nil {
return fmt.Errorf("failed to unmarshal response")
}
keyData := pem.EncodeToMemory(
&pem.Block{
Type: keytype["keys"][0]["kty"] + " PUBLIC KEY",
Bytes: pkeyBytes,
},
)
u.pubkeys[key] = keyData
return nil
}