-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.go
275 lines (239 loc) · 6.95 KB
/
gateway.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
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"time"
"gopkg.in/yaml.v2"
"github.com/gliderlabs/ssh"
gossh "golang.org/x/crypto/ssh"
)
// Config holds the authentication details
type Config struct {
ValidSSHKeys map[string]gossh.PublicKey // map[username]publicKey
PrivateKeys map[string]string // map[username]privateKeyPath
Allowlist []*net.IPNet // list of allowlisted IPs or IP ranges
HoneypotAddr string `yaml:"honeypot_addr"`
RealSSHAddr string `yaml:"real_ssh_addr"`
SSHPort int `yaml:"ssh_port"`
LogFilePath string `yaml:"log_file_path"`
}
type User struct {
Username string `yaml:"username"`
SSHKey string `yaml:"ssh_key,omitempty"`
PrivateKey string `yaml:"private_key,omitempty"`
}
var config Config
func loadConfig(filePath string) error {
config.ValidSSHKeys = make(map[string]gossh.PublicKey)
config.PrivateKeys = make(map[string]string)
// Load the config file
data, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
var rawConfig struct {
HoneypotAddr string `yaml:"honeypot_addr"`
RealSSHAddr string `yaml:"real_ssh_addr"`
SSHPort int `yaml:"ssh_port"`
Allowlist []string `yaml:"allowlist"`
LogFilePath string `yaml:"log_file_path"`
Users []User `yaml:"users"`
}
err = yaml.Unmarshal(data, &rawConfig)
if err != nil {
return err
}
config.HoneypotAddr = rawConfig.HoneypotAddr
config.RealSSHAddr = rawConfig.RealSSHAddr
config.SSHPort = rawConfig.SSHPort
config.LogFilePath = rawConfig.LogFilePath
// Parse allowlist
for _, cidr := range rawConfig.Allowlist {
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
ip := net.ParseIP(cidr)
if ip == nil {
log.Printf("Invalid IP range: %s", cidr)
} else {
ipNet = &net.IPNet{
IP: ip,
Mask: net.CIDRMask(32, 32),
}
}
}
config.Allowlist = append(config.Allowlist, ipNet)
}
// Parse users
for _, user := range rawConfig.Users {
if user.SSHKey != "" {
parsedKey, _, _, _, err := gossh.ParseAuthorizedKey([]byte(user.SSHKey))
if err != nil {
log.Printf("Failed to parse SSH key for user %s: %v", user.Username, err)
continue
}
config.ValidSSHKeys[user.Username] = parsedKey
config.PrivateKeys[user.Username] = user.PrivateKey
log.Printf("Loaded SSH key for user %s: %s", user.Username, gossh.MarshalAuthorizedKey(parsedKey))
} else {
log.Printf("Invalid user configuration: %v", user)
}
}
return nil
}
func isAllowlisted(ip string) bool {
for _, ipNet := range config.Allowlist {
if ipNet.Contains(net.ParseIP(ip)) {
return true
}
}
return false
}
func logMatchedKeyConnection(username, ip string) {
f, err := os.OpenFile(config.LogFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Printf("Failed to open log file: %v", err)
return
}
defer f.Close()
logEntry := fmt.Sprintf("%s - Username: %s, IP: %s\n", time.Now().Format(time.RFC3339), username, ip)
if _, err := f.WriteString(logEntry); err != nil {
log.Printf("Failed to write to log file: %v", err)
}
}
func main() {
configFilePath := "config.yaml" // Path to your config file
err := loadConfig(configFilePath)
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
sshServer := &ssh.Server{
Addr: fmt.Sprintf(":%d", config.SSHPort),
Handler: func(s ssh.Session) {
user := s.User()
clientIP := s.RemoteAddr().String()
log.Printf("Session started for user %s from IP %s", user, clientIP)
if isAllowlisted(clientIP) {
log.Printf("IP %s is allowlisted, forwarding to real server", clientIP)
forwardConnection(s, config.RealSSHAddr)
return
}
pubKey := s.PublicKey()
if pubKey != nil {
marshaledKey := string(gossh.MarshalAuthorizedKey(pubKey))
log.Printf("Received public key for user %s: %s", user, marshaledKey)
if validateSSHKey(user, pubKey) {
log.Printf("SSH key for user %s matches, forwarding to honeypot", user)
logMatchedKeyConnection(user, clientIP)
privateKeyPath := config.PrivateKeys[user]
forwardToHoneypot(s, config.HoneypotAddr, user, privateKeyPath)
return
} else {
log.Printf("SSH key for user %s does not match, forwarding to real server", user)
}
} else {
log.Printf("No public key received for user %s, forwarding to real server", user)
}
forwardConnection(s, config.RealSSHAddr)
},
PublicKeyHandler: func(ctx ssh.Context, key ssh.PublicKey) bool {
// This will be called during authentication
return true
},
}
log.Printf("Starting SSH proxy server on :%d", config.SSHPort)
log.Fatal(sshServer.ListenAndServe())
}
func validateSSHKey(username string, key gossh.PublicKey) bool {
if storedKey, ok := config.ValidSSHKeys[username]; ok {
marshaledKey := gossh.MarshalAuthorizedKey(key)
storedMarshaledKey := gossh.MarshalAuthorizedKey(storedKey)
log.Printf("Comparing provided key:\n%s\nwith stored key:\n%s", marshaledKey, storedMarshaledKey)
return string(marshaledKey) == string(storedMarshaledKey)
}
log.Printf("No valid SSH key found for user %s", username)
return false
}
func forwardToHoneypot(s ssh.Session, honeypotAddr, username, privateKeyPath string) {
privateKey, err := ioutil.ReadFile(privateKeyPath)
if err != nil {
log.Printf("Failed to read private key file: %v", err)
s.Exit(1)
return
}
signer, err := gossh.ParsePrivateKey(privateKey)
if err != nil {
log.Printf("Failed to parse private key: %v", err)
s.Exit(1)
return
}
config := &gossh.ClientConfig{
User: username,
Auth: []gossh.AuthMethod{
gossh.PublicKeys(signer),
},
HostKeyCallback: gossh.InsecureIgnoreHostKey(),
}
client, err := gossh.Dial("tcp", honeypotAddr, config)
if err != nil {
log.Printf("Failed to connect to honeypot: %v", err)
s.Exit(1)
return
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
log.Printf("Failed to create session: %v", err)
s.Exit(1)
return
}
defer session.Close()
// Set up the channels to proxy the data
stdin, err := session.StdinPipe()
if err != nil {
log.Printf("Unable to setup stdin for session: %v", err)
s.Exit(1)
return
}
stdout, err := session.StdoutPipe()
if err != nil {
log.Printf("Unable to setup stdout for session: %v", err)
s.Exit(1)
return
}
stderr, err := session.StderrPipe()
if err != nil {
log.Printf("Unable to setup stderr for session: %v", err)
s.Exit(1)
return
}
go io.Copy(stdin, s)
go io.Copy(s, stdout)
go io.Copy(s.Stderr(), stderr)
err = session.Shell()
if err != nil {
log.Printf("Failed to start shell: %v", err)
s.Exit(1)
return
}
err = session.Wait()
if err != nil {
log.Printf("Session ended with error: %v", err)
}
}
func forwardConnection(s ssh.Session, addr string) {
client, err := net.Dial("tcp", addr)
if err != nil {
log.Printf("Failed to connect to %s: %v", addr, err)
s.Exit(1)
return
}
defer client.Close()
go func() {
io.Copy(client, s)
}()
io.Copy(s, client)
}