-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkangaroo.go
287 lines (254 loc) · 6.47 KB
/
kangaroo.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
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/gliderlabs/ssh"
"github.com/hamptonmoore/ping"
gossh "golang.org/x/crypto/ssh"
)
// direct-tcpip data struct as specified in RFC4254, Section 7.2
type localForwardChannelData struct {
DestAddr string
DestPort uint32
OriginAddr string
OriginPort uint32
}
func IPInPolicy(src net.IP, sets []string) bool {
for _, name := range sets {
ipSets := compiledIPSets[name]
for _, ipnet := range ipSets {
if ipnet.Contains(src) {
return true
}
}
}
return false
}
func customDirectHandler(srv *ssh.Server, conn *gossh.ServerConn, newChan gossh.NewChannel, ctx ssh.Context) {
d := localForwardChannelData{}
if err := gossh.Unmarshal(newChan.ExtraData(), &d); err != nil {
newChan.Reject(gossh.ConnectionFailed, "error parsing forward data: "+err.Error())
return
}
dhost := d.DestAddr
// Lets get the IP address of the remote host
addrs, err := net.LookupIP(dhost)
if err != nil {
newChan.Reject(gossh.ConnectionFailed, "error looking up IP: "+err.Error())
return
}
if len(addrs) == 0 {
newChan.Reject(gossh.ConnectionFailed, "no IP found for "+dhost)
return
}
dhost = addrs[0].String()
// Now lets apply some policies
srcip := conn.RemoteAddr().String()
if strings.Contains(srcip, "]") {
split := strings.Split(srcip, "]")
srcip = split[0][1:]
} else {
srcip = strings.Split(srcip, ":")[0]
}
action := ""
requireSameL2 := false
for name, policy := range Policies {
fmt.Println("Checking policy", name, "for", srcip, "->", dhost)
// Lets see if the policy applies
if !IPInPolicy(net.ParseIP(srcip), []string{name}) {
fmt.Println("Policy", name, "does not apply to", srcip)
continue
}
fmt.Println("Policy", name, "does apply to", srcip)
if IPInPolicy(net.ParseIP(dhost), policy.Deny) {
// Deny it
action = "deny"
break
}
if IPInPolicy(net.ParseIP(dhost), policy.Allow) {
// Accept it
action = "allow"
if policy.SameL2 {
requireSameL2 = true
}
break
}
if policy.Default != "" {
action = strings.ToLower(policy.Default)
if action == "allow" {
if policy.SameL2 {
requireSameL2 = true
}
}
break
}
}
if action == "" {
// No policy applies, so we just drop it
newChan.Reject(gossh.ConnectionFailed, "no policy applies to "+srcip+"->"+dhost)
return
}
if action == "deny" {
newChan.Reject(gossh.ConnectionFailed, "access to "+dhost+" is not allowed")
return
}
// Now we have a policy, lets see if we need to check for L2
if requireSameL2 {
if !TTL1(net.ParseIP(dhost)) {
newChan.Reject(gossh.ConnectionFailed, "access to "+dhost+" is not allowed")
return
}
}
dest := net.JoinHostPort(d.DestAddr, strconv.FormatInt(int64(d.DestPort), 10))
var dialer net.Dialer
dconn, err := dialer.DialContext(ctx, "tcp", dest)
if err != nil {
newChan.Reject(gossh.ConnectionFailed, err.Error())
return
}
ch, reqs, err := newChan.Accept()
if err != nil {
dconn.Close()
return
}
go gossh.DiscardRequests(reqs)
go func() {
defer ch.Close()
defer dconn.Close()
io.Copy(ch, dconn)
}()
go func() {
defer ch.Close()
defer dconn.Close()
io.Copy(dconn, ch)
}()
}
type IPSets map[string][]string
type Policy struct {
SameL2 bool `json:"samel2"`
Default string `json:"default"`
Allow []string `json:"allow"`
Deny []string `json:"deny"`
}
type Config struct {
Addr string `json:"addr"`
Port int `json:"port"`
Sets IPSets `json:"IPSet"`
SSHKey string `json:"sshkey"`
Message string `json:"message"`
Policy map[string]Policy `json:"Policy"`
}
var compiledIPSets = make(map[string][]net.IPNet)
var Policies map[string]Policy
func main() {
var config_file string
flag.StringVar(&config_file, "c", "", "SSH config file")
flag.Parse()
default_IPSets := make(IPSets)
default_IPSets["All"] = []string{"::/0"}
config := Config{
Addr: "",
Port: 2222,
Sets: default_IPSets,
Message: "------ Kangaroo -----\nYou've attempt to connect directly to a Kangaroo server.\nKangaroo is a module SSH bastion for jumping between hosts.\nProper usage is `ssh -J [email protected] [email protected]`\n",
}
if config_file != "" {
fmt.Println("Loading config from", config_file)
data, err := ioutil.ReadFile(config_file)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(data, &config)
if err != nil {
log.Fatal(err)
}
}
// for each IPSet
for name, set := range config.Sets {
// for each IP
IPNets := make([]net.IPNet, 0)
for _, ip := range set {
if strings.Contains(ip, "/") {
// It's a CIDR
_, ipnet, err := net.ParseCIDR(ip)
if err != nil {
log.Fatal(err)
}
IPNets = append(IPNets, *ipnet)
} else {
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
log.Fatal("Invalid IP:", ip)
}
if parsedIP.To4() == nil {
IPNets = append(IPNets, net.IPNet{IP: parsedIP, Mask: net.CIDRMask(128, 128)})
} else {
IPNets = append(IPNets, net.IPNet{IP: parsedIP, Mask: net.CIDRMask(32, 32)})
}
}
}
compiledIPSets[name] = IPNets
}
Policies = config.Policy
// list compiled ipsets
for name, compiledIPSet := range compiledIPSets {
fmt.Printf("%s: %v\n", name, compiledIPSet)
}
// Load SSH key
if config.SSHKey == "" {
log.Fatal("SSH key not specified")
}
if strings.HasPrefix(config.SSHKey, "~") {
config.SSHKey = os.Getenv("HOME") + config.SSHKey[1:]
}
var bytes []byte
if strings.HasPrefix(config.SSHKey, "raw:") {
bytes = []byte(config.SSHKey[4:])
} else {
var err error
bytes, err = ioutil.ReadFile(config.SSHKey)
if err != nil {
log.Fatal(err)
}
}
signer, err := gossh.ParsePrivateKey(bytes)
if err != nil {
log.Fatal(err)
}
server := ssh.Server{
Addr: fmt.Sprintf("%s:%d", config.Addr, config.Port),
HostSigners: []ssh.Signer{signer},
Handler: ssh.Handler(func(s ssh.Session) {
io.WriteString(s, config.Message)
s.Close()
select {}
}),
ChannelHandlers: map[string]ssh.ChannelHandler{
"direct-tcpip": customDirectHandler,
"session": ssh.DefaultSessionHandler,
},
}
log.Printf("starting ssh server on %s", server.Addr)
log.Fatal(server.ListenAndServe())
}
func TTL1(dst net.IP) bool {
pinger, err := ping.NewPinger(dst.String())
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
return false
}
pinger.Timeout = time.Second
pinger.Count = 1
pinger.TTL = 1
pinger.Run()
return pinger.Statistics().PacketsRecv != 0
}