-
Notifications
You must be signed in to change notification settings - Fork 182
/
sshprox.go
215 lines (186 loc) · 5.64 KB
/
sshprox.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
package sshprox
import (
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/google/uuid"
"imuslab.com/zoraxy/mod/reverseproxy"
"imuslab.com/zoraxy/mod/utils"
"imuslab.com/zoraxy/mod/websocketproxy"
)
/*
SSH Proxy
This is a tool to bind gotty into Zoraxy
so that you can do something similar to
online ssh terminal
*/
type Manager struct {
StartingPort int
Instances []*Instance
}
type Instance struct {
UUID string
ExecPath string
RemoteAddr string
RemotePort int
AssignedPort int
conn *reverseproxy.ReverseProxy //HTTP proxy
tty *exec.Cmd //SSH connection ported to web interface
Parent *Manager
}
func NewSSHProxyManager() *Manager {
return &Manager{
StartingPort: 14810,
Instances: []*Instance{},
}
}
// Get the next free port in the list
func (m *Manager) GetNextPort() int {
nextPort := m.StartingPort
occupiedPort := make(map[int]bool)
for _, instance := range m.Instances {
occupiedPort[instance.AssignedPort] = true
}
for {
if !occupiedPort[nextPort] {
return nextPort
}
nextPort++
}
}
func (m *Manager) HandleHttpByInstanceId(instanceId string, w http.ResponseWriter, r *http.Request) {
targetInstance, err := m.GetInstanceById(instanceId)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
if targetInstance.tty == nil {
//Server side already closed
http.Error(w, "Connection already closed", http.StatusInternalServerError)
return
}
r.Header.Set("X-Forwarded-Host", r.Host)
requestURL := r.URL.String()
if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
//Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
r.Header.Set("Zr-Origin-Upgrade", "websocket")
requestURL = strings.TrimPrefix(requestURL, "/")
u, _ := url.Parse("ws://127.0.0.1:" + strconv.Itoa(targetInstance.AssignedPort) + "/" + requestURL)
wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
SkipTLSValidation: false,
SkipOriginCheck: false,
Logger: nil,
})
wspHandler.ServeHTTP(w, r)
return
}
targetInstance.conn.ProxyHTTP(w, r)
}
func (m *Manager) GetInstanceById(instanceId string) (*Instance, error) {
for _, instance := range m.Instances {
if instance.UUID == instanceId {
return instance, nil
}
}
return nil, fmt.Errorf("instance not found: %s", instanceId)
}
func (m *Manager) NewSSHProxy(binaryRoot string) (*Instance, error) {
//Check if the binary exists in system/gotty/
binary := "gotty_" + runtime.GOOS + "_" + runtime.GOARCH
if runtime.GOOS == "windows" {
binary = binary + ".exe"
}
//Extract it from embedfs if not exists locally
execPath := filepath.Join(binaryRoot, binary)
//Create the storage folder structure
os.MkdirAll(filepath.Dir(execPath), 0775)
//Create config file if not exists
if !utils.FileExists(filepath.Join(filepath.Dir(execPath), ".gotty")) {
configFile, _ := gotty.ReadFile("gotty/.gotty")
os.WriteFile(filepath.Join(filepath.Dir(execPath), ".gotty"), configFile, 0775)
}
//Create web.ssh binary if not exists
if !utils.FileExists(execPath) {
//Try to extract it from embedded fs
executable, err := gotty.ReadFile("gotty/" + binary)
if err != nil {
//Binary not found in embedded
return nil, errors.New("platform not supported")
}
//Extract to target location
err = os.WriteFile(execPath, executable, 0777)
if err != nil {
//Binary not found in embedded
log.Println("Extract web.ssh failed: " + err.Error())
return nil, errors.New("web.ssh sub-program extract failed")
}
}
//Convert the binary path to realpath
realpath, err := filepath.Abs(execPath)
if err != nil {
return nil, err
}
thisInstance := Instance{
UUID: uuid.New().String(),
ExecPath: realpath,
AssignedPort: -1,
Parent: m,
}
m.Instances = append(m.Instances, &thisInstance)
return &thisInstance, nil
}
// Create a new Connection to target address
func (i *Instance) CreateNewConnection(listenPort int, username string, remoteIpAddr string, remotePort int) error {
//Create a gotty instance
connAddr := remoteIpAddr
if username != "" {
connAddr = username + "@" + remoteIpAddr
}
configPath := filepath.Join(filepath.Dir(i.ExecPath), ".gotty")
title := username + "@" + remoteIpAddr
if remotePort != 22 {
title = title + ":" + strconv.Itoa(remotePort)
}
sshCommand := []string{"ssh", "-t", connAddr, "-p", strconv.Itoa(remotePort)}
cmd := exec.Command(i.ExecPath, "-w", "-p", strconv.Itoa(listenPort), "--once", "--config", configPath, "--title-format", title, "bash", "-c", strings.Join(sshCommand, " "))
cmd.Dir = filepath.Dir(i.ExecPath)
cmd.Env = append(os.Environ(), "TERM=xterm")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
go func() {
cmd.Run()
i.Destroy()
}()
i.tty = cmd
i.AssignedPort = listenPort
i.RemoteAddr = remoteIpAddr
i.RemotePort = remotePort
//Create a new proxy agent for this root
path, err := url.Parse("http://127.0.0.1:" + strconv.Itoa(listenPort))
if err != nil {
return err
}
//Create new proxy objects to the proxy
proxy := reverseproxy.NewReverseProxy(path)
i.conn = proxy
return nil
}
func (i *Instance) Destroy() {
// Remove the instance from the Manager's Instances list
for idx, inst := range i.Parent.Instances {
if inst == i {
// Remove the instance from the slice by swapping it with the last instance and slicing the slice
i.Parent.Instances[len(i.Parent.Instances)-1], i.Parent.Instances[idx] = i.Parent.Instances[idx], i.Parent.Instances[len(i.Parent.Instances)-1]
i.Parent.Instances = i.Parent.Instances[:len(i.Parent.Instances)-1]
break
}
}
}