-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
443 lines (350 loc) · 9.98 KB
/
main.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
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
package main
import (
"bufio"
"encoding/hex"
"fmt"
"io"
"log"
"log/syslog"
"net"
"net/http"
"net/http/httputil"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
)
// Build A version string that can be set with
//
// -ldflags "-X main.Build=SOMEVERSION"
//
// at compile-time.
var Build string
const (
appName = "james"
)
var (
fingerprint string
home string
key string
keytype string
uid string
username string
hostname string
port uint16
useSyslog = true
url string
guessRemoteIP bool
remoteIP string
dumpPath string
rootCmd = &cobra.Command{
Use: appName,
PreRun: prerun,
Short: "A helper for OpenSSH's AuthorizedKeysCommand",
Run: root,
Version: Build,
}
dumpWriter io.Writer
)
// fqdn will try to guess the FQDN based on the same technique used by
// hostname -f.
func fqdn() string {
// Use Go's standard library hysteresis to determine the hostname.
hostname, err := os.Hostname()
if err != nil {
return ""
}
// Get an IP for the hostname returned from /etc/hostname.
ips, err := net.LookupIP(hostname)
if err != nil {
return hostname
}
for _, ip := range ips {
// We only do the lookup on 127.0.0.0/8 IP adresses to avoid
// depending on a resolver that might resolve one of our
// networked IP's to something generic and non-usable for
// our use-case.
if ipv4 := ip.To4(); ipv4 != nil && ip.IsLoopback() {
ip, err := ipv4.MarshalText()
if err != nil {
return hostname
}
hosts, err := net.LookupAddr(string(ip))
if err != nil || len(hosts) == 0 {
return hostname
}
return strings.TrimSuffix(hosts[0], ".")
}
}
return hostname
}
func init() {
helpFlag := false
// Trick to use '-h' for something else than help. This works by
// replacing the default help flag with one with no shorthand set.
rootCmd.PersistentFlags().BoolVarP(&helpFlag, "help", "", false, "Help for "+os.Args[0])
// Tokens supported by OpenSSH server.
rootCmd.PersistentFlags().StringVarP(&fingerprint, "fingerprint", "f", "", "The fingerprint of the key or certificate (%f)")
rootCmd.PersistentFlags().StringVarP(&home, "home", "h", "", "The home directory of the user (%h)")
rootCmd.PersistentFlags().StringVarP(&key, "key", "k", "", "The base64-encoded key or certificate for authentication (%k)")
rootCmd.PersistentFlags().StringVarP(&keytype, "keytype", "t", "", "The key or certificate type (%t)")
rootCmd.PersistentFlags().StringVarP(&uid, "uid", "U", "", "The numeric user ID of the target user (%U)")
rootCmd.PersistentFlags().StringVarP(&username, "username", "u", "", "The username (%u)")
rootCmd.PersistentFlags().StringVarP(&hostname, "hostname", "", fqdn(), "The local hostname")
rootCmd.PersistentFlags().Uint16VarP(&port, "port", "", 22, "The port SSH is listening to")
rootCmd.PersistentFlags().StringVarP(&url, "url", "", "", "URL to use")
rootCmd.PersistentFlags().BoolVarP(&guessRemoteIP, "guess-remote-ip", "", true, "Try to guess remote IP. Requires root")
rootCmd.PersistentFlags().StringVarP(&remoteIP, "remote-ip", "", "", "The IP address of the connecting user")
rootCmd.PersistentFlags().BoolVarP(&useSyslog, "use-syslog", "", useSyslog, "Log to syslog")
rootCmd.PersistentFlags().StringVarP(&dumpPath, "dump", "", "", "Dump HTTP request/response to path")
}
func prerun(_ *cobra.Command, _ []string) {
if useSyslog {
writer, err := syslog.New(syslog.LOG_ERR|syslog.LOG_AUTH, appName)
if err != nil {
log.Fatalf("Error connecting to syslog: %s", err.Error())
}
log.SetOutput(writer)
}
if dumpPath != "" {
w, err := os.OpenFile(dumpPath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatalf("Error opening %s: %s", dumpPath, err.Error())
}
dumpWriter = w
}
}
// httpDo will try a http request multiple times if the server responds
// with an internal error.
func httpDo(req *http.Request) (*http.Response, error) {
backOff := time.Millisecond * 250
req.Header.Set("User-Agent", fmt.Sprintf("%s/1.0", strings.Title(appName)))
if req.Body != nil {
panic("httpDo() only supports requests without body")
}
if dumpWriter != nil {
d, _ := httputil.DumpRequestOut(req, false)
_, _ = dumpWriter.Write(d)
}
for retryCount := 0; retryCount < 5; retryCount++ {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if dumpWriter != nil {
d, _ := httputil.DumpResponse(resp, false)
_, _ = dumpWriter.Write(d)
}
if resp.StatusCode < 500 {
return resp, err
}
err = resp.Body.Close()
if err != nil {
return nil, err
}
time.Sleep(backOff * time.Duration(retryCount))
}
return nil, fmt.Errorf("giving up on %s", url)
}
func root(_ *cobra.Command, _ []string) {
if url == "" {
url = fmt.Sprintf("https://github.com/%s.keys", username)
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatalf("Error: %s", err.Error())
}
q := req.URL.Query()
req.URL.RawQuery = q.Encode()
switch {
case remoteIP != "":
q.Add("remote_ip", remoteIP)
case guessRemoteIP:
sockets, err := getOpenSockets(os.Getppid())
if err != nil {
log.Fatalf("Error: %s", err.Error())
}
connections4, err := getTCP4Connections(sockets)
if err != nil {
log.Fatalf("Error: %s", err.Error())
}
connections6, err := getTCP6Connections(sockets)
if err != nil {
log.Fatalf("Error: %s", err.Error())
}
if len(connections4) == len(connections6) && len(connections4) == 1 {
ip4 := connections4[0]
ip6 := connections6[0]
if !ip4.Equal(ip6) {
log.Fatalf("Unable to guess remote IP, found unmatching ipv4 and ipv6 addr %s != %s", ip4.String(), ip6.String())
}
// Just keep the ipv4 if we get the same ip in both forms
connections6 = nil
}
connections := append(connections4, connections6...)
connectionsMap := make(map[string]bool, len(connections))
for _, ip := range connections {
connectionsMap[ip.String()] = true
}
if len(connectionsMap) != 1 {
log.Fatalf("Unable to guess remote IP for %s. %d results returned, connectionMap '%v', ipv4 connections '%v' , ipv6 connections '%v'", hostname, len(connectionsMap), connectionsMap, connections4, connections6)
}
q.Add("remote_ip", connections[0].String())
}
q.Add("service_hostname", hostname)
if port != 0 && port != 22 {
q.Add("service_port", strconv.Itoa(int(port)))
}
if fingerprint != "" {
q.Add("fingerprint", fingerprint)
}
if home != "" {
q.Add("home", home)
}
if key != "" {
q.Add("key", key)
}
if keytype != "" {
q.Add("keytype", keytype)
}
if uid != "" {
q.Add("uid", uid)
}
if username != "" {
q.Add("username", username)
}
req.URL.RawQuery = q.Encode()
resp, err := httpDo(req)
if err != nil {
log.Fatalf("HTTP error: %s", err.Error())
}
defer resp.Body.Close()
_, err = io.Copy(os.Stdout, resp.Body)
if err != nil {
log.Fatalf("Error copying response to stdout: %s", err.Error())
}
}
func getOpenSockets(pid int) ([]int, error) {
t := regexp.MustCompile(`socket:\[([0-9]*)\]`)
fdPath := fmt.Sprintf("/proc/%d/fd", pid)
f, err := os.Open(fdPath)
if err != nil {
return nil, err
}
defer f.Close()
names, err := f.Readdirnames(-1)
if err != nil {
return nil, err
}
var sockets []int
for _, name := range names {
resolved, err := os.Readlink(fdPath + "/" + name)
if err != nil {
continue
}
// Check if it's a socket.
matches := t.FindSubmatch([]byte(resolved))
if len(matches) > 1 {
i, err := strconv.Atoi(string(matches[1]))
if err != nil {
continue
}
sockets = append(sockets, i)
}
}
return sockets, nil
}
func hexToIP(hexStr string) (net.IP, error) {
data, err := hex.DecodeString(hexStr)
if err != nil {
return nil, err
}
ip := net.IP{data[3], data[2], data[1], data[0]}
return ip, nil
}
func hexToIP6(hexStr string) (net.IP, error) {
data, err := hex.DecodeString(hexStr)
if err != nil {
return nil, err
}
ip := net.IP{data[3], data[2], data[1], data[0], data[7], data[6], data[5], data[4], data[11], data[10], data[9], data[8], data[15], data[14], data[13], data[12]}
return ip, nil
}
func getTCP4Connections(sockets []int) ([]net.IP, error) {
t := regexp.MustCompile(`\w[0-9]*\:\ [0-9A-F]{8}:[0-9A-F]{4} ([0-9A-F]{8}):[0-9A-F]{4} [0-9A-F]{2} [0-9A-F]{8}:[0-9A-F]{8} [0-9A-F]{2}:[0-9A-F]{8} [0-9A-F]{8} *[0-9]* *[0-9] ([0-9]*)`)
f, err := os.Open("/proc/net/tcp")
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
// Throw away the first line containing headers.
scanner.Scan()
var connections []net.IP
for scanner.Scan() {
line := scanner.Bytes()
matches := t.FindSubmatch(line)
if len(matches) > 2 {
inode, err := strconv.Atoi(string(matches[2]))
if err != nil {
return nil, err
}
for _, s := range sockets {
if s == inode {
ip, err := hexToIP(string(matches[1]))
if err != nil {
return nil, err
}
connections = append(connections, ip)
}
}
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return connections, nil
}
func getTCP6Connections(sockets []int) ([]net.IP, error) {
t := regexp.MustCompile(`\w[0-9]*\:\ [0-9A-F]{32}:[0-9A-F]{4} ([0-9A-F]{32}):[0-9A-F]{4} [0-9A-F]{2} [0-9A-F]{8}:[0-9A-F]{8} [0-9A-F]{2}:[0-9A-F]{8} [0-9A-F]{8} *[0-9]* *[0-9] ([0-9]*)`)
f, err := os.Open("/proc/net/tcp6")
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
// Throw away the first line containing headers.
scanner.Scan()
var connections []net.IP
for scanner.Scan() {
line := scanner.Bytes()
matches := t.FindSubmatch(line)
if len(matches) > 2 {
inode, err := strconv.Atoi(string(matches[2]))
if err != nil {
return nil, err
}
for _, s := range sockets {
if s == inode {
ip, err := hexToIP6(string(matches[1]))
if err != nil {
return nil, err
}
connections = append(connections, ip)
}
}
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return connections, nil
}
func main() {
err := rootCmd.Execute()
if err != nil {
log.Fatalf("Error: %s", err.Error())
}
}