-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh.go
More file actions
200 lines (176 loc) · 5.07 KB
/
ssh.go
File metadata and controls
200 lines (176 loc) · 5.07 KB
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
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
"io"
"log"
"net"
"os"
"sync"
// "crypto/md5"
"encoding/hex"
)
type DefAuth struct {
service string
name string
token string
state bool
}
var GenAuth []DefAuth
var sshChannelsMonitor []*ssh.Channel
var sshChannelsSerial []*ssh.Channel
func ssh_init(nMonitor, nSerial int) {
sshChannelsMonitor = make([]*ssh.Channel, nMonitor)
sshChannelsSerial = make([]*ssh.Channel, nSerial)
}
func checkPerm(token string, service string) bool {
for _, i := range GenAuth {
if (token == i.token) && (service == i.service) {
return i.state
}
}
return false
}
func SSHHandler(sshcfg SSHCFG, desc string, r *Router, def_aut bool) {
debugPrint(log.Printf, levelDebug, "request descr=%s", desc)
authorizedKeysBytes, err := os.ReadFile(sshcfg.Authorized_keys)
if err != nil {
log.Fatalf("SSH %s: failed to load authorized_keys: %v", desc, err)
}
authorizedKeysMap := map[string]bool{}
for len(authorizedKeysBytes) > 0 {
pubKey, comment, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)
if err != nil {
log.Fatalf("SSH %s: invalid authorized_keys format: %v", desc, err)
}
debugPrint(log.Printf, levelDebug, "add key for %s", comment) //hex.EncodeToString(pubKey.Marshal())
GenAuth = append(GenAuth, DefAuth{
service: desc,
name: comment,
token: hex.EncodeToString(pubKey.Marshal()),
state: def_aut,
})
authorizedKeysMap[string(pubKey.Marshal())] = true
authorizedKeysBytes = rest
}
config := &ssh.ServerConfig{
PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
if authorizedKeysMap[string(pubKey.Marshal())] {
debugPrint(log.Printf, levelDebug, "Authorized user attempt check permissions")
if checkPerm(hex.EncodeToString(pubKey.Marshal()), desc) {
return &ssh.Permissions{
Extensions: map[string]string{
"pubkey-fp": ssh.FingerprintSHA256(pubKey),
},
}, nil
} else {
return nil, fmt.Errorf("unauthorized user")
}
}
return nil, fmt.Errorf("unknown public key for %q", c.User())
},
}
privateBytes, err := os.ReadFile(sshcfg.IdentitFn)
if err != nil {
log.Fatalf("SSH %s: failed to load private key: %v", desc, err)
}
private, err := ssh.ParsePrivateKey(privateBytes)
if err != nil {
log.Fatalf("SSH %s: failed to parse private key: %v", desc, err)
}
config.AddHostKey(private)
listener, err := net.Listen("tcp4", "0.0.0.0:"+sshcfg.Port)
if err != nil {
log.Fatalf("SSH %s: failed to listen: %v", desc, err)
}
defer listener.Close()
debugPrint(log.Printf, levelWarning, "Starting %s SSH server on port %s\n", desc, sshcfg.Port)
for {
conn, err := listener.Accept()
if err != nil {
debugPrint(log.Printf, levelPanic, "failed to accept incoming connection: %s", err.Error())
}
go handleSSHConnection(conn, config, r, desc)
}
}
func checkBrokenConnections(conn ssh.Conn, r *Router, n int, desc string) {
conn.Wait()
r.DetachAt(n)
debugPrint(log.Printf, levelInfo, "Closing broken connection, detach %d", n)
conn.Close()
}
func handleSSHConnection(conn net.Conn, config *ssh.ServerConfig, r *Router, desc string) {
defer conn.Close()
debugPrint(log.Printf, levelDebug, "request descr=%s", desc)
sshConn, chans, reqs, err := ssh.NewServerConn(conn, config)
if err != nil {
debugPrint(log.Printf, levelError, "failed to establish SSH connection: %s", err.Error())
return
}
defer sshConn.Close()
n, err := r.GetFreePos()
if err == nil {
debugPrint(log.Printf, levelDebug, "The new channels in router for this connection are at %d", n)
r.AttachAt(n, SrcHuman)
go checkBrokenConnections(sshConn, r, n, desc)
go ssh.DiscardRequests(reqs)
for newChannel := range chans {
go handleSSHChannel(newChannel, r, n, desc)
}
} else {
debugPrint(log.Printf, levelWarning, "Failed to get new channels in router")
}
}
func handleSSHChannel(newChannel ssh.NewChannel, r *Router, nchan int, desc string) {
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
return
}
channel, _, err := newChannel.Accept()
if err != nil {
debugPrint(log.Printf, levelError, "failed to accept channel: %s", err.Error())
return
}
if desc == "monitor" {
sshChannelsMonitor[nchan] = &channel
} else {
sshChannelsSerial[nchan] = &channel
}
defer channel.Close()
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
data := <-r.In[nchan] //sshOut
_, err := channel.Write([]byte{data})
if err != nil {
if err != io.EOF {
debugPrint(log.Printf, levelError, "Error writing to SSH channel: %s", err.Error())
}
return
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
buf := make([]byte, 4096)
for {
n, err := channel.Read(buf)
if err != nil {
if err != io.EOF {
debugPrint(log.Printf, levelError, "Error reading from SSH channel: %s", err.Error())
}
return
}
if n > 0 {
debugPrint(log.Printf, levelCrazy, "read %d bytes = '%s'", len(buf), string(buf[:n]))
for i := 0; i < n; i++ {
r.Out[nchan] <- buf[i] //sshIn
}
}
}
}()
wg.Wait()
}