This repository has been archived by the owner on Jan 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathserver_git.go
117 lines (98 loc) · 2.14 KB
/
server_git.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
package main
import (
"io/ioutil"
"log"
"net"
"os"
"strings"
"golang.org/x/crypto/ssh"
)
var (
hostPrivateKeySigner ssh.Signer
)
func init() {
keyPath := "./host_key"
if os.Getenv("HOST_KEY") != "" {
keyPath = os.Getenv("HOST_KEY")
}
hostPrivateKey, err := ioutil.ReadFile(keyPath)
if err != nil {
panic(err)
}
hostPrivateKeySigner, err = ssh.ParsePrivateKey(hostPrivateKey)
if err != nil {
panic(err)
}
}
func keyAuth(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
log.Println(conn.RemoteAddr(), "authenticate with", key.Type())
return nil, nil
}
func main() {
config := ssh.ServerConfig{
PublicKeyCallback: keyAuth,
}
config.AddHostKey(hostPrivateKeySigner)
port := "2222"
if os.Getenv("PORT") != "" {
port = os.Getenv("PORT")
}
socket, err := net.Listen("tcp", ":"+port)
if err != nil {
panic(err)
}
for {
conn, err := socket.Accept()
if err != nil {
panic(err)
}
// From a standard TCP connection to an encrypted SSH connection
sshConn, newChans, _, err := ssh.NewServerConn(conn, &config)
if err != nil {
panic(err)
}
defer sshConn.Close()
log.Println("Connection from", sshConn.RemoteAddr())
go func() {
for chanReq := range newChans {
go handleChanReq(chanReq)
}
}()
}
}
func handleChanReq(chanReq ssh.NewChannel) {
if chanReq.ChannelType() != "session" {
chanReq.Reject(ssh.Prohibited, "channel type is not a session")
return
}
ch, reqs, err := chanReq.Accept()
if err != nil {
log.Println("fail to accept channel request", err)
return
}
req := <-reqs
if req.Type != "exec" {
ch.Write([]byte("request type '" + req.Type + "' is not 'exec'\r\n"))
ch.Close()
return
}
handleExec(ch, req)
}
// Payload: int: command size, string: command
func handleExec(ch ssh.Channel, req *ssh.Request) {
command := string(req.Payload[4:])
gitCmds := []string{"git-receive-pack", "git-upload-pack"}
valid := false
for _, cmd := range gitCmds {
if strings.HasPrefix(command, cmd) {
valid = true
}
}
if !valid {
ch.Write([]byte("command is not a GIT command\r\n"))
ch.Close()
return
}
ch.Write([]byte("well done!\r\n"))
ch.Close()
}