summaryrefslogtreecommitdiff
path: root/model/comm_model.go
blob: f89b6c5024cf8fdc2cf07cd15957e5de2718a7bc (plain)
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
/*
 * @Author: your name
 * @Date: 2021-01-06 09:56:18
 * @LastEditTime: 2021-01-19 12:02:23
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /commdetection/model/comm_model.go
 */

package model

import (
	"commdetection/logger"
	"fmt"
	"reflect"
	"sort"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

//IntSlice includes a list of n array in order to use sort.Sort() method to sort n
type IntSlice []int

func (s IntSlice) Len() int           { return len(s) }
func (s IntSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s IntSlice) Less(i, j int) bool { return s[i] > s[j] }

// Command contains command and its flags or symbols
type Command struct {
	CommName  string    `json:"commname" bson:"commname"`
	Args      []string  `json:"args" bson:"args,omitempty"`
	Flags     []string  `json:"flags" bson:"flags,omitempty"`
	TimeStamp time.Time `json:"timestamp" bson:"timestamp"`
	User      string    `json:"user" bson:"user"`
	Mac       string    `json:"mac" bson:"mac"`
}

// Commands is the multi type of Command
type Commands []Command

func (c Commands) Len() int {
	return len(c)
}

func (c Commands) Swap(i, j int) {
	c[i], c[j] = c[j], c[i]
}

func (c Commands) Less(i, j int) bool {
	return c[i].TimeStamp.Before(c[j].TimeStamp)
}

// Has returns whether c has the command
func (c Commands) Has(command Command) bool {
	sort.Sort(c)
	if sort.Search(c.Len(), func(i int) bool {
		return reflect.DeepEqual(c[i], command)
	}) == c.Len() {
		return false
	}
	return true
}

// removeOneCommand removes only one command from the list given the index
func removeOneCommand(commands []Command, n int) []Command {
	return append(commands[:n], commands[n+1:]...)
}

// RemoveCommands removes a list of commands using index
func RemoveCommands(commands []Command, n IntSlice) []Command {
	if len(n) == 0 {
		return commands
	}
	sort.Sort(n)
	for i := range n {
		commands = removeOneCommand(commands, n[i])
	}
	return commands
}

// GetCommandsFrom gets all the commands in the mongodb collections
func (c *Commands) GetCommandsFrom(dbName string, cName string) error {
	return mongoOpsWithoutIndex(getCommandsFromFn, opParams{
		dbName:   dbName,
		cName:    cName,
		commands: c,
	})
}

func getCommandsFromFn(sc mongo.SessionContext) error {
	client := sc.Client()
	params, ok := sc.Value(key("params")).(opParams)
	if !ok {
		return fmt.Errorf("Error transfering the params")
	}
	collection := client.Database(params.dbName).Collection(params.cName)
	cur, err := collection.Find(sc, bson.D{})
	if err != nil {
		return err
	}
	defer cur.Close(sc)
	for cur.Next(sc) {
		var next Command
		err := cur.Decode(&next)
		if err != nil {
			logger.Warnln(err)
		}
		*params.commands = append(*params.commands, next)
	}
	return nil
}

// InsertAllTo insert the given commands to the specified database and collection
func (c *Commands) InsertAllTo(dbName string, cName string) error {
	return mongoOpsWithoutIndex(insertAllCommandsToFn, opParams{
		dbName:   dbName,
		cName:    cName,
		commands: c,
	})
}

func insertAllCommandsToFn(sc mongo.SessionContext) error {
	client := sc.Client()
	params, ok := sc.Value(key("params")).(opParams)
	if !ok {
		return fmt.Errorf("Error tranfering the params")
	}
	if params.commands.Len() == 0 {
		return nil
	}

	var deleteIndexes []int
	for i := 0; i < params.commands.Len()-1; i++ {
		if reflect.DeepEqual((*params.commands)[i], (*params.commands)[i+1]) {
			deleteIndexes = append(deleteIndexes, i)
		}
	}
	*params.commands = RemoveCommands(*params.commands, deleteIndexes)
	collections := client.Database(params.dbName).Collection(params.cName)
	var documents []interface{}
	for _, command := range *params.commands {
		// if the command is not found in the mongodb
		if res := collections.FindOne(sc, command); res.Err() == mongo.ErrNoDocuments {
			// add the command to the ready-inserted documents
			documents = append(documents, command)
		}
	}
	// If every command is inserted into the db, documents may be nil
	if documents == nil {
		return nil
	}
	_, err := collections.InsertMany(sc, documents)
	if err != nil {
		return err
	}
	return nil
}

// InsertAnyTo inserts one command to the dbName.cName
func (c *Commands) InsertAnyTo(dbName, cName string, index uint) error {
	return mongoOpsWithIndex(insertAnyCommandToFn, opParams{
		dbName:   dbName,
		cName:    cName,
		index:    index,
		commands: c,
	})
}

func insertAnyCommandToFn(sc mongo.SessionContext) error {
	client := sc.Client()
	params, ok := sc.Value(key("params")).(opParams)
	if !ok {
		return fmt.Errorf("Error transfering the params")
	}
	collections := client.Database(params.dbName).Collection(params.cName)
	if res := collections.FindOne(sc, (*params.commands)[int(params.index)]); res.Err() != mongo.ErrNoDocuments {
		return nil
	}
	_, err := collections.InsertOne(sc, (*params.commands)[int(params.index)])
	if err != nil {
		return err
	}
	return nil
}

// UpdateAnyTo updates the command in the mongodb
func (c *Commands) UpdateAnyTo(dbName, cName string, index uint, updateFilter interface{}) error {
	return mongoOpsWithIndex(updateAnyCommandFn, opParams{
		dbName:       dbName,
		cName:        cName,
		index:        index,
		commands:     c,
		updateFilter: updateFilter,
	})
}

func updateAnyCommandFn(sc mongo.SessionContext) error {
	client := sc.Client()
	params, ok := sc.Value(key("params")).(opParams)
	if !ok {
		return fmt.Errorf("Error transfering the params")
	}
	collection := client.Database(params.dbName).Collection(params.cName)
	command := (*params.commands)[int(params.index)]
	// if the command is found in the mongodb, update will be useless, so return nil
	if res := collection.FindOne(sc, command); res.Err() != mongo.ErrNoDocuments {
		return nil
	}
	_, err := collection.UpdateOne(sc, params.updateFilter, bson.D{{
		"$set",
		command,
	}})
	if err != nil {
		return err
	}
	return nil
}

// DeleteOneFrom deletes one command from the dbName.cName
func (c *Commands) DeleteOneFrom(dbName, cName string, index uint) error {
	return mongoOpsWithIndex(deleteOneCommandFromFn, opParams{
		dbName:   dbName,
		cName:    cName,
		index:    index,
		commands: c,
	})
}

func deleteOneCommandFromFn(sc mongo.SessionContext) error {
	client := sc.Client()
	params, ok := sc.Value(key("params")).(opParams)
	if !ok {
		return fmt.Errorf("Error transfering the params")
	}
	collections := client.Database(params.dbName).Collection(params.cName)
	_, err := collections.DeleteOne(sc, (*params.commands)[int(params.index)])
	if err != nil {
		return err
	}
	return nil
}

// DeleteAllFrom deletes many commands from dbName.cName
func (c *Commands) DeleteAllFrom(dbName, cName string) error {
	return mongoOpsWithoutIndex(deleteAllCommandsFromFn, opParams{
		dbName:   dbName,
		cName:    cName,
		commands: c,
	})
}

func deleteAllCommandsFromFn(sc mongo.SessionContext) error {
	client := sc.Client()
	params, ok := sc.Value(key("params")).(opParams)
	if !ok {
		return fmt.Errorf("Error tranfering the params")
	}
	collections := client.Database(params.dbName).Collection(params.cName)
	var deleteResults []*mongo.DeleteResult
	for _, command := range *params.commands {
		res, err := collections.DeleteOne(sc, command)
		if err != nil {
			return err
		}
		deleteResults = append(deleteResults, res)
	}
	return nil
}