forked from ysrc/yulong-hids-archived
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.go
129 lines (121 loc) · 2.62 KB
/
common.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
package common
import (
"crypto/tls"
"net/http"
"os"
"os/exec"
"runtime"
"strings"
"sync"
"time"
"net"
"strings"
"fmt"
"github.com/axgle/mahonia"
"github.com/kardianos/service"
)
var (
// M 安全锁
M *sync.Mutex
// Cmd agent进程
Cmd *exec.Cmd
// Service daemon服务
Service service.Service
// ServerIP 服务IP地址
ServerIP string
// AgentStatus agent状态,是否启动中
AgentStatus bool
// InstallPath agent安装目录
InstallPath string
// Arch 系统位数
Arch string
// PublicKey 与Server通讯公钥
PublicKey string
// HTTPClient httpclient
HTTPClient *http.Client
// Proto 请求协议,测试模式为HTTP
Proto string
)
func init() {
M = new(sync.Mutex)
if TESTMODE {
Proto = "http"
} else {
Proto = "https"
}
Arch = "64"
if runtime.GOOS == "windows" {
// 不受程序编译位数干扰
if _, err := os.Stat(os.Getenv("SystemDrive") + `/Windows/SysWOW64/`); err != nil {
Arch = "32"
} else {
Arch = "64"
}
InstallPath = os.Getenv("SystemDrive") + `/yulong-hids/`
} else {
InstallPath = `/usr/yulong-hids/`
if data, _ := CmdExec("getconf LONG_BIT"); InArray([]string{"32", "64"}, data, false) {
Arch = data
}
}
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true, MaxVersion: 0},
}
HTTPClient = &http.Client{
Transport: transport,
Timeout: time.Second * 60,
}
}
// KillAgent 结束agent
func KillAgent() error {
if AgentStatus {
return Cmd.Process.Kill()
}
return nil
}
// CmdExec 执行系统命令
func CmdExec(cmd string) (string, error) {
var c *exec.Cmd
var data string
system := runtime.GOOS
if system == "windows" {
argArray := strings.Split("/c "+cmd, " ")
c = exec.Command("cmd", argArray...)
} else {
c = exec.Command("/bin/sh", "-c", cmd)
}
out, err := c.CombinedOutput()
if err != nil {
return data, err
}
data = string(out)
if system == "windows" {
dec := mahonia.NewDecoder("gbk")
data = dec.ConvertString(data)
}
return data, nil
}
// InArray 判断值是否存在于指定列表中,like为true则为包含判断
func InArray(list []string, value string, like bool) bool {
for _, v := range list {
if like {
if strings.Contains(value, v) {
return true
}
} else {
if value == v {
return true
}
}
}
return false
}
// 获取一个可以绑定的内网IP
func BindAddr() string{
// 通过连接一个可达的任何一个地址,获取本地的内网的地址
conn, _ := net.Dial("udp", "114.114.114.114:53")
defer conn.Close()
localAddr := conn.LocalAddr().String()
idx := strings.LastIndex(localAddr, ":")
return fmt.Sprintf("%s:65512", localAddr[0:idx])
}