-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
263 lines (243 loc) · 7.93 KB
/
auth.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
261
262
263
package main
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
b64 "encoding/base64"
"fmt"
"log/slog"
"net"
"os"
"github.com/netinternet/remoteaddr"
)
type Auth struct {
Users map[string]User
Config ConfigType
HostHeaders []string
Permissions struct {
ListFull *ConfigPermissions
List *ConfigPermissions
}
}
var AnonymounsUser User
// https://www.alexedwards.net/blog/basic-authentication-in-go
// https://medium.com/@matryer/the-http-handler-wrapper-technique-in-golang-updated-bc7fbcffa702
func (Auth *Auth) Authentication(request *RequestParameters) bool {
user, ok := Auth.Users[request.Basic.Username]
debugLogger := request.Logger.Ext.With("function", "Authentication")
debugLogger.Debug(fmt.Sprintf("User in database : %v", ok), "found", ok)
if ok {
request.Authentication.User = &user
if request.Basic.Ok {
passwordHash := AuthHash(request.Basic.Password)
if AuthTest(passwordHash, user.PasswordEnc) {
request.Authentication.Verified.Password = true
}
if user.HostAllowed(request.RequestIP, request.Logger.Ext) {
request.Authentication.Verified.Host = true
}
if request.Authentication.Verified.Password && request.Authentication.Verified.Host {
return true
}
return request.Authentication.Verified.Ok()
}
}
return false
}
func (Auth *Auth) NoAuth(permissions *ConfigPermissions) bool {
return !permissions.List && !permissions.Read && !permissions.Write
}
func (User *User) Autorization(request *RequestParameters, permissions *ConfigPermissions) bool {
debugLogger := request.Logger.Ext.With("function", "Autorization")
if request.Api == "system" {
debugLogger.Debug("Skipping Auth for system api")
return true
}
userPermissions, ok := User.Permissions[request.Namespace]
debugLogger.Debug("Testing User Permissions",
"userPermissions", userPermissions, "expectedPermissions", permissions,
"gobal", !ok)
if ok {
return AuthTestPermission(userPermissions, *permissions)
} else {
return AuthTestPermission(User.GlobalPermissions, *permissions)
}
}
func (Auth *Auth) GetIPHeaderFromRequest(request *RequestParameters) (string, string) {
debugLogger := request.Logger.Ext.With("function", "GetIPHeaderFromRequest")
address, _ := remoteaddr.Parse().IP(request.orgRequest)
foundHeaderName := "remoteaddr"
debugLogger.Debug("Remote address: " + address)
var trustedProxy bool
for _, proxyAddress := range Auth.Config.TrustedProxies {
if proxyAddress == address {
debugLogger.Debug("Remote address is a trusted proxy")
trustedProxy = true
break
}
}
if trustedProxy {
for _, headerName := range Auth.HostHeaders {
header := request.orgRequest.Header[headerName]
if len(header) > 0 {
debugLogger.Debug(fmt.Sprintf("Found address in headder [%v] = %v", headerName, header[0]))
request.Logger.Ext = request.Logger.Ext.With("address", header[0], "proxy", address, "proxy-header", headerName)
request.Logger.Log = request.Logger.Log.With("address", header[0], "proxy", address)
return header[0], headerName
}
}
} else {
if len(Auth.Config.TrustedProxies) > 0 {
logger.Debug("Remote address is not a trusted proxy")
}
}
request.Logger.Ext = request.Logger.Ext.With("address", address)
request.Logger.Log = request.Logger.Log.With("address", address)
return address, foundHeaderName
}
func AuthHash(data string) [32]byte {
return sha256.Sum256([]byte(data))
}
func AuthTest(test [32]byte, fact [32]byte) bool {
return (subtle.ConstantTimeCompare(test[:], fact[:]) == 1)
}
func AuthEncode(data [32]byte) string {
return b64.StdEncoding.EncodeToString(data[:])
}
func AuthDecode(data string) [32]byte {
bytes, err := b64.StdEncoding.DecodeString(data)
if err != nil {
panic(err)
}
if len(bytes) != 32 {
panic(fmt.Sprintf("E wrong datalength %d should be 32", len(bytes)))
}
byteArray := [32]byte{}
copy(byteArray[:], bytes)
return byteArray
}
func (Auth *Auth) AuthGenerate(generate string, test string) {
if generate != "" {
hash := AuthHash(generate)
encodedHash := AuthEncode(hash)
logger.Debug("encodedHash: "+encodedHash, "function", "AuthGenerate", "struct", "Auth")
if test == "" {
fmt.Println(encodedHash)
} else {
testHash := AuthDecode(test)
success := AuthTest(testHash, hash)
fmt.Println("Test: ", success)
}
os.Exit(0)
}
}
func (Auth *Auth) Init(config ConfigType) {
Auth.Config = config
Auth.LoadConfig(config)
logger.Debug(fmt.Sprintf("Auth.Users: %+v", Auth.Users), "function", "Init", "struct", "Auth")
logger.Debug(fmt.Sprintf("Loaded %v users", len(Auth.Users)), "function", "Init", "struct", "Auth")
Auth.HostHeaders = []string{
"X-Forwarded-For",
"HTTP_FORWARDED",
"HTTP_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_FORWARDED_FOR",
"HTTP_CLIENT_IP",
"HTTP_VIA",
"HTTP_X_CLUSTER_CLIENT_IP",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"REMOTE_ADDR"}
}
func (Auth *Auth) LoadConfig(config ConfigType) {
users := make(map[string]User)
for _, v := range config.Users {
users[v.Username] = AuthUnpack(v)
}
Auth.Users = users
Auth.Permissions.ListFull = &ConfigPermissions{List: true, Read: true}
Auth.Permissions.List = &ConfigPermissions{List: true}
logger.Debug(fmt.Sprintf("Loaded %v users", len(Auth.Users)), "function", "Init", "struct", "Auth")
}
type User struct {
PasswordEnc [32]byte
Permissions map[string]ConfigPermissions
GlobalPermissions ConfigPermissions
Hosts []string
}
func (User *User) HostAllowed(address string, dLogger *slog.Logger) bool {
debugLogger := dLogger.With("function", "HostAllowed", "struct", "User")
ip := net.ParseIP(address)
for _, host := range User.Hosts {
_, testSubnet, _ := net.ParseCIDR(host)
if testSubnet != nil {
if testSubnet.Contains(ip) {
debugLogger.Debug("matched CIDR for for host: " + host)
return true
}
} else {
testIP := net.ParseIP(host)
if testIP != nil {
if ip.Equal(testIP) {
debugLogger.Debug("matched IP for for host: " + host)
return true
}
} else {
testIPs, err := net.LookupIP(host)
if err != nil {
debugLogger.Error("Failed to parse address for DNS: "+host, "error", err)
continue
}
for _, testIP := range testIPs {
debugLogger.Debug(fmt.Sprintf("DNS Lookup for for domain %s resolved to %s ", host, testIP.String()))
if ip.Equal(testIP) {
debugLogger.Debug(fmt.Sprintf("Matched DNS Lookup for host %s ", host))
return true
}
}
}
}
}
debugLogger.Debug(address + " not matched to any of users hosts")
return false
}
func AuthUnpack(Data ConfigUser) User {
logger.Debug("ReadingUser", "user", Data.Username, "function", "AuthUnpack")
user := User{
PasswordEnc: AuthDecode(Data.Password),
Permissions: make(map[string]ConfigPermissions),
Hosts: Data.Hosts,
}
logger.Debug("Reading Permissionsset", "user", Data.Username, "function", "AuthUnpack", "size", len(Data.Permissionsset))
for _, permissionset := range Data.Permissionsset {
logger.Debug("Reading Permissionsset for Namespaces", "user", Data.Username, "function", "AuthUnpack", "size", len(permissionset.Namespaces), "namespaces", permissionset.Namespaces, "permissions", permissionset.Permissions)
for _, namespace := range permissionset.Namespaces {
if namespace == "*" {
user.GlobalPermissions = permissionset.Permissions
} else {
user.Permissions[namespace] = permissionset.Permissions
}
}
}
return user
}
func AuthTestPermission(permission ConfigPermissions, expected ConfigPermissions) bool {
return ((!expected.Read || permission.Read) &&
(!expected.Write || permission.Write) &&
(!expected.List || permission.List))
}
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func AuthGenerateRandomString(length int) string {
bytes := make([]byte, length)
_, err := rand.Read(bytes)
if err != nil {
panic(err)
}
StringAsBytes := make([]byte, length)
for i, b := range bytes {
location := int(b) % len(charset)
char := charset[location]
StringAsBytes[i] = char
}
return string(StringAsBytes)
}