-
-
Notifications
You must be signed in to change notification settings - Fork 108
/
server.go
386 lines (331 loc) · 12.1 KB
/
server.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
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"text/template"
"time"
"crawshaw.io/sqlite/sqlitex"
"github.com/google/go-github/v42/github"
"golang.org/x/crypto/ssh"
"golang.org/x/oauth2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var sshConns = promauto.NewCounterVec(prometheus.CounterOpts{Name: "ssh_connections_total"},
[]string{"agent", "x11", "roaming", "keyCount", "identified", "error"})
var hsErrs = promauto.NewCounter(prometheus.CounterOpts{Name: "handshake_errors_total"})
func main() {
metricsMux := http.NewServeMux()
metricsMux.Handle("/metrics", promhttp.Handler())
metricsServer := &http.Server{Addr: ":9091", Handler: metricsMux,
ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second}
go func() { log.Fatal(metricsServer.ListenAndServe()) }()
httpServer := &http.Server{Addr: ":8080",
Handler: http.RedirectHandler("https://words.filippo.io/dispatches/whoami-updated/", 302),
ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second}
go func() { log.Fatal(httpServer.ListenAndServe()) }()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")},
)
tc := oauth2.NewClient(context.Background(), ts)
ghClient := github.NewClient(tc)
_, _, err := ghClient.Users.Get(context.Background(), "")
fatalIfErr(err)
log.Println("Connected to GitHub...")
db, err := sqlitex.Open(os.Getenv("DB_PATH"), 0, 3)
fatalIfErr(err)
log.Println("Opened database...")
server := &Server{
githubClient: ghClient,
db: db,
sessionInfo: make(map[string]sessionInfo),
}
server.sshConfig = &ssh.ServerConfig{
KeyboardInteractiveCallback: server.KeyboardInteractiveCallback,
PublicKeyCallback: server.PublicKeyCallback,
}
private, err := ssh.ParsePrivateKey([]byte(os.Getenv("SSH_HOST_KEY")))
fatalIfErr(err)
server.sshConfig.AddHostKey(private)
privateEd, err := ssh.ParsePrivateKey([]byte(os.Getenv("SSH_HOST_KEY_ED25519")))
fatalIfErr(err)
server.sshConfig.AddHostKey(privateEd)
log.Println("Loaded keys...")
listener, err := net.Listen("tcp", ":2222")
fatalIfErr(err)
log.Println("Listening...")
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Accept failed:", err)
continue
}
go server.Handle(conn)
}
}
func fatalIfErr(err error) {
if err != nil {
log.Fatal(err)
}
}
var termTmpl = template.Must(template.New("termTmpl").Parse(strings.Replace(`
+---------------------------------------------------------------------+
| |
| _o/ Hello {{ .Name }}!
| |
| |
| Did you know that ssh sends all your public keys to any server |
| it tries to authenticate to? |
| |
| We matched them to the keys of your GitHub account, |
| @{{ .User }}, which are available via the GraphQL API
| and at https://github.com/{{ .User }}.keys
| |
| -- Filippo (https://filippo.io) |
| |
| |
| P.S. The source of this server is at |
| https://github.com/FiloSottile/whoami.filippo.io |
| |
+---------------------------------------------------------------------+
`, "\n", "\n\r", -1)))
var failedMsg = []byte(strings.Replace(`
+---------------------------------------------------------------------+
| |
| _o/ Hello! |
| |
| |
| Did you know that ssh sends all your public keys to any server |
| it tries to authenticate to? You can see yours echoed below. |
| |
| We tried to use them to lookup your GitHub account, |
| but got no match :( |
| |
| -- Filippo (https://filippo.io) |
| |
| |
| P.S. The source of this server is at |
| https://github.com/FiloSottile/whoami.filippo.io |
| |
+---------------------------------------------------------------------+
`, "\n", "\n\r", -1))
var agentMsg = []byte(strings.Replace(`
***** WARNING ***** WARNING *****
You have SSH agent forwarding turned (universally?) on.
That is a VERY BAD idea. For example, right now this server
has access to your agent and can use your keys however it
likes as long as you are connected.
ANY SERVER YOU LOG IN TO AND ANYONE WITH ROOT ON
THOSE SERVERS CAN LOGIN AS YOU ANYWHERE.
Read more: http://git.io/vO2A6
`, "\n", "\n\r", -1))
var x11Msg = []byte(strings.Replace(`
***** WARNING ***** WARNING *****
You have X11 forwarding turned (universally?) on.
That is a VERY BAD idea. For example, right now this server
has access to your desktop, windows, and keystrokes
as long as you are connected.
ANY SERVER YOU LOG IN TO AND ANYONE WITH ROOT ON
THOSE SERVERS CAN SNIFF YOUR KEYSTROKES AND ACCESS YOUR WINDOWS.
Read more: http://www.hackinglinuxexposed.com/articles/20040705.html
`, "\n", "\n\r", -1))
var roamingMsg = []byte(strings.Replace(`
***** WARNING ***** WARNING *****
You have roaming turned on. If you are using OpenSSH, that most likely
means you are vulnerable to the CVE-2016-0777 information leak.
THIS MEANS THAT ANY SERVER YOU CONNECT TO MIGHT OBTAIN YOUR PRIVATE KEYS.
Add "UseRoaming no" to the "Host *" section of your ~/.ssh/config or
/etc/ssh/ssh_config file, rotate keys and update ASAP.
Read more: https://www.qualys.com/2016/01/14/cve-2016-0777-cve-2016-0778/openssh-cve-2016-0777-cve-2016-0778.txt
`, "\n", "\n\r", -1))
type sessionInfo struct {
User string
Keys []ssh.PublicKey
}
type Server struct {
githubClient *github.Client
sshConfig *ssh.ServerConfig
db *sqlitex.Pool
mu sync.RWMutex
sessionInfo map[string]sessionInfo
}
func (s *Server) PublicKeyCallback(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
s.mu.Lock()
si := s.sessionInfo[string(conn.SessionID())]
si.User = conn.User()
si.Keys = append(si.Keys, key)
s.sessionInfo[string(conn.SessionID())] = si
s.mu.Unlock()
// Never accept a key, or we might not see the next.
return nil, errors.New("")
}
func (s *Server) KeyboardInteractiveCallback(ssh.ConnMetadata, ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
// keyboard-interactive is tried when all public keys failed, and
// since it's server-driven we can just pass without user
// interaction to let the user in once we got all the public keys.
return nil, nil
}
type logEntry struct {
Timestamp string
Username string `json:",omitempty"`
RequestTypes []string `json:",omitempty"`
Error string `json:",omitempty"`
KeysOffered []string `json:",omitempty"`
GitHubID int64 `json:",omitempty"`
GitHubName string `json:",omitempty"`
ClientVersion string `json:",omitempty"`
}
func (s *Server) Handle(nConn net.Conn) {
conn, chans, reqs, err := ssh.NewServerConn(nConn, s.sshConfig)
if err != nil {
// Port scan, health check, or dictionary attack.
hsErrs.Inc()
return
}
le := &logEntry{Timestamp: time.Now().Format(time.RFC3339)}
defer json.NewEncoder(os.Stdout).Encode(le)
var agentFwd, x11, roaming bool
defer func() {
sshConns.With(prometheus.Labels{
"keyCount": fmt.Sprintf("%v", len(le.KeysOffered)),
"error": fmt.Sprintf("%v", le.Error != ""),
"identified": fmt.Sprintf("%v", le.GitHubID != 0),
"agent": fmt.Sprintf("%v", agentFwd),
"x11": fmt.Sprintf("%v", x11),
"roaming": fmt.Sprintf("%v", roaming),
}).Inc()
s.mu.Lock()
delete(s.sessionInfo, string(conn.SessionID()))
s.mu.Unlock()
time.Sleep(500 * time.Millisecond)
conn.Close()
}()
go func(in <-chan *ssh.Request) {
for req := range in {
le.RequestTypes = append(le.RequestTypes, req.Type)
if req.Type == "roaming@appgate.com" {
roaming = true
}
if req.WantReply {
req.Reply(false, nil)
}
}
}(reqs)
s.mu.RLock()
si := s.sessionInfo[string(conn.SessionID())]
s.mu.RUnlock()
le.Username = conn.User()
le.ClientVersion = string(conn.ClientVersion())
for _, key := range si.Keys {
le.KeysOffered = append(le.KeysOffered, string(ssh.MarshalAuthorizedKey(key)))
}
for newChannel := range chans {
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, requests, err := newChannel.Accept()
if err != nil {
le.Error = "Channel accept failed: " + err.Error()
return
}
defer channel.Close()
reqLock := &sync.Mutex{}
reqLock.Lock()
timeout := time.AfterFunc(30*time.Second, func() { reqLock.Unlock() })
go func(in <-chan *ssh.Request) {
for req := range in {
le.RequestTypes = append(le.RequestTypes, req.Type)
ok := false
switch req.Type {
case "shell":
fallthrough
case "pty-req":
ok = true
// "auth-agent-req@openssh.com" and "x11-req" always arrive
// before the "pty-req", so we can go ahead now
if timeout.Stop() {
reqLock.Unlock()
}
case "auth-agent-req@openssh.com":
agentFwd = true
case "x11-req":
x11 = true
}
if req.WantReply {
req.Reply(ok, nil)
}
}
}(requests)
reqLock.Lock()
if agentFwd {
channel.Write(agentMsg)
}
if x11 {
channel.Write(x11Msg)
}
if roaming {
channel.Write(roamingMsg)
}
userID, err := s.findUser(si.Keys)
if err != nil {
le.Error = "findUser failed: " + err.Error()
return
}
if userID == 0 {
channel.Write(failedMsg)
for _, key := range si.Keys {
channel.Write(ssh.MarshalAuthorizedKey(key))
channel.Write([]byte("\r"))
}
channel.Write([]byte("\n\r"))
return
}
le.GitHubID = userID
u, _, err := s.githubClient.Users.GetByID(context.TODO(), userID)
if err != nil {
le.Error = "getUserName failed: " + err.Error()
return
}
login := *u.Login
le.GitHubName = *u.Login
name := "@" + login
if u.Name != nil {
name = *u.Name
}
termTmpl.Execute(channel, struct{ Name, User string }{name, login})
return
}
}
func (s *Server) findUser(keys []ssh.PublicKey) (int64, error) {
conn := s.db.Get(context.TODO())
if conn == nil {
return 0, errors.New("couldn't get db connection")
}
defer s.db.Put(conn)
for _, pk := range keys {
key := bytes.TrimSpace(ssh.MarshalAuthorizedKey(pk))
keyHash := sha256.Sum256(key)
stmt := conn.Prep("SELECT userID FROM key_userid WHERE keyHash = $kh;")
stmt.SetBytes("$kh", keyHash[:16])
if hasRow, err := stmt.Step(); err != nil {
return 0, err
} else if !hasRow {
continue
}
defer stmt.Reset()
return stmt.GetInt64("userID"), nil
}
return 0, nil
}