-
Notifications
You must be signed in to change notification settings - Fork 355
/
examples_test.go
581 lines (499 loc) · 14.6 KB
/
examples_test.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
package ldap
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"time"
)
// This example demonstrates how to bind a connection to an ldap user
// allowing access to restricted attributes that user has access to
func ExampleConn_Bind() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
err = l.Bind("cn=read-only-admin,dc=example,dc=com", "password")
if err != nil {
log.Fatal(err)
}
}
// This example demonstrates how to use the search interface
func ExampleConn_Search() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
searchRequest := NewSearchRequest(
"dc=example,dc=com", // The base dn to search
ScopeWholeSubtree, NeverDerefAliases, 0, 0, false,
"(&(objectClass=organizationalPerson))", // The filter to apply
[]string{"dn", "cn"}, // A list attributes to retrieve
nil,
)
sr, err := l.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
for _, entry := range sr.Entries {
fmt.Printf("%s: %v\n", entry.DN, entry.GetAttributeValue("cn"))
}
}
// This example demonstrates how to search asynchronously
func ExampleConn_SearchAsync() {
l, err := DialURL(fmt.Sprintf("%s:%d", "ldap.example.com", 389))
if err != nil {
log.Fatal(err)
}
defer l.Close()
searchRequest := NewSearchRequest(
"dc=example,dc=com", // The base dn to search
ScopeWholeSubtree, NeverDerefAliases, 0, 0, false,
"(&(objectClass=organizationalPerson))", // The filter to apply
[]string{"dn", "cn"}, // A list attributes to retrieve
nil,
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
r := l.SearchAsync(ctx, searchRequest, 64)
for r.Next() {
entry := r.Entry()
fmt.Printf("%s has DN %s\n", entry.GetAttributeValue("cn"), entry.DN)
}
if err := r.Err(); err != nil {
log.Fatal(err)
}
}
// This example demonstrates how to do syncrepl (persistent search)
func ExampleConn_Syncrepl() {
l, err := DialURL(fmt.Sprintf("%s:%d", "ldap.example.com", 389))
if err != nil {
log.Fatal(err)
}
defer l.Close()
searchRequest := NewSearchRequest(
"dc=example,dc=com", // The base dn to search
ScopeWholeSubtree, NeverDerefAliases, 0, 0, false,
"(&(objectClass=organizationalPerson))", // The filter to apply
[]string{"dn", "cn"}, // A list attributes to retrieve
nil,
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
mode := SyncRequestModeRefreshAndPersist
var cookie []byte = nil
r := l.Syncrepl(ctx, searchRequest, 64, mode, cookie, false)
for r.Next() {
entry := r.Entry()
if entry != nil {
fmt.Printf("%s has DN %s\n", entry.GetAttributeValue("cn"), entry.DN)
}
controls := r.Controls()
if len(controls) != 0 {
fmt.Printf("%s", controls)
}
}
if err := r.Err(); err != nil {
log.Fatal(err)
}
}
// This example demonstrates how to start a TLS connection
func ExampleConn_StartTLS() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
// Reconnect with TLS
err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
if err != nil {
log.Fatal(err)
}
// Operations via l are now encrypted
}
// This example demonstrates how to compare an attribute with a value
func ExampleConn_Compare() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
matched, err := l.Compare("cn=user,dc=example,dc=com", "uid", "someuserid")
if err != nil {
log.Fatal(err)
}
fmt.Println(matched)
}
func ExampleConn_PasswordModify_admin() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
err = l.Bind("cn=admin,dc=example,dc=com", "password")
if err != nil {
log.Fatal(err)
}
passwordModifyRequest := NewPasswordModifyRequest("cn=user,dc=example,dc=com", "", "NewPassword")
_, err = l.PasswordModify(passwordModifyRequest)
if err != nil {
log.Fatalf("Password could not be changed: %s", err.Error())
}
}
func ExampleConn_PasswordModify_generatedPassword() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
err = l.Bind("cn=user,dc=example,dc=com", "password")
if err != nil {
log.Fatal(err)
}
passwordModifyRequest := NewPasswordModifyRequest("", "OldPassword", "")
passwordModifyResponse, err := l.PasswordModify(passwordModifyRequest)
if err != nil {
log.Fatalf("Password could not be changed: %s", err.Error())
}
generatedPassword := passwordModifyResponse.GeneratedPassword
log.Printf("Generated password: %s\n", generatedPassword)
}
func ExampleConn_PasswordModify_setNewPassword() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
err = l.Bind("cn=user,dc=example,dc=com", "password")
if err != nil {
log.Fatal(err)
}
passwordModifyRequest := NewPasswordModifyRequest("", "OldPassword", "NewPassword")
_, err = l.PasswordModify(passwordModifyRequest)
if err != nil {
log.Fatalf("Password could not be changed: %s", err.Error())
}
}
func ExampleConn_Modify() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
// Add a description, and replace the mail attributes
modify := NewModifyRequest("cn=user,dc=example,dc=com", nil)
modify.Add("description", []string{"An example user"})
modify.Replace("mail", []string{"[email protected]"})
err = l.Modify(modify)
if err != nil {
log.Fatal(err)
}
}
// Example_userAuthentication shows how a typical application can verify a login attempt
// Refer to https://github.com/go-ldap/ldap/issues/93 for issues revolving around unauthenticated binds, with zero length passwords
func Example_userAuthentication() {
// The username and password we want to check
username := "someuser"
password := "userpassword"
bindusername := "readonly"
bindpassword := "password"
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
// Reconnect with TLS
err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
if err != nil {
log.Fatal(err)
}
// First bind with a read only user
err = l.Bind(bindusername, bindpassword)
if err != nil {
log.Fatal(err)
}
// Search for the given username
searchRequest := NewSearchRequest(
"dc=example,dc=com",
ScopeWholeSubtree, NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=organizationalPerson)(uid=%s))", EscapeFilter(username)),
[]string{"dn"},
nil,
)
sr, err := l.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
if len(sr.Entries) != 1 {
log.Fatal("User does not exist or too many entries returned")
}
userdn := sr.Entries[0].DN
// Bind as the user to verify their password
err = l.Bind(userdn, password)
if err != nil {
log.Fatal(err)
}
// Rebind as the read only user for any further queries
err = l.Bind(bindusername, bindpassword)
if err != nil {
log.Fatal(err)
}
}
func Example_beherappolicy() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
controls := []Control{}
controls = append(controls, NewControlBeheraPasswordPolicy())
bindRequest := NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", controls)
r, err := l.SimpleBind(bindRequest)
ppolicyControl := FindControl(r.Controls, ControlTypeBeheraPasswordPolicy)
var ppolicy *ControlBeheraPasswordPolicy
if ppolicyControl != nil {
ppolicy = ppolicyControl.(*ControlBeheraPasswordPolicy)
} else {
log.Printf("ppolicyControl response not available.\n")
}
if err != nil {
errStr := "ERROR: Cannot bind: " + err.Error()
if ppolicy != nil && ppolicy.Error >= 0 {
errStr += ":" + ppolicy.ErrorString
}
log.Print(errStr)
} else {
logStr := "Login Ok"
if ppolicy != nil {
if ppolicy.Expire >= 0 {
logStr += fmt.Sprintf(". Password expires in %d seconds\n", ppolicy.Expire)
} else if ppolicy.Grace >= 0 {
logStr += fmt.Sprintf(". Password expired, %d grace logins remain\n", ppolicy.Grace)
}
}
log.Print(logStr)
}
}
func Example_vchuppolicy() {
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
l.Debug = true
bindRequest := NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", nil)
r, err := l.SimpleBind(bindRequest)
passwordMustChangeControl := FindControl(r.Controls, ControlTypeVChuPasswordMustChange)
var passwordMustChange *ControlVChuPasswordMustChange
if passwordMustChangeControl != nil {
passwordMustChange = passwordMustChangeControl.(*ControlVChuPasswordMustChange)
}
if passwordMustChange != nil && passwordMustChange.MustChange {
log.Printf("Password Must be changed.\n")
}
passwordWarningControl := FindControl(r.Controls, ControlTypeVChuPasswordWarning)
var passwordWarning *ControlVChuPasswordWarning
if passwordWarningControl != nil {
passwordWarning = passwordWarningControl.(*ControlVChuPasswordWarning)
} else {
log.Printf("ppolicyControl response not available.\n")
}
if err != nil {
log.Print("ERROR: Cannot bind: " + err.Error())
} else {
logStr := "Login Ok"
if passwordWarning != nil {
if passwordWarning.Expire >= 0 {
logStr += fmt.Sprintf(". Password expires in %d seconds\n", passwordWarning.Expire)
}
}
log.Print(logStr)
}
}
// This example demonstrates how to use ControlPaging to manually execute a
// paginated search request instead of using SearchWithPaging.
func ExampleControlPaging_manualPaging() {
conn, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
var pageSize uint32 = 32
searchBase := "dc=example,dc=com"
filter := "(objectClass=group)"
pagingControl := NewControlPaging(pageSize)
attributes := []string{}
controls := []Control{pagingControl}
for {
request := NewSearchRequest(searchBase, ScopeWholeSubtree, DerefAlways, 0, 0, false, filter, attributes, controls)
response, err := conn.Search(request)
if err != nil {
log.Fatalf("Failed to execute search request: %s", err.Error())
}
// [do something with the response entries]
// In order to prepare the next request, we check if the response
// contains another ControlPaging object and a not-empty cookie and
// copy that cookie into our pagingControl object:
updatedControl := FindControl(response.Controls, ControlTypePaging)
if ctrl, ok := updatedControl.(*ControlPaging); ctrl != nil && ok && len(ctrl.Cookie) != 0 {
pagingControl.SetCookie(ctrl.Cookie)
continue
}
// If no new paging information is available or the cookie is empty, we
// are done with the pagination.
break
}
}
// This example demonstrates how to use DirSync to manually execute a
// DirSync search request
func ExampleConn_DirSync() {
conn, err := Dial("tcp", "ad.example.org:389")
if err != nil {
log.Fatalf("Failed to connect: %s\n", err)
}
defer conn.Close()
_, err = conn.SimpleBind(&SimpleBindRequest{
Username: "cn=Some User,ou=people,dc=example,dc=org",
Password: "MySecretPass",
})
if err != nil {
log.Fatalf("failed to bind: %s", err)
}
req := &SearchRequest{
BaseDN: `DC=example,DC=org`,
Filter: `(&(objectClass=person)(!(objectClass=computer)))`,
Attributes: []string{"*"},
Scope: ScopeWholeSubtree,
}
// This is the initial sync with all entries matching the filter
doMore := true
var cookie []byte
for doMore {
res, err := conn.DirSync(req, DirSyncObjectSecurity, 1000, cookie)
if err != nil {
log.Fatalf("failed to search: %s", err)
}
for _, entry := range res.Entries {
entry.Print()
}
ctrl := FindControl(res.Controls, ControlTypeDirSync)
if ctrl == nil || ctrl.(*ControlDirSync).Flags == 0 {
doMore = false
}
cookie = ctrl.(*ControlDirSync).Cookie
}
// We're done with the initial sync. Now pull every 15 seconds for the
// updated entries - note that you get just the changes, not a full entry.
for {
res, err := conn.DirSync(req, DirSyncObjectSecurity, 1000, cookie)
if err != nil {
log.Fatalf("failed to search: %s", err)
}
for _, entry := range res.Entries {
entry.Print()
}
time.Sleep(15 * time.Second)
}
}
// This example demonstrates how to use DirSync search asynchronously
func ExampleConn_DirSyncAsync() {
conn, err := Dial("tcp", "ad.example.org:389")
if err != nil {
log.Fatalf("Failed to connect: %s\n", err)
}
defer conn.Close()
_, err = conn.SimpleBind(&SimpleBindRequest{
Username: "cn=Some User,ou=people,dc=example,dc=org",
Password: "MySecretPass",
})
if err != nil {
log.Fatalf("failed to bind: %s", err)
}
req := &SearchRequest{
BaseDN: `DC=example,DC=org`,
Filter: `(&(objectClass=person)(!(objectClass=computer)))`,
Attributes: []string{"*"},
Scope: ScopeWholeSubtree,
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var cookie []byte = nil
r := conn.DirSyncAsync(ctx, req, 64, DirSyncObjectSecurity, 1000, cookie)
for r.Next() {
entry := r.Entry()
if entry != nil {
entry.Print()
}
controls := r.Controls()
if len(controls) != 0 {
fmt.Printf("%s", controls)
}
}
if err := r.Err(); err != nil {
log.Fatal(err)
}
}
// This example demonstrates how to use EXTERNAL SASL with TLS client certificates.
func ExampleConn_ExternalBind() {
ldapCert := "/path/to/cert.pem"
ldapKey := "/path/to/key.pem"
ldapCAchain := "/path/to/ca_chain.pem"
// Load client cert and key
cert, err := tls.LoadX509KeyPair(ldapCert, ldapKey)
if err != nil {
log.Fatal(err)
}
// Load CA chain
caCert, err := ioutil.ReadFile(ldapCAchain)
if err != nil {
log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
// Setup TLS with ldap client cert
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
InsecureSkipVerify: true,
}
// connect to ldap server
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
// reconnect using tls
err = l.StartTLS(tlsConfig)
if err != nil {
log.Fatal(err)
}
// sasl external bind
err = l.ExternalBind()
if err != nil {
log.Fatal(err)
}
// Conduct ldap queries
}
// ExampleConn_WhoAmI demonstrates how to run a whoami request according to https://tools.ietf.org/html/rfc4532
func ExampleConn_WhoAmI() {
conn, err := DialURL("ldap.example.org:389")
if err != nil {
log.Fatalf("Failed to connect: %s\n", err)
}
_, err = conn.SimpleBind(&SimpleBindRequest{
Username: "uid=someone,ou=people,dc=example,dc=org",
Password: "MySecretPass",
})
if err != nil {
log.Fatalf("Failed to bind: %s\n", err)
}
res, err := conn.WhoAmI(nil)
if err != nil {
log.Fatalf("Failed to call WhoAmI(): %s\n", err)
}
fmt.Printf("I am: %s\n", res.AuthzID)
}