model.go 17.3 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
package backend

import (
	"context"
ale's avatar
ale committed
5
6
7
	"fmt"
	"math/rand"
	"strconv"
ale's avatar
ale committed
8
	"strings"
9
	"time"
ale's avatar
ale committed
10
11

	ldaputil "git.autistici.org/ai3/go-common/ldap"
12
	"github.com/tstranex/u2f"
ale's avatar
ale committed
13
14
	"gopkg.in/ldap.v2"

15
	as "git.autistici.org/ai3/accountserver"
ale's avatar
ale committed
16
17
)

18
19
const (
	// Names of some well-known LDAP attributes.
20
21
22
23
24
25
26
27
28
29
30
	totpSecretLDAPAttr         = "totpSecret"
	preferredLanguageLDAPAttr  = "preferredLanguage"
	recoveryHintLDAPAttr       = "recoverQuestion"
	recoveryResponseLDAPAttr   = "recoverAnswer"
	aspLDAPAttr                = "appSpecificPassword"
	storagePublicKeyLDAPAttr   = "storagePublicKey"
	storagePrivateKeyLDAPAttr  = "storageEncryptedSecretKey"
	passwordLDAPAttr           = "userPassword"
	passwordLastChangeLDAPAttr = "shadowLastChange"
	u2fRegistrationsLDAPAttr   = "u2fRegistration"
	uidNumberLDAPAttr          = "uidNumber"
31
32
)

33
// backend is the interface to an LDAP-backed user database.
ale's avatar
ale committed
34
35
36
37
38
//
// We keep a set of LDAP queries for each resource type, each having a
// "resource" query to return a specific resource belonging to a user,
// and a "presence" query that checks for existence of a resource for
// all users.
39
type backend struct {
ale's avatar
ale committed
40
	conn                ldapConn
ale's avatar
ale committed
41
	baseDN              string
42
43
	userQuery           *queryTemplate
	userResourceQueries []*queryTemplate
ale's avatar
ale committed
44
	resources           *resourceRegistry
ale's avatar
ale committed
45
46
47

	// Range for new user IDs.
	minUID, maxUID int
ale's avatar
ale committed
48
49
}

ale's avatar
ale committed
50
51
52
53
54
const (
	defaultMinUID = 10000
	defaultMaxUID = 1000000
)

ale's avatar
ale committed
55
56
// backendTX holds the business logic (that runs within a single
// transaction).
57
58
59
60
61
type backendTX struct {
	*ldapTX
	backend *backend
}

ale's avatar
ale committed
62
63
const ldapPoolSize = 20

64
func (b *backend) NewTransaction() (as.TX, error) {
65
66
67
68
69
70
	return &backendTX{
		ldapTX:  newLDAPTX(b.conn),
		backend: b,
	}, nil
}

ale's avatar
ale committed
71
72
// NewLDAPBackend initializes an LDAPBackend object with the given LDAP
// connection pool.
73
func NewLDAPBackend(uri, bindDN, bindPw, base string) (as.Backend, error) {
ale's avatar
ale committed
74
75
76
77
	pool, err := ldaputil.NewConnectionPool(uri, bindDN, bindPw, ldapPoolSize)
	if err != nil {
		return nil, err
	}
78
79
	return newLDAPBackendWithConn(pool, base)
}
ale's avatar
ale committed
80

81
func newLDAPBackendWithConn(conn ldapConn, base string) (*backend, error) {
ale's avatar
ale committed
82
	rsrc := newResourceRegistry()
83
84
85
86
87
88
	rsrc.register(as.ResourceTypeEmail, &emailResourceHandler{baseDN: base})
	rsrc.register(as.ResourceTypeMailingList, &mailingListResourceHandler{baseDN: base})
	rsrc.register(as.ResourceTypeDAV, &webdavResourceHandler{baseDN: base})
	rsrc.register(as.ResourceTypeWebsite, &websiteResourceHandler{baseDN: base})
	rsrc.register(as.ResourceTypeDomain, &domainResourceHandler{baseDN: base})
	rsrc.register(as.ResourceTypeDatabase, &databaseResourceHandler{baseDN: base})
ale's avatar
ale committed
89

90
	return &backend{
ale's avatar
ale committed
91
92
		conn:   conn,
		baseDN: base,
93
94
95
96
97
98
		userQuery: &queryTemplate{
			Base:   joinDN("uid=${user}", "ou=People", base),
			Filter: "(objectClass=*)",
			Scope:  ldap.ScopeBaseObject,
		},
		userResourceQueries: []*queryTemplate{
ale's avatar
ale committed
99
			// Find all resources that are children of the main uid object.
100
101
102
103
			&queryTemplate{
				Base:  joinDN("uid=${user}", "ou=People", base),
				Scope: ldap.ScopeWholeSubtree,
			},
ale's avatar
ale committed
104
			// Find mailing lists, which are nested under a different root.
105
106
			&queryTemplate{
				Base:   joinDN("ou=Lists", base),
ale's avatar
ale committed
107
				Filter: "(&(objectClass=mailingList)(listOwner=${user}))",
108
109
				Scope:  ldap.ScopeSingleLevel,
			},
ale's avatar
ale committed
110
		},
ale's avatar
ale committed
111
		resources: rsrc,
ale's avatar
ale committed
112
113
		minUID:    defaultMinUID,
		maxUID:    defaultMaxUID,
ale's avatar
ale committed
114
	}, nil
ale's avatar
ale committed
115
116
}

117
func newUser(entry *ldap.Entry) (*as.RawUser, error) {
118
119
120
121
122
123
124
	// Note that some user-level attributes related to
	// authentication are stored on the uid= object, while others
	// are on the email= object. We set the latter in the GetUser
	// function later.
	//
	// The case of password recovery attributes is more complex:
	// the current schema has those on email=, but we'd like to
125
126
	// move them to uid=, so we currently have to support both
	// (but the uid= one takes precedence).
127
	uidNumber, _ := strconv.Atoi(entry.GetAttributeValue(uidNumberLDAPAttr)) // nolint
128
129
	user := &as.RawUser{
		User: as.User{
130
131
132
133
134
135
136
			Name: entry.GetAttributeValue("uid"),
			Lang: entry.GetAttributeValue(preferredLanguageLDAPAttr),
			UID:  uidNumber,
			LastPasswordChangeStamp: decodeShadowTimestamp(entry.GetAttributeValue(passwordLastChangeLDAPAttr)),
			AccountRecoveryHint:     entry.GetAttributeValue(recoveryHintLDAPAttr),
			U2FRegistrations:        decodeU2FRegistrations(entry.GetAttributeValues(u2fRegistrationsLDAPAttr)),
			HasOTP:                  entry.GetAttributeValue(totpSecretLDAPAttr) != "",
137
138
139
140
		},
		// Remove the legacy LDAP {crypt} prefix on old passwords.
		Password:         strings.TrimPrefix(entry.GetAttributeValue(passwordLDAPAttr), "{crypt}"),
		RecoveryPassword: strings.TrimPrefix(entry.GetAttributeValue(recoveryResponseLDAPAttr), "{crypt}"),
ale's avatar
ale committed
141
	}
142
143

	// The user has 2FA enabled if it has a TOTP secret or U2F keys.
144
	user.Has2FA = (user.HasOTP || (len(user.U2FRegistrations) > 0))
145

ale's avatar
ale committed
146
147
148
149
150
151
	if user.Lang == "" {
		user.Lang = "en"
	}
	return user, nil
}

152
func userToLDAP(user *as.User) (attrs []ldap.PartialAttribute) {
ale's avatar
ale committed
153
154
	// Most attributes are read-only and have specialized methods to set them.
	attrs = append(attrs, []ldap.PartialAttribute{
155
		{Type: "objectClass", Vals: []string{"top", "person", "posixAccount", "shadowAccount", "organizationalPerson", "inetOrgPerson", "investiciUser"}},
ale's avatar
ale committed
156
157
		{Type: "uid", Vals: s2l(user.Name)},
		{Type: "cn", Vals: s2l(user.Name)},
ale's avatar
ale committed
158
		{Type: uidNumberLDAPAttr, Vals: s2l(strconv.Itoa(user.UID))},
ale's avatar
ale committed
159
160
161
162
163
		{Type: "givenName", Vals: []string{"Private"}},
		{Type: "sn", Vals: []string{"Private"}},
		{Type: "gecos", Vals: s2l(user.Name)},
		{Type: "loginShell", Vals: []string{"/bin/false"}},
		{Type: "homeDirectory", Vals: []string{"/var/empty"}},
164
		{Type: passwordLastChangeLDAPAttr, Vals: []string{"12345"}},
ale's avatar
ale committed
165
166
167
		{Type: "shadowWarning", Vals: []string{"7"}},
		{Type: "shadowMax", Vals: []string{"99999"}},
		{Type: preferredLanguageLDAPAttr, Vals: s2l(user.Lang)},
168
		{Type: u2fRegistrationsLDAPAttr, Vals: encodeU2FRegistrations(user.U2FRegistrations)},
ale's avatar
ale committed
169
170
171
172
	}...)
	return
}

173
func decodeU2FRegistration(enc string) (*as.U2FRegistration, error) {
174
175
176
177
	var reg u2f.Registration
	if err := reg.UnmarshalBinary([]byte(enc)); err != nil {
		return nil, err
	}
178
	return &as.U2FRegistration{Registration: &reg}, nil
179
180
}

181
182
183
func encodeU2FRegistration(r *as.U2FRegistration) string {
	// MarshalBinary can't fail, ignore error.
	b, _ := r.MarshalBinary() // nolint
184
185
186
	return string(b)
}

187
188
func decodeU2FRegistrations(encRegs []string) []*as.U2FRegistration {
	var out []*as.U2FRegistration
189
190
191
192
193
194
195
196
	for _, enc := range encRegs {
		if r, err := decodeU2FRegistration(enc); err == nil {
			out = append(out, r)
		}
	}
	return out
}

197
func encodeU2FRegistrations(regs []*as.U2FRegistration) []string {
198
199
200
201
202
203
204
	var out []string
	for _, r := range regs {
		out = append(out, encodeU2FRegistration(r))
	}
	return out
}

205
func (tx *backendTX) getUserDN(user *as.User) string {
ale's avatar
ale committed
206
	return joinDN("uid="+user.Name, "ou=People", tx.backend.baseDN)
ale's avatar
ale committed
207
208
}

ale's avatar
ale committed
209
// CreateUser creates a new user.
210
func (tx *backendTX) CreateUser(ctx context.Context, user *as.User) error {
ale's avatar
ale committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
	dn := tx.getUserDN(user)

	tx.create(dn)
	for _, attr := range userToLDAP(user) {
		tx.setAttr(dn, attr.Type, attr.Vals...)
	}

	// Create all resources.
	for _, r := range user.Resources {
		if err := tx.CreateResource(ctx, r); err != nil {
			return err
		}
	}

	return nil
}

228
// UpdateUser updates values for the user only (not the resources).
229
func (tx *backendTX) UpdateUser(ctx context.Context, user *as.User) error {
230
231
232
233
234
235
236
	dn := tx.getUserDN(user)
	for _, attr := range userToLDAP(user) {
		tx.setAttr(dn, attr.Type, attr.Vals...)
	}
	return nil
}

ale's avatar
ale committed
237
// GetUser returns a user.
238
func (tx *backendTX) GetUser(ctx context.Context, username string) (*as.RawUser, error) {
ale's avatar
ale committed
239
240
	// First of all, find the main user object, and just that one.
	vars := map[string]string{"user": username}
241
	result, err := tx.search(ctx, tx.backend.userQuery.query(vars))
ale's avatar
ale committed
242
243
244
245
246
247
	if err != nil {
		if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
			return nil, nil
		}
		return nil, err
	}
248
249
250
	if len(result.Entries) == 0 {
		return nil, nil
	}
ale's avatar
ale committed
251
252
253
254
255
256
257
258
259
260

	user, err := newUser(result.Entries[0])
	if err != nil {
		return nil, err
	}

	// Now run the resource queries, and accumulate results on the User
	// object we just created.
	// TODO: parallelize.
	// TODO: add support for non-LDAP resource queries.
261
262
	for _, tpl := range tx.backend.userResourceQueries {
		result, err = tx.search(ctx, tpl.query(vars))
ale's avatar
ale committed
263
264
265
266
267
		if err != nil {
			continue
		}

		for _, entry := range result.Entries {
268
269
270
271
272
273
			// Some user-level attributes are actually stored on
			// the email object, which is desired in some cases,
			// but in others is a shortcoming of the legacy A/I
			// database model. Set them on the main User
			// object. For the latter, attributes on the main User
			// object take precedence.
ale's avatar
ale committed
274
			if isObjectClass(entry, "virtualMailUser") {
275
276
277
278
				if user.AccountRecoveryHint == "" {
					if s := entry.GetAttributeValue(recoveryHintLDAPAttr); s != "" {
						user.AccountRecoveryHint = s
					}
279
				}
280

281
				user.AppSpecificPasswords = getASPInfo(decodeAppSpecificPasswords(entry.GetAttributeValues(aspLDAPAttr)))
282
283
				user.Keys = decodeUserEncryptionKeys(
					entry.GetAttributeValues(storagePrivateKeyLDAPAttr))
284
				user.HasEncryptionKeys = (entry.GetAttributeValue(storagePublicKeyLDAPAttr) != "")
ale's avatar
ale committed
285
			}
ale's avatar
ale committed
286

ale's avatar
ale committed
287
			// Parse the resource and add it to the User.
ale's avatar
ale committed
288
			if r, err := tx.backend.resources.FromLDAP(entry); err == nil {
ale's avatar
ale committed
289
290
291
292
293
294
295
296
				user.Resources = append(user.Resources, r)
			}
		}
	}

	return user, nil
}

297
func (tx *backendTX) SetUserPassword(ctx context.Context, user *as.User, encryptedPassword string) (err error) {
298
299
	dn := tx.getUserDN(user)
	tx.setAttr(dn, passwordLDAPAttr, encryptedPassword)
300
	tx.setAttr(dn, passwordLastChangeLDAPAttr, encodeShadowTimestamp(time.Now()))
301
302
303
304
305
	for _, r := range user.GetResourcesByType(as.ResourceTypeEmail) {
		dn, err = tx.backend.resources.GetDN(r.ID)
		if err != nil {
			return
		}
306
307
		tx.setAttr(dn, passwordLDAPAttr, encryptedPassword)
	}
308
	return
ale's avatar
ale committed
309
310
}

311
func (tx *backendTX) SetAccountRecoveryHint(ctx context.Context, user *as.User, hint, response string) error {
312
313
	// Write the password recovery attributes on the uid= object,
	// as per the new schema.
ale's avatar
ale committed
314
315
316
317
318
319
	dn := tx.getUserDN(user)
	tx.setAttr(dn, recoveryHintLDAPAttr, hint)
	tx.setAttr(dn, recoveryResponseLDAPAttr, response)
	return nil
}

320
func (tx *backendTX) DeleteAccountRecoveryHint(ctx context.Context, user *as.User) error {
321
322
323
324
325
326
	// Write the password recovery attributes on the uid= object,
	// as per the new schema.
	dn := tx.getUserDN(user)
	tx.setAttr(dn, recoveryHintLDAPAttr)
	tx.setAttr(dn, recoveryResponseLDAPAttr)
	return nil
ale's avatar
ale committed
327
328
}

329
func (tx *backendTX) SetUserEncryptionKeys(ctx context.Context, user *as.User, keys []*as.UserEncryptionKey) error {
330
	encKeys := encodeUserEncryptionKeys(keys)
331
332
333
334
335
	for _, r := range user.GetResourcesByType(as.ResourceTypeEmail) {
		dn, err := tx.backend.resources.GetDN(r.ID)
		if err != nil {
			return err
		}
336
337
		tx.setAttr(dn, storagePrivateKeyLDAPAttr, encKeys...)
	}
338
	return nil
ale's avatar
ale committed
339
340
}

341
342
343
344
345
346
func (tx *backendTX) SetUserEncryptionPublicKey(ctx context.Context, user *as.User, pub []byte) error {
	for _, r := range user.GetResourcesByType(as.ResourceTypeEmail) {
		dn, err := tx.backend.resources.GetDN(r.ID)
		if err != nil {
			return err
		}
347
348
		tx.setAttr(dn, storagePublicKeyLDAPAttr, string(pub))
	}
349
350
351
352
353
354
355
356
357
	return nil
}

func excludeASPFromList(asps []*appSpecificPassword, id string) []*appSpecificPassword {
	var out []*appSpecificPassword
	for _, asp := range asps {
		if asp.ID != id {
			out = append(out, asp)
		}
358
	}
359
	return out
360
361
}

362
363
364
365
366
func (tx *backendTX) setASPOnResource(ctx context.Context, r *as.Resource, info *as.AppSpecificPasswordInfo, encryptedPassword string) {
	dn, err := tx.backend.resources.GetDN(r.ID)
	if err != nil {
		return
	}
ale's avatar
ale committed
367

368
	// Obtain the full list of ASPs from the backend and replace/append the new one.
369
	asps := decodeAppSpecificPasswords(tx.readAttributeValues(ctx, dn, aspLDAPAttr))
370
371
	asps = append(excludeASPFromList(asps, info.ID), newAppSpecificPassword(*info, encryptedPassword))
	outASPs := encodeAppSpecificPasswords(asps)
372
	tx.setAttr(dn, aspLDAPAttr, outASPs...)
ale's avatar
ale committed
373
374
}

375
376
func (tx *backendTX) SetApplicationSpecificPassword(ctx context.Context, user *as.User, info *as.AppSpecificPasswordInfo, encryptedPassword string) error {
	for _, r := range user.GetResourcesByType(as.ResourceTypeEmail) {
377
		tx.setASPOnResource(ctx, r, info, encryptedPassword)
ale's avatar
ale committed
378
	}
379
380
	return nil
}
ale's avatar
ale committed
381

382
383
384
385
386
func (tx *backendTX) deleteASPOnResource(ctx context.Context, r *as.Resource, id string) {
	dn, err := tx.backend.resources.GetDN(r.ID)
	if err != nil {
		return
	}
387
	asps := decodeAppSpecificPasswords(tx.readAttributeValues(ctx, dn, aspLDAPAttr))
388
389
	asps = excludeASPFromList(asps, id)
	outASPs := encodeAppSpecificPasswords(asps)
390
391
	tx.setAttr(dn, aspLDAPAttr, outASPs...)
}
ale's avatar
ale committed
392

393
394
func (tx *backendTX) DeleteApplicationSpecificPassword(ctx context.Context, user *as.User, id string) error {
	for _, r := range user.GetResourcesByType(as.ResourceTypeEmail) {
395
396
		tx.deleteASPOnResource(ctx, r, id)
	}
397
	return nil
ale's avatar
ale committed
398
399
}

400
func (tx *backendTX) SetUserTOTPSecret(ctx context.Context, user *as.User, secret string) error {
401
	tx.setAttr(tx.getUserDN(user), totpSecretLDAPAttr, secret)
402
	return nil
ale's avatar
ale committed
403
404
}

405
func (tx *backendTX) DeleteUserTOTPSecret(ctx context.Context, user *as.User) error {
406
	tx.setAttr(tx.getUserDN(user), totpSecretLDAPAttr)
407
	return nil
ale's avatar
ale committed
408
409
}

410
411
412
413
414
func (tx *backendTX) SetResourcePassword(ctx context.Context, r *as.Resource, encryptedPassword string) error {
	dn, err := tx.backend.resources.GetDN(r.ID)
	if err != nil {
		return err
	}
415
	tx.setAttr(dn, passwordLDAPAttr, encryptedPassword)
416
	return nil
ale's avatar
ale committed
417
418
}

ale's avatar
ale committed
419
func (tx *backendTX) hasResource(ctx context.Context, resourceType, resourceName string) (bool, error) {
420
	tpl, err := tx.backend.resources.SearchQuery(resourceType)
ale's avatar
ale committed
421
422
	if err != nil {
		return false, err
ale's avatar
ale committed
423
424
425
	}

	// Make a quick LDAP search that only fetches the DN attribute.
426
427
	tpl.Attrs = []string{"dn"}
	result, err := tx.search(ctx, tpl.query(map[string]string{
ale's avatar
ale committed
428
429
		"resource": resourceName,
		"type":     resourceType,
430
	}))
ale's avatar
ale committed
431
432
433
434
435
436
437
438
439
440
441
442
443
	if err != nil {
		if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
			return false, nil
		}
		return false, err
	}
	if len(result.Entries) == 0 {
		return false, nil
	}
	return true, nil
}

// HasAnyResource returns true if any of the specified resources exists.
444
func (tx *backendTX) HasAnyResource(ctx context.Context, resourceIDs []as.FindResourceRequest) (bool, error) {
ale's avatar
ale committed
445
446
	for _, req := range resourceIDs {
		has, err := tx.hasResource(ctx, req.Type, req.Name)
ale's avatar
ale committed
447
448
449
450
451
452
453
		if err != nil || has {
			return has, err
		}
	}
	return false, nil
}

454
// GetResource returns a ResourceWrapper, as part of a read-modify-update transaction.
455
func (tx *backendTX) GetResource(ctx context.Context, rsrcID as.ResourceID) (*as.Resource, error) {
ale's avatar
ale committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
	// From the resource ID we can obtain the DN, and fetch it
	// straight from LDAP without even doing a real search.
	dn, err := tx.backend.resources.GetDN(rsrcID)
	if err != nil {
		return nil, err
	}

	// This is just a 'point' search.
	req := ldap.NewSearchRequest(
		dn,
		ldap.ScopeBaseObject,
		ldap.NeverDerefAliases,
		0,
		0,
		false,
		"(objectClass=*)",
		nil,
		nil,
	)

	result, err := tx.search(ctx, req)
477
478
479
480
481
482
483
	if err != nil {
		if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
			return nil, nil
		}
		return nil, err
	}

ale's avatar
ale committed
484
485
	// We know the resource type so we don't have to guess.
	return tx.backend.resources.FromLDAPWithType(rsrcID.Type(), result.Entries[0])
486
487
}

ale's avatar
ale committed
488
// CreateResource creates a new LDAP-backed resource object.
489
func (tx *backendTX) CreateResource(ctx context.Context, r *as.Resource) error {
ale's avatar
ale committed
490
491
492
493
494
495
496
497
498
499
500
501
502
	dn, err := tx.backend.resources.GetDN(r.ID)
	if err != nil {
		return err
	}

	tx.create(dn)
	for _, attr := range tx.backend.resources.ToLDAP(r) {
		tx.setAttr(dn, attr.Type, attr.Vals...)
	}

	return nil
}

503
// UpdateResource updates a LDAP-backed resource that was obtained by a previous GetResource call.
504
func (tx *backendTX) UpdateResource(ctx context.Context, r *as.Resource) error {
ale's avatar
ale committed
505
506
507
508
	dn, err := tx.backend.resources.GetDN(r.ID)
	if err != nil {
		return err
	}
509

510
511
	// We can simply dump all attribute/value pairs and let the
	// code in ldapTX do the work of finding the differences.
ale's avatar
ale committed
512
	for _, attr := range tx.backend.resources.ToLDAP(r) {
513
		tx.setAttr(dn, attr.Type, attr.Vals...)
514
515
	}

516
	return nil
517
518
}

ale's avatar
ale committed
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
// NextUID returns an available user ID (uidNumber). It does so
// without keeping state by just guessing random UIDs in the
// minUID-maxUID range, and checking if they are available (so it's
// best to keep the range largely underutilized).
func (tx *backendTX) NextUID(ctx context.Context) (uid int, err error) {
	// Won't actually run forever, at some point the context will expire.
	var ok bool
	for !ok && err == nil {
		uid = tx.backend.minUID + rand.Intn(tx.backend.maxUID-tx.backend.minUID)
		ok, err = tx.isUIDAvailable(ctx, uid)
	}
	return
}

func (tx *backendTX) isUIDAvailable(ctx context.Context, uid int) (bool, error) {
	// Try to make this query lightweight: ask for no attributes,
	// use a size limit of 1 and treat "Size Limit Exceeded"
	// errors as a successful result.
	result, err := tx.search(ctx, ldap.NewSearchRequest(
		tx.backend.baseDN,
		ldap.ScopeWholeSubtree,
		ldap.NeverDerefAliases,
		1, // just one result is enough
		0,
		false,
		fmt.Sprintf("(uidNumber=%d)", uid),
		[]string{"dn"},
		nil,
	))
	if err != nil {
		if ldap.IsErrorWithCode(err, ldap.LDAPResultSizeLimitExceeded) {
			return false, nil
		}
		return false, err
	}
	if len(result.Entries) > 0 {
		return false, nil
	}
	return true, nil
}
559
560
561
562
563
564
565
566
567
568
569
570
571
572

const oneDay = 86400

func encodeShadowTimestamp(t time.Time) string {
	d := t.UTC().Unix() / oneDay
	return strconv.FormatInt(d, 10)
}

func decodeShadowTimestamp(s string) (t time.Time) {
	if i, err := strconv.ParseInt(s, 10, 64); err == nil {
		t = time.Unix(i*oneDay, 0).UTC()
	}
	return
}