-
Notifications
You must be signed in to change notification settings - Fork 30
/
server.go
193 lines (174 loc) · 4.07 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
// 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 (
"crypto/rand"
"crypto/rsa"
"fmt"
"io"
"net"
"strconv"
"golang.org/x/crypto/ssh"
)
// Manage the SSH Server
type Server struct {
ServerConfig ssh.ServerConfig
Socket net.Listener
AuthorizedKeys map[string]bool
stop chan bool
done chan bool
}
var keyNames = []string{
"ssh_host_dsa_key",
"ssh_host_ecdsa_key",
"ssh_host_rsa_key",
}
func NewServer() *Server {
s := &Server{}
s.AuthorizedKeys = make(map[string]bool)
s.ServerConfig.PublicKeyCallback = s.VerifyPublicKey
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 {
go 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) 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.")
}
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
}