-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
252 lines (227 loc) · 5.74 KB
/
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
242
243
244
245
246
247
248
249
250
251
252
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// TODO: High-level file comment.
package main
import (
"bufio"
"crypto/rand"
"crypto/rsa"
"fmt"
"golang.org/x/crypto/ssh"
"io"
"net"
"os"
"strconv"
"strings"
)
var (
AllowAnonymous = false
)
// Manage the SSH Server
type Server struct {
ServerConfig ssh.ServerConfig
Socket net.Listener
AuthorizedKeys map[string]bool
Credentials map[string]string
stop chan bool
done chan bool
}
var keyNames = []string{
"ssh_host_dsa_key",
"ssh_host_ecdsa_key",
"ssh_host_rsa_key",
}
/*
cd config
ssh-keygen -q -N "" -t rsa -b 4096 -f ./ssh_host_rsa_key
ssh-keygen -q -N "" -t dsa -b 1024 -f ./ssh_host_dsa_key
ssh-keygen -q -N "" -t ecdsa -b 521 -f ./ssh_host_ecdsa_key
*/
func NewServer() *Server {
s := &Server{}
s.AuthorizedKeys = make(map[string]bool)
s.Credentials = make(map[string]string)
s.ServerConfig.NoClientAuth= AllowAnonymous
s.ServerConfig.MaxAuthTries = 10
s.ServerConfig.PasswordCallback = s.VerifyPassword
s.ServerConfig.PublicKeyCallback = s.VerifyPublicKey
s.ServerConfig.BannerCallback = s.Banner
s.stop = make(chan bool)
s.done = make(chan bool, 1)
return s
}
func (s *Server) listen(port int16) error {
sPort := ":" + strconv.Itoa(int(port))
if sock, err := net.Listen("tcp", sPort); err != nil {
dbg.Debug("Unable to listen: %v", err)
return err
} else {
dbg.Debug("Listening on %s", sPort)
s.Socket = sock
}
return nil
}
func (s *Server) acceptChannel() <-chan net.Conn {
c := make(chan net.Conn)
go func() {
defer close(c)
for {
conn, err := s.Socket.Accept()
if err != nil {
dbg.Debug("Unable to accept: %v", err)
return
}
dbg.Debug("Accepted connection from: %s", conn.RemoteAddr())
c <- conn
}
}()
return c
}
func (s *Server) handleConn(conn net.Conn) {
sConn, err := NewServerConn(conn, s)
if err != nil {
if err == io.EOF {
dbg.Debug("Connection closed by remote host.")
return
}
dbg.Debug("Unable to negotiate SSH: %v", err)
return
}
dbg.Debug("Authenticated client from: %s", sConn.RemoteAddr())
go sConn.HandleConn()
}
func (s *Server) serveLoop() error {
acceptChan := s.acceptChannel()
defer func() {
dbg.Debug("done serveLoop")
s.Socket.Close()
s.done <- true
}()
for {
dbg.Debug("select...")
select {
case conn, ok := <-acceptChan:
if ok {
s.handleConn(conn)
} else {
dbg.Debug("failed to accept")
acceptChan = nil
return nil
}
case <-s.stop:
dbg.Debug("Stop signal received, stopping.")
return nil
}
}
return nil
}
func (s *Server) ListenAndServe(port int16) (error, func()) {
if err := s.listen(port); err != nil {
return err, nil
}
go s.serveLoop()
return nil, s.Stop
}
func (s *Server) ListenAndServeForever(port int16) error {
if err, _ := s.ListenAndServe(port); err != nil {
return err
}
s.Wait()
return nil
}
// Wait for server shutdown
func (s *Server) Wait() {
dbg.Debug("Waiting for shutdown.")
<-s.done
}
// Ask for shutdown
func (s *Server) Stop() {
dbg.Debug("requesting shutdown.")
s.stop <- true
close(s.stop)
}
func (s *Server) AddAuthorizedKeys(keyData []byte) {
for len(keyData) > 0 {
newKey, _, _, left, err := ssh.ParseAuthorizedKey(keyData)
keyData = left
if err != nil {
dbg.Debug("Error parsing key: %v", err)
break
}
s.AuthorizedKeys[string(newKey.Marshal())] = true
}
}
func (s *Server) AddCredentials( user string, password string ) {
dbg.Debug("Add credentials for %s", user)
s.Credentials[user] = password
}
func (s *Server) AddCredentialsFromFile( filename string ) {
nb := 0
file, err := os.Open(filename)
if err != nil {
s.AddCredentials("user","pass")
fmt.Println(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
words := strings.Fields(scanner.Text())
s.AddCredentials(words[0],words[1])
nb = nb + 1
}
if( nb == 0 ) { s.AddCredentials("user","pass") }
if err := scanner.Err(); err != nil {
fmt.Println(err)
}
}
func (s *Server) VerifyPublicKey(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
keyStr := string(key.Marshal())
if _, ok := s.AuthorizedKeys[keyStr]; !ok {
dbg.Debug("Key not found!")
return nil, fmt.Errorf("No valid key found.")
}
dbg.Debug("Authentication with public key")
return &ssh.Permissions{}, nil
}
func (s *Server) AddHostkey(keyData []byte) error {
key, err := ssh.ParsePrivateKey(keyData)
if err == nil {
s.ServerConfig.AddHostKey(key)
return nil
}
return err
}
func (s *Server) RandomHostkey() error {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
signer, err := ssh.NewSignerFromSigner(key)
if err != nil {
return err
}
s.ServerConfig.AddHostKey(signer)
return nil
}
func (s *Server) Banner(conn ssh.ConnMetadata) (string) {
return "This is sshdog\nAvailable authentication methods:\n - password\n - public key\n"
}
func (s *Server) VerifyPassword(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
if pass,ok := s.Credentials[conn.User()]; !ok || pass!=string(password) {
dbg.Debug( "Wrong password" )
return nil, fmt.Errorf("password rejected for %q", conn.User())
}
dbg.Debug("Authentication with password")
return &ssh.Permissions{}, nil
}