-
Notifications
You must be signed in to change notification settings - Fork 29
/
passwd.go
80 lines (65 loc) · 2.14 KB
/
passwd.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
package auth
import (
"errors"
"fmt"
ldap "github.com/go-ldap/ldap/v3"
"golang.org/x/text/encoding/unicode"
)
//ModifyDNPassword sets a new password for the given user or returns an error if one occurred.
//ModifyDNPassword is used for resetting user passwords using administrative privileges.
func (c *Conn) ModifyDNPassword(dn, newPasswd string) error {
utf16 := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
encoded, err := utf16.NewEncoder().String(fmt.Sprintf(`"%s"`, newPasswd))
if err != nil {
return fmt.Errorf("Password error: Unable to encode password: %w", err)
}
req := ldap.NewModifyRequest(dn, nil)
req.Replace("unicodePwd", []string{encoded})
err = c.Conn.Modify(req)
if err != nil {
return fmt.Errorf("Password error: Unable to modify password: %w", err)
}
return nil
}
//UpdatePassword checks if the given credentials are valid and updates the password if they are,
//or returns an error if one occurred. UpdatePassword is used for users resetting their own password.
func UpdatePassword(config *Config, username, oldPasswd, newPasswd string) error {
utf16 := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
oldEncoded, err := utf16.NewEncoder().String(fmt.Sprintf(`"%s"`, oldPasswd))
if err != nil {
return fmt.Errorf("Password error: Unable to encode old password: %w", err)
}
newEncoded, err := utf16.NewEncoder().String(fmt.Sprintf(`"%s"`, newPasswd))
if err != nil {
return fmt.Errorf("Password error: Unable to encode new password: %w", err)
}
upn, err := config.UPN(username)
if err != nil {
return err
}
conn, err := config.Connect()
if err != nil {
return err
}
defer conn.Conn.Close()
//bind
status, err := conn.Bind(upn, oldPasswd)
if err != nil {
return err
}
if !status {
return errors.New("Password error: credentials not valid")
}
dn, err := conn.GetDN("userPrincipalName", upn)
if err != nil {
return err
}
req := ldap.NewModifyRequest(dn, nil)
req.Delete("unicodePwd", []string{oldEncoded})
req.Add("unicodePwd", []string{newEncoded})
err = conn.Conn.Modify(req)
if err != nil {
return fmt.Errorf("Password error: Unable to modify password: %w", err)
}
return nil
}