forked from childe/ldap-nginx-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nginx-ldap-auth-daemon.go
204 lines (173 loc) · 4.95 KB
/
nginx-ldap-auth-daemon.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
package main
import (
"crypto/tls"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"gopkg.in/ldap.v2"
"io/ioutil"
"log"
"net/http"
"strings"
)
var options = &struct {
configArg string
host string
port int
ldapserver string
basedn string
binddn string
bindpw string
filter string
useSSL bool
insecureSkipVerify bool
}{}
func ladpAuth(username string, password string) bool {
var l *ldap.Conn
var err error
if options.useSSL {
l, err = ldap.DialTLS("tcp", options.ldapserver, &tls.Config{ServerName: strings.SplitN(options.ldapserver, ":", 2)[0], InsecureSkipVerify: options.insecureSkipVerify})
} else {
l, err = ldap.Dial("tcp", options.ldapserver)
}
if err != nil {
log.Printf("connecting ldap server failed: %s\n", err)
return false
}
bindErr := l.Bind(options.binddn, options.bindpw)
if bindErr != nil {
log.Printf("bind failed: %s", bindErr)
return false
}
filterString := fmt.Sprintf(options.filter, username)
log.Println(filterString)
searchRequest := ldap.NewSearchRequest(
options.basedn,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
filterString,
nil,
nil,
)
searchResult, searchErr := l.Search(searchRequest)
if searchErr != nil {
log.Printf("search failed: %s\n", searchErr)
return false
}
if len(searchResult.Entries) != 1 {
log.Println("search result is not only one(more or less)")
return false
}
userDN := searchResult.Entries[0].DN
log.Println(userDN)
err = l.Bind(userDN, password)
if err != nil {
log.Println(err)
return false
} else {
return true
}
}
func authHandler(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.Path)
authorization := r.Header.Get("Authorization")
if authorization == "" {
w.Header().Add("WWW-Authenticate", "Basic realm=\"\"")
w.WriteHeader(401)
//fmt.Fprintf(w, "")
return
}
authorizationBytes, err := base64.StdEncoding.DecodeString(authorization[len("Basic "):])
if err != nil {
log.Println(err)
//w.Header().Add("WWW-Authenticate", "Basic realm=\"\"")
w.WriteHeader(403)
return
}
authorizationValue := string(authorizationBytes)
userANDpw := strings.SplitN(authorizationValue, ":", 2)
if len(userANDpw) != 2 {
log.Println("Authenticate Value Format Error")
w.Header().Add("WWW-Authenticate", "Basic realm=\"\"")
w.WriteHeader(403)
return
}
username := userANDpw[0]
password := userANDpw[1]
log.Printf("username: %s", username)
if ladpAuth(username, password) {
w.WriteHeader(200)
} else {
w.Header().Add("WWW-Authenticate", "Basic realm=\"\"")
w.WriteHeader(403)
log.Println("Auth Failed")
}
return
}
func init() {
flag.StringVar(&options.configArg, "config", "", "path to ldap-auth-daemon configuration file")
flag.StringVar(&options.host, "host", "127.0.0.1", "ip/host that bind to, default 127.0.0.1")
flag.IntVar(&options.port, "port", 8080, "port that bind to, default 8080")
flag.StringVar(&options.ldapserver, "ldapserver", "", "required. ldapserver")
flag.StringVar(&options.basedn, "basedn", "", "required. basedn.")
flag.StringVar(&options.binddn, "binddn", "", "required if search action need bind first")
flag.StringVar(&options.bindpw, "bindpw", "", "required if search action need bind first")
flag.StringVar(&options.filter, "filter", "", "required. filter template, such as (sAMAccountName=%s)")
flag.BoolVar(&options.useSSL, "useSSL", true, "if use SSL. default true")
flag.BoolVar(&options.insecureSkipVerify, "insecureSkipVerify", false, "if skip verity when ldap server cert is not insecure. default false")
}
func mergeConfigToOptions(config map[string]interface{}) {
if options.ldapserver == "" {
if value, ok := config["ldapserver"]; ok {
options.ldapserver = value.(string)
} else {
flag.PrintDefaults()
log.Fatal("ldapserver is required")
}
}
if options.basedn == "" {
if value, ok := config["basedn"]; ok {
options.basedn = value.(string)
} else {
flag.PrintDefaults()
log.Fatal("basedn is required")
}
}
if options.filter == "" {
if value, ok := config["filter"]; ok {
options.filter = value.(string)
} else {
flag.PrintDefaults()
log.Fatal("filter is required")
}
}
if options.binddn == "" {
if value, ok := config["binddn"]; ok {
options.binddn = value.(string)
}
}
if options.bindpw == "" {
if value, ok := config["bindpw"]; ok {
options.bindpw = value.(string)
}
}
}
func main() {
flag.Parse()
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
config := map[string]interface{}{}
if options.configArg != "" {
configValue, err := ioutil.ReadFile(options.configArg)
if err != nil {
log.Fatal(err)
return
}
if err := json.Unmarshal(configValue, &config); err != nil {
log.Fatal(err)
}
}
mergeConfigToOptions(config)
http.HandleFunc("/", authHandler)
log.Println(fmt.Sprintf("%s:%d", options.host, options.port))
http.ListenAndServe(fmt.Sprintf("%s:%d", options.host, options.port), nil)
}