-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
361 lines (295 loc) · 10.8 KB
/
main.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package main
import (
"crypto/tls"
"flag"
"fmt"
"net"
"os"
"strconv"
"strings"
"gopkg.in/ldap.v2"
)
const (
// defaultLDAPTLSPort is the default port for using TLS over LDAP. If an LDAP server is running on this, it will
// need TLS setup during dial, whereas other ports will accept upgrading to TLS with `.StartTLS(...)`.
defaultLDAPTLSPort = 636
)
// bold wraps the input string in special characters which make text bold in a bash terminal.
func bold(input string) string {
// \033[1m starts printing in bold, \033[0m stops the bold
return fmt.Sprintf("\033[1m%s\033[0m ", input)
}
// getResponse will get a response from the user, it uses the 'validate' function to check if the input is valid. It
// will repeatedly ask the user for further input if the input is invalid.
func getResponse(prompt string, validate func(string) bool) string {
var resp string
for {
fmt.Print(bold(prompt))
n, err := fmt.Scanln(&resp)
// If n==0, the user entered no input, ignore error and just validate the response
if (err != nil && n != 0) || !validate(resp) {
fmt.Println("Invalid input, please try again.")
continue
}
break
}
return resp
}
func getUsernamePass() (string, string) {
username := getResponse("Please enter the username you'd like to log into the LDAP server with:", func(s string) bool { return s != "" })
password := getResponse("Please enter the password you'd like to log into the LDAP server with. Note: this value will be printed to the console and may be output during the testing process:", func(_ string) bool { return true })
return username, password
}
func getAttrs(e ldap.Entry, name string) []string {
for _, a := range e.Attributes {
if a.Name != name {
continue
}
return a.Values
}
if name == "dn" || name == "DN" {
return []string{e.DN}
}
return nil
}
func getAttr(e ldap.Entry, name string) string {
if a := getAttrs(e, name); len(a) > 0 {
return a[0]
}
return ""
}
// groups will search the ldap for the given users groups membership
// using the configuration group search params. it will then return the found groups
// or an error
func groups(user ldap.Entry, l *ldap.Conn) ([]string, error) {
var groups []*ldap.Entry
var groupNames []string
for _, attr := range getAttrs(user, LDAPGroupSearchUserAttr()) {
fmt.Printf("Finding users groups, user search attr: %s\n", attr)
filter := fmt.Sprintf("(%s=%s)", LDAPGroupSearchGroupAttr(), ldap.EscapeFilter(attr))
if LDAPGroupSearchFilter() != "" {
filter = fmt.Sprintf("(&%s%s)", LDAPGroupSearchFilter(), filter)
}
baseDN := LDAPBase()
if LDAPGroupSearchDN() != "" {
baseDN = LDAPGroupSearchDN()
}
// Search for the given users groups
req := &ldap.SearchRequest{
BaseDN: baseDN,
Filter: filter,
Scope: ldap.ScopeWholeSubtree,
Attributes: []string{LDAPGroupSearchNameAttr(), LDAPGroupSearchUserAttr()},
}
fmt.Printf("Searching for LDAP groups:\n\tBaseDN: %s\n\tFilter: %s\n\tAttributes: %v\n", req.BaseDN, req.Filter, req.Attributes)
sr, err := l.Search(req)
if err != nil {
fmt.Printf("Could not search active directory: %v", err)
return nil, err
}
groups = append(groups, sr.Entries...)
if len(groups) == 0 {
fmt.Println("Warning: No groups found from LDAP search")
} else {
for _, group := range groups {
name := getAttr(*group, LDAPGroupSearchNameAttr())
if name != "" {
groupNames = append(groupNames, name)
}
}
fmt.Printf("Found %d groups for user\n", len(groupNames))
}
}
return groupNames, nil
}
//nolint:funlen // Core utility app loop, loc irrelevant
func main() {
configFlag := flag.String("config-file", configPath, "The full path to the YAML config file")
flag.Parse()
if getResponse("This test application will read and output all LDAP data from your Flix config file. This may include sensitive passwords. Do you wish to continue? [y/N]", func(_ string) bool { return true }) != "y" {
fmt.Println("Exiting test application due to user response.")
os.Exit(0)
}
if configFlag != nil && *configFlag != "" {
configPath = *configFlag
}
fmt.Printf("Loading config from %s\n", configPath)
if err := processYML(); err != nil {
fmt.Printf("Unable to load config from file\n")
os.Exit(1)
}
if !LDAPUse() {
fmt.Println("UseLDAP is set to false, cannot continue test")
os.Exit(0)
}
fmt.Printf("Loaded config: %v\n", loadedConfig)
// Use default port if not set
ldapPort := LDAPPort()
if ldapPort == 0 {
fmt.Println("LDAP port not set in config, will use 389 as the port")
ldapPort = 389
}
addr := net.JoinHostPort(LDAPHost(), strconv.Itoa(ldapPort))
fmt.Printf("Attempting to dial the LDAP server at %s...\n", addr)
var l *ldap.Conn
var err error
//nolint:gosec // Secure verification not supported by Flix
tlsConf := tls.Config{InsecureSkipVerify: true}
// If the config needs the default LDAP TLS port, we need to use DialTLS, otherwise a normal Dial is correct.
if LDAPPort() != defaultLDAPTLSPort {
l, err = ldap.Dial("tcp", addr)
} else {
l, err = ldap.DialTLS("tcp", addr, &tlsConf)
}
if err != nil {
fmt.Printf("Failed to dial the LDAP server: %v\n", err)
os.Exit(1)
}
defer l.Close()
fmt.Println("✓ Connected to LDAP Server")
// Reconnect with TLS
if LDAPUseSSL() && LDAPPort() != defaultLDAPTLSPort {
fmt.Println("Attempting to start TLS on the LDAP connection...")
if err = l.StartTLS(&tlsConf); err != nil {
fmt.Printf("Could not start TLS on the LDAP server connection: %v\n", err)
os.Exit(1)
}
fmt.Println("✓ Start TLS Complete")
}
// decide to user the user search DN if its specified
dn := LDAPBase()
if LDAPUserSearchDN() != "" {
dn = LDAPUserSearchDN()
}
username, password := getUsernamePass()
fmt.Printf("Will log into the LDAP server as %s:%s\n", username, password)
// Bind on the LDAP server. We only need to bind if the binduser and bind password have
// been set in config. OR we have self auth set. We dont need to bind if these values are
// not set.
if LDAPBindUser() != "" || LDAPBindPassword() != "" || LDAPSelfAuth() {
fmt.Println("Attempting to bind on LDAP server")
// the bind users requires a full DN field for it to be able to search for the
// user in the ldap. These values use the logging in users credentials to
// set the user and password
bindUser := fmt.Sprintf("%s=%s,%s", LDAPUserSearchUserAttr(), username, dn)
bindPass := password
// if we are not using selfAuth then we just want to use the values stored
// in the config.
if !LDAPSelfAuth() {
// Do not self bind, use the provided readonly user credentials
fmt.Println("Self auth is set to false, will attempt to bind with bind user set in config")
bindUser = LDAPBindUser()
bindPass = LDAPBindPassword()
}
fmt.Printf("✓ Established bind user - %s:%s\n", bindUser, bindPass)
//nolint:govet // Shadowing false positive
if err := l.Bind(bindUser, bindPass); err != nil {
fmt.Printf("Could not bind to LDAP server: %v\n", err)
os.Exit(1)
}
}
fmt.Println("✓ Bind Complete")
// create the search string
filter := fmt.Sprintf("(%s=%s)", LDAPUserSearchUserAttr(), username)
if LDAPUserSearchUserFilter() != "" {
filter = fmt.Sprintf("(&%s%s)", LDAPUserSearchUserFilter(), filter)
}
// attributes
attributes := []string{"dn", "cn", "uid", "displayName", "mail", "ou"}
if LDAPUserSearchNameAttr() != "" {
attributes = append(attributes, LDAPUserSearchNameAttr())
}
if LDAPUserSearchUserAttr() != "" {
attributes = append(attributes, LDAPUserSearchUserAttr())
}
// We need to add the group-user attribute, so the user is returned with that attribute, then we can map it to a
// group.
if LDAPGroupSearchUserAttr() != "" {
attributes = append(attributes, LDAPGroupSearchUserAttr())
}
// Search for the given username
req := ldap.NewSearchRequest(
dn,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
filter,
attributes,
nil,
)
fmt.Printf("Searching for LDAP Users\n\tDN: %s\n\tFilter: %s\n\t Attributes %v\n", req.BaseDN, req.Filter, req.Attributes)
sr, err := l.Search(req)
if err != nil {
fmt.Printf("Could not search active directory: %v\n", err)
os.Exit(1)
}
if len(sr.Entries) != 1 {
fmt.Printf("Expected exactly 1 entry returned, got %d entries\n", len(sr.Entries))
os.Exit(1)
}
userdn := sr.Entries[0].DN
// Bind as the user to verify their password
fmt.Printf("Binding as returned user to verify credentials - %s:%s\n", userdn, password)
//nolint:govet // Shadowing false positive
if err := l.Bind(userdn, password); err != nil {
fmt.Printf("Credentials mismatch: %v\n", err)
os.Exit(1)
}
usernameAttr := LDAPUserSearchUserAttr()
if usernameAttr == "" {
usernameAttr = "uid"
}
fmt.Printf(
"Got user details:\n\tUsername: %s\n\tCN: %s\n\tMail: %s\n\tDisplay name: %s\n",
sr.Entries[0].GetAttributeValue(usernameAttr),
sr.Entries[0].GetAttributeValue("cn"),
sr.Entries[0].GetAttributeValue("mail"),
sr.Entries[0].GetAttributeValue("displayName"),
)
userAttrsStrings := make([]string, len(sr.Entries[0].Attributes))
for i, ea := range sr.Entries[0].Attributes {
valStr := strings.Join(ea.Values, ", ")
userAttrsStrings[i] = fmt.Sprintf("%s:%s", ea.Name, valStr)
}
fmt.Printf("Got user attributes: %s\n", strings.Join(userAttrsStrings, ", "))
// set the name as the specified search name attribute
if LDAPUserSearchNameAttr() != "" {
fmt.Printf("UserSearchNameAttr set, overriding display name to %s\n", sr.Entries[0].GetAttributeValue(LDAPUserSearchNameAttr()))
}
groupNames, err := groups(*sr.Entries[0], l)
if err != nil {
fmt.Printf("Failed to query groups: %v\n", err)
os.Exit(1)
}
fmt.Printf("✓ Got group names: [%s]\n", strings.Join(groupNames, ", "))
fmt.Println("Attempting to filter group names based on prefix and suffix")
fmt.Printf("\tPrefix: %s\n", LDAPGroupPrefix())
fmt.Printf("\tSuffix: %s\n", LDAPGroupSuffix())
matchedGroupNames := make([]string, 0, len(groupNames))
for _, gn := range groupNames {
fmt.Println("---")
fmt.Printf("Testing group name '%s'\n", gn)
if len(gn) < len(LDAPGroupPrefix()) {
fmt.Println("Group name is too short to match prefix")
continue
}
if len(gn) < len(LDAPGroupSuffix()) {
fmt.Println("Group name is too short to match suffix")
continue
}
if gn[:len(LDAPGroupPrefix())] != LDAPGroupPrefix() {
fmt.Println("First part of group name does not match prefix")
fmt.Printf("\t%s != %s\n", gn[:len(LDAPGroupPrefix())], LDAPGroupPrefix())
continue
}
if gn[len(gn)-len(LDAPGroupSuffix()):] != LDAPGroupSuffix() {
fmt.Println("Last part of group name does not match suffix")
fmt.Printf("\t%s != %s\n", gn[:len(LDAPGroupSuffix())], LDAPGroupSuffix())
continue
}
fmt.Println("Group name matches prefix and suffix")
matchedGroupNames = append(matchedGroupNames, gn)
}
fmt.Printf("Matched group names: [%s]\n", strings.Join(matchedGroupNames, ", "))
fmt.Println("Closing connection to LDAP server")
l.Close()
fmt.Println("✓ Finished.")
}