-
Notifications
You must be signed in to change notification settings - Fork 1
/
agent.go
348 lines (303 loc) · 7.92 KB
/
agent.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/kardianos/service"
)
// TODO:
// - Add system logging support
// - Get command exit code
// - Post output to API
var logger service.Logger
type program struct{}
func (p *program) Start(s service.Service) error {
// Start should not block. Do the actual work async.
go p.run()
return nil
}
func (p *program) run() {
agentinit()
}
func (p *program) Stop(s service.Service) error {
// Stop should not block. Return with a few seconds.
return nil
}
type JSONResponse struct {
Commands []string `json:"commands"`
}
type agent struct {
mac string
apikey string
version string
apiuri string
agentpath string
execpath string
install bool
separator string
blocked bool
debug bool
os string
command
}
type command struct {
execstring string
exitcode int
interpreter string
output string
}
func orFail(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
panic(fmt.Sprintf("%s: %s", msg, err))
}
}
func vmDebug(debug bool, msg string) {
if debug {
fmt.Println(msg)
}
}
func checkForAdmin() bool {
if runtime.GOOS == "windows" {
_, err := os.Open("\\\\.\\PHYSICALDRIVE0")
if err != nil {
return false
}
} else {
if os.Geteuid() != 0 {
return false
}
}
return true
}
func getUpdateFromURL(filepath string, url string) error {
out, err := os.Create(filepath)
orFail(err, "Error creating a temp path for agent update")
defer out.Close()
resp, err := http.Get(url)
orFail(err, "Error while GETing agent update from GITHUB")
defer resp.Body.Close()
_, err = io.Copy(out, resp.Body)
orFail(err, "Error while writing agent update to file")
return nil
}
func (pvm *agent) waitRandomly() {
rand.Seed(time.Now().Unix())
r := rand.Intn(10) + 20
time.Sleep(time.Duration(r) * time.Second)
}
func (pvm *agent) print() {
fmt.Println("Agent VER: ", pvm.version)
fmt.Println("Agent MAC: ", pvm.mac)
fmt.Println("Agent KEY: ", pvm.apikey)
fmt.Println("Agent URI: ", pvm.apiuri)
fmt.Println("Agent OS: ", pvm.os)
fmt.Println("Agent TMP_PATH: ", pvm.execpath)
fmt.Println("Agent RUN_PATH: ", pvm.agentpath)
}
func (pvm *agent) setMacAddr() {
interfaces, err := net.Interfaces()
addr := "aa:bb:cc:dd:ee:ff"
if err == nil {
for _, i := range interfaces {
if i.Flags&net.FlagUp != 0 && bytes.Compare(i.HardwareAddr, nil) != 0 {
addr = i.HardwareAddr.String()
break
}
}
}
r := strings.NewReplacer(":", "-")
pvm.mac = r.Replace(addr)
}
func (pvm *agent) selfUpdate() {
vmDebug(pvm.debug, "Starting slef update subrutine")
dir, err := filepath.Abs(filepath.Dir(pvm.agentpath))
orFail(err, "Error while reading path")
vmDebug(pvm.debug, "Getting last agent build")
fileUrl := "https://github.com/tuwid/monx-agent/raw/master/builds/agent-" + pvm.os
if pvm.os == "windows" {
fileUrl += ".exe"
}
updatedFile := dir + pvm.separator + "agent_update"
error := getUpdateFromURL(updatedFile, fileUrl)
orFail(error, "Error while getUpdateFromURL")
os.Rename(pvm.agentpath, pvm.agentpath+".bck")
os.Rename(updatedFile, pvm.agentpath)
if pvm.os != "windows" {
os.Chmod(pvm.agentpath, 0755)
}
}
func (pvm *agent) selfInstall() {
if !checkForAdmin() {
fmt.Println("Please execute with administrative priviledges!")
os.Exit(5)
}
if pvm.os == "windows" {
params := ` create monxagent binPath= "C:\monx\agent.exe ` + pvm.apikey + ` " start= auto`
os.Mkdir("C:\\monx\\", 0777)
sa, err := os.Open(pvm.agentpath)
orFail(err, "Error while reading from agent binary")
defer sa.Close()
da, err := os.OpenFile("C:\\monx\\agent.exe", os.O_RDWR|os.O_CREATE, 0755)
orFail(err, "Error while writing new agent binary")
defer da.Close()
_, err = io.Copy(da, sa)
orFail(err, "Error while reading from agent binary")
vmDebug(pvm.debug, "sc "+params)
_, ierr := exec.Command("sc", params).Output()
orFail(ierr, "Could not install")
_, serr := exec.Command("net start monxagent").Output()
orFail(serr, "Could not start")
}
}
func (pvm *agent) block() {
pvm.blocked = true
vmDebug(pvm.debug, "Blocking executions")
}
func (pvm *agent) unBlock() {
pvm.blocked = false
vmDebug(pvm.debug, "Unblocking executions")
}
func (pvm *agent) setEnv(key []string) {
pvm.os = runtime.GOOS
pvm.blocked = false
pvm.version = "1.1.1"
if os.Getenv("AGENT_DEBUG") == "1" {
fmt.Println("Turning ON debug logs")
pvm.debug = true
}
pvm.agentpath = key[0]
pvm.apikey = key[1]
// if key[2] == "install" {
// pvm.install = true
// } else {
// pvm.install = false
// }
pvm.apiuri = "https://api.monx.me/api/hub/agent/command?apikey=" + pvm.apikey + "&mac=" + pvm.mac
if pvm.os == "windows" {
pvm.separator = "\\"
// pvm.execpath = filepath.Join(os.Getenv("TEMP"), "_monxagent.bat")
pvm.execpath = filepath.Join("C:\\_monxagent.bat")
} else {
pvm.separator = "/"
pvm.execpath = filepath.Join(os.Getenv("HOME"), "_monxagent.sh")
}
}
func (pvm *agent) getDataFromBase() bool {
resp, err := http.Get(pvm.apiuri)
vmDebug(pvm.debug, "Got code "+strconv.Itoa(resp.StatusCode)+" from API")
orFail(err, "Error while GETing from the API")
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
vmDebug(pvm.debug, "Response body: "+string(body))
orFail(err, "Error decoding the body from the API")
if body == nil {
fmt.Println("Wrong body response.")
return false
}
var jsonObject JSONResponse
err = json.Unmarshal(body, &jsonObject)
orFail(err, "Error decoding the JSON")
if len(jsonObject.Commands) == 0 {
vmDebug(pvm.debug, "List of commands empty, returning")
return false
}
os.Remove(pvm.execpath)
if len(jsonObject.Commands) > 1 {
vmDebug(pvm.debug, "Got multiple commands, will aggregate")
}
pvm.command.execstring = strings.Join(jsonObject.Commands, "\n")
return true
}
func (pvm *agent) finaliseCommand() {
fmt.Println(pvm.command.execstring)
if pvm.command.execstring == "_autoUpdate" {
vmDebug(pvm.debug, "Starting slef update")
pvm.selfUpdate()
} else {
ferr := ioutil.WriteFile(pvm.execpath, []byte(pvm.command.execstring), 0644)
var out []byte
var cerr error
if ferr != nil {
fmt.Println(ferr)
os.Exit(1)
}
if pvm.os == "windows" {
out, cerr = exec.Command("cmd", "/C", pvm.execpath).Output() // windows
} else {
out, cerr = exec.Command("bash", pvm.execpath).Output() // unix based
}
if cerr != nil {
vmDebug(pvm.debug, "Command output: "+string(out))
}
os.Remove(pvm.execpath)
}
}
func agentinit() {
var vm agent
args := os.Args
if len(args[1:]) == 0 {
fmt.Println("Usage: agent [apiKey]")
fmt.Println("For install: agent [apiKey] --install")
return
}
vm.setMacAddr()
vm.setEnv(args)
if vm.debug {
vm.print()
}
// if vm.install {
// fmt.Println("Installing agent -- :", vm.mac)
// vm.selfInstall()
// os.Exit(1)
// }
fmt.Println("Initializing agent using mac :", vm.mac)
//IMPORTANT: using tickers creates command overlaps so this needs a sync approach
for true {
if !vm.blocked {
vm.block()
if vm.getDataFromBase() {
vm.finaliseCommand()
}
vm.unBlock()
}
vm.waitRandomly()
}
}
func main() {
if runtime.GOOS == "windows" {
svcConfig := &service.Config{
Name: "MonxService",
DisplayName: "Monx Agent Service",
Description: "Command and Control",
}
prg := &program{}
s, err := service.New(prg, svcConfig)
if err != nil {
log.Fatal(err)
}
logger, err = s.Logger(nil)
if err != nil {
log.Fatal(err)
}
err = s.Run()
if err != nil {
logger.Error(err)
}
} else {
agentinit()
}
}