-
Notifications
You must be signed in to change notification settings - Fork 1
/
ldap.go
205 lines (178 loc) · 5.72 KB
/
ldap.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
package main
import (
"fmt"
"log"
"regexp"
"strconv"
"strings"
"gopkg.in/mgo.v2/bson"
ldapMsg "github.com/lor00x/goldap/message"
ldap "github.com/vjeantet/ldapserver"
)
var (
tagRegex, userRegex, groupRegex *regexp.Regexp
)
func makeLDAPServer(listenAddr string) *ldap.Server {
//Create a new LDAP Server
server := ldap.NewServer()
ldap.Logger = ldap.DiscardingLogger
//Create routes bindings
routes := ldap.NewRouteMux()
routes.Abandon(handleAbandon)
routes.Bind(handleBind)
// Regexes
tagRegex = regexp.MustCompile(`tag=([\w-]+)`)
userRegex = regexp.MustCompile(`(uid)=([\w-]+)`)
groupRegex = regexp.MustCompile(`(cn)=([\w-]+)`)
routes.Search(handleSearch)
//Attach routes to server
server.Handle(routes)
// listen on 10389 and serve
go func() {
if err := server.ListenAndServe(listenAddr); err != nil {
log.Printf("LDAP Listen Error: %s", err.Error())
}
}()
return server
}
func handleAbandon(w ldap.ResponseWriter, m *ldap.Message) {
var req = m.GetAbandonRequest()
// retreive the request to abandon, and send a abort signal to it
if requestToAbandon, ok := m.Client.GetMessageByID(int(req)); ok {
requestToAbandon.Abandon()
log.Printf("Abandon signal sent to request processor [messageID=%d]", int(req))
}
}
// handleBind handles simple authentication
func handleBind(w ldap.ResponseWriter, m *ldap.Message) {
r := m.GetBindRequest()
logger.Debugf("Request bind: %s", string(r.Name()))
res := ldap.NewBindResponse(ldap.LDAPResultSuccess)
if r.AuthenticationChoice() == "simple" {
dn := string(r.Name()) // uid=xxxx,ou=xxx
if dn == "" {
// Allow anonymous bind
w.Write(res)
return
}
cnPair := strings.Split(dn, ",")[0]
cn := strings.Split(cnPair, "=")[1]
mg := getMongo()
defer mg.Close()
logger.Debugf("Filter user: %s", cn)
users := mg.FindUsers(bson.M{"username": cn}, "")
if len(users) > 0 {
user := users[0]
logger.Debugf("User: %#v", user)
pass := string(r.AuthenticationSimple())
if user.Authenticate(pass) {
logger.Debugf("Successfully authenticated user: %s", user.Username)
w.Write(res)
return
}
res.SetResultCode(ldap.LDAPResultInvalidCredentials)
res.SetDiagnosticMessage("invalid credentials")
} else {
res.SetResultCode(ldap.LDAPResultNoSuchObject)
res.SetDiagnosticMessage("User not found")
}
} else {
res.SetResultCode(ldap.LDAPResultUnwillingToPerform)
res.SetDiagnosticMessage("Authentication choice not supported")
}
w.Write(res)
}
// handle search function
func handleSearch(w ldap.ResponseWriter, m *ldap.Message) {
r := m.GetSearchRequest()
logger.Debugf("Request BaseDN: %s", r.BaseObject())
logger.Debugf("Request Filter: %s", r.FilterString())
logger.Debugf("Request Attributes: %s", r.Attributes())
// filter out invalid suffixes
if !strings.HasSuffix(string(r.BaseObject()), dcfg.LDAP.Suffix) {
return
}
// Handle Stop Signal (server stop / client disconnected / Abandoned request....)
select {
case <-m.Done:
log.Print("Leaving handleSearch...")
return
default:
}
mg := getMongo()
defer mg.Close()
// determine people/group and tag
segs := strings.Split(string(r.BaseObject()), ",")
baseFilter := bson.M{}
var tag, ou, baseKey, baseVal string
var keymap map[string]string
for _, seg := range segs {
switch seg {
case "ou=people", "ou=People", "ou=users", "ou=Users":
ou = "people"
keymap = userldap2bson
case "ou=groups", "ou=Group", "ou=group", "ou=Groups":
ou = "groups"
keymap = groupldap2bson
}
if tagRegex.MatchString(seg) {
tag = tagRegex.FindStringSubmatch(seg)[1]
} else if userRegex.MatchString(seg) {
fields := userRegex.FindStringSubmatch(seg)
baseKey, baseVal = fields[1], fields[2]
} else if groupRegex.MatchString(seg) {
fields := groupRegex.FindStringSubmatch(seg)
baseKey, baseVal = fields[1], fields[2]
}
}
if ou == "" {
logger.Warningf("Invalid search DN")
return
}
if baseKey != "" {
baseFilter[keymap[baseKey]] = baseVal
}
filter := ldapQueryToBson(r.Filter(), keymap)
if len(filter) == 0 {
filter = baseFilter
} else if len(baseFilter) > 0 {
filter = bson.M{"$and": []bson.M{
filter, baseFilter,
}}
}
logger.Debugf("Mongo Filter: %#v", filter)
if ou == "people" {
users := mg.FindUsers(filter, tag)
for _, u := range users {
e := ldap.NewSearchResultEntry(fmt.Sprintf("uid=%s,ou=people,%s", u.Username, dcfg.LDAP.Suffix))
e.AddAttribute("uid", ldapMsg.AttributeValue(u.Username))
e.AddAttribute("cn", ldapMsg.AttributeValue(u.Username))
e.AddAttribute("mail", ldapMsg.AttributeValue(u.Email))
e.AddAttribute("gecos", ldapMsg.AttributeValue(u.Name))
e.AddAttribute("uidNumber", ldapMsg.AttributeValue(strconv.Itoa(u.UID)))
e.AddAttribute("gidNumber", ldapMsg.AttributeValue(strconv.Itoa(u.GID)))
e.AddAttribute("loginShell", ldapMsg.AttributeValue(u.LoginShell))
e.AddAttribute("homeDirectory", ldapMsg.AttributeValue(fmt.Sprintf("/home/%s", u.Username)))
e.AddAttribute("userPassword", ldapMsg.AttributeValue(u.Password))
e.AddAttribute("objectClass", "top", "posixAccount", "shadowAccount")
e.AddAttribute("shadowMax", "99999")
w.Write(e)
}
} else if ou == "groups" {
groups := mg.FindGroups(filter, tag)
for _, g := range groups {
e := ldap.NewSearchResultEntry(fmt.Sprintf("cn=%s,ou=groups,%s", g.Name, dcfg.LDAP.Suffix))
e.AddAttribute("cn", ldapMsg.AttributeValue(g.Name))
e.AddAttribute("gidNumber", ldapMsg.AttributeValue(strconv.Itoa(g.GID)))
members := []ldapMsg.AttributeValue{}
for _, username := range g.Members {
members = append(members, ldapMsg.AttributeValue(username))
}
e.AddAttribute("memberUid", members...)
e.AddAttribute("objectClass", "top", "posixGroup")
w.Write(e)
}
}
res := ldap.NewSearchResultDoneResponse(ldap.LDAPResultSuccess)
w.Write(res)
}