-
Notifications
You must be signed in to change notification settings - Fork 18
/
notruler.go
640 lines (561 loc) · 17.3 KB
/
notruler.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
package main
import (
"bytes"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"strings"
"github.com/howeyc/gopass"
"github.com/sensepost/notruler/autodiscover"
"github.com/sensepost/ruler/mapi"
"github.com/sensepost/ruler/utils"
"github.com/urfave/cli"
)
//globals
var config utils.Session
var autodiscURL string
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)
}
//ReadYml reads the supplied config file, Unmarshals the data into the global config struct.
func readMailboxes(path string) (outputs []string, err error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
for _, line := range strings.Split(string(data), "\n") {
if line != "" {
outputs = append(outputs, line)
}
}
return outputs, err
}
//Function to connect to the Exchange server
func connect(c *cli.Context, mailbox string) error {
var err error
config.Email = mailbox
//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(mailbox, "@"); 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)
//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(mailbox, "@"); len(eparts) == 2 {
cdomain = eparts[1]
} else {
return fmt.Errorf("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)
}
if autodiscURL == "" {
autodiscURL = c.GlobalString("url")
}
if c.GlobalBool("o365") == true {
autodiscURL = "https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml"
}
autodiscover.SessionConfig = &config
var resp *utils.AutodiscoverResp
var rawAutodiscover string
var mapiURL, abkURL, userDN string
//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
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(mailbox)
}
if resp == nil {
resp, rawAutodiscover, autodiscURL, err = autodiscover.GetMapiHTTP(mailbox, autodiscURL, resp)
if err != nil {
return err
}
}
mapiURL = mapi.ExtractMapiURL(resp)
abkURL = mapi.ExtractMapiAddressBookURL(resp)
userDN = resp.Response.User.LegacyDN
if mapiURL == "" { //try RPC
resp, rawAutodiscover, config.RPCURL, config.RPCMailbox, config.RPCNtlm, autodiscURL, err = autodiscover.GetRPCHTTP(mailbox, autodiscURL, 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(mailbox, rawAutodiscover) //store the autodiscover for future use
}
} else {
utils.Trace.Println("MAPI URL found: ", mapiURL)
//mapi.Init(&config, userDN, mapiURL, abkURL, mapi.HTTP)
if c.GlobalBool("nocache") == false {
autodiscover.CreateCache(mailbox, 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(mailbox)
}
resp, rawAutodiscover, config.RPCURL, config.RPCMailbox, config.RPCNtlm, autodiscURL, err = autodiscover.GetRPCHTTP(mailbox, autodiscURL, resp)
if err != nil {
return err
}
userDN = resp.Response.User.LegacyDN
if c.GlobalBool("nocache") == false {
autodiscover.CreateCache(mailbox, 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 {
return 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 {
cols := make([]mapi.PropertyTag, 3)
cols[0] = mapi.PidTagRuleID
cols[1] = mapi.PidTagRuleName
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][1].ValueArray)) > maxwidth {
maxwidth = len(string(rows.RowData[k][1].ValueArray))
}
}
maxwidth -= 10
for k := 0; k < int(rows.RowCount); k++ {
rd := mapi.RuleAction{}
rd.Unmarshal(rows.RowData[k][2].ValueArray)
if rd.ActionType == 0x05 {
//utils.Info.Printf("Found client-side rule: name [%s], id [%x], trigger [%s]\n", string(utils.FromUnicode(rows.RowData[k][1].ValueArray)), rows.RowData[k][0].ValueArray, string(utils.FromUnicode(rd.ActionData.Trigger)))
for _, v := range rd.ActionData.Conditions {
if v.Tag[1] == 0x49 {
utils.Warning.Printf("Found client-side rule: [%x:%s] Application: [%s]\n", rows.RowData[k][0].ValueArray, string(utils.FromUnicode(rows.RowData[k][1].ValueArray)), string(utils.FromUnicode(v.Value)))
break
}
}
}
}
} else {
utils.Info.Printf("No Rules Found\n")
}
return nil
}
func displayForms() error {
folderid := mapi.AuthSession.Folderids[mapi.INBOX]
columns := make([]mapi.PropertyTag, 2)
columns[0] = mapi.PidTagOfflineAddressBookName
columns[1] = mapi.PidTagMid
assoctable, err := mapi.GetAssociatedContents(folderid, columns)
if err != nil {
utils.Error.Println("Failed to find any forms.")
return err
}
var forms []string
for k := 0; k < len(assoctable.RowData); k++ {
if assoctable.RowData[k][0].Flag != 0x00 {
continue
}
name := utils.FromUnicode(assoctable.RowData[k][0].ValueArray)
forms = append(forms, name)
columns := make([]mapi.PropertyTag, 1)
columns[0] = mapi.PidTagAttachDataBinary
a, e := mapi.OpenAttachment(folderid, assoctable.RowData[k][1].ValueArray, 1, columns)
if e == nil {
body := a.TransferBuffer[8:] //hack to get rid of the row header..
//scan the body to locate VBScript
//in an ideal world we would have a .emf decoder here
//scan for 0xAA 0x00 0x4A 0x55, 0xE8 -- this should be our magic value. for ruler atleast
index := -1
for k := 0; k < len(body)-5; k++ {
v := body[k : k+5]
if bytes.Equal(v, []byte{0xAA, 0x00, 0x4A, 0x55, 0xE8}) {
index = k + 5
break
}
}
if index > -1 {
utils.Warning.Printf("Found form with VBScript! [%s]\n", name)
vbs, _ := utils.ReadUnicodeString(0, body[index:])
if vbs == nil {
utils.Clear.Println(strings.Trim(utils.FromUnicode(body[index:]), " "))
} else {
utils.Clear.Println(utils.FromUnicode(vbs))
}
}
}
}
return nil
}
func checkHomepage() error {
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
} else {
utils.Warning.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 main() {
app := cli.NewApp()
app.Name = "notruler"
app.Usage = "A tool to check for abused Exchange Services"
app.Version = "0.0.1"
app.Author = "Etienne Stalmans <etienne@sensepost.com>, @_staaldraad"
app.Description = `
A tool by @_staaldraad from @sensepost for Exchange Admins to check for abused Exchange Services.`
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "domain,d",
Value: "",
Usage: "A domain for the user (optional in most cases. Otherwise allows: domain\\username)",
},
cli.BoolFlag{
Name: "o365",
Usage: "We know the target is on Office365, so authenticate directly against that.",
},
cli.StringFlag{
Name: "username,u",
Value: "",
Usage: "A valid username for the Exchange Admin",
},
cli.StringFlag{
Name: "password,p",
Value: "",
Usage: "A valid password for the Exchange Admin",
},
cli.StringFlag{
Name: "mailbox,m",
Value: "",
Usage: "The target mailbox account email address",
},
cli.StringFlag{
Name: "mailboxes,mm",
Value: "",
Usage: "The file path to a list of mailboxes to check",
},
cli.StringFlag{
Name: "config",
Value: "",
Usage: "The path to a config file to use",
},
cli.StringFlag{
Name: "url",
Value: "",
Usage: "If you know the Autodiscover URL or the autodiscover service is failing. Requires full URI, https://autodisc.d.com/autodiscover/autodiscover.xml",
},
cli.StringFlag{
Name: "proxy",
Value: "",
Usage: "If you need to use an upstream proxy. Works with https://user:pass@ip:port or https://ip:port",
},
cli.BoolFlag{
Name: "insecure,k",
Usage: "Ignore server SSL certificate errors",
},
cli.BoolFlag{
Name: "noencrypt",
Usage: "Don't use encryption the RPC level - some environments require this",
},
cli.BoolFlag{
Name: "basic,b",
Usage: "Force Basic authentication",
},
cli.BoolFlag{
Name: "nocache",
Usage: "Don't use the cached autodiscover record",
},
cli.BoolFlag{
Name: "rpc",
Usage: "Force RPC/HTTP rather than MAPI/HTTP",
},
cli.BoolFlag{
Name: "verbose",
Usage: "Be verbose and show some of thei inner workings",
},
cli.BoolFlag{
Name: "debug",
Usage: "Be print debug info",
}, cli.BoolFlag{
Name: "self",
Usage: "Check your own account (not Exchange Admin)",
},
}
app.Before = func(c *cli.Context) error {
if c.Bool("verbose") == true && c.Bool("debug") == false {
utils.Init(os.Stdout, os.Stdout, os.Stdout, os.Stderr)
} else if c.Bool("verbose") == false && c.Bool("debug") == true {
utils.Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)
} else if c.Bool("debug") == true {
utils.Init(os.Stdout, os.Stdout, os.Stdout, os.Stderr)
} else {
utils.Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)
}
//if no password or hash was supplied, read from stdin
if c.GlobalString("password") == "" {
fmt.Printf("Password: ")
var pass []byte
pass, err := gopass.GetPasswd()
if err != nil {
// Handle gopass.ErrInterrupted or getch() read error
utils.Error.Println("Password required.")
cli.OsExiter(1)
}
config.Pass = string(pass)
} else {
config.Pass = c.GlobalString("password")
}
//setup our autodiscover service
config.Domain = c.GlobalString("domain")
config.User = c.GlobalString("username")
config.Basic = c.GlobalBool("basic")
config.Insecure = c.GlobalBool("insecure")
config.Verbose = c.GlobalBool("verbose")
config.Admin = !c.GlobalBool("self")
config.RPCEncrypt = !c.GlobalBool("noencrypt")
config.CookieJar, _ = cookiejar.New(nil)
config.Proxy = c.GlobalString("proxy")
config.Email = c.GlobalString("mailbox")
return nil
}
app.Commands = []cli.Command{
{
Name: "check",
Aliases: []string{"c"},
Usage: "Check if the credentials work and we can interact with the mailbox[s]",
Action: func(c *cli.Context) error {
var mailboxes []string
if config.Email != "" {
mailboxes = append(mailboxes, config.Email)
}
if c.GlobalString("mailboxes") != "" {
//read mailbox file
mailboxes, _ = readMailboxes(c.GlobalString("mailboxes"))
}
for _, mailbox := range mailboxes {
err := connect(c, mailbox)
if err != nil {
utils.Error.Printf("Looks like %s failed: %s\n", mailbox, err)
} else {
utils.Info.Printf("Looks like we are good to go for %s!\n", mailbox)
}
}
return nil
},
},
{
Name: "rules",
Aliases: []string{"r"},
Usage: "Reviews all rules and tries to find Execute rules that have a remote path.",
Action: func(c *cli.Context) error {
var mailboxes []string
if config.Email != "" {
mailboxes = append(mailboxes, config.Email)
}
if c.GlobalString("mailboxes") != "" {
//read mailbox file
mailboxes, _ = readMailboxes(c.GlobalString("mailboxes"))
}
for _, mailbox := range mailboxes {
err := connect(c, mailbox)
if err != nil {
utils.Error.Printf("Looks like %s failed: %s\n", mailbox, err)
} else {
utils.Info.Printf("Checking [%s]\n", mailbox)
printRules()
}
}
mapi.Disconnect()
return nil
},
},
{
Name: "forms",
Aliases: []string{"r"},
Usage: "Reviews all forms and tries to find forms with attached vbscript",
Action: func(c *cli.Context) error {
var mailboxes []string
if config.Email != "" {
mailboxes = append(mailboxes, config.Email)
}
if c.GlobalString("mailboxes") != "" {
//read mailbox file
mailboxes, _ = readMailboxes(c.GlobalString("mailboxes"))
}
for _, mailbox := range mailboxes {
err := connect(c, mailbox)
if err != nil {
utils.Error.Printf("Looks like %s failed: %s\n", mailbox, err)
} else {
utils.Info.Printf("Checking [%s]\n", mailbox)
displayForms()
}
}
mapi.Disconnect()
return nil
},
},
{
Name: "homepage",
Aliases: []string{"r"},
Usage: "Reviews all mailboxes and checks if a homepage is set (only checks the inbox)",
Action: func(c *cli.Context) error {
var mailboxes []string
if config.Email != "" {
mailboxes = append(mailboxes, config.Email)
}
if c.GlobalString("mailboxes") != "" {
//read mailbox file
mailboxes, _ = readMailboxes(c.GlobalString("mailboxes"))
}
for _, mailbox := range mailboxes {
err := connect(c, mailbox)
if err != nil {
utils.Error.Printf("Looks like %s failed: %s\n", mailbox, err)
} else {
utils.Info.Printf("Checking [%s]\n", mailbox)
checkHomepage()
}
}
mapi.Disconnect()
return nil
},
},
}
app.Action = func(c *cli.Context) error {
cli.ShowAppHelp(c)
return nil
}
app.Run(os.Args)
}