|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 |
import os import re import sys import ctypes import struct import subprocess from pathlib import Path from ctypes import wintypes # ============================================================ # CONFIGURACION # ============================================================ UNIDAD_ORIGEN = "F" CARPETA_DESTINO = r"C:\Recuperados" # Tamaño máximo de lectura por operación TAMANO_BLOQUE = 1024 * 1024 # ============================================================ # API WINDOWS # ============================================================ if os.name != "nt": raise SystemExit("Este programa solo funciona en Windows.") kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) GENERIC_READ = 0x80000000 FILE_SHARE_READ = 0x00000001 FILE_SHARE_WRITE = 0x00000002 FILE_SHARE_DELETE = 0x00000004 OPEN_EXISTING = 3 FILE_FLAG_OVERLAPPED = 0x40000000 ERROR_IO_PENDING = 997 WAIT_OBJECT_0 = 0 ULONG_PTR = ctypes.c_size_t class OVERLAPPED(ctypes.Structure): _fields_ = [ ("Internal", ULONG_PTR), ("InternalHigh", ULONG_PTR), ("Offset", wintypes.DWORD), ("OffsetHigh", wintypes.DWORD), ("hEvent", wintypes.HANDLE), ] kernel32.CreateFileW.argtypes = [ wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE, ] kernel32.CreateFileW.restype = wintypes.HANDLE kernel32.ReadFile.argtypes = [ wintypes.HANDLE, wintypes.LPVOID, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(OVERLAPPED), ] kernel32.ReadFile.restype = wintypes.BOOL kernel32.CreateEventW.argtypes = [ wintypes.LPVOID, wintypes.BOOL, wintypes.BOOL, wintypes.LPCWSTR, ] kernel32.CreateEventW.restype = wintypes.HANDLE kernel32.GetOverlappedResult.argtypes = [ wintypes.HANDLE, ctypes.POINTER(OVERLAPPED), ctypes.POINTER(wintypes.DWORD), wintypes.BOOL, ] kernel32.GetOverlappedResult.restype = wintypes.BOOL kernel32.WaitForSingleObject.argtypes = [ wintypes.HANDLE, wintypes.DWORD, ] kernel32.WaitForSingleObject.restype = wintypes.DWORD kernel32.CloseHandle.argtypes = [wintypes.HANDLE] kernel32.CloseHandle.restype = wintypes.BOOL def comprobar_administrador(): try: if not ctypes.windll.shell32.IsUserAnAdmin(): raise SystemExit( "Ejecuta PowerShell como administrador." ) except AttributeError: raise SystemExit("No se pudo comprobar el administrador.") def abrir_unidad(letra): ruta = rf"\\.\{letra}:" handle = kernel32.CreateFileW( ruta, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, None, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, None ) if handle == wintypes.HANDLE(-1).value: error = ctypes.get_last_error() raise OSError(error, ctypes.FormatError(error)) return handle def leer_disco(handle, offset, cantidad): """ Lectura directa de una posición concreta del volumen. Utiliza OVERLAPPED para evitar SetFilePointerEx. """ resultado = bytearray() while cantidad > 0: bloque = min(cantidad, TAMANO_BLOQUE) buffer = ctypes.create_string_buffer(bloque) evento = kernel32.CreateEventW(None, True, False, None) if not evento: raise ctypes.WinError(ctypes.get_last_error()) ov = OVERLAPPED() ov.Offset = offset & 0xFFFFFFFF ov.OffsetHigh = (offset >> 32) & 0xFFFFFFFF ov.hEvent = evento leidos = wintypes.DWORD(0) try: ok = kernel32.ReadFile( handle, buffer, bloque, ctypes.byref(leidos), ctypes.byref(ov) ) if not ok: error = ctypes.get_last_error() if error != ERROR_IO_PENDING: raise ctypes.WinError(error) espera = kernel32.WaitForSingleObject( evento, 30000 ) if espera != WAIT_OBJECT_0: raise OSError("Tiempo de espera agotado.") if not kernel32.GetOverlappedResult( handle, ctypes.byref(ov), ctypes.byref(leidos), False ): raise ctypes.WinError(ctypes.get_last_error()) if leidos.value == 0: break resultado.extend(buffer.raw[:leidos.value]) offset += leidos.value cantidad -= leidos.value if leidos.value < bloque: break finally: kernel32.CloseHandle(evento) return bytes(resultado) # ============================================================ # UTILIDADES NTFS # ============================================================ def corregir_fixup(registro, bytes_sector): """ Comprueba y corrige los Update Sequence Arrays de los registros FILE de NTFS. """ datos = bytearray(registro) if datos[:4] != b"FILE": return None usa_offset = struct.unpack_from("<H", datos, 4)[0] usa_count = struct.unpack_from("<H", datos, 6)[0] if usa_count < 2: return None if usa_offset + usa_count * 2 > len(datos): return None firma = datos[usa_offset:usa_offset + 2] for i in range(1, usa_count): posicion = i * bytes_sector - 2 if posicion + 2 > len(datos): return None if datos[posicion:posicion + 2] != firma: return None reemplazo = datos[ usa_offset + i * 2: usa_offset + i * 2 + 2 ] datos[posicion:posicion + 2] = reemplazo return bytes(datos) def decodificar_data_runs(datos): """ Decodifica las extensiones físicas de un atributo NTFS. """ runs = [] posicion = 0 vcn = 0 lcn_anterior = 0 while posicion < len(datos): cabecera = datos[posicion] posicion += 1 if cabecera == 0: break bytes_longitud = cabecera & 0x0F bytes_offset = (cabecera >> 4) & 0x0F if bytes_longitud == 0: break if posicion + bytes_longitud + bytes_offset > len(datos): break longitud = int.from_bytes( datos[posicion:posicion + bytes_longitud], "little" ) posicion += bytes_longitud if bytes_offset: desplazamiento = int.from_bytes( datos[posicion:posicion + bytes_offset], "little", signed=True ) lcn_anterior += desplazamiento lcn = lcn_anterior posicion += bytes_offset else: lcn = None if longitud <= 0: break runs.append((vcn, longitud, lcn)) vcn += longitud return runs def obtener_atributos(registro): """ Devuelve los atributos presentes en un registro FILE. """ inicio = struct.unpack_from("<H", registro, 20)[0] posicion = inicio while posicion + 8 <= len(registro): tipo = struct.unpack_from("<I", registro, posicion)[0] if tipo == 0xFFFFFFFF: break longitud = struct.unpack_from( "<I", registro, posicion + 4 )[0] if longitud < 8 or posicion + longitud > len(registro): break no_residente = registro[posicion + 8] nombre_length = registro[posicion + 9] nombre_offset = struct.unpack_from( "<H", registro, posicion + 10 )[0] nombre = "" if nombre_length: inicio_nombre = posicion + nombre_offset fin_nombre = inicio_nombre + nombre_length * 2 if fin_nombre <= posicion + longitud: nombre = registro[ inicio_nombre:fin_nombre ].decode("utf-16le", errors="replace") yield { "tipo": tipo, "inicio": posicion, "longitud": longitud, "no_residente": no_residente, "nombre": nombre, "registro": registro[posicion:posicion + longitud] } posicion += longitud # ============================================================ # LECTURA DE LA MFT # ============================================================ class RecuperadorNTFS: def __init__(self, letra, destino): self.letra = letra self.destino = Path(destino) self.handle = None self.bytes_sector = 0 self.sectores_cluster = 0 self.tamano_cluster = 0 self.tamano_registro = 0 self.mft_lcn = 0 self.tamano_mft = 0 self.runs_mft = [] self.recuperados = 0 self.errores = 0 def iniciar(self): self.handle = abrir_unidad(self.letra) boot = leer_disco(self.handle, 0, 512) if len(boot) < 512 or boot[3:11] != b"NTFS ": raise RuntimeError( "No se ha encontrado un sector de arranque NTFS válido." ) self.bytes_sector = struct.unpack_from( "<H", boot, 11 )[0] self.sectores_cluster = boot[13] if self.bytes_sector not in (512, 1024, 2048, 4096): raise RuntimeError("Tamaño de sector no compatible.") if self.sectores_cluster == 0: raise RuntimeError("Número de sectores por clúster inválido.") self.tamano_cluster = ( self.bytes_sector * self.sectores_cluster ) self.mft_lcn = struct.unpack_from("<Q", boot, 48)[0] clusters_registro = struct.unpack_from( "<b", boot, 64 )[0] if clusters_registro < 0: self.tamano_registro = 1 << (-clusters_registro) else: self.tamano_registro = ( clusters_registro * self.tamano_cluster ) if self.tamano_registro < 512: raise RuntimeError("Tamaño de registro MFT inválido.") print("\n[+] Sistema NTFS detectado") print(f"[+] Sector: {self.bytes_sector} bytes") print(f"[+] Clúster: {self.tamano_cluster} bytes") print(f"[+] Registro MFT: {self.tamano_registro} bytes") print(f"[+] MFT comienza en LCN: {self.mft_lcn}") self.cargar_mft() def cargar_mft(self): """ Lee el registro 0 ($MFT) y obtiene sus data runs. """ offset = self.mft_lcn * self.tamano_cluster registro = leer_disco( self.handle, offset, self.tamano_registro ) registro = corregir_fixup( registro, self.bytes_sector ) if registro is None: raise RuntimeError("No se pudo validar el registro $MFT.") for atributo in obtener_atributos(registro): if atributo["tipo"] != 0x80: continue attr = atributo["registro"] if not atributo["no_residente"]: continue inicio_runs = struct.unpack_from("<H", attr, 32)[0] self.tamano_mft = struct.unpack_from( "<Q", attr, 48 )[0] self.runs_mft = decodificar_data_runs( attr[inicio_runs:] ) break if not self.runs_mft or self.tamano_mft <= 0: raise RuntimeError( "No se pudo obtener la extensión de $MFT." ) print(f"[+] Tamaño MFT: {self.tamano_mft:,} bytes") print(f"[+] Extensiones MFT: {len(self.runs_mft)}") def leer_mft(self, offset, cantidad): """ Traduce una posición virtual de la MFT a sectores físicos. """ salida = bytearray() while cantidad > 0: vcn = offset // self.tamano_cluster dentro_cluster = offset % self.tamano_cluster encontrado = False for inicio_vcn, longitud, lcn in self.runs_mft: if inicio_vcn <= vcn < inicio_vcn + longitud: encontrado = True clusters_disponibles = ( inicio_vcn + longitud - vcn ) bytes_disponibles = ( clusters_disponibles * self.tamano_cluster - dentro_cluster ) tomar = min(cantidad, bytes_disponibles) if lcn is None: salida.extend(b"\x00" * tomar) else: offset_fisico = ( lcn * self.tamano_cluster + (vcn - inicio_vcn) * self.tamano_cluster + dentro_cluster ) datos = leer_disco( self.handle, offset_fisico, tomar ) if len(datos) != tomar: raise RuntimeError( "Lectura incompleta de la MFT." ) salida.extend(datos) offset += tomar cantidad -= tomar break if not encontrado: raise RuntimeError( "La MFT tiene una extensión que no se ha podido localizar." ) return bytes(salida) # ======================================================== # INFORMACIÓN DE ARCHIVOS # ======================================================== def nombre_archivo(self, registro): nombres = [] for atributo in obtener_atributos(registro): if atributo["tipo"] != 0x30: continue attr = atributo["registro"] if len(attr) < 90: continue contenido_length = struct.unpack_from( "<I", attr, 16 )[0] contenido_offset = struct.unpack_from( "<H", attr, 20 )[0] contenido = attr[ contenido_offset: contenido_offset + contenido_length ] if len(contenido) < 66: continue longitud_nombre = contenido[64] namespace = contenido[65] nombre = contenido[ 66:66 + longitud_nombre * 2 ].decode("utf-16le", errors="replace") if nombre: nombres.append((namespace, nombre)) # Preferir nombres Win32/Win32-DOS. for namespace, nombre in nombres: if namespace in (1, 3): return nombre return nombres[0][1] if nombres else None def obtener_data(self, registro): for atributo in obtener_atributos(registro): if atributo["tipo"] != 0x80: continue if atributo["nombre"]: continue attr = atributo["registro"] if not atributo["no_residente"]: longitud = struct.unpack_from( "<I", attr, 16 )[0] offset = struct.unpack_from( "<H", attr, 20 )[0] return { "residente": True, "datos": attr[offset:offset + longitud], "tamano": longitud } if len(attr) < 64: continue flags = struct.unpack_from("<H", attr, 12)[0] # No intentar reconstruir archivos comprimidos # ni cifrados con este recuperador básico. if flags & 0x0001 or flags & 0x4000: continue inicio_vcn = struct.unpack_from( "<Q", attr, 16 )[0] if inicio_vcn != 0: continue offset_runs = struct.unpack_from( "<H", attr, 32 )[0] tamano_real = struct.unpack_from( "<Q", attr, 48 )[0] runs = decodificar_data_runs( attr[offset_runs:] ) if runs: return { "residente": False, "runs": runs, "tamano": tamano_real } return None # ======================================================== # RECUPERACIÓN # ======================================================== def guardar_archivo(self, numero_registro, nombre, data): nombre = re.sub( r'[<>:"/\\|?*\x00-\x1f]', "_", nombre ).strip(" .") if not nombre: nombre = "archivo_sin_nombre" # El número de registro evita sobrescribir archivos # con nombres iguales. nombre_final = f"{numero_registro}_{nombre}" ruta = self.destino / nombre_final contador = 1 while ruta.exists(): ruta = self.destino / ( f"{numero_registro}_{contador}_{nombre}" ) contador += 1 with open(ruta, "wb") as archivo: if data["residente"]: archivo.write(data["datos"]) else: restante = data["tamano"] for inicio_vcn, longitud, lcn in data["runs"]: if restante <= 0: break longitud_bytes = ( longitud * self.tamano_cluster ) tomar = min(restante, longitud_bytes) if lcn is None: bloque_ceros = b"\x00" * min( tomar, TAMANO_BLOQUE ) while tomar: parte = min(tomar, len(bloque_ceros)) archivo.write(bloque_ceros[:parte]) tomar -= parte restante -= parte else: offset_fisico = ( lcn * self.tamano_cluster ) datos_leidos = leer_disco( self.handle, offset_fisico, tomar ) archivo.write(datos_leidos) restante -= len(datos_leidos) if len(datos_leidos) != tomar: raise RuntimeError( "No se pudieron leer todos los datos." ) return ruta def ejecutar(self): self.destino.mkdir(parents=True, exist_ok=True) total_registros = ( self.tamano_mft // self.tamano_registro ) print("\n[+] Comenzando análisis de la MFT") print(f"[+] Registros estimados: {total_registros:,}") print(f"[+] Destino: {self.destino}") print("\nNo cierres el programa durante el análisis.\n") for numero in range(total_registros): try: offset = numero * self.tamano_registro registro = self.leer_mft( offset, self.tamano_registro ) registro = corregir_fixup( registro, self.bytes_sector ) if registro is None: continue # Registro FILE if registro[:4] != b"FILE": continue flags = struct.unpack_from( "<H", registro, 22 )[0] # Solo registros que ya no están en uso. if flags & 0x01: continue # Excluir directorios. if flags & 0x02: continue nombre = self.nombre_archivo(registro) if not nombre: continue data = self.obtener_data(registro) if data is None or data["tamano"] <= 0: continue try: ruta = self.guardar_archivo( numero, nombre, data ) self.recuperados += 1 print( f"[RECUPERADO] {nombre} " f"({data['tamano']:,} bytes)" ) except Exception as error: self.errores += 1 print( f"[ERROR] Registro {numero}: {error}" ) except KeyboardInterrupt: print("\n[!] Análisis interrumpido.") break except Exception as error: self.errores += 1 if numero % 100 == 0: porcentaje = ( numero / max(total_registros, 1) ) * 100 print( f"\rAnalizando: {porcentaje:.1f}% " f"({numero:,}/{total_registros:,})", end="", flush=True ) print("\n\n================================") print("RESULTADO DE LA RECUPERACIÓN") print("================================") print(f"Archivos recuperados: {self.recuperados}") print(f"Errores: {self.errores}") print(f"Carpeta: {self.destino}") def cerrar(self): if self.handle: kernel32.CloseHandle(self.handle) self.handle = None # ============================================================ # COMPROBACIONES DE SEGURIDAD # ============================================================ def obtener_disco(letra): comando = ( f"(Get-Partition -DriveLetter {letra} " f"-ErrorAction Stop).DiskNumber" ) resultado = subprocess.run( ["powershell", "-NoProfile", "-Command", comando], capture_output=True, text=True ) if resultado.returncode != 0: raise RuntimeError( f"No se pudo identificar el disco de {letra}:" ) return resultado.stdout.strip() def comprobar_destino(origen, destino): unidad_destino = os.path.splitdrive(destino)[0] if not unidad_destino: raise RuntimeError("La carpeta destino no tiene unidad.") letra_destino = unidad_destino[0].upper() disco_origen = obtener_disco(origen) disco_destino = obtener_disco(letra_destino) print(f"Disco de origen {origen}: {disco_origen}") print(f"Disco de destino {letra_destino}: {disco_destino}") if disco_origen == disco_destino: raise RuntimeError( "ORIGEN Y DESTINO ESTÁN EN EL MISMO DISCO FÍSICO. " "Cambia CARPETA_DESTINO a otra unidad física." ) # ============================================================ # PROGRAMA PRINCIPAL # ============================================================ def main(): print("========================================") print(" RECUPERADOR DE ARCHIVOS NTFS") print("========================================") comprobar_administrador() print(f"\nUnidad origen: {UNIDAD_ORIGEN}:") print(f"Destino: {CARPETA_DESTINO}") comprobar_destino( UNIDAD_ORIGEN, CARPETA_DESTINO ) recuperador = RecuperadorNTFS( UNIDAD_ORIGEN, CARPETA_DESTINO ) try: recuperador.iniciar() recuperador.ejecutar() except Exception as error: print("\n[ERROR FATAL]") print(error) finally: recuperador.cerrar() input("\nPulsa ENTER para salir...") if __name__ == "__main__": main() |