-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglauth.go
More file actions
319 lines (274 loc) · 8.03 KB
/
glauth.go
File metadata and controls
319 lines (274 loc) · 8.03 KB
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
package main
import (
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"time"
"github.com/fsnotify/fsnotify"
"github.com/glauth/glauth/pkg/config"
gologgingr "github.com/glauth/glauth/pkg/gologgingr"
"github.com/glauth/glauth/pkg/server"
"github.com/go-logr/logr"
logging "github.com/op/go-logging"
)
const programName = "glauth"
var usage = `glauth: expose caddy-auth-portal config for LDAP auth
Usage:
glauth [options] -c <file>
glauth -h --help
glauth -version
Options:
`
type caddyAuthUser struct {
Username string
Id string
EmailAddresses []struct {
Address string
Domain string
} `json:"email_addresses"`
Passwords []struct {
Algorithm string
Hash string
// TODO: Expired and disabled
}
Roles []struct {
Name string
}
}
type caddyAuthConfig struct {
Revision int
Users []caddyAuthUser
}
var (
log logr.Logger
stderr *logging.LogBackend
activeConfig = &config.Config{}
)
// Reads builtime vars and returns a full string containing info about
// the currently running version of the software. Primarily used by the
// --version flag at runtime.
func getVersionString() string {
return "GLauth\nNon-release build for caddy-auth-portal\n\n"
}
func main() {
stderr = initLogging()
log.V(6).Info("AP start")
flag.StringVar(&activeConfig.ConfigFile, "c", "", "Config file.")
flag.StringVar(&activeConfig.Backend.BaseDN, "basedn", "dc=glauth,dc=local", "LDAP Base domain")
flag.StringVar(&activeConfig.LDAP.Listen, "ldap", "", "ldap bind address")
flag.StringVar(&activeConfig.LDAPS.Listen, "ldaps", "", "ldaps bind address")
flag.StringVar(&activeConfig.LDAPS.Cert, "ldaps-cert", "", "ldaps certificate")
flag.StringVar(&activeConfig.LDAPS.Key, "ldaps-key", "", "ldaps key")
flag.BoolVar(&activeConfig.Debug, "v", false, "Debug logging")
version := flag.Bool("version", false, "ldaps key")
flag.Usage = func() {
fmt.Fprint(os.Stderr, usage)
flag.PrintDefaults()
}
flag.Parse()
if *version {
fmt.Fprintln(os.Stderr, getVersionString())
os.Exit(0)
}
// Setup a default backend
// activeConfig.Backend.BaseDN
activeConfig.Backend.Datastore = "config"
activeConfig.Backend.NameFormat = "cn"
activeConfig.Backend.GroupFormat = "ou"
activeConfig.Backend.SSHKeyAttr = "sshPublicKey"
activeConfig.Backends = append(activeConfig.Backends, activeConfig.Backend)
// The listen fields are configured from the cli
activeConfig.LDAP.Enabled = len(activeConfig.LDAP.Listen) != 0
activeConfig.LDAPS.Enabled = len(activeConfig.LDAPS.Listen) != 0
if len(activeConfig.ConfigFile) == 0 {
log.Error(fmt.Errorf("configuration file not specified"), "Configuration file error")
os.Exit(1)
}
if !activeConfig.LDAP.Enabled && !activeConfig.LDAPS.Enabled {
log.Error(fmt.Errorf("no server configuration found: please provide either LDAP or LDAPS configuration"), "Configuration file error")
os.Exit(1)
}
// Load the JSON config
if err := updateConfig(); err != nil {
log.Error(err, "Configuration file error")
os.Exit(1)
}
log.V(3).Info("Loaded users and groups from config")
stderr = initLogging()
startService()
}
func startService() {
startConfigWatcher()
s, err := server.NewServer(
server.Logger(log),
server.Config(activeConfig),
)
if err != nil {
log.Error(err, "Could not create server")
os.Exit(1)
}
if activeConfig.LDAP.Enabled {
// Don't block if also starting a LDAPS server afterwards
shouldBlock := !activeConfig.LDAPS.Enabled
if shouldBlock {
if err := s.ListenAndServe(); err != nil {
log.Error(err, "Could not start LDAP server")
os.Exit(1)
}
} else {
go func() {
if err := s.ListenAndServe(); err != nil {
log.Error(err, "Could not start LDAP server")
os.Exit(1)
}
}()
}
}
if activeConfig.LDAPS.Enabled {
// Always block here
if err := s.ListenAndServeTLS(); err != nil {
log.Error(err, "Could not start LDAPS server")
os.Exit(1)
}
}
log.V(0).Info("AP exit")
os.Exit(1)
}
func startConfigWatcher() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Error(err, "Could not start config-watcher")
return
}
ticker := time.NewTicker(1 * time.Second)
go func() {
isChanged, isRemoved := false, false
for {
select {
case event := <-watcher.Events:
log.V(6).Info("watcher got event", "e", event.Op.String())
if event.Op&fsnotify.Write == fsnotify.Write {
isChanged = true
} else if event.Op&fsnotify.Remove == fsnotify.Remove { // vim edit file with rename/remove
isChanged, isRemoved = true, true
}
case err := <-watcher.Errors:
log.Error(err, "Error!")
case <-ticker.C:
// wakeup, try finding removed config
}
if _, err := os.Stat(activeConfig.ConfigFile); !os.IsNotExist(err) && (isRemoved || isChanged) {
if isRemoved {
log.V(6).Info("rewatching config", "file", activeConfig.ConfigFile)
watcher.Add(activeConfig.ConfigFile) // overwrite
isChanged, isRemoved = true, false
}
if isChanged {
if err := updateConfig(); err != nil {
log.V(2).Info("Could not reload config. Holding on to old config", "error", err.Error())
} else {
log.V(3).Info("Config was reloaded")
}
isChanged = false
}
}
}
}()
watcher.Add(activeConfig.ConfigFile)
}
/* Update the in-memory users and groups from the JSON file on disk.
If errors occur, it will return before changing the users/groups
*/
func updateConfig() error {
c := &caddyAuthConfig{} // JSON file from caddy auth portal
bytes, err := ioutil.ReadFile(activeConfig.ConfigFile)
if err != nil {
return err
}
if err := json.Unmarshal(bytes, c); err != nil {
return err
}
nextGid := 1001
// Convert the caddyAuth config into a glauth config
configUsers := make([]config.User, 0, len(c.Users))
// Make a default group and set it as the primary group for all users
groups := map[string]int{
"user": 1000,
}
groupsInverse := map[int]string{
1000: "user",
}
for i, user := range c.Users {
u := config.User{
Name: user.Username,
UIDNumber: 1000 + i, // Doesnt really matter
PrimaryGroup: 1000,
OtherGroups: make([]int, 0),
}
if len(user.EmailAddresses) > 0 {
u.Mail = user.EmailAddresses[0].Address
}
if len(user.Passwords) == 0 {
continue
}
pw := user.Passwords[0]
if pw.Algorithm != "bcrypt" {
return fmt.Errorf("invalid password type %s for user %s", pw.Algorithm, user.Username)
}
u.PassBcrypt = hex.EncodeToString([]byte(pw.Hash))
// Add the roles
for _, r := range user.Roles {
// use the existing group or make a new one
if id, ok := groups[r.Name]; ok {
u.OtherGroups = append(u.OtherGroups, id)
} else {
groups[r.Name] = nextGid
u.OtherGroups = append(u.OtherGroups, nextGid)
groupsInverse[nextGid] = r.Name
nextGid++
}
}
configUsers = append(configUsers, u)
}
activeConfig.Users = configUsers
activeConfig.Groups = make([]config.Group, 0, len(groups))
for group, gid := range groups {
activeConfig.Groups = append(activeConfig.Groups, config.Group{
Name: group,
GIDNumber: gid,
})
}
// log the users
if activeConfig.Debug {
for _, u := range activeConfig.Users {
groups := make([]string, 0, len(u.OtherGroups))
for _, g := range u.OtherGroups {
groups = append(groups, groupsInverse[g])
}
fmt.Println(u.Name, groups)
}
}
return nil
}
// initLogging sets up logging to stderr
func initLogging() *logging.LogBackend {
l := logging.MustGetLogger(programName)
l.ExtraCalldepth = 2 // add extra call depth for the logr wrapper
log = gologgingr.New(
gologgingr.Logger(l),
)
gologgingr.SetVerbosity(10) // do not filter by verbosity. glauth uses the go-logging lib to filter the levels
format := "%{color}%{time:15:04:05.000000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}"
logBackend := logging.NewLogBackend(os.Stderr, "", 0)
logging.SetBackend(logBackend)
logging.SetLevel(logging.NOTICE, programName)
logging.SetFormatter(logging.MustStringFormatter(format))
if activeConfig.Debug {
logging.SetLevel(logging.DEBUG, programName)
log.V(6).Info("Debugging enabled")
}
return logBackend
}