Wednesday, 29 January 2014

Powershell fun

runas /user:Admin powershell
   --> does not give you an elevated admin powershell console
start-Process powershell -Verb runAs 
  --> UAC promt --> Elevated.
Set-ExecutionPolicy RemoteSigned
  --> Allow executation of home-made powershell script (off by default)
Example powershell script to find find who log on to what in domain (similar to psloggedon) by querying HKEY_USERS:

Import-Module ActiveDirectory
#$output = "PSLoggedOn_Results.csv"
$domainname = 'dc=test,dc=com,dc=au'
$allComputers=@(Get-ADComputer -SearchBase $domainname -Filter '*' | Select-Object -ExpandProperty Name)
foreach ($computername in $allComputers) {
write-warning "Connecting to $computername"
Trap {
write-warning "Something went wrong with $computername"
write-warning $_.Exception.Message
Continue
}
$regKey=[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::Users, $computername)
$allSid = $regKey.GetSubKeyNames() | where {$_ -match "Classes"}
foreach ($sidC in $allSid) {
$sid = $sidC.Substring(0,46)
$objSID = New-Object System.Security.Principal.SecurityIdentifier($sid)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
$username=$objUser.Value
$computername+","+$username
}
}


Tuesday, 28 January 2014

PythonFu

Example class in python (implementing some awesome underscore classes (http://www.rafekettler.com/magicmethods.html) :


class test:
    def __init__(self,input1, input2):
        self.var1=input1
        self.var2=input2
    def __call__(self,param):
        print "hello "+param
    def __iadd__(self,val):
        self.var1 += val
        self.var2 += val
        return self
    def __str__(self):
        return str(self.var1)+" "+str(self.var2)

obj=test(1,2) #initialize object obj
obj("san")         #equivalent with obj.__call__("san")
obj += 2      #adding 2 to self.var1 and self.var2
print str(b)  #print out self.var1 and self.var2 by calling __str__



Saturday, 25 January 2014

Let's do ... django!

pgmodeler is a sweet tool for creating database in postgresql from scratch. However it doesn't export to django model file, so what do you do?

First, export the database to your postgresql database

Then in your django project modify your settings.py with the database name, credentials, host, port, etc...and run the following command:


python manage.py inspectdb > APP_NAME/model.py

and voila! Here is an example:


from __future__ import unicode_literals
from django.db import models

class Family(models.Model):
#    familyid = models.BigIntegerField(db_column='familyId', primary_key=True)  
    familyid = models.AutoField(db_column='familyId', primary_key=True)     #Change BigIntegerField to AutoField -> Auto increment field!
    familyname = models.CharField(db_column='familyName', max_length=255)
    familydescription = models.CharField(db_column='familyDescription', max_length=1000)
    publicviewsettingid = models.SmallIntegerField(db_column='publicViewSettingId', blank=True, null=True) 
    createon = models.DateTimeField(db_column='createOn', blank=True, null=True) 
    class Meta:
        managed = False         ####<-------------- NOTE THAT FOR "manage.py syncdb"  to work, you need to REMOVE THIS LINE
        db_table = 'Family'


After modifying the model.py to your need and remove the "managed=False" line for the tables that you want to create, you can now drop the table and recreate with "manage.py syncdb"

Now that you already have the models in place, having some dummy data would be nice  so let's use autofixture for that!
Install autofixture:

pip install django-autofixture

Add "autofixture" into the list of INSTALLED_APPS in "settings.py",
run this command to generate 5 Family dummy data:

python manage.py loadtestdata PROJECT.Family:5

And now, for future usage we can put it into "fixture" folder under family application, let's call it initial_data.json:

python manage.py dumpdata > family/fixtures/initial_data.json




Sunday, 23 June 2013

-reset root password for mysql:
sudo bash 
service mysql stop 
sudo mysqld --skip-grant-tables &
mysql -u root mysql
update user set password=password('NEWPASSWORD') where user='root'; FLUSH PRIVILEGES; 
killall mysqld
service mysql start
 
 
- BurpProxy extension example:




from burp import IBurpExtender
from burp import IHttpRequestResponse
from burp import IResponseInfo
from burp import ITab
from burp import IContextMenuFactory
from burp import IContextMenuInvocation
from javax import swing
from java.awt import Dimension
from javax.swing import JMenuItem
from javax.swing import JPanel;

class BurpExtender(IBurpExtender, IContextMenuFactory, ITab):

    # define registerExtenderCallbacks: From IBurpExtender Interface
    def registerExtenderCallbacks(self, callbacks):
        self.initGui()
        # keep a reference to our callbacks object (Burp Extensibility Feature)
        self._callbacks = callbacks
        # obtain an extension helpers object (Burp Extensibility Feature)
        # http://portswigger.net/burp/extender/api/burp/IExtensionHelpers.html
        self._helpers = callbacks.getHelpers()
        # set our extension name that will display in Extender Tab
        self._callbacks.setExtensionName("Request to Code")
        # register ourselves as an HTTP listener
        callbacks.registerContextMenuFactory(self)
        callbacks.addSuiteTab(self)
        return
    def initGui(self):
        self._jPanel = JPanel()
        boxVertical = swing.Box.createVerticalBox()
        boxHorizontal = swing.Box.createHorizontalBox()
        boxHorizontal.add(swing.JLabel("Output"))
        boxVertical.add(boxHorizontal)
        boxHorizontal = swing.Box.createHorizontalBox()
        self._resultsTextArea = swing.JTextArea()
        resultsOutput = swing.JScrollPane(self._resultsTextArea)
        resultsOutput.setPreferredSize(Dimension(800,800))
        boxHorizontal.add(resultsOutput)
        boxVertical.add(boxHorizontal)
        self._jPanel.add(boxVertical)
        #self._resultsTextArea.append("test this")
    def getTabCaption(self):
        return "Request to Code"
    def getUiComponent(self):
        return self._jPanel
    def createMenuItems(self, invocation):
        menu=[]
        #print("invocationContext = "+str(invocation.getInvocationContext()))
        if ((invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST)|(invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_PROXY_HISTORY)):
                menu.append(JMenuItem("Convert to Python", None, actionPerformed=lambda x, inv=invocation: self.doSomething(inv)))
                menu.append(JMenuItem("Convert to Perl", None, actionPerformed=lambda x, inv=invocation: self.doSomething(inv)))
        print("I am done!")
        return menu
               
    def doSomething(self,invocation):
        print "Getting data"
        invMessage=invocation.getSelectedMessages()
        request = invMessage[0].getRequest().tostring()
        requestArray=request.split('\n')
        print requestArray
        host='_'.join(requestArray[1].split(':')[1].split('.')).strip()
        output = 'def make_request():\n    response=None\n    if(request_(response):\n        pass'
        output += '\n\n'
        output += 'def (response):\n     response = None\n    try:\n'
        output += '        req.urllib2.Request("<")'
        output = output.replace('',host)
        self._resultsTextArea.setText(output)
        for i in range (2,len(requestArray)):
            print requestArray[i]

Monday, 3 December 2012

ARM GDB script

GDB is not quite friendly for someone who is used to ollydbg , immunity or ida but GDB script is an amazing tool for analyse code if you know some nifty trick. For some reverse engineering job, I was lucky to have a go at it and here are a few notes for the future me:

#Saving breakpoints
define bsave
    save-breakpoints san.bp
end
#Restore breakpoints
define brestore
  source san.bp
end

#Logging stuffs to a file
define sanLog
  set logging file /var/root/san.out
  set logging on
end
#Logging without stdout
define sanLogNoSTDOUT
  set logging redirect on
  set logging file /var/root/san.out
  set logging on
end

define gothoughAllinstruction
        while(1)
        if ($pc < 0x00C25494)  #size of main code
                p/x $pc
                ni             #next instruction
        else
                n              #if the code is outside of main (import lib for ex) then get past it ASAP
        end
end

define sanMod
#       i reg r0 r1 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 sp lr pc   #print out all registers
        if ($pc == 0x00859fff)   
                printf "something meaningful here:"
                x/s $r0 #print r0 register in string form
                x/x $r1  #print r1 in hex form
        end
        thread apply 1 where   #if there are multiple thread, this would run "where"(similar to "i stacks") on thread 1(eg main thread (you can get this info by running "i threads"))
        printf "\n--------------------------------------------------\n"
end




In IDA, we can use this information to color the code and see which instruction the device goes through:
 

from idautils import *
from idc import *

def main():
#  SetColor(int("0039EAE8",16), CIC_ITEM, 0xF4A430)
  print "Color it up!"
  f = open('c:\\blah\\firstrun.out','r')
  for i in f:
    if (i[0:2] == "0x"):
      SetColor(int(i[2:10],16), CIC_ITEM, 0xF4A430)

if __name__ == '__main__':
  main()

Enable Concurrent Sessions in Windows 7 (x86)+(x64)

Nifty trick to enable multiple mstsc session on a windows 7 machine:
(HxD is best for this sort of job ;) )

x86 Hex edit

find: 
00 3B 86 20 03 00 00 0F ** ** ** **
replace: 
00 B8 00 01 00 00 90 89 86 20 03 00

find: 
FF 43 50 C7
replace: 
FF 90 50 C7

find: 
F8 74 2F 68 ** **
replace: 
F8 E9 2C 00 00 00


x64 Hex edit

find: 
8B 87 38 06 00 00 39 87 ** ** ** ** ** ** ** ** ** **
replace: 
B8 00 01 00 00 90 89 87 38 06 00 00 90 90 90 90 90 90

find: 
60 BB 01 00 00 00
replace: 
60 BB 00 00 00 00

find: 
50 00 74 18 48 8D
replace: 
50 00 EB 18 48 8D

Taken from http://www.winmatrix.com/forums/index.php?//topic/22479-enable-concurrent-sessions-in-windows-7-x86x64/

Wednesday, 21 November 2012

zigbee stuffs

killerbee framework for zigbee exploitation

zbid --> show zigbee devices
zbwireshark -i <id> -f <channel> to sniff
zbfind for channel hoping and search for available devices