Tuesday, November 21, 2017

Unicode-Preeti-English Transliteration

Days ago I wrote python scripts for converting texts between Unicode, Preeti and English(transliteration). The initial motivation was to convert Unicode Nepali names in a database to their English transliterations for the ease of carrying out SQL queries. That led me to put together the first script. One or two days later, a friend of mine asked if I could write something for converting between Preeti and Unicode and so I gave it a try and consequently produced Preeti to Unicode and Unicode to Preeti scripts.
The above scripts at their core are mapping-dictionaries complemented with rules for outliers/exceptions that occur rather frequently during the conversion process. As a result, they probably aren't perfect but can certainly be refined to near that.
Now, the only thing missing is conversion from English to Unicode which I don't think is necessary because ... Google Input Tools - among other alternatives.
Oh, and while I was pushing revision commits to the Unicode to Preeti script on GitHub, I wondered if there already was a better, reliable program for it. So, I searched GitHub for any existing 'Unicode to Preeti converter', and among others, I landed upon this which is pretty good at its job.

Saturday, May 6, 2017

CSArp Netcut

I use Arcai's Netcut sometimes. It works. But sometimes, it abruptly crashes and doesn't go quite as easy as I would like it to. I found it to be a little too sluggish.
Then I thought to give SharpPcap a try, just to fool around, to see if I could capture some packets here and there, knowing that it must be such an insurmountable task to complete such a project, especially with the limited networking knowledge I have. But, one thing led to another and I had dived in too deep. On the first day, May 4, 2017, I tried using the GetIpNetTable API to get the ids of devices currently connected to my LAN. It was a tough thing for me to finally get something of some value that could accomplish some semblance of my goal. The entire day, I spent searching the internet for that one API and gluing together pieces to make it tick. And tick it did but I realised the system ARP table information it provided was little indication of all the devices of my LAN. Frustrated, I slept on it.
The next morning, I actually started fiddling with SharpPcap, it was a low level based high level API after all. I quite successfully and pretty quickly realised that capturing ARP packets with this .NET library was trivial and upon analysing numerous Debug.Print() outputs from my Visual Studio 2017's Output Window of the captured packets, and knitting them together with the information I gathered on ARP from the internet, I finally pieced together a method to produce a list of devices connected in the LAN. In short, I did it by basically sending ARP Request packets to every possible IP on a LAN that utilises the ipv4 protocol. Then, to actually perform an ARP spoofing/"cache poisoning" attack, I tried some 4-5 combinations of Requests/Response/To gateway/To target device/Broadcast/"Unicast"(targetted transmission) packets. That day, I was unable to make it work without raising alarms on the target device; for instance, when sending(Unicasting/Broadcasting) ARP packets(Request and/or Response) pretending to be sent by  the gateway device(router in my case), my desktop's ESET Smart Security 10 shouted at the screen non-stop and while it did work on my android phone, I wanted my program to work on every device, like Arcai's Netcut seemed to, so cleanly. It was yesterday.
Determined to get it right, today morning, I changed the code to send targetted ARP requests to the gateway, while pretending to be the target device. I ran it and voila! It worked perfectly. No alarm bells or warning signs. It just worked! With some cosmetic touches to the program(which took, as they always do, significant amount of time for the auxiliary function they serve) I uploaded the first version, 0, to GitHub. After that, I immediately thought of why I wanted so desperately a program like Arcai's Netcut in the first place and added some improvements/extra functionalities. And just some time ago, I published it in my GitHub repository for the program.
So.
Here it is, in its infant glory...


It may be brittle yet. But it works for me, and it's open source. So, feel free to do anything and everything with it.
Download here
GitHub @ here
PS: SharpPcap, used by this application, requires WinPCap to be installed. At the time of this writing, it can be downloaded from here

Thursday, April 27, 2017

CSWall

A C# equivalent of pyWall I wrote yesterday.
Simply fetches random images matching the specified categories from 500px.com and sets them as desktop wallpaper in specified intervals of time.


Download here
Project @ github

Saturday, March 4, 2017

pyWall

A simple script for periodically changing windows desktop wallpaper written in Python 3.5
It took me 2 days to bring it to "completion".
The UI was very difficult to write, especially with multithreading.
The primary reason I chose python instead of say, C#, was the easy availability and ease of use of libraries such as Requests, BeautifulSoup and the like; and while the core functional part of the program was completed relatively quickly, actually polishing the program further, I found, was very tough in python.
Needless to say, there's a lot of stuff that could be improved on but I don't think I will be continuing this project with python any more. I found it very cumbersome to say the least.

Anyway, here is the UI of the program:
The actual script is available here
Installing Anaconda with Python >= 3.5 is recommended since that's what it was written under.

Saturday, December 31, 2016

Simple Single Layer Perceptron in VBA

I've been tinkering with machine learning and AI for some days now. I've come across TensorFlow, what seems to be the standard library to use for machine learning these days. But to use it and to understand what it was actually doing underneath the high level APIs it provides, I searched for the most basic of machine learning codes on the internet.
I found a great C source for a single layer perceptron(a simple linear classifier based on artificial neural network) here by Richard Knop. I studied it and thought it was simple enough to be implemented in Visual Basic 6. And because it would be useful to represent training and test data in a graphical form, I thought Excel VBA would be better.


So, here it is.
What's being done in the excel file is this: 20 $(x,y)$ data that fall in the $(-,+)$ quadrant of the XY plane are generated in random with the constraint $x \in [-5,0]$ and  $y \in [0,10]$ and 20 that lie in the $(+,-)$ quadrant with the constraint $x \in [0,5]$ and $y \in [-10,0]$. These fill the first two columns X and Y of the worksheet. The next column is the $y$ data from the line $y=x$ for checking the prediction validity later whether a given $(x,y)$ falls above or below this line, which we know beforehand and with certainty that divides the two classes of data linearly. So, the fourth column Bool represents what the prediction should be i.e. it is a column of the boolean expression : column 2 $>$ column 3, for use as a benchmark and more importantly for use as the training data for the algorithm. The next column Prediction is the actual output of the perceptron after being fed all the 40 training datasets of $(col.1,col.2,col.4)$. The remaining two columns are only auxiliary and show a measure of the overall accuracy of the predictions it made on the same training datasets used as test.
And, since the activation function used in this single layer perceptron is just a unit step/threshold function $$t(p(x,y)) \text{ where,}\\  p(x,y)=w_1x+w_2y+w_3$$ that returns 1 for any non-negative input i.e. $>=0$, the function $p(x,y)$ is essentially the equation of the line that, the algorithm guesses, best separates the two classes of data.

Wednesday, February 10, 2016

Plane Truss solver

This is a simple program to solve determinate plane trusses with point loading at pins.
There is a lot of room for improvement: the interface is basic, more features could be added, but it works.
Download here

Sunday, January 10, 2016

OpenProcess API hook in MSVC++(C)

This is a C program I've written in Visual Studio 2015 to hook OpenProcess API calls to prevent a target application from obtaining a handle to a ProcessId of our choice which can render other APIs dependent on process handles useless(such as TerminateProcess) when acting on the ProcessId.
I was trying to do inline assembly injection in Delphi 7 to this very effect but the disassembler viewer, and the IDE in general was not very smooth. So I gave Microsoft Visual C++ a go recalling I had a copy of the latest Visual Studio 2015. The IDE was just amazingly productive. So, working on and off, with a lot of debugging and disassembling and hours of scouring the internet for answers to questions that arose along the way, I finally managed to write a functioning program.

The code is, I think, fairly well commented. So it should be easy enough to understand:
//the characterset property is set to "Not Set" which defaults everything to ANSI(non-unicode)
//disable optimization under C/C++=>Optimization from Project=>Project Properties. otherwise a lot of variables
//are "optimized away" when debugging; you can't see their values from the IDE while debugging.
//also, optimize for small code under C/C++=>Optimization. otherwise, the compiler will append
//a ton of INT 3 instructions to your assembly functions.
//so, make a custom optimization profile with the above criteria met

#include "stdafx.h"
#include <conio.h>
#include <Windows.h>


void jmp();
void trampoline();
void fake();

int main()
{

/*
 //Process Killer program
    repeat:
    DWORD pid = 0;
    HANDLE hProcess = 0;
    printf("Enter PID to terminate ");
   
    scanf_s("%d", &pid);
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
    if (hProcess == 0)
    {
        printf("Cannot get a handle to the PID!\n");
        printf("Error : %d\n\n", GetLastError());
        goto repeat;
    }
    if (!TerminateProcess(hProcess, 0) )
    {
        printf("Cannot terminate PID : %d\n", pid);
        printf("Error : %d\n\n", GetLastError());
        goto repeat;
    }
    else
    {
        printf("Killed!\n\n");
    }
    goto repeat;
    */

   
    DWORD protectpid;
    DWORD hookpid;//process to inject to
    printf("Enter the PID to inject to : ");
    scanf_s("%d", &hookpid);
    printf("Enter the PID to protect : ");
    scanf_s("%d", &protectpid);
    LPVOID OPPt = GetProcAddress(GetModuleHandle("kernel32.dll"), "OpenProcess");
   
   
    /****************Read the raw jmp and trampoline functions from own memory************/
    HANDLE myhProcess = OpenProcess(PROCESS_ALL_ACCESS, false, GetCurrentProcessId());
    SIZE_T size = SIZE_T((long)(&fake) - (long)(&trampoline));//size of trampoline
    SIZE_T size2 = (SIZE_T)(((long)(&trampoline) - (long)(&jmp)));//size of jmp
    SIZE_T readbytes;
    char *jmpBytes = (char *)calloc((size_t)size2,sizeof(char));
    ReadProcessMemory(myhProcess, &jmp, jmpBytes, size2, &readbytes);//read the jmp function into jmpBytes
    char *trampolineBytes = (char *)calloc((size_t)size, sizeof(char));
    ReadProcessMemory(myhProcess, &trampoline, trampolineBytes, size, &readbytes);//read the trampoline function into trampolineBytes
    /*************************************************************************************/

    /************Allocate space in the remote process for trampoline function************/
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, hookpid);
    LPVOID hAddress = VirtualAllocEx(hProcess, (LPVOID)0, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);//address of trampoline
    /************************************************************************************/

    /**********************Fix the jmp address and the pid to filter********************/
    memcpy(&jmpBytes[1], &hAddress,(size_t) 4);
    memcpy(&trampolineBytes[5], &protectpid, (size_t)4);
    /***********************************************************************************/

    CloseHandle(myhProcess);
    /********************Shellcode read!*************************************/

   

    SIZE_T writtenbytes;
    if (WriteProcessMemory(hProcess, hAddress, trampolineBytes, size, &writtenbytes))//write the fixed trampoline
    {
       
        if (WriteProcessMemory(hProcess, OPPt, jmpBytes, size2, &writtenbytes))//write the fixed jmp
        {
            //jmp was written
            MessageBox(0, "Patched!", ":D", 0);
           
        }
    }
    DWORD laterror = GetLastError();
   
   
    return 0;
}



__declspec(naked) void jmp()
/* the __declspec(naked) suppresses the extra opcodes the compiler would automatically add
before and after a function which would be bad for our to-be-injected asm block */
{
    __asm
    {
        mov eax, 0x93250000//trampoline address to be patched
        call trick
        trick:
        pop esi//esi=address of this statement
        jmp eax
       
        /*
 This part isn't very relevant to the above code but is still informative and is something I wrote when I was trying a simple mov and jmp combination.
        Must be careful not to do a partial overwrite:

        The normal opcodes before overwriting the OpenProcess code in kernel32.dll are:

        75891952 > 8BFF             MOV EDI,EDI                                                       ; ucrtbase.60682104
        75891954   55               PUSH EBP
        75891955   8BEC             MOV EBP,ESP
        75891957   5D               POP EBP
        75891958   EB 05            JMP SHORT <JMP.&API-MS-Win-Core-Synch-L1-1-0.OpenProcess>          ; relative jump to the JMP below
        7589195A   90               NOP
        7589195B   90               NOP
        7589195C   90               NOP
        7589195D   90               NOP
        7589195E   90               NOP
        7589195F  -FF25 54098975    JMP DWORD PTR DS:[<&API-MS-Win-Core-Synch-L1-1-0.OpenProcess>]    ; KERNELBA.OpenProcess
       
        Say we have only a mov and a jmp code. It ends up overwriting the above opcodes starting from the
        first byte 8B. The corresponding opcodes are:

        00C7118C B8 00 00 25 93       mov         eax,93250000h
        00C71191 FF E0                jmp         eax

        Clearly, the size of opcodes to be written is 7(one byte each for B8, 00, 00, 25, 93, FF, E0)

        After being overwritten, the modified OpenProcess code in kernel32.dll looks like:

        75891952 > B8 00002593      MOV EAX,93250000
        75891957   FFE0             JMP EAX
        75891959   05 90909090      ADD EAX,90909090
        7589195E   90               NOP
        7589195F  -FF25 54098975    JMP DWORD PTR DS:[<&API-MS-Win-Core-Synch-L1-1-0.OpenProcess>]    ; KERNELBA.OpenProcess

        Clearly, the original bytes 8B, FF, 55, 8B, EC, 5D, EB, a total of 7 bytes have been overwritten
        as expected by our mov and jmp. But the remaining 05, 90, 90... bytes give a different opcode
        altogether, the ADD EAX,90909090 thing, which is unwanted. So, the 05 byte is replaced with an extra
        opcode, a simple nop i.e. 90 so that the modified version looks like:

        75891952 > B8 00002593      MOV EAX,93250000
        75891957   FFE0             JMP EAX
        75891959   90               NOP
        7589195A   90               NOP
        7589195B   90               NOP
        7589195C   90               NOP
        7589195D   90               NOP
        7589195E   90               NOP
        7589195F  -FF25 54098975    JMP DWORD PTR DS:[<&API-MS-Win-Core-Synch-L1-1-0.OpenProcess>]    ; KERNELBA.OpenProcess

        which is what we would want if we needed only a mov and jmp injected.       
       
        */




        /*
        Now what our code does:

        Original contents inside the OpenProcess procedure in the target process' kernel32:

        76571952 > 8BFF             MOV EDI,EDI                              ; ucrtbase.74772104
        76571954   55               PUSH EBP
        76571955   8BEC             MOV EBP,ESP
        76571957   5D               POP EBP
        76571958   EB 05            JMP SHORT <JMP.&API-MS-Win-Core-Synch-L1>
        7657195A   90               NOP
        7657195B   90               NOP
        7657195C   90               NOP
        7657195D   90               NOP
        7657195E   90               NOP
        7657195F  -FF25 54095776    JMP DWORD PTR DS:[<&API-MS-Win-Core-Sync>; KERNELBA.OpenProcess

        The disassembly of our jmp() code:

        00B91218 B8 00 00 25 93       mov         eax,93250000h
        00B9121D E8 00 00 00 00       call        0B91222h
        00B91222 5E                   pop         esi
        00B91223 FF E0                jmp         eax

        The OpenProcess routine after injection:

        76571952 > B8 00002593      MOV EAX,93250000
        76571957   E8 00000000      CALL kernel32.7657195C
        7657195C   5E               POP ESI
        7657195D   FFE0             JMP EAX
        7657195F  -FF25 54095776    JMP DWORD PTR DS:[<&API-MS-Win-Core-Sync>; KERNELBA.OpenProcess


        */
    }
}


__declspec(naked) void trampoline()
{
    __asm
    {
        pop edx
        pop ecx
        pop ebx
        pop eax
        cmp eax, 14902//pid to protect
       
        jne skipper
        xor eax, eax
       
       
    skipper:
        push eax
        push ebx
        push ecx           
        push edx
        add esi,3//coz instruction at esi is followed by a jmp which is 2 bytes
        jmp esi


    }
}

__declspec(naked) void fake()
{
    __asm
    {

    }
}