-
Notifications
You must be signed in to change notification settings - Fork 14
/
maigret.go
executable file
·654 lines (577 loc) · 15.3 KB
/
maigret.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/dlclark/regexp2"
color "github.com/fatih/color"
chrm "github.com/krishpranav/maigret/chrome"
downloader "github.com/krishpranav/maigret/downloader"
"golang.org/x/net/proxy"
)
const (
userAgent string = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
screenShotRes string = "1024x768"
torProxyAddress string = "socks5://127.0.0.1:9050"
)
var (
maxGoroutines int = 32
guard chan int
)
type Result struct {
Username string
Exist bool
Proxied bool
Site string
URL string
URLProbe string
Link string
Err bool
ErrMsg string
}
var (
waitGroup = &sync.WaitGroup{}
logger = log.New(color.Output, "", 0)
siteData = map[string]SiteData{}
dataFileName = "data.json"
specifiedSites string
options struct {
noColor bool
verbose bool
updateBeforeRun bool
runTest bool
useCustomData bool
withTor bool
withScreenshot bool
specifySite bool
download bool
}
)
type SiteData struct {
ErrorType string `json:"errorType"`
ErrorMsg string `json:"errorMsg"`
URL string `json:"url"`
URLMain string `json:"urlMain"`
URLProbe string `json:"urlProbe"`
URLError string `json:"errorUrl"`
UsedUsername string `json:"username_claimed"`
UnusedUsername string `json:"username_unclaimed"`
RegexCheck string `json:"regexCheck"`
}
type RequestError interface {
Error() string
}
type counter struct {
n int32
}
func (c *counter) Add() {
atomic.AddInt32(&c.n, 1)
}
func (c *counter) Get() int {
return int(atomic.LoadInt32(&c.n))
}
func parseArguments() []string {
args := os.Args[1:]
var argIndex int
if help, _ := HasElement(args, "-h", "--help"); help && !options.runTest {
fmt.Print(
`maigret - User Osint Across Social Networks.
usage: maigret USERNAME [USERNAMES...] flags options
perform test: maigret --test
positional arguments:
USERNAMES one or more usernames to investigate
flags:
-h, --help show this help message and exit
--no-color disable colored stdout output
--update update database before run from Sherlock repository
-t, --tor use tor proxy
-s, --screenshot take a screenshot of each matched urls
-v, --verbose verbose output
-d, --download download the contents of site if available
options:
--database DATABASE use custom database
--site SITE specific site to investigate
`,
)
os.Exit(0)
}
if len(args) < 1 {
fmt.Println("WARNING: You executed maigret without arguments. Use `-h` flag if you need help.")
fmt.Printf("Input username to investigate:")
var _usernames string
fmt.Scanln(&_usernames)
return strings.Split(_usernames, " ")
}
options.noColor, argIndex = HasElement(args, "--no-color")
if options.noColor {
logger = log.New(os.Stdout, "", 0)
args = append(args[:argIndex], args[argIndex+1:]...)
}
options.withTor, argIndex = HasElement(args, "-t", "--tor")
if options.withTor {
args = append(args[:argIndex], args[argIndex+1:]...)
}
options.withScreenshot, argIndex = HasElement(args, "-s", "--screenshot")
if options.withScreenshot {
args = append(args[:argIndex], args[argIndex+1:]...)
maxGoroutines = 8
} else {
maxGoroutines = 32
}
options.runTest, argIndex = HasElement(args, "--test")
if options.runTest {
args = append(args[:argIndex], args[argIndex+1:]...)
}
options.verbose, argIndex = HasElement(args, "-v", "--verbose")
if options.verbose {
args = append(args[:argIndex], args[argIndex+1:]...)
}
options.updateBeforeRun, argIndex = HasElement(args, "--update")
if options.updateBeforeRun {
args = append(args[:argIndex], args[argIndex+1:]...)
}
options.useCustomData, argIndex = HasElement(args, "--database")
if options.useCustomData {
dataFileName = args[argIndex+1]
args = append(args[:argIndex], args[argIndex+2:]...)
}
options.specifySite, argIndex = HasElement(args, "--site")
if options.specifySite {
specifiedSites = strings.ToLower(args[argIndex+1])
options.verbose = true
args = append(args[:argIndex], args[argIndex+2:]...)
}
options.download, argIndex = HasElement(args, "-d", "--download")
if options.download {
if len(args) <= 1 {
fmt.Println("List of sites that can download userdata")
for key := range downloader.Impls {
fmt.Fprintf(color.Output, "[%s] %s\n", color.HiGreenString("+"), color.HiWhiteString(key))
}
os.Exit(0)
}
args = append(args[:argIndex], args[argIndex+1:]...)
}
return args
}
func main() {
usernames := parseArguments()
initializeSiteData(options.updateBeforeRun)
guard = make(chan int, maxGoroutines)
if options.runTest {
test()
os.Exit(0)
}
if options.specifySite {
for _, username := range usernames {
_siteData := map[string]SiteData{}
for siteName, v := range siteData {
_siteData[strings.ToLower(siteName)] = v
}
if options.noColor {
fmt.Printf("\nInvestigating %s on:\n", username)
} else {
fmt.Fprintf(color.Output, "Investigating %s on:\n", color.HiGreenString(username))
}
site := specifiedSites
if val, ok := _siteData[site]; ok {
res := maigret(username, site, val)
WriteResult(res)
} else {
log.Printf("[!] %s is not a valid site.", site)
}
}
} else {
for _, username := range usernames {
if options.noColor {
fmt.Printf("\nInvestigating %s on:\n", username)
} else {
fmt.Fprintf(color.Output, "Investigating %s on:\n", color.HiGreenString(username))
}
waitGroup.Add(len(siteData))
for site := range siteData {
guard <- 1
go func(site string) {
defer waitGroup.Done()
res := maigret(username, site, siteData[site])
WriteResult(res)
<-guard
}(site)
}
waitGroup.Wait()
}
}
}
func initializeSiteData(forceUpdate bool) {
jsonFile, err := os.Open(dataFileName)
if err != nil || forceUpdate {
if err != nil {
if options.noColor {
fmt.Printf(
"[!] Cannot open database \"%s\"\n",
dataFileName,
)
} else {
fmt.Fprintf(
color.Output,
"[%s] Cannot open database \"%s\"\n",
color.HiRedString("!"), (dataFileName),
)
}
}
if options.noColor {
fmt.Printf(
"%s Update database: %s",
("[!]"),
("Downloading..."),
)
} else {
fmt.Fprintf(
color.Output,
"[%s] Update database: %s",
color.HiBlueString("!"),
color.HiYellowString("Downloading..."),
)
}
if forceUpdate {
jsonFile.Close()
}
r, err := Request("https://raw.githubusercontent.com/sherlock-project/sherlock/master/sherlock/resources/data.json")
if err != nil || r.StatusCode != 200 {
if options.noColor {
fmt.Printf(" [%s]\n", ("Failed"))
} else {
fmt.Fprintf(color.Output, " [%s]\n", color.HiRedString("Failed"))
}
if err != nil {
panic("Failed to update database.\n" + err.Error())
} else {
panic("Failed to update database: " + r.Status)
}
} else {
defer r.Body.Close()
}
if _, err := os.Stat(dataFileName); !os.IsNotExist(err) {
if err = os.Remove(dataFileName); err != nil {
panic(err)
}
}
_updateFile, _ := os.OpenFile(dataFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if _, err := _updateFile.WriteString(ReadResponseBody(r)); err != nil {
if options.noColor {
fmt.Printf("Failed to update data.\n")
} else {
fmt.Fprint(color.Output, color.RedString("Failed to update data.\n"))
}
panic(err)
}
_updateFile.Close()
jsonFile, _ = os.Open(dataFileName)
if options.noColor {
fmt.Println(" [Done]")
} else {
fmt.Fprintf(color.Output, " [%s]\n", color.GreenString("Done"))
}
}
defer jsonFile.Close()
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
panic("Error while read " + dataFileName)
} else {
json.Unmarshal([]byte(byteValue), &siteData)
}
}
func Request(target string) (*http.Response, RequestError) {
request, err := http.NewRequest("GET", target, nil)
if err != nil {
return nil, err
}
request.Header.Set("User-Agent", userAgent)
client := &http.Client{
Timeout: 60 * time.Second,
}
if options.withTor {
tbProxyURL, err := url.Parse(torProxyAddress)
if err != nil {
return nil, err
}
tbDialer, err := proxy.FromURL(tbProxyURL, proxy.Direct)
if err != nil {
return nil, err
}
tbTransport := &http.Transport{
Dial: tbDialer.Dial,
}
client.Transport = tbTransport
}
return client.Do(request)
}
func ReadResponseBody(response *http.Response) string {
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
return string(bodyBytes)
}
func HasElement(array []string, targets ...string) (bool, int) {
for index, item := range array {
for _, target := range targets {
if item == target {
return true, index
}
}
}
return false, -1
}
func getHash(username string, password string, site string) Result {
var user string
var password string
var site string
if data.url != "" {
}
}
func maigret(username string, site string, data SiteData) Result {
var u, urlProbe string
var result Result
u = strings.Replace(data.URL, "{}", username, 1)
if data.URLProbe != "" {
urlProbe = strings.Replace(data.URLProbe, "{}", username, 1)
} else {
urlProbe = u
}
if data.RegexCheck != "" {
re := regexp2.MustCompile(data.RegexCheck, 0)
if match, _ := re.MatchString(username); !match {
return Result{
Username: username,
URL: data.URL,
Proxied: options.withTor,
Site: site,
Exist: false,
Err: false,
}
}
}
r, err := Request(urlProbe)
if err != nil {
if r != nil {
r.Body.Close()
}
return Result{
Username: username,
URL: data.URL,
URLProbe: data.URLProbe,
Proxied: options.withTor,
Exist: false,
Site: site,
Err: true,
ErrMsg: err.Error(),
}
}
switch data.ErrorType {
case "status_code":
if r.StatusCode == http.StatusOK {
result = Result{
Username: username,
URL: data.URL,
URLProbe: data.URLProbe,
Proxied: options.withTor,
Exist: true,
Link: u,
Site: site,
}
} else {
result = Result{
Username: username,
URL: data.URL,
Proxied: options.withTor,
Site: site,
Exist: false,
Err: false,
}
}
case "message":
if !strings.Contains(ReadResponseBody(r), data.ErrorMsg) {
result = Result{
Username: username,
URL: data.URL,
URLProbe: data.URLProbe,
Proxied: options.withTor,
Exist: true,
Link: u,
Site: site,
}
} else {
result = Result{
Username: username,
URL: data.URL,
Proxied: options.withTor,
Site: site,
Exist: false,
Err: false,
}
}
case "response_url":
if (r.StatusCode <= 300 || r.StatusCode < 200) && r.Request.URL.String() == u {
result = Result{
Username: username,
URL: data.URL,
URLProbe: data.URLProbe,
Proxied: options.withTor,
Exist: true,
Link: u,
Site: site,
}
} else {
result = Result{
Username: username,
URL: data.URL,
Proxied: options.withTor,
Site: site,
Exist: false,
Err: false,
}
}
default:
result = Result{
Username: username,
Proxied: options.withTor,
Exist: false,
Err: true,
ErrMsg: "Unsupported error type `" + data.ErrorType + "`",
Site: site,
}
}
if result.Exist && options.withScreenshot {
urlParts, _ := url.Parse(urlProbe)
folderPath := filepath.Join("screenshots", username)
outputPath := filepath.Join(folderPath, urlParts.Host+".png")
if err := os.MkdirAll(folderPath, 0755); err != nil {
log.Fatal(err)
}
if err := getScreenshot(screenShotRes, urlProbe, outputPath); err != nil {
log.Fatal(err)
}
}
if result.Exist && options.download {
if downloadFunc, ok := downloader.Impls[strings.ToLower(site)]; ok {
downloadFunc.(func(string, *log.Logger))(urlProbe, logger)
}
}
r.Body.Close()
return result
}
func WriteResult(result Result) {
if options.noColor {
if result.Exist {
logger.Printf("[%s] %s: %s\n", ("+"), result.Site, result.Link)
} else {
if options.verbose {
if result.Err {
logger.Printf("[%s] %s: %s: %s", ("!"), result.Site, ("ERROR"), (result.ErrMsg))
} else {
logger.Printf("[%s] %s: %s", ("-"), result.Site, ("Not Found!"))
}
}
}
} else {
if result.Exist {
logger.Printf("[%s] %s: %s\n", color.HiGreenString("+"), color.HiWhiteString(result.Site), result.Link)
} else {
if options.verbose {
if result.Err {
logger.Printf("[%s] %s: %s: %s", color.HiRedString("!"), result.Site, color.HiMagentaString("ERROR"), color.HiRedString(result.ErrMsg))
} else {
logger.Printf("[%s] %s: %s", color.HiRedString("-"), result.Site, color.HiYellowString("Not Found!"))
}
}
}
}
}
func getScreenshot(resolution, targetURL, outputPath string) error {
chrome := &chrm.Chrome{
Resolution: resolution,
ChromeTimeout: 60,
ChromeTimeBudget: 60,
UserAgent: userAgent,
}
chrome.Setup()
u, err := url.ParseRequestURI(targetURL)
if err != nil {
return err
}
chrome.ScreenshotURL(u, outputPath)
return nil
}
func test() {
log.Println("maigret is activated for checking site validity.")
if options.withScreenshot {
log.Println("Taking screenshot is not available in this sequence. Aborted.")
return
}
tc := counter{}
waitGroup.Add(len(siteData))
for site := range siteData {
guard <- 1
go func(site string) {
defer waitGroup.Done()
var _currentContext = siteData[site]
_usedUsername := _currentContext.UsedUsername
_unusedUsername := _currentContext.UnusedUsername
_resUsed := maigret(_usedUsername, site, siteData[site])
_resUnused := maigret(_unusedUsername, site, siteData[site])
if _resUsed.Exist && !_resUnused.Exist {
// Works
} else {
var _errMsg string
if _resUsed.Err {
_errMsg += fmt.Sprintf("[%s]", _resUsed.ErrMsg)
}
if _resUnused.Err {
_errMsg += fmt.Sprintf("[%s]", _resUnused.ErrMsg)
}
if _errMsg != "" {
if options.noColor {
logger.Printf("[-] %s: %s %s", site, ("Failed with error"), _errMsg)
} else {
logger.Printf("[-] %s: %s %s", site, color.RedString("Failed with error"), _errMsg)
}
} else {
if options.noColor {
logger.Printf("[-] %s: %s (%s: expected true, but %s, %s: expected false, but %s)",
site, ("Not working"),
_usedUsername, strconv.FormatBool(_resUsed.Exist),
_unusedUsername, strconv.FormatBool(_resUnused.Exist),
)
} else {
logger.Printf("[-] %s: %s (%s: expected true, but %s, %s: expected false, but %s)",
site, color.RedString("Not working"),
_usedUsername, strconv.FormatBool(_resUsed.Exist),
_unusedUsername, strconv.FormatBool(_resUnused.Exist),
)
}
}
tc.Add()
}
<-guard
}(site)
}
waitGroup.Wait()
if options.noColor {
fmt.Println("[Done]")
} else {
fmt.Fprintf(color.Output, "[%s]\n", color.GreenString("Done"))
}
logger.Printf("\nThese %d sites are not compatible with the Sherlock database.\n"+
"Please check https://github.com/krishpranav/maigret/#to-fix-incompatible-sites", tc.Get())
}