aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: 975311d456d5239d94754c1467ea56dfc463d9d3 (plain) (blame)
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package main


import (
	"crypto/rand"
	"crypto/tls"
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/signal"
	"syscall"

	ldap "bottin/ldapserver"

	consul "github.com/hashicorp/consul/api"
	message "github.com/lor00x/goldap/message"
	log "github.com/sirupsen/logrus"
)

const ATTR_USERPASSWORD = "userpassword"
const ATTR_MEMBER = "member"
const ATTR_MEMBEROF = "memberof"
const ATTR_ENTRYUUID = "entryuuid"
const ATTR_CREATORSNAME = "creatorsname"
const ATTR_CREATETIMESTAMP = "createtimestamp"
const ATTR_MODIFIERSNAME = "modifiersname"
const ATTR_MODIFYTIMESTAMP = "modifytimestamp"

type ConfigFile struct {
	Suffix        string   `json:"suffix"`
	Bind          string   `json:"bind"`
	BindSecure    string   `json:"bind_secure"`
	ConsulHost    string   `json:"consul_host"`
	Acl           []string `json:"acl"`
	TLSCertFile   string   `json:"tls_cert_file"`
	TLSKeyFile    string   `json:"tls_key_file"`
	TLSServerName string   `json:"tls_server_name"`
	LogLevel      string   `json:"log_level"`
}

type Config struct {
	Suffix     string
	Bind       string
	BindSecure string
	ConsulHost string
	LogLevel   log.Level

	Acl ACL

	TLSConfig *tls.Config
}

type Server struct {
	logger *log.Logger
	config Config
	kv     *consul.KV
}

type State struct {
	login Login
}

type Entry map[string][]string

var configFlag = flag.String("config", "./config.json", "Configuration file path")

func readConfig(logger *log.Logger) Config {
	config_file := ConfigFile{
		Bind:       "0.0.0.0:389",
		BindSecure: "0.0.0.0:636",
	}

	bytes, err := ioutil.ReadFile(*configFlag)
	if err != nil {
		logger.Fatal(err)
	}

	err = json.Unmarshal(bytes, &config_file)
	if err != nil {
		logger.Fatal(err)
	}

	acl, err := ParseACL(config_file.Acl)
	if err != nil {
		logger.Fatal(err)
	}

	log_level := log.InfoLevel
	if config_file.LogLevel != "" {
		log_level, err = log.ParseLevel(config_file.LogLevel)
		if err != nil {
			logger.Fatal(err)
		}
	}

	ret := Config{
		Suffix:     config_file.Suffix,
		Bind:       config_file.Bind,
		BindSecure: config_file.BindSecure,
		ConsulHost: config_file.ConsulHost,
		Acl:        acl,
		LogLevel:   log_level,
	}

	if config_file.TLSCertFile != "" && config_file.TLSKeyFile != "" && config_file.TLSServerName != "" {
		cert_txt, err := ioutil.ReadFile(config_file.TLSCertFile)
		if err != nil {
			logger.Fatal(err)
		}
		key_txt, err := ioutil.ReadFile(config_file.TLSKeyFile)
		if err != nil {
			logger.Fatal(err)
		}
		cert, err := tls.X509KeyPair(cert_txt, key_txt)
		if err != nil {
			logger.Fatal(err)
		}
		ret.TLSConfig = &tls.Config{
			MinVersion:   tls.VersionTLS10,
			MaxVersion:   tls.VersionTLS12,
			Certificates: []tls.Certificate{cert},
			ServerName:   config_file.TLSServerName,
		}
	}

	return ret
}

func main() {
	flag.Parse()

	logger := log.New()
	logger.SetOutput(os.Stdout)
	logger.SetFormatter(&log.TextFormatter{})

	config := readConfig(logger)

	if log_level := os.Getenv("BOTTIN_LOG_LEVEL"); log_level != "" {
		level, err := log.ParseLevel(log_level)
		if err != nil {
			logger.Fatal(err)
		}
		logger.SetLevel(level)
	} else {
		logger.SetLevel(config.LogLevel)
	}

	ldap.Logger = logger

	// Connect to Consul
	consul_config := consul.DefaultConfig()
	if config.ConsulHost != "" {
		consul_config.Address = config.ConsulHost
	}
	consul_client, err := consul.NewClient(consul_config)
	if err != nil {
		logger.Fatal(err)
	}
	kv := consul_client.KV()

	// Create bottin server
	bottin := Server{
		logger: logger,
		config: config,
		kv:     kv,
	}
	err = bottin.init()
	if err != nil {
		logger.Fatal(err)
	}

	// Create routes
	routes := ldap.NewRouteMux()

	routes.Bind(bottin.handleBind)
	routes.Search(bottin.handleSearch)
	routes.Add(bottin.handleAdd)
	routes.Compare(bottin.handleCompare)
	routes.Delete(bottin.handleDelete)
	routes.Modify(bottin.handleModify)

	if config.TLSConfig != nil {
		routes.Extended(bottin.handleStartTLS).
			RequestName(ldap.NoticeOfStartTLS).Label("StartTLS")
	}

	// Create LDAP servers
	var ldapServer, ldapServerSecure *ldap.Server = nil, nil

	// Bind on standard LDAP port without TLS
	if config.Bind != "" {
		ldapServer = ldap.NewServer()
		ldapServer.Handle(routes)
		ldapServer.NewUserState = bottin.newUserState
		go func() {
			err := ldapServer.ListenAndServe(config.Bind)
			if err != nil {
				logger.Fatal(err)
			}
		}()
	}

	// Bind on LDAP secure port with TLS
	if config.BindSecure != "" {
		if config.TLSConfig != nil {
			ldapServerSecure := ldap.NewServer()
			ldapServerSecure.Handle(routes)
			ldapServerSecure.NewUserState = bottin.newUserState
			secureConn := func(s *ldap.Server) {
				s.Listener = tls.NewListener(s.Listener, config.TLSConfig)
			}
			go func() {
				err := ldapServerSecure.ListenAndServe(config.BindSecure, secureConn)
				if err != nil {
					logger.Fatal(err)
				}
			}()
		} else {
			logger.Warnf("Warning: no valid TLS configuration was provided, not binding on %s", config.BindSecure)
		}
	}

	if ldapServer == nil && ldapServerSecure == nil {
		logger.Fatal("Not doing anything.")
	}

	// When CTRL+C, SIGINT and SIGTERM signal occurs
	// Then stop server gracefully
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	<-ch
	close(ch)

	if ldapServer != nil {
		ldapServer.Stop()
	}
	if ldapServerSecure != nil {
		ldapServerSecure.Stop()
	}
}

func (server *Server) newUserState() ldap.UserState {
	return &State{
		login: Login{
			user:   "ANONYMOUS",
			groups: []string{},
		},
	}
}

func (server *Server) init() error {
	path, err := dnToConsul(server.config.Suffix)
	if err != nil {
		return err
	}

	pair, _, err := server.kv.Get(path+"/attribute=objectClass", nil)
	if err != nil {
		return err
	}

	if pair != nil {
		return nil
	}

	base_attributes := Entry{
		"objectClass":           []string{"top", "dcObject", "organization"},
		"structuralObjectClass": []string{"Organization"},
		ATTR_CREATORSNAME:       []string{server.config.Suffix},
		ATTR_CREATETIMESTAMP:    []string{genTimestamp()},
		ATTR_ENTRYUUID:          []string{genUuid()},
	}
	suffix_dn, err := parseDN(server.config.Suffix)
	if err != nil {
		return err
	}
	base_attributes[suffix_dn[0].Type] = []string{suffix_dn[0].Value}

	err = server.addElements(server.config.Suffix, base_attributes)
	if err != nil {
		return err
	}

	admin_pass := make([]byte, 8)
	_, err = rand.Read(admin_pass)
	if err != nil {
		return err
	}
	admin_pass_str := base64.RawURLEncoding.EncodeToString(admin_pass)
	admin_pass_hash := SSHAEncode([]byte(admin_pass_str))

	admin_dn := "cn=admin," + server.config.Suffix
	admin_attributes := Entry{
		"objectClass":           []string{"simpleSecurityObject", "organizationalRole"},
		"displayname":           []string{"LDAP administrator"},
		"description":           []string{"Administrator account automatically created by Bottin"},
		"cn":                    []string{"admin"},
		"structuralObjectClass": []string{"organizationalRole"},
		ATTR_USERPASSWORD:       []string{admin_pass_hash},
		ATTR_CREATORSNAME:       []string{server.config.Suffix},
		ATTR_CREATETIMESTAMP:    []string{genTimestamp()},
		ATTR_ENTRYUUID:          []string{genUuid()},
	}

	err = server.addElements(admin_dn, admin_attributes)
	if err != nil {
		return err
	}

	server.logger.Printf(
		"It seems to be a new installation, we created a default user for you:\n\n    dn:          %s\n    password:    %s\n\nWe recommend replacing it as soon as possible.",
		admin_dn,
		admin_pass_str,
	)

	return nil
}

func (server *Server) addElements(dn string, attrs Entry) error {
	prefix, err := dnToConsul(dn)
	if err != nil {
		return err
	}

	for k, v := range attrs {
		path := prefix + "/attribute=" + k
		if len(v) == 0 {
			// If we have zero values, delete associated k/v pair
			_, err := server.kv.Delete(path, nil)
			if err != nil {
				return err
			}
		} else {
			json, err := json.Marshal(v)
			if err != nil {
				return err
			}
			pair := &consul.KVPair{Key: path, Value: json}
			_, err = server.kv.Put(pair, nil)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func (server *Server) getAttribute(dn string, attr string) ([]string, error) {
	path, err := dnToConsul(dn)
	if err != nil {
		return nil, err
	}

	pair, _, err := server.kv.Get(path+"/attribute="+attr, nil)
	if err != nil {
		return nil, err
	}

	if pair == nil {
		return nil, nil
	}

	return parseValue(pair.Value)
}

func (server *Server) objectExists(dn string) (bool, error) {
	prefix, err := dnToConsul(dn)
	if err != nil {
		return false, err
	}

	data, _, err := server.kv.List(prefix+"/", nil)
	if err != nil {
		return false, err
	}
	return len(data) > 0, nil
}

func (server *Server) checkDN(dn string, allow_extend bool) (string, error) {
	// 1. Canonicalize: remove spaces between things
	dn, err := canonicalDN(dn)
	if err != nil {
		return "", err
	}

	// 2. Check suffix (add it if allow_extend is set)
	suffix := server.config.Suffix
	if len(dn) < len(suffix) {
		if dn != suffix[len(suffix)-len(dn):] || !allow_extend {
			return suffix, fmt.Errorf(
				"Only handling stuff under DN %s", suffix)
		}
		return suffix, nil
	} else {
		if dn[len(dn)-len(suffix):] != suffix {
			return suffix, fmt.Errorf(
				"Only handling stuff under DN %s", suffix)
		}
		return dn, nil
	}
}

func (server *Server) handleStartTLS(s ldap.UserState, w ldap.ResponseWriter, m *ldap.Message) {
	tlsConn := tls.Server(m.Client.GetConn(), server.config.TLSConfig)
	res := ldap.NewExtendedResponse(ldap.LDAPResultSuccess)
	res.SetResponseName(ldap.NoticeOfStartTLS)
	w.Write(res)

	if err := tlsConn.Handshake(); err != nil {
		server.logger.Printf("StartTLS Handshake error %v", err)
		res.SetDiagnosticMessage(fmt.Sprintf("StartTLS Handshake error : \"%s\"", err.Error()))
		res.SetResultCode(ldap.LDAPResultOperationsError)
		w.Write(res)
		return
	}

	m.Client.SetConn(tlsConn)
}

func (server *Server) handleBind(s ldap.UserState, w ldap.ResponseWriter, m *ldap.Message) {
	state := s.(*State)
	r := m.GetBindRequest()

	result_code, err := server.handleBindInternal(state, &r)

	res := ldap.NewBindResponse(result_code)
	if err != nil {
		res.SetDiagnosticMessage(err.Error())
	}
	if result_code == ldap.LDAPResultSuccess {
		server.logger.Printf("Successfully bound to %s", string(r.Name()))
	} else {
		server.logger.Printf("Failed to bind to %s (%s)", string(r.Name()), err)
	}
	w.Write(res)
}

func (server *Server) handleBindInternal(state *State, r *message.BindRequest) (int, error) {
	// Check permissions
	if !server.config.Acl.Check(&state.login, "bind", string(r.Name()), []string{}) {
		return ldap.LDAPResultInsufficientAccessRights, fmt.Errorf("Insufficient access rights for %#v", state.login)
	}

	// Try to retrieve password and check for match
	passwd, err := server.getAttribute(string(r.Name()), ATTR_USERPASSWORD)
	if err != nil {
		return ldap.LDAPResultOperationsError, err
	}
	if passwd == nil {
		return ldap.LDAPResultNoSuchObject, fmt.Errorf("%s has no password", string(r.Name()))
	}

	for _, hash := range passwd {
		valid := SSHAMatches(hash, []byte(r.AuthenticationSimple()))
		if valid {
			groups, err := server.getAttribute(string(r.Name()), ATTR_MEMBEROF)
			if err != nil {
				return ldap.LDAPResultOperationsError, err
			}
			state.login = Login{
				user:   string(r.Name()),
				groups: groups,
			}
			return ldap.LDAPResultSuccess, nil
		}
	}
	return ldap.LDAPResultInvalidCredentials, fmt.Errorf("No password match")
}