styx/matcher/main.go
2020-05-27 12:05:53 +02:00

156 lines
2.7 KiB
Go

package matcher
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"runtime"
"sync"
"time"
"github.com/dgraph-io/dgo/v2"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"gitlab.dcso.lolcat/LABS/styx/models"
)
var (
_, b, _, _ = runtime.Caller(0)
basepath = filepath.Dir(b)
)
type Matcher struct {
Running bool
StopChan chan bool
StoppedChan chan bool
}
func (m *Matcher) Initialize() bool {
if !viper.GetBool("matcher.activated") {
return false
}
logrus.Info("matching is activated")
return true
}
func (m *Matcher) Stop(wg *sync.WaitGroup) {
if m.Running {
m.StopChan = make(chan bool)
close(m.StopChan)
<-m.StopChan
wg.Done()
m.Running = false
}
}
type Result struct {
Result []models.Node `json:"Node,omiempty"`
}
// Run runs the routine trying to find matches in the ingested data.
func (m *Matcher) Run(wg *sync.WaitGroup, graphClient *dgo.Dgraph) {
if !m.Running {
m.StoppedChan = make(chan bool)
wg.Add(1)
for {
q := `query allofterms($a: string) {
Node(func: allofterms(full, $a)) {
uid
id
type
ndata
pasteNode {
id
type
created
modified
fullPaste {
full
meta {
full_url
size
expire
title
syntax
user
scrape_url
date
key
}
}
}
}
}`
ctx := context.Background()
txn := graphClient.NewTxn()
defer txn.Discard(ctx)
res, err := txn.QueryWithVars(ctx, q, map[string]string{"$a": "code"})
if err != nil {
logrus.Warn(err)
}
n := Result{}
json.Unmarshal([]byte(res.Json), &n)
if len(n.Result) != 0 {
// TODO: review time and id to be updated on new resulsts
uuid := uuid.New().String()
t := time.Now()
rfc3339time := t.Format(time.RFC3339)
matcher := models.Match{
ID: uuid,
Timestamp: rfc3339time,
Target: "code",
}
for _, res := range n.Result {
matcher.Nodes = append(matcher.Nodes, res)
}
fmt.Println("matcher:", matcher)
}
m.Running = true
}
}
}
// RunDomainMatch looks for a target within the identified IOCs in /matcher/data.
// the function could be refactored with RunDomainFilters
func RunDomainMatch(domain string) bool {
path := basepath + "/data/domains.txt"
sliceDomain, err := ioutil.ReadDir(path)
if err != nil {
logrus.Warn("matcher#ReadDir#domains", err)
}
for _, file := range sliceDomain {
f, err := os.OpenFile(path+file.Name(), 1, 0644)
if err != nil {
logrus.Warn("matcher#OpenFile#", err)
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
r, err := regexp.Compile(scanner.Text())
if err != nil {
logrus.Warn("matcher#Compile#", err)
}
if r.MatchString(domain) {
return false
}
}
}
return true
}