Mostrando las entradas con la etiqueta hack. Mostrar todas las entradas
Mostrando las entradas con la etiqueta hack. Mostrar todas las entradas

25 nov 2014

Consultas WMI



Genérica
Set objWMIService = GetObject("winmgmts:\\" & host & "\root\cimv2")
Registro
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & host & "\root\default:StdRegProv")
Políticas
Set objRsop=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & host & "\root\rsop\computer")

Usuarios locales: "Select * from Win32_UserAccount Where LocalAccount = True"
Grupos locales: "Select * from Win32_Group  Where LocalAccount = True"
Usuarios dentro de un grupo: SELECT * FROM Win32_GroupUser WHERE (groupcomponent = 'win32_group.name="Administrators",domain="MyHostName"')
Informacion de un User Profile: "Select * From Win32_UserProfile"
Servicios: "Select * from Win32_Service"
Shares: "Select * from Win32_Share"

Politicas

"select * from RSOP_SecuritySettingNumeric where precedence=1"
"Select * from RSOP_UserPrivilegeRight where precedence=1"
"Select * from RSOP_PolicySetting where precedence=1"
"Select * from RSOP_AuditPolicy where precedence=1"

2 ago 2014

Obteniendo informacion desde un HTML con python


Un poco de código para extraer información mediante un script en python , algo básico, para empezar a familiarizarme con las librerías disponibles en Kali.

Las librerías usadas:

  • urllib2 para descargar el código html de una pagina web
  • beutifulsoup para extraer los enlaces que contiene
  • urlparse para validar que los enlaces sean validos y extraer el hostname
  • finalmente, la libreria dns para extraer la IP de los nombres de dominios obtenidos

url_extractor.py
# pylint: disable-msg=C0301
'''
apt-get install html5lib
apt-get install python-beautifulsoup
apt-get install python-lxml 
apt-get install python-pyquery 

http://yuji.wordpress.com/2008/05/14/python-basics-of-python-dictionary-and-looping-through-them/
http://stackoverflow.com/questions/493819/python-join-why-is-it-string-joinlist-instead-of-list-joinstring
'''

from utils import utils

def main():
    '''
    para que pylint no muestre tantos mensajes =)
    http://stackoverflow.com/questions/709490/python-code-convention-using-pylint
    '''
    url = "www.google.com"
    html = utils.HtmlExtractor(url)
    #aseguramos que url siempre comienze por http:// o https://
    url = html.get_url()
    #print html.get_body()
    data_extractor = utils.DataExtractor(html.get_body(), url, only_href = True)
    urls = data_extractor.get_urls()
    print "URLS: "
    for temp in urls:
        print temp
    domains = data_extractor.get_domains(urls)
    print "Dominios: "
    for temp in domains:
        print temp
    ips = data_extractor.get_ips_for_domains(domains)
    for key in ips.iterkeys():
        print key, ": ", " ".join(ips[key])

if __name__ == "__main__":
    main()

utils/utils.py
'''

http://docs.python.org/library/urlparse.html
http://docs.python.org/tutorial/errors.html
http://docs.python.org/library/urllib2.html
http://docs.python.org/library/urllib2.html#urllib2.Request
http://www.crummy.com/software/BeautifulSoup/documentation.html
http://blog.elcodiguero.com/python/23-eliminar-duplicados-lista.html
http://www.mail-archive.com/dnspython-users@dnspython.org/msg00006.html
http://www.dnspython.org/examples.html
http://docs.python.org/release/2.5.2/lib/typesmapping.html
'''
from urlparse import urlparse
import urllib2
import BeautifulSoup
import dns.resolver

def valida_url(url):
    '''
    
    @param url:
    @type url:
    '''
    #si la url no empieza por http temp https lo anexa al inicio
    if url[:7].lower() != "http://" or url[:8].lower() != "https://":
        url = "http://" + url
    #verificamos que es una url completa, es decir, contiene al hostname
    temp = urlparse(url)
    if temp.hostname is None:
        url = None
    return url

# pylint: disable-msg=W0232
class _MyRedirects(urllib2.HTTPRedirectHandler):
    '''
    Clase de redireccion
    '''
# pylint: disable-msg=C0301,R0913,C0111
    def http_error_301(self, req, fpc, code, msg, headers):
        print code, " http_error_301 ", headers['Location']
        return urllib2.HTTPRedirectHandler.http_error_301(self, req, fpc, code, msg, headers)
# pylint: disable-msg=C0301,R0913,C0111
    def http_error_302(self, req, fpc, code, msg, headers):
        print code, " http_error_302 ", headers['Location']
        return urllib2.HTTPRedirectHandler.http_error_302(self, req, fpc, code, msg, headers)
# pylint: disable-msg=C0301,R0913,C0111
    def http_error_303(self, req, fpc, code, msg, headers):
        print code, " http_error_303 ", headers['Location']
        return urllib2.HTTPRedirectHandler.http_error_303(self, req, fpc, code, msg, headers)
# pylint: disable-msg=C0301,R0913,C0111
    def http_error_307(self, req, fpc, code, msg, headers):
        print code, " http_error_304 ", headers['Location']
        return urllib2.HTTPRedirectHandler.http_error_307(self, req, fpc, code, msg, headers)

class HtmlExtractor(object):
    '''
    Clase que extrae el codigo HTML de un origen.
    '''
    def __init__(self, url):
        '''
        
        @param url: URL completa, no acepta rutas relativas o absolutas
        @type url: string
        '''
        self.follow_redirects = False
        self.html_body = None
        self.url = valida_url(url)
        if self.url is None:
            raise ValueError("URL No valida")


    def get_url(self):
        '''
        retorna la url parseada, por ejemplo:
        para www.google.com.pe retorna http://www.google.com.pe
        '''
        return self.url


    def get_body(self, follow_redirects = False):
        '''
        Retorna el html resultante de la peticion.
        
        @param follow_redirects: En caso de estar seteado a verdadero, interpreta los mensajes HTTP 301, 302
        @type follow_redirects: boolean
        '''
        self.follow_redirects = follow_redirects
        request = urllib2.Request(self.url)
        opener = urllib2.build_opener(_MyRedirects())
        content = opener.open(request)
        self.html_body = content.read()
        return self.html_body





class DataExtractor(object):
    '''
    Clase para extraer Datos de un html.
    
    url -- direccion desde la cual se extrajo el html, opcional si se desea que se 
    interpreten las rutas relativas o absolutas que se puedan encontrar en el html
    
    only_href -- Solamente devuelve el contenido de los href, el texto entre las etiquetas  no necesariamente puede coincidir con el valor
    '''
    def __init__(self, html_body, url = None, only_href = False):
        self.html_body = html_body
        self.url = url
        self.only_href = only_href
        self.urls = []
        self.domains = []
        self.domain_ips = {}


    def get_urls(self):
        '''
        devuelve todas las URL encontradas en el html analizado
        '''
        result = BeautifulSoup.BeautifulSoup(self.html_body)
        lst_tag = result.findAll("a")
        for c_url in lst_tag:
            self.urls.append(c_url["href"])
        return self.urls


    def get_domains(self, urls = None):
        '''
        
        @param urls: Listado de urls a extraer los dominios, es la informacion devuelta por
        get_urls()
        @type urls: list
        '''
        if urls is None:
            self.urls = self.get_urls()
        for url in urls:
            temp = urlparse(url)
            if temp.hostname is None:
                continue
            self.domains.append(temp.hostname)
        return dict.fromkeys(self.domains).keys()


    def get_ips_for_domains(self, domains = None):
        '''
        
        @param domains: Listado de dominios a extraer los IP, es la informacion devuelta por
        get_domains()
        @type domains: list
        '''
        if domains is None:
            self.domains = self.get_domains()
        for domain in domains:
            answer = dns.resolver.query(domain, 'A')
            temp = []
            for rdata in answer:
                temp.append(rdata.address)
            self.domain_ips[domain] = temp
        return self.domain_ips

29 jul 2014

Mi entorno python en windows

Para mis pruebas de Hy (http://hy.readthedocs.org/en/latest/) y diversos scripts que normalmente ejecuto en Linux.

Usaré python 2.7, teniendo en cuenta hacer código migrable a python3, el porqué no usar python3 es debido a que algunas librerías no están migradas aún a python3.

Sistema base: windows 8.1 64 bits

Python (Seleccionar agregar python al PATH durante la instalación)
https://www.python.org/downloads/

Setup tools
Ejecutar PowerShell como administrador y ejecutar lo siguiente
(Invoke-WebRequest https://bootstrap.pypa.io/ez_setup.py).Content | python -

Pip
Ejecutar PowerShell como administrador y ejecutar lo siguiente
(Invoke-WebRequest https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py).Content | python -

PyWin32
Descargar la ultima versión disponible desde http://sourceforge.net/projects/pywin32/
PD: Instalarla como usuario estándar, cuando lo intente como administrador por algún motivo fallaba en windows 8.1

Agregar rutas al PATH en PowerShell
setx PATH "%PATH%;C:\Python27\Scripts"

Pylint
python code static checker
pip install pylint

Ipython
pip install ipython

BeautifulSoup4
Para automatizar el analisis de código HTML
pip install beautifulsoup4

Hy
"Hy is a lisp dialect, but one that converts its structure into Python" =)
pip install hy

libdnet
No existe un instalador oficial para python 2.7 pero desde https://twitter.com/dloss/status/18457222544
http://dirk-loss.de/scapy/dnet-1.12.win32-py2.7.exe

dpkt
"fast, simple packet creation / parsing, with definitions for the basic TCP/IP protocols"
El texto menciona python 2.6 pero tambien sirve para 2.7
https://code.google.com/p/dpkt/downloads/detail?name=dpkt-1.7.win32.exe&can=2&q=

pypcap
"simplified object-oriented Python extension module for libpcap"
Tampoco tiene instalador oficial pero lo obtuve de aqui https://code.google.com/p/pypcap/issues/detail?id=36
https://pypcap.googlecode.com/issues/attachment?aid=360000000&name=pcap-1.1.win32-py2.7.exe&token=ABZ6GAdluPCo_hMK4vnsnR7oKqP_Gjomow%3A1406650615796

scapy
http://www.secdev.org/projects/scapy/doc/installation.html
http://bb.secdev.org/scapy/downloads/scapy-2.2.0.zip

wireshark
instalar la version de 32 bits
www.wireshark.org

Pycrypto
http://www.voidspace.org.uk/python/modules.shtml#pycrypto
http://www.voidspace.org.uk/downloads/pycrypto26/pycrypto-2.6.win32-py2.7.exe

dnspython
"dnspython is a DNS toolkit for Python. It supports almost all record types"
pip install dnspython

IDE:
Aptana Studio (Pydev)
http://www.aptana.com/products/studio3/download

5 feb 2012

plugin en python para xchat : whois automatico

Un poco de código, es un script para xchat que hace que al momento de abrir un privado automáticamente muestra la información "whois" de la persona con quien se esta chateando. El script es muy simple y me sirve para encontrar otros canales que quizas puedan interesarme en Freenode. Lo he programado en ubuntu 11.10 y xchat 2.8.8.

Para mayor informacion de como extender las funcionalidades de xchat:
http://xchat.org/docs/ 


'''
Created on 04/02/2012
querywhois.py
@author: christian
cquispe.dev@gmail.com
'''
__module_name__ = "querywhois"
__module_version__ = "1.0"
__module_description__ = "muestra la informacion de whois del otro usuario cuando se abre o recibe un mensaje privado. Probado en xchat 2.8.8"
__module_author__ = "Christian "

import xchat #@UnresolvedImport

def mensaje_nuevo(word, word_eol, userdata):
    cntx = xchat.get_context()
    user = cntx.get_info("channel")
    if user[0] != "#":
        cntx.command("whois " + user)
    return xchat.EAT_NONE

def whois_info(word, word_eol, userdata):
    #print word
    cntx = xchat.find_context(channel = word[0])
    if cntx is None:
        #para cuando se hace whois sin abrir privado, lo envia a la salida normal
        cntx = xchat.get_context()
    cntx.prnt(" ".join(word))
    return xchat.EAT_XCHAT

#capturamos todos los eventos de whois 
WHOIS_EVENTS = [
                "WhoIs Authenticated",
                "WhoIs Away Line",
                "WhoIs Channel/Oper Line",
                "WhoIs End",
                "WhoIs Identified",
                "WhoIs Idle Line",
                "WhoIs Idle Line with Signon",
                "WhoIs Name Line",
                "WhoIs Real Host",
                "WhoIs Server Line",
                "WhoIs Special"
              ]
for whois_event in WHOIS_EVENTS:
    xchat.hook_print(whois_event, whois_info)

# xchat.hook_print("WhoIs Channel/Oper Line", whois_info)
# xchat.hook_print("WhoIs Authenticated", whois_info)
# xchat.hook_print("WhoIs Away Line", whois_info)
# xchat.hook_print("WhoIs End", whois_info)
# xchat.hook_print("WhoIs Identified", whois_info)
# xchat.hook_print("WhoIs Idle Line with Signon", whois_info)
# xchat.hook_print("WhoIs Idle Line", whois_info)
# xchat.hook_print("WhoIs Name Line", whois_info)
# xchat.hook_print("WhoIs Real Host", whois_info)
# xchat.hook_print("WhoIs Server Line", whois_info)
# xchat.hook_print("WhoIs Special", whois_info)

#captura los eventos de creacion de ventana, cuando se hace abre o recibe un privado
#Open Context esta mencionado en la documentacion de plugin de C++ pero no en la de python
xchat.hook_print("Open Context", mensaje_nuevo)

print "querywhois loaded"

13 nov 2008

Configuracion de Ruby para ejecutar Metasploit framework

Porque instalar a partir de codigo fuente y no a traves de los paquetes de la distribucion?
La distribucion que uso (Debian SID), viene con la version 1.8.7.72, la cual tiene varios problemas, tal como aparece en la imagen:
Una opcion es usar la version 1.8.6 que no esta disponible en debian sid o usar el ultimo snapshot stable, esto ultimo es lo que haremos:
Creamos nuestro directorio de trabajo
mkdir src
cd src
Instalamos las librerias necesarias para compilar ruby
apt-get build-dep ruby
apt-get build-dep gems

Descargar el metasploit framework
Bajamos la version en desarrollo, se va actualizando casi a diario
svn co http://metasploit.com/svn/framework3/trunk/ metasploit
Instalacion de Ruby
wget ftp://ftp.ruby-lang.org/pub/ruby/stable-snapshot.tar.gz
tar zxvf stable-snapshot.tar.gz
cd ruby
./configure --prefix=/opt/ruby
make
make test
make install
cd ..
rubygems
http://rubyforge.org/projects/rubygems/
tar zxvf rubygems-1.3.1.tgz
cd rubygems-1.3.1
export PATH=/opt/ruby/bin:$PATH
export GEM_HOME=/opt/ruby/lib/ruby/gems/1.8
export RUBYLIB=/opt/ruby/lib/ruby:/opt/ruby/lib/ruby/site_ruby/1.8:/opt/ruby/lib
/opt/ruby/bin/ruby setup.rb all --prefix=/opt/ruby
cd ..
Ejecutando Metasploit
Podemos usarlo desde el navegador:
cd metasploit
./msfweb
Luego, abrimos el explorador en http://127.0.0.1:55555/
Tambien podemos ejecutarlo en el terminal
./msfcli
enjoy !!!

8 sept 2006