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
|
package main
import (
"errors"
"fmt"
"github.com/msteinert/pam"
"github.com/nmcclain/asn1-ber"
"github.com/nmcclain/ldap"
"log"
"net"
"os"
"os/user"
"strings"
)
type Backend struct {
ldap.Binder
ldap.Searcher
ldap.Closer
logger *log.Logger
Listen string
BaseDN string
PAMServiceName string
PeopleDN string
GroupsDN string
BindAdminDN string
BindAdminPassword string
}
var logger = log.New(os.Stdout, "", log.LstdFlags)
func main() {
logger.Println("start")
l := ldap.NewServer()
l.EnforceLDAP = true
var backend = Backend{
PAMServiceName: "password-auth",
logger: logger,
Listen: "127.0.0.1:10389",
BaseDN: "dc=example,dc=com",
PeopleDN: "ou=people,dc=example,dc=com",
GroupsDN: "ou=groups,dc=example,dc=com",
BindAdminDN: "uid=user,dc=example,dc=com",
BindAdminPassword: "password",
}
l.BindFunc("", backend)
l.SearchFunc("", backend)
l.CloseFunc("", backend)
if err := l.ListenAndServe(backend.Listen); err != nil {
backend.logger.Fatalf("LDAP serve failed: %s", err.Error())
}
}
func (b Backend) Bind(bindDN, bindSimplePw string, conn net.Conn) (resultCode ldap.LDAPResultCode, err error) {
b.logger.Printf("Bind attempt addr=%s bindDN=%s", conn.RemoteAddr().String(), bindDN)
if bindDN == b.BindAdminDN {
if bindSimplePw != b.BindAdminPassword {
return ldap.LDAPResultInvalidCredentials, errors.New("Password Incorrect")
}
return ldap.LDAPResultSuccess, nil
} else {
var username string
if username, err = b.getUserNameFromBindDN(bindDN); err != nil {
return ldap.LDAPResultInvalidCredentials, err
}
if err := PAMAuth(b.PAMServiceName, username, bindSimplePw); err != nil {
return ldap.LDAPResultInvalidCredentials, err
}
return ldap.LDAPResultSuccess, nil
}
}
func (b Backend) Search(bindDN string, req ldap.SearchRequest, conn net.Conn) (result ldap.ServerSearchResult, err error) {
b.logger.Printf("Search bindDN=%s baseDN=%s filter=%s addr=%s", bindDN, req.BaseDN, req.Filter, conn.RemoteAddr().String())
filterObjectClass, err := ldap.GetFilterObjectClass(req.Filter)
if err != nil {
b.logger.Printf("Search Error: error parsing ObjectClass: %s", req.Filter)
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, fmt.Errorf("Search Error: error parsing ObjectClass: %s", req.Filter)
}
var username string
var user_entity_name string
if filterObjectClass == "posixaccount" || filterObjectClass == "" {
user_entity_name = "uid"
} else if filterObjectClass == "posixgroup" {
user_entity_name = "memberUid"
} else {
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, fmt.Errorf("Filter does not contain objectclass=posixaccount nor objectclass=posixgroup")
}
if bindDN == b.BindAdminDN {
filterUid, err := GetFilterEntity(user_entity_name, req.Filter)
if err != nil {
b.logger.Printf("Search Error: error find condition uid: %s", req.Filter)
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, fmt.Errorf("Search Error: error find condition uid: %s", req.Filter)
}
username = filterUid
} else {
if username, err = b.getUserNameFromBindDN(bindDN); err != nil {
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, err
}
}
var entry *ldap.Entry
if filterObjectClass == "posixaccount" || filterObjectClass == "" {
if entry, err = b.makeSearchEntryAccount("cn="+username+","+b.PeopleDN, username); err != nil {
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, err
}
} else if filterObjectClass == "posixgroup" {
if entry, err = b.makeSearchEntryGroup(b.GroupsDN, username); err != nil {
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, err
}
} else {
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, fmt.Errorf("Filter does not contain objectclass=posixaccount nor objectclass=posixgroup")
}
return ldap.ServerSearchResult{[]*ldap.Entry{entry}, []string{}, []ldap.Control{}, ldap.LDAPResultSuccess}, nil
return ldap.ServerSearchResult{make([]*ldap.Entry, 0), []string{}, []ldap.Control{}, ldap.LDAPResultSuccess}, nil
}
func (b Backend) Close(bindDN string, conn net.Conn) (err error) {
b.logger.Printf("Close addr=%s bindDN=%s", conn.RemoteAddr().String(), bindDN)
return nil
}
func PAMAuth(serviceName, userName, passwd string) error {
t, err := pam.StartFunc(serviceName, userName, func(s pam.Style, msg string) (string, error) {
switch s {
case pam.PromptEchoOff:
return passwd, nil
case pam.PromptEchoOn, pam.ErrorMsg, pam.TextInfo:
return "", nil
}
return "", errors.New("Unrecognized PAM message style")
})
if err != nil {
return err
}
if err = t.Authenticate(0); err != nil {
return err
}
return nil
}
func (b Backend) getUserNameFromBindDN(bindDN string) (username string, err error) {
if bindDN == "" {
return "", errors.New("bindDN not specified")
}
if !strings.HasSuffix(bindDN, ","+b.PeopleDN) {
return "", errors.New("bindDN not matched")
}
rest := strings.TrimSuffix(bindDN, ","+b.PeopleDN)
if rest == "" {
return "", errors.New("bindDN format error")
}
if strings.Contains(rest, ",") {
return "", errors.New("bindDN has too much entities")
}
if strings.HasPrefix(rest, "uid=") {
username = strings.TrimPrefix(rest, "uid=")
} else if strings.HasPrefix(rest, "cn=") {
username = strings.TrimPrefix(rest, "cn=")
} else {
return "", errors.New("bindDN contains no cn/uid entry")
}
return username, nil
}
func (b Backend) makeSearchEntryAccount(dn string, username string) (entry *ldap.Entry, err error) {
attrs := []*ldap.EntryAttribute{}
var u *user.User
if u, err = user.Lookup(username); err != nil {
return entry, err
}
attrs = append(attrs, &ldap.EntryAttribute{"objectClass", []string{"posixAccount"}})
attrs = append(attrs, &ldap.EntryAttribute{"cn", []string{username}})
attrs = append(attrs, &ldap.EntryAttribute{"uid", []string{username}})
attrs = append(attrs, &ldap.EntryAttribute{"uidNumber", []string{u.Uid}})
attrs = append(attrs, &ldap.EntryAttribute{"givenName", []string{u.Name}})
attrs = append(attrs, &ldap.EntryAttribute{"gidNumber", []string{u.Gid}})
attrs = append(attrs, &ldap.EntryAttribute{"homeDirectory", []string{u.HomeDir}})
entry = &ldap.Entry{dn, attrs}
return entry, nil
}
func (b Backend) makeSearchEntryGroup(basedn string, username string) (entry *ldap.Entry, err error) {
attrs := []*ldap.EntryAttribute{}
var (
u *user.User
g *user.Group
)
if u, err = user.Lookup(username); err != nil {
return entry, err
}
if g, err = user.LookupGroupId(u.Gid); err != nil {
return entry, err
}
attrs = append(attrs, &ldap.EntryAttribute{"objectClass", []string{"posixGroup"}})
attrs = append(attrs, &ldap.EntryAttribute{"cn", []string{g.Name}})
attrs = append(attrs, &ldap.EntryAttribute{"gidNumber", []string{u.Gid}})
attrs = append(attrs, &ldap.EntryAttribute{"memberUid", []string{username}})
dn := "cn=" + g.Name + "," + basedn
entry = &ldap.Entry{dn, attrs}
return entry, nil
}
func GetFilterEntity(entity string, filter string) (string, error) {
f, err := ldap.CompileFilter(filter)
if err != nil {
return "", err
}
return parseFilterEntity(entity, f)
}
func parseFilterEntity(entity string, f *ber.Packet) (string, error) {
foundEntity := ""
switch ldap.FilterMap[f.Tag] {
case "Equality Match":
if len(f.Children) != 2 {
return "", errors.New("Equality match must have only two children")
}
attribute := strings.ToLower(f.Children[0].Value.(string))
value := f.Children[1].Value.(string)
if attribute == entity {
foundEntity = strings.ToLower(value)
}
case "And":
for _, child := range f.Children {
subType, err := parseFilterEntity(entity, child)
if err != nil {
return "", err
}
if len(subType) > 0 {
foundEntity = subType
}
}
case "Or":
for _, child := range f.Children {
subType, err := parseFilterEntity(entity, child)
if err != nil {
return "", err
}
if len(subType) > 0 {
foundEntity = subType
}
}
case "Not":
if len(f.Children) != 1 {
return "", errors.New("Not filter must have only one child")
}
subType, err := parseFilterEntity(entity, f.Children[0])
if err != nil {
return "", err
}
if len(subType) > 0 {
foundEntity = subType
}
}
return strings.ToLower(foundEntity), nil
}
|