-
Notifications
You must be signed in to change notification settings - Fork 3
/
simple_server.go
241 lines (221 loc) · 6.03 KB
/
simple_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
package sshproxy
import (
"bytes"
"context"
"fmt"
"net"
"net/url"
"path"
"strconv"
"time"
"github.com/wzshiming/sshd"
"github.com/wzshiming/sshproxy/permissions"
"golang.org/x/crypto/ssh"
)
// SimpleServer is a simplified server, which can be configured as easily as client.
type SimpleServer struct {
Server
Listener net.Listener
Username string
Password string
Network string
Address string
}
// NewSimpleServer creates a new NewSimpleServer
func NewSimpleServer(addr string) (*SimpleServer, error) {
user, pwd, host, config, userPermissions, err := serverConfig(addr)
if err != nil {
return nil, err
}
s := &SimpleServer{
Server: Server{
ServerConfig: *config,
UserPermissions: userPermissions,
},
Network: "tcp",
Address: host,
Username: user,
Password: pwd,
}
return s, nil
}
func serverConfig(addr string) (host, user, pwd string, config *ssh.ServerConfig, userPermissions func(user string) sshd.Permissions, err error) {
ur, err := url.Parse(addr)
if err != nil {
return "", "", "", nil, nil, err
}
isPwd := false
if ur.User != nil {
user = ur.User.Username()
pwd, isPwd = ur.User.Password()
}
config = &ssh.ServerConfig{}
if isPwd {
user := user
pwd := pwd
config.PasswordCallback = func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
if conn.User() == user && string(password) == pwd {
return nil, nil
}
return nil, fmt.Errorf("denied")
}
} else {
user = ""
pwd = ""
}
hostkeyDatas, err := getQuery(ur.Query()["hostkey_data"], ur.Query()["hostkey_file"])
if err != nil {
return "", "", "", nil, nil, err
}
if len(hostkeyDatas) == 0 {
key, err := sshd.RandomHostkey()
if err != nil {
return "", "", "", nil, nil, err
}
config.AddHostKey(key)
} else {
for _, data := range hostkeyDatas {
key, err := sshd.ParseHostkey(data)
if err != nil {
return "", "", "", nil, nil, err
}
config.AddHostKey(key)
}
}
pks := []func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error){}
authorizedDatas, err := getQuery(ur.Query()["authorized_data"], ur.Query()["authorized_file"])
if err != nil {
return "", "", "", nil, nil, err
}
if len(authorizedDatas) != 0 {
keys, err := sshd.ParseAuthorized(bytes.NewBuffer(bytes.Join(authorizedDatas, []byte{'\n'})))
if err != nil {
return "", "", "", nil, nil, err
}
if len(keys.Data) != 0 {
pks = append(pks, func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
ok, _ := keys.Allow(key)
if ok {
return nil, nil
}
return nil, fmt.Errorf("denied")
})
}
}
homeDirs := ur.Query()["home_dir"]
if len(homeDirs) != 0 && homeDirs[0] != "" {
homeDir := homeDirs[0]
sshDirName := ".ssh"
sshDirNames := ur.Query()["ssh_dir_name"]
if len(sshDirNames) != 0 {
sshDirName = sshDirNames[0]
}
authorizedFileName := "authorized_keys"
authorizedFileNames := ur.Query()["authorized_file_name"]
if len(authorizedFileNames) != 0 {
authorizedFileName = authorizedFileNames[0]
}
pks = append(pks, func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
file := path.Join(homeDir, conn.User(), sshDirName, authorizedFileName)
keys, err := sshd.GetAuthorizedFile(file)
if err != nil {
return nil, fmt.Errorf("denied")
}
ok, _ := keys.Allow(key)
if ok {
return nil, nil
}
return nil, fmt.Errorf("denied")
})
// Other sshd implementations do not have such fine-grained permissions control,
// and this is a fine-grained set of permissions control files defined by the project itself
permissionsFileName := ""
permissionsFileNames := ur.Query()["permissions_file_name"]
if len(permissionsFileNames) != 0 {
permissionsFileName = permissionsFileNames[0]
}
if permissionsFileName != "" {
permissionsFileUpdatePeriod := time.Duration(0)
permissionsFileUpdatePeriods := ur.Query()["permissions_file_update_period"]
if len(permissionsFileUpdatePeriods) != 0 {
permissionsFileUpdatePeriod, _ = time.ParseDuration(permissionsFileUpdatePeriods[0])
}
userPermissions = func(user string) sshd.Permissions {
file := path.Join(homeDir, user, sshDirName, permissionsFileName)
return permissions.NewPermissionsFromFile(file, permissionsFileUpdatePeriod)
}
}
}
if len(pks) != 0 {
if len(pks) == 1 {
config.PublicKeyCallback = pks[0]
} else {
config.PublicKeyCallback = func(conn ssh.ConnMetadata, key ssh.PublicKey) (p *ssh.Permissions, err error) {
for _, pk := range pks {
p, err = pk(conn, key)
if err == nil {
break
}
}
return
}
}
}
// must have be authenticated or not, default is false
authenticate, _ := strconv.ParseBool(ur.Query().Get("authenticate"))
if !authenticate && config.PasswordCallback == nil && config.PublicKeyCallback == nil && config.KeyboardInteractiveCallback == nil {
config.NoClientAuth = true
}
host = ur.Hostname()
port := ur.Port()
if port == "" {
port = "22"
}
host = net.JoinHostPort(host, port)
return user, pwd, host, config, userPermissions, nil
}
// Run the server
func (s *SimpleServer) Run(ctx context.Context) error {
var listenConfig net.ListenConfig
if s.Listener == nil {
listener, err := listenConfig.Listen(ctx, s.Network, s.Address)
if err != nil {
return err
}
s.Listener = listener
}
s.Address = s.Listener.Addr().String()
return s.Serve(s.Listener)
}
// Start the server
func (s *SimpleServer) Start(ctx context.Context) error {
var listenConfig net.ListenConfig
if s.Listener == nil {
listener, err := listenConfig.Listen(ctx, s.Network, s.Address)
if err != nil {
return err
}
s.Listener = listener
}
s.Address = s.Listener.Addr().String()
go s.Serve(s.Listener)
return nil
}
// Close closes the listener
func (s *SimpleServer) Close() error {
if s.Listener == nil {
return nil
}
return s.Listener.Close()
}
// ProxyURL returns the URL of the proxy
func (s *SimpleServer) ProxyURL() string {
u := url.URL{
Scheme: "ssh",
Host: s.Address,
}
if s.Username != "" {
u.User = url.UserPassword(s.Username, s.Password)
}
return u.String()
}