forked from jech/galene-ldap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgalene-ldap.go
346 lines (304 loc) · 7.6 KB
/
galene-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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package main
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"io/ioutil"
"github.com/go-ldap/ldap/v3"
"github.com/jech/cert"
)
// jsonSet is an array that unmarshals as a hashtable.
type jsonSet map[string]bool
func (s *jsonSet) UnmarshalJSON(b []byte) error {
var a []string
err := json.Unmarshal(b, &a)
if err != nil {
return err
}
*s = make(map[string]bool, len(a))
for _, v := range a {
(*s)[v] = true
}
return nil
}
func (s jsonSet) MarshalJSON() ([]byte, error) {
a := make([]string, 0, len(s))
for v, vv := range s {
if vv {
a = append(a, v)
}
}
return json.Marshal(a)
}
type UserGroup struct {
Group string `json:"group"`
Username []string `json:"username"`
}
type configuration struct {
Groups jsonSet `json:"groups-exception"`
PasswordFallback bool `json:"passwordFallback"`
HttpAddress string `json:"httpAddress"`
Insecure bool `json:"insecure"`
Key map[string]interface{} `json:"key"`
LdapServer string `json:"ldapServer"`
LdapBase string `json:"ldapBase"`
LdapAuthDN string `json:"ldapAuthDN"`
LdapAuthPassword string `json:"ldapAuthPassword"`
LdapClientSideValidate bool `json:"ldapClientSideValidate"`
Op []UserGroup `json:"op"`
}
var debug bool
var config configuration
var signingKey interface{}
var signingKeyAlg string
var verifyCh chan verifyReq
func main() {
var dataDir string
flag.StringVar(&dataDir, "data", ".", "data `directory`")
flag.BoolVar(&debug, "debug", false, "enable debugging")
flag.Parse()
configFile := filepath.Join(dataDir, "galene-ldap.json")
f, err := os.Open(configFile)
if err != nil {
log.Fatalf("Open(%v): %v", configFile, err)
}
defer f.Close()
decoder := json.NewDecoder(f)
decoder.DisallowUnknownFields()
err = decoder.Decode(&config)
if err != nil {
log.Fatalf("Read(%v): %v", configFile, err)
}
signingKeyAlg, signingKey, err = parseKey(config.Key)
if err != nil {
log.Fatalf("Parse key: %v", err)
}
if config.HttpAddress == "" {
config.HttpAddress = ":8443"
}
// unbuffered, so we can discard requests
verifyCh = make(chan verifyReq)
go verifier(verifyCh)
http.HandleFunc("/", httpHandler)
server := &http.Server{
Addr: config.HttpAddress,
ReadHeaderTimeout: 60 * time.Second,
IdleTimeout: 120 * time.Second,
}
if !config.Insecure {
certificate := cert.New(
filepath.Join(dataDir, "cert.pem"),
filepath.Join(dataDir, "key.pem"),
)
server.TLSConfig = &tls.Config{
GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return certificate.Get()
},
}
err = server.ListenAndServeTLS("", "")
} else {
err = server.ListenAndServe()
}
log.Fatal(err)
}
func debugf(format string, v ...interface{}) {
if debug {
log.Printf(format, v...)
}
}
type galeneRequest struct {
Username string `json:"username"`
Location string `json:"location"`
Password string `json:"password"`
}
func extractContentType(ctype string) string {
fields := strings.Split(ctype, ";")
if len(fields) == 0 {
return ""
}
return strings.TrimSpace(fields[0])
}
func httpHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == "OPTIONS" {
w.Header().Set("Access-Control-Allow-Methods", "POST")
w.Header().Set("Access-Control-Allow-Headers",
"Content-Type",
)
return
}
if r.Method != "POST" {
w.Header().Set("Allow", "OPTIONS, POST")
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
ctype := extractContentType(r.Header.Get("Content-Type"))
if !strings.EqualFold(ctype, "application/json") {
log.Printf("Unexpected content-type: %v", ctype)
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
fallback := func() {
if config.PasswordFallback {
w.WriteHeader(http.StatusNoContent)
} else {
http.Error(w, "Not authorised", http.StatusUnauthorized)
}
}
decoder := json.NewDecoder(r.Body)
var req galeneRequest
err := decoder.Decode(&req)
if err != nil {
log.Printf("Decode(request): %v", err)
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
if req.Username == "" || req.Location == "" || req.Password == "" {
log.Print("Missing field in request.")
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
loc, err := url.Parse(req.Location)
if err != nil {
log.Printf("Parse(request.location): %v", err)
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
p := loc.Path
if !strings.HasPrefix(p, "/group/") {
debugf("Path doesn't start with /group/")
fallback()
return
}
group := strings.TrimSuffix(strings.TrimPrefix(p, "/group/"), "/")
if config.Groups[group] {
debugf("This group cannot be accessed via LDAP")
fallback()
return
}
found, valid, err := verify(r.Context(), req.Username, req.Password)
if err != nil {
log.Printf("Verify: %v", err)
http.Error(w, "Internal server error",
http.StatusInternalServerError)
return
}
debugf("Verify: found=%v, valid=%v", found, valid)
if !found {
fallback()
return
}
if !valid {
http.Error(w, "Not authorised", http.StatusUnauthorized)
return
}
token, err := makeToken(
signingKeyAlg, signingKey, "",
req.Location, req.Username, req.Password,
)
if err != nil {
log.Printf("makeToken: %v", err)
http.Error(w, "Couldn't generate token",
http.StatusInternalServerError)
return
}
w.Header().Set("content-type", "application/jwt")
w.Header().Set("cache-control", "no-store")
io.WriteString(w, token)
}
type verifyResp struct {
found, valid bool
error error
}
type verifyReq struct {
user, password string
ch chan verifyResp
}
func verifier(ch <-chan verifyReq) {
var conn *ldap.Conn
var err error
var justConnected bool
for {
req, ok := <-ch
if !ok {
return
}
connectAgain:
if conn == nil {
conn, err = ldapConnect(
config.LdapServer,
config.LdapAuthDN,
config.LdapAuthPassword,
)
if err != nil {
conn = nil
req.ch <- verifyResp{error: err}
close(req.ch)
continue
}
justConnected = true
} else {
justConnected = false
}
found, valid, err :=
ldapVerify(
conn, config.LdapClientSideValidate,
config.LdapAuthDN, config.LdapAuthPassword,
req.user, req.password)
if err != nil {
conn.Close()
conn = nil
var lerr *ldap.Error
if !justConnected && errors.As(err, &lerr) &&
lerr.ResultCode == ldap.ErrorNetwork {
goto connectAgain
}
req.ch <- verifyResp{error: err}
close(req.ch)
continue
}
req.ch <- verifyResp{found: found, valid: valid}
close(req.ch)
}
}
func verify(ctx context.Context, user, password string) (bool, bool, error) {
ch := make(chan verifyResp, 1)
select {
case verifyCh <- verifyReq{user: user, password: password, ch: ch}:
select {
case resp := <-ch:
return resp.found, resp.valid, resp.error
case <-ctx.Done():
return false, false, ctx.Err()
}
case <-ctx.Done():
return false, false, ctx.Err()
}
}
func readOpFromConfigFile(dataDir string) ([]UserGroup, error) {
configFile := filepath.Join(dataDir, "galene-ldap.json")
f, err := ioutil.ReadFile(configFile)
if err != nil {
return nil, err
}
var config configuration
err = json.Unmarshal(f, &config)
if err != nil {
return nil, err
}
return config.Op, nil
}