tacticalrmm/natsapi/tasks.go

258 lines
5.7 KiB
Go
Raw Normal View History

2021-01-29 20:10:52 +00:00
package api
import (
2021-03-27 19:21:52 +00:00
"encoding/json"
2021-06-27 06:23:37 +00:00
"fmt"
2021-03-27 19:21:52 +00:00
"io/ioutil"
"log"
"math/rand"
2021-02-16 08:33:54 +00:00
"sync"
2021-01-29 20:10:52 +00:00
"time"
2021-06-27 06:23:37 +00:00
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
2021-01-29 20:10:52 +00:00
nats "github.com/nats-io/nats.go"
"github.com/ugorji/go/codec"
)
2021-03-27 19:21:52 +00:00
type JsonFile struct {
Agents []string `json:"agents"`
Key string `json:"key"`
NatsURL string `json:"natsurl"`
}
2021-06-27 06:23:37 +00:00
type DjangoConfig struct {
Key string `json:"key"`
NatsURL string `json:"natsurl"`
User string `json:"user"`
Pass string `json:"pass"`
Host string `json:"host"`
Port int `json:"port"`
DBName string `json:"dbname"`
}
type Agent struct {
ID int `db:"id"`
AgentID string `db:"agent_id"`
}
2021-03-27 19:21:52 +00:00
type Recovery struct {
Func string `json:"func"`
Data map[string]string `json:"payload"`
}
func setupNatsOptions(key string) []nats.Option {
opts := []nats.Option{
nats.Name("TacticalRMM"),
nats.UserInfo("tacticalrmm", key),
nats.ReconnectWait(time.Second * 2),
nats.RetryOnFailedConnect(true),
nats.MaxReconnects(3),
nats.ReconnectBufSize(-1),
}
return opts
}
2021-07-17 05:13:40 +00:00
func CheckIn(file string) {
agents, db, r, err := GetAgents(file)
2021-03-27 19:21:52 +00:00
if err != nil {
log.Fatalln(err)
}
2021-07-17 05:13:40 +00:00
var payload []byte
ret := codec.NewEncoderBytes(&payload, new(codec.MsgpackHandle))
ret.Encode(map[string]string{"func": "ping"})
2021-03-27 19:21:52 +00:00
2021-07-17 05:13:40 +00:00
opts := setupNatsOptions(r.Key)
nc, err := nats.Connect(r.NatsURL, opts...)
2021-03-27 19:21:52 +00:00
if err != nil {
log.Fatalln(err)
}
defer nc.Close()
var wg sync.WaitGroup
2021-07-17 05:13:40 +00:00
wg.Add(len(agents))
2021-03-27 19:21:52 +00:00
2021-07-17 05:13:40 +00:00
loc, _ := time.LoadLocation("UTC")
now := time.Now().In(loc)
for _, a := range agents {
go func(id string, pk int, nc *nats.Conn, wg *sync.WaitGroup, db *sqlx.DB, now time.Time) {
2021-03-27 19:21:52 +00:00
defer wg.Done()
2021-07-17 05:13:40 +00:00
var resp string
var mh codec.MsgpackHandle
mh.RawToString = true
time.Sleep(time.Duration(randRange(100, 1500)) * time.Millisecond)
2021-03-27 19:21:52 +00:00
out, err := nc.Request(id, payload, 1*time.Second)
if err != nil {
return
}
2021-07-17 05:13:40 +00:00
2021-03-27 19:21:52 +00:00
dec := codec.NewDecoderBytes(out.Data, &mh)
if err := dec.Decode(&resp); err == nil {
if resp == "pong" {
2021-07-17 05:13:40 +00:00
_, err = db.NamedExec(
`UPDATE agents_agent SET last_seen=:lastSeen WHERE agents_agent.id=:pk`,
map[string]interface{}{"lastSeen": now, "pk": pk},
)
if err != nil {
fmt.Println(err)
}
2021-02-16 08:33:54 +00:00
}
2021-03-27 19:21:52 +00:00
}
2021-07-17 05:13:40 +00:00
}(a.AgentID, a.ID, nc, &wg, db, now)
2021-01-30 04:39:15 +00:00
}
2021-03-27 19:21:52 +00:00
wg.Wait()
2021-07-17 05:13:40 +00:00
db.Close()
2021-01-30 04:39:15 +00:00
}
2021-07-17 05:13:40 +00:00
func GetAgents(file string) (agents []Agent, db *sqlx.DB, r DjangoConfig, err error) {
2021-06-27 06:23:37 +00:00
jret, _ := ioutil.ReadFile(file)
2021-07-17 05:13:40 +00:00
err = json.Unmarshal(jret, &r)
2021-06-27 06:23:37 +00:00
if err != nil {
2021-07-17 05:13:40 +00:00
return
2021-06-27 06:23:37 +00:00
}
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
r.Host, r.Port, r.User, r.Pass, r.DBName)
2021-07-17 05:13:40 +00:00
db, err = sqlx.Connect("postgres", psqlInfo)
2021-06-27 06:23:37 +00:00
if err != nil {
2021-07-17 05:13:40 +00:00
return
2021-06-27 06:23:37 +00:00
}
db.SetMaxOpenConns(15)
agent := Agent{}
rows, err := db.Queryx("SELECT agents_agent.id, agents_agent.agent_id FROM agents_agent")
if err != nil {
2021-07-17 05:13:40 +00:00
return
2021-06-27 06:23:37 +00:00
}
for rows.Next() {
err := rows.StructScan(&agent)
if err != nil {
continue
}
agents = append(agents, agent)
}
2021-07-17 05:13:40 +00:00
return
}
func AgentInfo(file string) {
agents, db, r, err := GetAgents(file)
if err != nil {
log.Fatalln(err)
}
2021-06-27 06:23:37 +00:00
var payload []byte
ret := codec.NewEncoderBytes(&payload, new(codec.MsgpackHandle))
2021-07-17 05:13:40 +00:00
ret.Encode(map[string]string{"func": "agentinfo"})
2021-06-27 06:23:37 +00:00
opts := setupNatsOptions(r.Key)
nc, err := nats.Connect(r.NatsURL, opts...)
if err != nil {
log.Fatalln(err)
}
defer nc.Close()
var wg sync.WaitGroup
wg.Add(len(agents))
for _, a := range agents {
2021-07-17 05:13:40 +00:00
go func(id string, pk int, nc *nats.Conn, wg *sync.WaitGroup, db *sqlx.DB) {
2021-06-27 06:23:37 +00:00
defer wg.Done()
2021-07-17 05:13:40 +00:00
var r AgentInfoRet
2021-06-27 06:23:37 +00:00
var mh codec.MsgpackHandle
mh.RawToString = true
time.Sleep(time.Duration(randRange(100, 1500)) * time.Millisecond)
out, err := nc.Request(id, payload, 1*time.Second)
if err != nil {
return
}
dec := codec.NewDecoderBytes(out.Data, &mh)
2021-07-17 05:13:40 +00:00
if err := dec.Decode(&r); err == nil {
stmt := `
UPDATE agents_agent
SET version=$1, hostname=$2, operating_system=$3,
plat=$4, total_ram=$5, boot_time=$6, needs_reboot=$7, logged_in_username=$8
WHERE agents_agent.id=$9;`
_, err = db.Exec(stmt, r.Version, r.Hostname, r.OS, r.Platform, r.TotalRAM, r.BootTime, r.RebootNeeded, r.Username, pk)
if err != nil {
fmt.Println(err)
}
if r.Username != "None" {
stmt = `UPDATE agents_agent SET last_logged_in_user=$1 WHERE agents_agent.id=$2;`
_, err = db.Exec(stmt, r.Username, pk)
2021-06-27 06:23:37 +00:00
if err != nil {
fmt.Println(err)
}
}
}
2021-07-17 05:13:40 +00:00
}(a.AgentID, a.ID, nc, &wg, db)
2021-06-27 06:23:37 +00:00
}
wg.Wait()
db.Close()
}
2021-03-27 19:21:52 +00:00
func GetWMI(file string) {
var result JsonFile
2021-01-29 20:10:52 +00:00
var payload []byte
var mh codec.MsgpackHandle
mh.RawToString = true
ret := codec.NewEncoderBytes(&payload, new(codec.MsgpackHandle))
ret.Encode(map[string]string{"func": "wmi"})
2021-03-27 19:21:52 +00:00
jret, _ := ioutil.ReadFile(file)
err := json.Unmarshal(jret, &result)
if err != nil {
log.Fatalln(err)
}
2021-01-29 20:10:52 +00:00
2021-03-27 19:21:52 +00:00
opts := setupNatsOptions(result.Key)
nc, err := nats.Connect(result.NatsURL, opts...)
if err != nil {
log.Fatalln(err)
}
defer nc.Close()
var wg sync.WaitGroup
wg.Add(len(result.Agents))
for _, id := range result.Agents {
go func(id string, nc *nats.Conn, wg *sync.WaitGroup) {
defer wg.Done()
2021-06-27 06:23:37 +00:00
time.Sleep(time.Duration(randRange(0, 28)) * time.Second)
2021-03-27 19:21:52 +00:00
nc.Publish(id, payload)
}(id, nc, &wg)
2021-01-29 20:10:52 +00:00
}
2021-03-27 19:21:52 +00:00
wg.Wait()
}
func randRange(min, max int) int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(max-min) + min
2021-01-29 20:10:52 +00:00
}
2021-07-17 05:13:40 +00:00
type AgentInfoRet struct {
AgentPK int `json:"id"`
Version string `json:"version"`
Username string `json:"logged_in_username"`
Hostname string `json:"hostname"`
OS string `json:"operating_system"`
Platform string `json:"plat"`
TotalRAM float64 `json:"total_ram"`
BootTime int64 `json:"boot_time"`
RebootNeeded bool `json:"needs_reboot"`
}