-
Notifications
You must be signed in to change notification settings - Fork 1
/
goklp.go
346 lines (307 loc) · 8.15 KB
/
goklp.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 (
"crypto/tls"
"fmt"
"log"
"log/syslog"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/asaskevich/govalidator"
"github.com/docopt/docopt-go"
"github.com/kardianos/osext"
"github.com/vaughan0/go-ini"
"gopkg.in/ldap.v2"
)
const version = "1.6"
var usage = `goklp: OpenSSH Keys LDAP Provider for AuthorizedKeysCommand
Usage:
goklp <username>
goklp [--config=<config>] <username>
goklp -h --help
goklp --version
Options:
--version Show version.
-h, --help Show this screen.
-c, --config=<file> Path to goklp config file
Config file is required, named: goklp.ini or passed using --config=/path/to/file
goklp_ldap_uri = ldaps://server1:636,ldaps://server2:636 (required)
goklp_ldap_bind_dn = CN=someuser,O=someorg,C=sometld (required)
goklp_ldap_base_dn = O=someorg,C=sometld (required)
goklp_ldap_bind_pw = someSecretPassword (required)
goklp_ldap_timeout_secs = 10 (optional - default: 5)
goklp_ldap_user_attr = 10 (optional - default: uid)
goklp_debug = true (optional - default: false)
goklp_console = true (optional - default: false)
goklp_insecure_skip_verify = false (optional - default: false)
`
type opts struct {
username string
goklp_config_file string
goklp_ldap_base_dn string
goklp_ldap_bind_dn string
goklp_ldap_bind_pw string
goklp_ldap_user_attr string
goklp_ldap_uris []string
goklp_debug bool
goklp_console bool
goklp_insecure_skip_verify bool
goklp_ldap_timeout time.Duration
}
type query struct {
ldapURL string
baseDN string
filter string
Attributes []string
user string
passwd string
timeout time.Duration
}
type result struct {
sr *ldap.SearchResult
ldapURL string
}
// //
func main() {
// parse options and config file
o, err := getOpts()
if err != nil {
log.Fatal(err)
}
// setup logging
if o.goklp_debug {
if !o.goklp_console {
logger, err := syslog.New(syslog.LOG_DEBUG|syslog.LOG_USER, "goklp")
if err != nil {
log.Fatal(err)
}
log.SetOutput(logger)
}
}
// Finding our config file to parse
configFile, err := findConfigFile(o.goklp_config_file)
err = parseConfigFile(configFile, o)
if err != nil {
log.Fatal(err)
}
// run ldapsearch
keys, err := o.ldapsearch()
if err != nil {
if o.goklp_debug {
log.Println(fmt.Sprintf("Error in query while looking for keys for %s: %s", o.username, err.Error()))
}
}
// output keys
if len(keys) > 0 {
fmt.Println(strings.Join(keys, "\n"))
}
if o.goklp_debug {
log.Println(fmt.Sprintf("Successfully found %d keys for %s", len(keys), o.username))
}
}
// //
func (o *opts) ldapsearch() ([]string, error) {
keys := []string{}
// parallel search
ch := make(chan result, 1)
for _, server_url := range o.goklp_ldap_uris {
q := query{
baseDN: o.goklp_ldap_base_dn,
filter: fmt.Sprintf("(%s=%s)", o.goklp_ldap_user_attr, o.username),
Attributes: []string{"sshPublicKey"},
user: o.goklp_ldap_bind_dn,
passwd: o.goklp_ldap_bind_pw,
ldapURL: server_url,
}
go func() {
sr, err := o.doquery(q)
if err != nil {
log.Fatal(err)
return
}
r := result{sr: sr, ldapURL: q.ldapURL}
select {
case ch <- r:
default:
}
}()
}
select {
case r := <-ch:
if len(r.sr.Entries) > 1 {
return keys, fmt.Errorf("Too many results found.")
}
if len(r.sr.Entries) == 1 {
for _, attr := range r.sr.Entries[0].Attributes {
if attr.Name == "sshPublicKey" {
keys = append(keys, attr.Values...)
}
}
}
case <-time.After(o.goklp_ldap_timeout):
return keys, fmt.Errorf("No response before timeout.")
}
return keys, nil
}
// //
func (o *opts) doquery(q query) (*ldap.SearchResult, error) {
sr := &ldap.SearchResult{}
// parse the ldap URL
u, err := url.Parse(q.ldapURL)
if err != nil {
return sr, err
}
var port int
if u.Scheme == "ldaps" {
port = 636
} else if u.Scheme == "ldap" {
port = 389
} else {
return sr, fmt.Errorf("Unknown LDAP scheme: %s", u.Scheme)
}
parts := strings.Split(u.Host, ":")
hostname := parts[0]
if len(parts) > 1 {
port, err = strconv.Atoi(parts[1])
if err != nil {
return sr, err
}
}
// connect to the ldap server
var l *ldap.Conn
if u.Scheme == "ldaps" {
tlsConfig := tls.Config{}
if o.goklp_insecure_skip_verify {
tlsConfig.InsecureSkipVerify = true
} else {
tlsConfig.ServerName = hostname
}
l, err = ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", hostname, port), &tlsConfig)
if err != nil {
return sr, err
}
} else if u.Scheme == "ldap" {
l, err = ldap.Dial("tcp", fmt.Sprintf("%s:%d", hostname, port))
if err != nil {
return sr, err
}
}
defer l.Close()
// do an ldap bind
err = l.Bind(q.user, q.passwd)
if err != nil {
return sr, err
}
// do the ldap search
search := ldap.NewSearchRequest(
q.baseDN,
ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases, 0, 0, false,
q.filter,
q.Attributes,
nil)
sr, err = l.Search(search)
if err != nil {
return sr, err
}
return sr, nil
}
// //
func getOpts() (*opts, error) {
o := &opts{}
arguments, err := docopt.Parse(usage, nil, true, version, false)
if err != nil {
return o, err
}
o.username = arguments["<username>"].(string)
if arguments["--config"] != nil {
if ok, _ := govalidator.IsFilePath(arguments["--config"].(string)); ok == false {
panic(err)
} else {
o.goklp_config_file = arguments["--config"].(string)
}
} else {
o.goklp_config_file = ""
}
return o, nil
}
func findConfigFile(argConfigFile string) (string, error) {
var configFile string
if len(argConfigFile) > 0 {
configFile = argConfigFile
} else {
myDirectory, err := osext.ExecutableFolder()
if err != nil {
log.Fatal(err)
return "", err
}
configFile = myDirectory + "/goklp.ini"
}
fileInfo, err := os.Stat(configFile)
if err != nil {
log.Fatal(err)
return "", err
}
// enforce reasonable config file security
if !strings.HasSuffix(fileInfo.Mode().String(), "------") {
errMsg := fmt.Sprintf("Permissions on goklp.ini are too loose - try 'chmod 0600 %s'", configFile)
fmt.Errorf(errMsg)
log.Fatal(errMsg)
return "", err
}
return configFile, nil
}
func parseConfigFile(configFile string, o *opts) error {
// handle config file
config, err := ini.LoadFile(configFile)
if err != nil {
return err
}
goklp_ldap_uri, exists := config[""]["goklp_ldap_uri"]
if !exists {
return fmt.Errorf("Config option goklp_ldap_uri is not set.")
}
o.goklp_ldap_uris = strings.Split(goklp_ldap_uri, ",")
o.goklp_ldap_bind_dn, exists = config[""]["goklp_ldap_bind_dn"]
if !exists {
return fmt.Errorf("Config option goklp_ldap_bind_dn is not set.")
}
o.goklp_ldap_base_dn, exists = config[""]["goklp_ldap_base_dn"]
if !exists {
return fmt.Errorf("Config option goklp_ldap_base_dn is not set.")
}
o.goklp_ldap_bind_pw, exists = config[""]["goklp_ldap_bind_pw"]
if !exists {
return fmt.Errorf("Config option goklp_ldap_bind_pw is not set.")
}
// default to 5 second timeout
goklp_ldap_timeout_secs := 5
goklp_ldap_timeout_str, exists := config[""]["goklp_ldap_timeout"]
if exists {
goklp_ldap_timeout_secs, err = strconv.Atoi(goklp_ldap_timeout_str)
if err != nil {
return fmt.Errorf("Invalid timeout in goklp_ldap_timeout.")
}
}
o.goklp_ldap_timeout = time.Duration(goklp_ldap_timeout_secs) * time.Second
goklp_ldap_user_attr, exists := config[""]["goklp_ldap_user_attr"]
if !exists {
o.goklp_ldap_user_attr = "uid"
} else {
o.goklp_ldap_user_attr = goklp_ldap_user_attr
}
// debugging goes to syslog
if s, exists := config[""]["goklp_debug"]; exists && s == "true" {
o.goklp_debug = true
}
// or to console
if s, exists := config[""]["goklp_console"]; exists && s == "true" {
o.goklp_console = true
}
if s, exists := config[""]["goklp_insecure_skip_verify"]; exists && s == "true" {
o.goklp_insecure_skip_verify = true
}
return nil
}