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
|
package main
import (
"bytes"
"fmt"
"github.com/gliderlabs/ssh"
"github.com/kr/pty"
"io"
"log"
"net/http"
"os/exec"
)
var (
metrics_num_passwords int
)
func main() {
log.Println("Starting SSH listener")
//// start the ssh server
//go func() {
// listenErr := ssh.ListenAndServe(":2222", nil, ssh.PasswordAuth(handlePass))
// if listenErr != nil {
// log.Fatalln(listenErr.Error())
// }
//}()
go func() {
// star the metrics listener
log.Println("Starting HTTP metrics listener")
http.HandleFunc("/metrics", metricsHandler)
listenErr := http.ListenAndServe(":8080", nil)
if listenErr != nil {
log.Fatalln(listenErr.Error())
}
}()
ssh.Handle(handleConnection)
log.Fatal(ssh.ListenAndServe(":2222", nil, ssh.PasswordAuth(handlePass)))
}
func handleConnection(s ssh.Session) {
cmd := exec.Command("bash")
p, _ := pty.Start(cmd)
go func() {
var readErr error
for readErr == nil {
// create two buffers, one for storing the char input (buf)
// and the other for storing complete commands (commandBuffer)
buf := make([]byte, 1024)
commandBuffer := make([]byte, 0)
// the current char
var char string
// read until ENTER is pressed
for char != "\x0d" {
// read the char inserted by the user into the buffer
_, readErr = s.Read(buf)
if len(bytes.Trim(buf, "\x00")) == 0 {
buf[0] = []byte("\x108\x105")[0]
}
// trim the char and append it to the commandBuffer
currentChar := bytes.Trim(buf, "\x00")[0]
log.Println(currentChar)
// if <C-c> ist pressed, close the connection
if currentChar == []byte("\x03")[0] {
s.Close()
return
}
// append the current char to the command buffer
commandBuffer = append(commandBuffer, currentChar)
// write the char to stdout
char = string(bytes.Trim(buf, "\x00"))
input := string(bytes.Trim(buf, "\x00"))
io.WriteString(s, input)
}
// prepare the command for execution
input := string(bytes.Trim(commandBuffer, "\x00"))
// filter out unwanted commands
filteredInput := filter(input)
// write the string to the commandHandler
io.WriteString(p, filteredInput)
s.Close()
return
}
}()
io.Copy(s, p)
s.Close()
}
func filter(buffer string) string {
//if strings.Contains(buffer, "wget") == false {
// return "\n"
//}
//return buffer
// all ways return a newline -> track what is input
log.Printf("%s", buffer)
return "\n"
}
func handlePass(ctx ssh.Context, pass string) bool {
metrics_num_passwords++
log.Printf("%s@%s: '%s'", ctx.User(), ctx.RemoteAddr().String(), pass)
return true
}
// Handle HTTP /metrics requests
func metricsHandler(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "num_passwords %d\n", metrics_num_passwords)
}
|