Nicolás A. Economou Andrés Lopez Luksenberg EKO-PARTY 2011.

1 Nicolás A. Economou Andrés Lopez Luksenberg EKO-PARTY 2...
Author: Miguel Aguirre Alcaraz
0 downloads 1 Views

1 Nicolás A. Economou Andrés Lopez Luksenberg EKO-PARTY 2011

2  “There have been as many new MBR threats found in the first seven months of 2011 as there were in previous three years...”. Symantec Intelligence Report: August 2011 INTRO

3 Mecanismo de Booteo POWER ON CPU (BIST) EIP = 0xF000:0xFFF0 BIOS (POST) MBR LOADED OS LOADER EIP = 0x07C0:0x0000 INT 13h 0x07C0:0x0000

4  Luego, se ejecuta el codigo que levanta el proximo stage del LOADER del OS  Ej. Windows 7 –1. MBR –2. Bootmgr ( file ) –3. Winload.exe ( embebido en el bootmgr ) –4. Winload.exe ( file ) –5. Resto de los files ( kernel, drivers, etc ) Mecanismo de Booteo

5  Estando en el MBR ( Disco Rigido )  Booteando desde un dispositivo removible ( CDs, PENDRIVEs, ZIPs, FLOPPY )  PXE ( Network )  BIOS modificado ( ejecutando antes de 7C00h ).  WARM BOOT ( el segundo principio ) Ejecutando desde el principio

6  Usando la “INT 13H” del BIOS –Pattern Matching: » Recorrer el disco y patchear » Hookear mientras el OS se carga y patchear –Entender el file system y agregar/patchear un file ( e.g Computrace v.1 ) Tecnicas comunes ( File Patching)

7  E.g Hookeando la “INT 13H” (REAL MODE) Ejecucion / Tiempo time CPU inst int 13h call

8  Virtualizar el OS desde el principio –VMBR ( Virtual Machine Based Rootkit ) » E.g “SubVirt” (Univ. Michigan + Microsoft Research)  Deep Boot ;-) Tecnicas menos comunes

9  Es una tecnica/”tool”  Independiente del OS ( NO necesita pattern matching )  Ejecucion Continua: NO pierde NUNCA el control de la ejecucion ( durante el booteo )  Usa solo features del Intel 80386 !  Implementacion en C y ASM inlineado (16 y 32 bits) Que es Deep Boot ?

10  Se apoya sobre el mecanismo del TRAP FLAG ( SINGLE STEP ) para sobrevivir y controlar la ejecucion.  “Emula” algunas instrucciones CRITICAS  Sobrevive a los cambios de contexto del OS  NO AFECTA el funcionamiento del OS “victima” Que es Deep Boot ?

11 Taking Over from the init DEEP BOOT Stage 0 DEEP BOOT STAGE 1/2/T INT 13h BIOS POST INT 13h ORIGINAL BOOT SECTOR OS LOADEROS KERNEL INT 13h INT 13h + TRAP FLAG (0)(0)(1)(1) (2)(2) (3)(3)(4)(4) (5)(5)(6)(6)

12 Deep Boot Point of View DEEP BOOT OS DEEP BOOT OS REAL MODEPROTECTED MODE

13  Genera una excepcion por cada instrucción que se está por ejecutar  La excepcion es procesada por un “handler” ( callback )  El handler se encuentra en la misma memoria fisica que la instrucción a ejecutarse (EL TRUCO !)  Usado por todos los debuggers  Implementado en x86-x64 en el registro EFLAGS ( Trap Flag ) SINGLE STEP

14 Intel TRAP FLAG

15  Cuando esta prendido: –Invoca a la interrupcion numero 1 –En REAL MODE direcciona mediante la IVT –En PROTECTED MODE direcciona mediante la IDT Intel TRAP FLAG

16 Handling SINGLE STEPs EIP CS EFLAGS CURRENT DATA esp STACK 100 96 92 88 ADDR BEFOREAFTER

17  CPU Tables –GDT –IVT –IDT A little of theory...

18  GDT: “General Descriptor Table”  Usada por el micro en modo protegido  Sirve para “separar/proteger” areas de memoria  Cada entrada de llama DESCRIPTOR  El primer descriptor NO se usa ( NULL )  Longitud puede variar entre 3 a 8192 entradas.  Se carga usando la instrucción “lgdt” GDT

19  Define un segmento ( area ) de memoria  Se los referencia con un offset en la GDT ( SELECTOR – E.g CS, SS, DS, ES, FS,GS)  Es una estructura de 8 bytes » Base Address: DWORD ( 32 bits ) » Limit: WORD+NIBBLE ( 20 bits ) » Privileges: Code, Data, Gates GDT DESCRIPTOR

20  IVT: “Interrupt Vector Table”  Usada por el micro en modo real  Sirve para asociar interrupcion-handler  Interrupciones tambien son generadas por IRQs  Cada entrada mide 4 bytes ( SEGM:OFFSET )  Longitud de 256 entradas. IVT

21  IDT: “Interrupt Descriptor Table”  Usada por el micro en modo protegido  Sirve para asociar interrupcion-handler  Interrupciones tambien son generadas por IRQs  Cada entrada de llama DESCRIPTOR  Longitud puede variar entre 0 a 256 entradas.  Se carga usando la instrucción “lidt” IDT

22  Apunta a un handler ( “callback” ).  Los usa el micro cuando se produce una interrupcion –E.g:  ZERO DIVISION  excepcion  el CPU lee el descriptor numero 0 de la IDT  int 0  handler  Es una estructura de 8 bytes » Base Address: DWORD ( 32 bits ) » Selector: WORD ( 16 bits ) » Privileges: Ring desde donde puede ser llamado IDT DESCRIPTOR

23 A hard work... Deep Boot Development

24  Sobrevivir: –CONTEXT SWITCHS del OS: » 1. REAL MODE  PROTECTED MODE » 2. PROTECTED MODE  PROTECTED MODE » 3. PROTECTED MODE  REAL MODE –STACK SWITCHS del OS –Mantenerse en un area de memoria confiable –Mantener la integridad del OS ( MEM y REGS ) –Mantener el TRAP FLAG PRENDIDO... Principales Problemas

25  Pasos normales: –1. El OS carga una GDT ( “lgdt” ) –2. El OS carga una IDT ( “lidt” ) –3. El OS setea el PDE ( registro CR3 ) –4. El OS prende el bit 0-31 del registro CR0 –5. El OS finalmente ejecuta un JUMP FAR REAL MODE  PROT. MODE

26  Con Deep Boot corriendo: –El OS carga una GDT ( “lgdt” ) –El OS INTENTA cargar una IDT ( “lidt” ) –El OS setea el PDE ( registro CR3 ) –El OS INTENTA prender el bit 0-31 del registro CR0 –El OS generalmente ejecuta un JUMP FAR ( pero esta vez en REAL MODE ;-) ) REAL MODE  PROT. MODE

27  Condiciones para el Deep Boot’s CONTEXT SWITCH: –1. Si el bit 0 del registro CR0 intentó ser prendido –2. Si el OS hizo un JUMP FAR, RETF, CALL FAR, IRET » If ( LAST_CS != CURRENT_CS ) REAL MODE  PROT. MODE

28  Pasos de Deep Boot: –1. Agrega/reusa 2 descriptores de 32 bits en la GDT ( codigo y datos) –2. Setea 2 handlers en la IDT original ( SINGLE STEP y BREAKPOINT ) IDT original –3. Carga la IDT original ( la que no pudo el OS ) –4. Prende el bit 0-31 del registro CR0 –5. Hace un IRETD a CURRENT_CS:CURRENT EIP ( Cruce efectivo a MODO PROTEGIDO ) CRUZANDO A PROT. MODE

29  Pasos normales: –El OS carga una nueva GDT –El OS carga una nueva IDT –El OS habilita paginacion o cambia el PDE  Con Deep Boot corriendo: –IDEM para el OS PROT. MODE  PROT. MODE

30  Pasos de Deep Boot: –Si el OS está por cargar una GDT ( “lgdt” ) » Deep Boot agrega/reusa 2 descriptores » Deep Boot actualiza los IDT descriptors con la nueva GDT –Si el OS está por cargar una IDT ( “lidt” ) » Deep Boot setea los 2 handlers en la nueva IDT ( SINGLE STEP y BREAKPOINT ) –Si el OS cambia la base del PAGE DIRECTORY ENTRY ( CR3 ) » Deep Boot no hace nada... ??? PROT. MODE  PROT. MODE

31  Pasos normales: –1. El OS salta a codigo de 16 bits en PM –2. El OS apaga el bit 0 del registro CR0 –3. El OS ejecuta un JUMP FAR –4. El OS carga una nueva IDT apuntando a la direccion 0 ( IVT ) PROT. MODE  REAL MODE

32  Con Deep Boot corriendo: –1. El OS salta a codigo de 16 bits (IDEM) –2. Si el OS está por apagar el bit 0 del registro CR0 » Deep Boot setea una nueva IDT en 0 ( IVT ) –3. El OS apaga el bit 0 del registro CR0 –4. Se produce un “JUMP FAR” generado por el mismo SINGLE STEP ( “int 1” ) –5. La interrupcion es catcheada por el handler en REAL MODE –6. El handler cambia el CURRENT_CS por uno valido en REAL MODE PROT. MODE  REAL MODE

33  CS = selector de codigo de 16 bits –JUMP FAR to REAL_MODE  OK  CS = selector de codigo de 32 bits –JUMP FAR to REAL_MODE  HALT STATE ??? PROT. MODE  REAL MODE

34 Indocument mode ? Deep Boot (32 bits handler) 1. SINGLE STEP (PROT.M) 2. REAL MODE MOV ESI,1D6CXXXX ??? NEW EIP = 03DA ?????????? NEXT

35  REAL MODE  16 bits native code, 64 kb de direccionamiento de data.  UNREAL MODE  16 bits native code, hasta 4 GB de direccionamiento de data ( using instruct. prefixes ).  THIS MODE ( UNREAL MODE 32 ??? )  32 bits native code ( without prefixes ), 64 kb de direccionamiento Indocument mode ?

36  Recorte del Volumen 3 del manual de Intel OS Stack Switches

37  Ejemplo: –SS1 = 0x10, BASE = 0, ESP1 = 0x4444 –SS1:ESP1  0x0:0x4444  0x4444 –SS2 = 0x58, BASE = 0x70000, ESP2 = 0x1000 –SS2:ESP2  0x70000:0x1000  0x71000  Si el OS NO respeta la ATOMICIDAD ? –? SS 2 :ESP 1  0x70000:0x4444  0x74444  BAD FOR US !  MEMORY CORRUPTION  BSoD OS Stack Switches

38  NTLDR basic block ( Windows ) OS Stack Switches INCONSISTENT STACK AREA

39  Deep Boot Solution: –1.Si el OS va a ejecutar un “mov ss,algo” » Deep Boot apunta EIP a la proxima inst. y se pone en alerta –2. Si el OS va a ejecutar un “mov esp,valor” » Deep Boot salta a un trampoline para switchear al nuevo STACK OS Stack Switches

40  Area de memoria donde se ejecuta Deep Boot.  Direccion Base = 9E00h:0000h = 0x9E000  Dentro del primer MEGABYTE » En REAL MODE » En PROTECTED MODE  Codigo y variables contenidos en la misma area.  Memoria shareada con el OS ( comparten el mismo contexto ). BIOSFERA

41  Guardar y Restaurar el estado de todos los registros en cada SINGLE STEP handleado.  No escribir memoria que esté fuera de la BIOSFERA  No alterar el curso normal de la ejecucion Integridad del OS

42  En las primeras etapas, el OS puede NO necesitar una IDT ( Ej. GRUB )  Deep Boot necesita si o si una IDT para funcionar  Si el OS intenta pasar a modo protegido sin IDT –Deep Boot crea una IDT temporal propia Si el OS no usa IDT ?

43  Evitar que el TRAP FLAG sea apagado ? –Ningun OS intentó apagarlo...  Para poder correr codigo en C –Setear DS = SS y EBP = ESP  Codigo PIC en C –No usar ptr a funcions, strings ni variables globales –Hubo que crear la funcion “get_pic_address()” Misc

44  LGDT  LIDT  MOV CR0, REG32  MOV SS, REG16  MOV ESP, REG32  JUMP LARGE FAR ( RM  PM 32 ) Instrucciones “emuladas/interceptadas”

45  Cada instrucción traceada tiene un costo  Promedio de 500.000 inst/seg ( en esta notebook )  La idea es eliminar la mayor cantidad de handleos sin perder el control Performance

46  Emular algunas instrucciones basicas » jump condicionales » jump incondicionales » mov reg32,reg32 » nops  Usando Breakpoints –Chequear el destino y saltear algunas instrucciones de repeticion ( “rep movsX”, “rep stosX”, “rep outsX” ) –Bypassear llamados a funciones ( PELIGROSO ! ) Optimizaciones posibles

47  Compuesto por: –Stage 0 (loader de stage 1 + stage 2 + trailer en MBR, pendrive, PXE, CD, FDD, etc) –Stage 1 (Handler de 16 bits en REAL MODE) –Stage 2 ( Handler de 32 bits en PROT. MODE) –Trailer (CALLBACK de 32 bits llamado x cada instr. ejecutada en PROT. MODE ) Deep Boot Body e

48 Deep Boot Body today e STAGE 0 STAGE 1 REAL MODE (16 bits) TRAILER (32 bits) 512 bytes STAGE 2 PROT. MODE (32 bits) 10 bytes ~ nnnn bytes ~3000 bytes VARS = DEAD CODE ~2000 bytes

49  Rootkits ( ? )  Hot Patching ( bugs en kernel )  Bypasses en el codigo (e.g overwrite the kernel “setuid” function)  Agregarle nuevas funcionalidades al OS  Interaccion con el OS ( Uso de funciones )  Encapsulamiento del OS ( Hypervisor )  Debugger de kernel generico desde el booteo Posibles Usos para Deep Boot e

50  Victima: –OpenBSD v4.5  Boot Device: –Virtual FDD  Condicion de Corte: –70.000.000 instrucciones ejecutadas  Proposito: –Demostrar el funcionamiento de Deep Boot DEMO 1 e

51  Victima: –Debian v6.0  Boot Device: –Virtual FDD  Condicion de Corte: –??? instrucciones ejecutadas  Proposito: –Demostrar el funcionamiento de Deep Boot DEMO 2 e

52  MBR ( Master Boot Record ) –Primer sector del disco rigido –Mide 512 bytes –Contiene el stage 0 (primer loader) de cualquier OS –Contiene la tabla de particiones Que es el MBR ? e

53  Victima: –PC  Boot Device: –Virtual FDD  Condicion de Corte: –Escribir el MBR  Proposito: –Instalar un BOOTKIT en el MBR DEMO 3 e

54  BIOS + TPM ( Chip ) –BitLocker ( Microsoft ) » Windows Vista Ultimate/Enterprise » Windows 7 Ultimate/Enterprise » Windows 2008 –TrustedGRUB » Linux Como protegerse ? e

55  Victima: –Windows XP SP3 con Kaspersky AV  Boot Device: –HDD ( Master Boot Record )  Condicion de Corte: –Cuando se ejecuta la funcion “ntkrlnpa.KiSystemStartup()”  Proposito: –Ejecturar el BOOTKIT instalado previamente DEMO 4 e

56  Questions ? HLT