-
Notifications
You must be signed in to change notification settings - Fork 60
/
main.go
114 lines (96 loc) · 2.13 KB
/
main.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
package main
import (
"flag"
"fmt"
"log"
"time"
"encoding/base64"
"github.com/TNK-Studio/gortal/config"
"github.com/TNK-Studio/gortal/core/jump"
"github.com/TNK-Studio/gortal/core/sshd"
"github.com/TNK-Studio/gortal/utils"
"github.com/TNK-Studio/gortal/utils/logger"
"github.com/elfgzp/ssh"
)
var (
// Port port
Port *int
hostKeyFile *string
)
func init() {
Port = flag.Int("p", 2222, "Port")
hostKeyFile = flag.String("hk", "~/.ssh/id_rsa", "Host key file")
}
func passwordAuth(ctx ssh.Context, pass string) bool {
config.Conf.ReadFrom(*config.ConfPath)
var success bool
if (len(*config.Conf.Users)) < 1 {
success = (pass == "newuser")
} else {
success = jump.VarifyUser(ctx, pass)
}
if !success {
time.Sleep(time.Second * 3)
}
return success
}
func publickKeyAuth(ctx ssh.Context, key ssh.PublicKey) bool {
var pub string
config.Conf.ReadFrom(*config.ConfPath)
username := ctx.User()
for _, user := range *config.Conf.Users {
if user.Username == username {
pub = user.PublicKey
}
}
decodeBytes, _ := base64.StdEncoding.DecodeString(pub)
allowed, _, _, _, _ := ssh.ParseAuthorizedKey(decodeBytes)
return ssh.KeysEqual(key, allowed)
}
func sessionHandler(sess *ssh.Session) {
defer func() {
(*sess).Close()
}()
rawCmd := (*sess).RawCommand()
cmd, args, err := sshd.ParseRawCommand(rawCmd)
if err != nil {
sshd.ErrorInfo(err, sess)
return
}
switch cmd {
case "scp":
sshd.ExecuteSCP(args, sess)
default:
sshHandler(sess)
}
}
func sshHandler(sess *ssh.Session) {
jps := jump.Service{}
jps.Run(sess)
}
func scpHandler(args []string, sess *ssh.Session) {
sshd.ExecuteSCP(args, sess)
}
func main() {
flag.Parse()
if !utils.FileExited(*hostKeyFile) {
sshd.GenKey(*hostKeyFile)
}
ssh.Handle(func(sess ssh.Session) {
defer func() {
if e, ok := recover().(error); ok {
logger.Logger.Panic(e)
}
}()
sessionHandler(&sess)
})
log.Printf("starting ssh server on port %d...\n", *Port)
log.Fatal(ssh.ListenAndServe(
fmt.Sprintf(":%d", *Port),
nil,
ssh.PasswordAuth(passwordAuth),
ssh.PublicKeyAuth(publickKeyAuth),
ssh.HostKeyFile(utils.FilePath(*hostKeyFile)),
),
)
}