forked from ashmckenzie/go-sshoney
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
72 lines (60 loc) · 1.87 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
package sshoney
import (
"fmt"
"io/ioutil"
"net"
"strings"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
// "github.com/davecgh/go-spew/spew"
)
func Listen(port string, hostKey string) {
sshConfig, listener := setupSSHListener(port, hostKey)
processConnections(&sshConfig, listener)
}
func setupSSHListener(port string, hostKey string) (ssh.ServerConfig, net.Listener) {
sshConfig := &ssh.ServerConfig{
PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
remoteAddr := c.RemoteAddr().String()
ip := remoteAddr[0:strings.Index(remoteAddr, ":")]
log.Printf("SSH connection from ip=[%s], username=[%s], password=[%s], version=[%s]", ip, c.User(), pass, c.ClientVersion())
return nil, fmt.Errorf("invalid credentials")
},
}
privateBytes, err := ioutil.ReadFile(hostKey)
if err != nil {
log.Fatalf("Failed to load private key %s. Run make gen_ssh_key %s", hostKey, hostKey)
}
private, err := ssh.ParsePrivateKey(privateBytes)
if err != nil {
log.Fatal("Failed to parse private key")
}
sshConfig.AddHostKey(private)
portComplete := fmt.Sprintf(":%s", port)
listener, err := net.Listen("tcp4", portComplete)
if err != nil {
log.Fatalf("failed to listen on *:%s", port)
}
log.Printf("listening on %s", port)
return *sshConfig, listener
}
func processConnections(sshConfig *ssh.ServerConfig, listener net.Listener) {
for {
tcpConn, err := listener.Accept()
if err != nil {
log.Debugf("failed to accept incoming connection (%s)", err)
continue
}
go handleConnection(sshConfig, tcpConn)
}
}
func handleConnection(sshConfig *ssh.ServerConfig, tcpConn net.Conn) {
defer tcpConn.Close()
log.Debugf("new TCP connection from %s", tcpConn.RemoteAddr())
sshConn, _, _, err := ssh.NewServerConn(tcpConn, sshConfig)
if err != nil {
log.Debugf("failed to handshake (%s)", err)
} else {
sshConn.Close()
}
}