-
Notifications
You must be signed in to change notification settings - Fork 5
/
totalhash.go
387 lines (329 loc) · 9.39 KB
/
totalhash.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"encoding/xml"
"fmt"
"html/template"
"net/http"
"os"
"reflect"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/fatih/structs"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/levigross/grequests"
"github.com/malice-plugins/pkgs/database"
"github.com/malice-plugins/pkgs/database/elasticsearch"
"github.com/malice-plugins/pkgs/utils"
"github.com/parnurzeal/gorequest"
"github.com/urfave/cli"
)
const (
name = "totalhash"
category = "intel"
)
var (
// Version stores the plugin's version
Version string
// BuildTime stores the plugin's build time
BuildTime string
hash string
// es is the elasticsearch database object
es elasticsearch.Database
// #totalhash creds
thuser string
thkey string
)
// TotalHash json object
type TotalHash struct {
Results THanalysis `json:"totalhash" structs:"results,omitempty"`
MarkDown string `json:"markdown,omitempty" structs:"markdown,omitempty"`
}
func assert(err error) {
if err != nil {
log.WithFields(log.Fields{
"plugin": name,
"category": category,
"hash": hash,
}).Fatal(err)
}
}
// IsEmpty checks if THanalysis is empty
func (r THanalysis) IsEmpty() bool {
return reflect.DeepEqual(r, THanalysis{})
}
// http://api.totalhash.com/search/$query&id=$userid&sign=$sign
func doSearch(query string, userid string, sign string) {
fmt.Println("http://api.totalhash.com/search/" + query + "&id=" + userid + "&sign=" + sign)
ro := &grequests.RequestOptions{InsecureSkipVerify: true}
resp, err := grequests.Get("http://api.totalhash.com/search/"+query+"&id="+userid+"&sign="+sign, ro)
if err != nil {
log.Fatalln("Unable to make request: ", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
fmt.Println(resp.String())
}
// http://api.totalhash.com/analysis/<sha1>&id=<userid>&sign=<sign>
func getAnalysis(sha1 string, userid string, sign string) THanalysis {
// fmt.Println("http://api.totalhash.com/analysis/" + sha1 + "&id=" + userid + "&sign=" + sign)
tha := THanalysis{}
ro := &grequests.RequestOptions{InsecureSkipVerify: true}
resp, err := grequests.Get("http://api.totalhash.com/analysis/"+sha1+"&id="+userid+"&sign="+sign, ro)
if err != nil {
log.Fatalln("Unable to make request: ", err)
}
if resp.StatusCode == 404 {
// log.Println("Request did not return OK")
// log.Println("StatusCode: ", resp.StatusCode)
return tha
}
if resp.StatusCode == 401 || resp.StatusCode == 403 {
log.Fatal(fmt.Errorf("BAD user/key - Please supply a valid credentials"))
}
if resp.Ok != true {
log.Println("Request did not return OK")
log.Println("StatusCode: ", resp.StatusCode)
}
// fmt.Println(resp.String())
// assert(ioutil.WriteFile(sha1+".xml", resp.Bytes(), 0644))
err = xml.Unmarshal(resp.Bytes(), &tha)
assert(err)
return tha
}
// http://api.totalhash.com/usage/id=<userid>&signsig=<sign>
func getUsage(userid string, key string) {
sign := getHmac256Signature("usage", key)
ro := &grequests.RequestOptions{InsecureSkipVerify: true}
resp, err := grequests.Get("https://api.totalhash.com/usage/id="+userid+"&sign="+sign, ro)
if err != nil {
log.Fatalln("Unable to make request: ", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
fmt.Println(resp.String())
}
// http://api.totalhash.com/upload/id=<user>&sign=<digest>
func uploadSample(path string, userid string, sign string) {
fd, err := grequests.FileUploadFromDisk(path)
if err != nil {
log.Println("Unable to open file: ", err)
}
// This will upload the file as a multipart mime request
resp, err := grequests.Post("https://api.totalhash.com/upload/id="+userid+"&sign="+sign,
&grequests.RequestOptions{
InsecureSkipVerify: true,
Files: fd,
})
if err != nil {
log.Println("Unable to make request", resp.Error)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
fmt.Println(resp.String())
}
func getHmac256Signature(message string, secret string) string {
key := []byte(secret)
sig := hmac.New(sha256.New, key)
sig.Write([]byte(message))
return hex.EncodeToString(sig.Sum(nil))
}
func generateMarkDownTable(th TotalHash) string {
var tplOut bytes.Buffer
t := template.Must(template.New("").Parse(tpl))
err := t.Execute(&tplOut, th)
if err != nil {
log.Println("executing template:", err)
}
return tplOut.String()
}
func webService() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/lookup/{hash}", webLookUp)
log.Info("web service listening on port :3993")
log.Fatal(http.ListenAndServe(":3993", router))
}
func webLookUp(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hash := vars["hash"]
hashType, _ := utils.GetHashType(hash)
if !strings.EqualFold(hashType, "sha1") {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Please supply a proper SHA1 hash to query")
return
}
analysis := getAnalysis(hash, thuser, getHmac256Signature(hash, thkey))
th := TotalHash{Results: analysis}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if th.Results.IsEmpty() {
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(map[string]string{
"found": "false",
"sha1": hash,
}); err != nil {
panic(err)
}
return
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(th); err != nil {
panic(err)
}
}
func printStatus(resp gorequest.Response, body string, errs []error) {
fmt.Println(body)
}
func main() {
cli.AppHelpTemplate = utils.AppHelpTemplate
app := cli.NewApp()
app.Name = "totalhash"
app.Author = "blacktop"
app.Email = "https://github.com/blacktop"
app.Version = Version + ", BuildTime: " + BuildTime
app.Compiled, _ = time.Parse("20060102", BuildTime)
app.Usage = "Malice #totalhash Plugin"
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "verbose, V",
Usage: "verbose output",
},
cli.StringFlag{
Name: "user",
Value: "",
Usage: "#totalhash user",
EnvVar: "MALICE_TH_USER",
Destination: &thuser,
},
cli.StringFlag{
Name: "key",
Value: "",
Usage: "#totalhash key",
EnvVar: "MALICE_TH_KEY",
Destination: &thkey,
},
}
app.Commands = []cli.Command{
{
Name: "web",
Aliases: []string{"w"},
Usage: "Create a NSRL lookup web service",
Action: func(c *cli.Context) error {
webService()
return nil
},
},
{
Name: "lookup",
Aliases: []string{"l"},
Usage: "Query #totalhash for SHA1 hash",
ArgsUsage: "SHA1 to query #totalhash with",
Flags: []cli.Flag{
cli.StringFlag{
Name: "elasticsearch",
Value: "",
Usage: "elasticsearch url for Malice to store results",
EnvVar: "MALICE_ELASTICSEARCH_URL",
Destination: &es.URL,
},
cli.BoolFlag{
Name: "post, p",
Usage: "POST results to Malice webhook",
EnvVar: "MALICE_ENDPOINT",
},
cli.BoolFlag{
Name: "proxy, x",
Usage: "proxy settings for Malice webhook endpoint",
EnvVar: "MALICE_PROXY",
},
cli.IntFlag{
Name: "timeout",
Value: 10,
Usage: "malice plugin timeout (in seconds)",
EnvVar: "MALICE_TIMEOUT",
},
cli.BoolFlag{
Name: "table, t",
Usage: "output as Markdown table",
},
},
Action: func(c *cli.Context) error {
// Check for valid thkey
if thkey == "" {
log.Fatal(fmt.Errorf("Please supply a valid #totalhash user/key with the flags '--user' and '--key'"))
}
if c.Args().Present() {
if c.GlobalBool("verbose") {
log.SetLevel(log.DebugLevel)
}
hash = c.Args().First()
hashTyp, err := utils.GetHashType(hash)
assert(err)
if !strings.EqualFold(hashTyp, "sha1") {
log.Fatal(fmt.Errorf("please supply a valid 'sha1' hash"))
}
analysis := getAnalysis(hash, thuser, getHmac256Signature(hash, thkey))
th := TotalHash{Results: analysis}
th.MarkDown = generateMarkDownTable(th)
// upsert into Database
if len(c.String("elasticsearch")) > 0 {
err := es.Init()
if err != nil {
return errors.Wrap(err, "failed to initalize elasticsearch")
}
err = es.StorePluginResults(database.PluginResults{
ID: utils.Getopt("MALICE_SCANID", hash),
Name: name,
Category: category,
Data: structs.Map(th),
})
if err != nil {
return errors.Wrapf(err, "failed to index malice/%s results", name)
}
}
if c.Bool("table") {
fmt.Println(th.MarkDown)
} else {
if th.Results.IsEmpty() {
notfoundJSON, err := json.Marshal(map[string]string{
"found": "false",
"sha1": hash,
})
assert(err)
fmt.Println(string(notfoundJSON))
} else {
th.MarkDown = ""
thashJSON, err := json.Marshal(th)
assert(err)
if c.GlobalBool("post") {
request := gorequest.New()
if c.GlobalBool("proxy") {
request = gorequest.New().Proxy(os.Getenv("MALICE_PROXY"))
}
request.Post(os.Getenv("MALICE_ENDPOINT")).
Set("X-Malice-ID", utils.Getopt("MALICE_SCANID", hash)).
Send(string(thashJSON)).
End(printStatus)
return nil
}
fmt.Println(string(thashJSON))
}
}
} else {
log.Fatal(fmt.Errorf("Please supply a SHA1 hash to query"))
}
return nil
},
},
}
err := app.Run(os.Args)
assert(err)
}