Saturday, December 23, 2017

Firefox tunnel


A crucial element for the Red Team's task is a stealth in attack, success is its ability to espouse an aggressive mindset, a true  cracker's point of view, if the red team  win, can help to construct the better defense for the Blue Team at the future. Don't do bear  about this content, all content here have a good purpose.

At this blog post, the content is about a different attack approach to get remote control of the machine and bypass the firewall.  We have a lot of weapons to work in that perspective, something like veil framework, msfvenom...  but sometimes following different  path,  will generally bring good result.

Illustration by Anthony S Waters
The attack have a objective to use firefox to make all communication between client and server. Using hookings to do that, is not impossible, but DLL injection sometimes  is boring to implement, can be harder to turn in portable, do you know that ? x32 and x64 each architecture  need different approach to develop(at the future i discovery that the easyhook api can solve that).  Another day i was studying the firefox internals, reading something about the use of SQLite to work with cookies, that give to me a different focus.

Look that following:
That is a full plan to create a programm to use firefox with tunnel, i gonna explain in each step:

1- Programm of tunnel call firefox browser in hidden mode, sending a URL, that URL have a evil server, that evil server send a  cookie with command.

2- The  tunnel  get cookie of  evil server in cookie.sqlite, uses that to command shell

3- Result of command shell is used to write a HTML with javascript to make auto submit with content result.

4- Programm open writed html in hidden mode to send the result of CMD to evil server.

Now you can look that following:

For the sake of good conclusion,  i wrote the code and i recorded the proof of concept, the cool fact of empirical point is turn all in reality, you can view all stuff  at that  following:




Future insights:


Insert persistence, using function RegOpenKeyEx() to open path: 
"Software\Microsoft\Windows\CurrentVersion\Run" 
write with function RegSetValueEx() to launches a program automatically at system startup.

*Using images in I/O using steganography.

*Running process in  hidden mode.

*Turn tunnel unkillable process.

Possible mitigations:


* Global hooking, to get  OpenFile(), CreateFIle() functions and filter argv "cookie.sqlite" and block  when programm route is different of firefox.exe.

* File watch api to monitor the database of cookies.

* Programm to open database of cookies by periodicity and search evil domain or  hosts, that can use black list to find and uses DELETE query to remove evil cookie.






Thank you for reading this, cheers !

Saturday, December 31, 2016

Killing dragons spawned by arithmetic-related security pitfalls

In the last week which followed my attempt to earn money with financial trading, I glanced through Black & Scholes model.

This study resulted in creation of OptionsCat, an open-source tool to work with european options. When writing this tool, I faced a lot of Arithmetic-related security pitfalls which motivated me to study it and write a blog post.  
 
I always come up with my own implementations for the algorithms presented throughout the finance books. That's because the writers are often careless about security pitfalls. This is a problem, or dragon from the perspective of this article, that could possibly be solved by adding a chapter about validation.

Programming languages that enable direct memory access and do not provide buffer boundary checks and arithmetic numeric checks are particularly vulnerable to integer overflow attacks. Integer overflow may occur when computing the memory size to allocate a buffer, and it often leads to buffer overflow.

Look at the following quote: 

 "Integer overflows cannot be detected after they have happened, so there is not way for an application to tell if a result it has calculated previously is in fact correct.  This can get dangerous if the calculation has to do with the size of a buffer or how far into an array to index. Of course most integer overflows are not exploitable because memory is not being directly overwritten, but sometimes they can lead to other classes of bugs, frequently buffer overflows. As well as this, integer overflows can be difficult to spot, so even well audited code can spring surprises." 
 by blexim - Phrack Volume 0x0b, Issue 0x3c, Phile #0x0a of 0x10

Some people talk to me about use of Big integer library. like LibGMP to solve it, but when you work with big int need limit that numbers, arithmetic operations with bigint when a user has input with large length can causes Denial of service... The use of Integers is not hard to find at the stock markets. but double is than common and can bring to you a problem, if you don't control the length, for example:

#include < math.h>
#include < stdio.h> 

double mul_code(double x,double y) 
{
  double result=0;
   
  return result = x*y;
}

int main()
{
 double a=90000000000, b=20000000000000;

 printf("Result: %f\n", mul_code(a,b));
 return 0;
}

If you compile it and run, returns something like "1799999999999999916112.*(dirts...)". You ask to me "why return it ?", you don' t validate operation and pass the limit of carry, this causes undefined behavior, overflow...

Killing dragons in integers 

There are lots of ways for you solve, one is validate user input, this way you can use automatons, regular expressions, strnlen() to try put limit in the number of length. Remember phrack; the correct way to test for integer overflow during multiplication is to test before the multiplication, test if number is negative, replace functions like atoi() to strtol()...


Some operating systems has solutions at libraries for mitigate the problem, for example OSX have os/overflow.h, with this header you can do something like it:

#include < "os/overflow.h">
 
if (os_mul_overflow(m, n, &bytes)) {
    /* Overflow occured.  Handle appropriately. */
} else {
    /* Allocate "bytes" space. */

Other way to mitigate, this way is from OpenBSD:

#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t)*4))
// based in OpenBSD reallocarray() function http://man.openbsd.org/reallocarray.3
void *reallocarray (void *ptr, size_t nmemb, size_t size) 
{
 if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && nmemb > 0 && SIZE_MAX / nmemb < size) 
 {
  DEBUG("integer overflow block");
  return NULL;
 }

 void *p = realloc (ptr, nmemb*size);

 if (p == NULL) 
  return NULL;

 return p;
}

Other approaches that you can see, is the using libraries and other ways to write safe code with integers, sometimes calling each function safe_add(), safe_sub(), safe_mul() and safe_div() is very boring when have large expressions, thinking about it i writed a solution, look my project Here!

Killing dragons in double


At the Cert C book by Robert Seacord has a example to solve problem at double, the derivatives and futures has a lot of operations with double, one way to detect possible bug is using the function fetestexcept() :



At inputs don't use atof() function, replace to strtod(), other examples with double look this following code here.


Thank you for reading.
Cheers !

Monday, August 8, 2016

Steps to create your WAF(web application firewall) in C

Following definition (like OWASP), a WAF is a piece of software intended to protect a web app that is on the level of the application. nowadays, a WAF is not defined by the web app, it’s not a customized solution specific to that application but similarly to a general software firewall, where one that contains parameters to protect against intrusion in a wide variety of frameworks and codes.

Firewall burning invasors hehehe !
Trying clear your mind, there is overlap between the different types of firewalls. Software and hardware firewalls are used in their own right to protect networks. However, WAFs with their specialized function for web applications, can take the form input of either of those two main types. Per default, a firewall uses a blacklist, protecting against an individual, previously logged attacks. Additionally, it can also use a white list, providing allowable users and instances of interaction for the application, another function is block SQL Injection attacks and XSS attacks... Another context  WAFs can create random tokens and put in forms to try blocks web robots and automated attacks, this practice can try mitigate CSRF pitfalls.
Before you ask "How i can do  it?", i gotta bring to you some principles, anyway the theory around facts...

Have two common WAFs:

1-Uses plugin in HTTPd to get information of data INPUT or OUTPUT, before finish he gets the request and block some contents, this function focuses at HTTP METHODs POST, GET... 
2-this way, is my favorite, is a independent reverse proxy server, he bring all requests of the client to the proxy, the proxy makes some analysis in the content, if not block, he send all the information to the external server...

Number One is a cold, this path is not fully portable... other bad thing you need create a diferent plugin each HTTPd, something to apache another to NGINX, IIs, lighttpd...  its not cool! If you are not a good low level programmer... you can try use twisted of python, is easy make reverse proxy with it, but is not good way, because not have good performance in production... if you piss off for it, study the Stevens book of sockets.

Its OK, the title of this post is "create waf in C", Task fully done here and commented and with some documentations in LaTex... relax, you can get it in this repository: https://github.com/CoolerVoid/raptor_waf
 
Raptor WAF is a simple web application firewall made in C, using KISS principle, to make poll use select() function, is not better than epoll() or kqueue() from *BSD but is portable,  the core of match engine using DFA to detect XSS, SQLi and path traversal, you can see here https://github.com/CoolerVoid/raptor_waf/tree/master/doc/test_dfa
 No more words, look at the following :



Thank you for reading this! 
Cheeers!

Monday, August 1, 2016

Talking about text classifiers

In last year following search something about machine learning, like a try to detect SPAMs at my private projects. i saw something about KNN, random decision forests  and naive bayes.

Consequently, i wrote C++ library to classify texts, and some slides for apresentation, you can view at end of this blog post. 

So i choice  Naive Bayes because Naive Bayes is one of the simplest classifier which is based on Bayes theorem with strong and naïve independence assumptions. It is one of the most basic text classification techniques with various applications in email spam detection, document categorization, sexually explicit content detection, personal email sorting, language detection and sentiment detection(i think something like NLP). Despite the naïve design and oversimplified assumptions that this technique uses, Naive Bayes performs well in many complex real-world problems. Other good thing, Naive Bayes is good to limited resources in terms of CPU and Memory.

To optimize accuracy of detection i uses DFA(deterministic  finite automaton) is util to match patterns and put each pattern in ranking, that ranking have one classification. You can view the following code here. To make your automaton you can use Flex, bison other way that you like...

If you view apresentation, at slide number 12, you can see my point view about ranking to optimize accuracy of classifier at results.



SO, This is a very cool trick to gain accuracy. No more words friends. Thank you for reading this! 

Cheers !

References:


Wednesday, May 18, 2016

Uncommon trick to bypass windows firewall

When I was about to write post I remembered a scene from the movie Monty Python. It's about a black knight that blocks a bridge (his main purpose) saying the following to Arthur, a guy who insisted on crossing the bridge in safety: "None shall pass!". But Arthur kept on insisting, so the black night said: "Then you shall die.".

A firewall is supposed to stop all applications that don't have a good reason to get privileged access to computers or networks. If your app could "bypass" it, so could malicious applications. Firewall plays the same role as the black night, i.e. prevent anything suspicious from going through the bridge.

You can configure firewalls to let particular connections go through the checks, but sometimes you need physical access to the equipment running the firewall to do that.  Don't you have access to the equipment running the firewall? If so, you need to bypass it.

Are you willing to change rules via RegEdit to allow a specific service to run? I have some bad news to you. Your antivirus can detect this trick, because it's a common approach used by malwares.
  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile
  • SYSTEM\ControlSet%03d\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile\AuthorizedApplications\List

Before you say "I can try to hook it" or "I can execute a function like execl(), system() with the argument: 
  • netsh advfirewall set currentprofile state off
What if I tell you that you can use Windows API to simulate a keystroke so as to bypass firewall checks?

Windows has the function SendInput() to simulate a keystroke. This function accepts as argument an array of INPUT structures. The INPUT structures can be either a mouse or a keyboard event. The keyboard event structure has a member called wVk which can be any key on the keyboard.

SendInput() played an important role when writing the code for bypassing Windows firewall. How does it work? 

Firstly, it finds a window with title 'Windows Security Alert' using the function GetWindowText(). Secondly, it calls SendInput() with TAB and ENTER keys to choose button 'allow access'. As simple as that

Take a look at the following video:



Take a look at my code that bypasses Windows firewall:
https://github.com/CoolerVoid/X_files/blob/master/docs/PoCs/bypass_firewall_windows.cpp 

This is a very cool trick. No more words friends. Thank you for reading this!


cheers !

Thursday, April 21, 2016

Hack any TV remote control

Do you have an old TV remote? What if I told you can create your code to make communication with this remote controller.

You can do it!

Infrared remote control is cool, the idea of this blog post is turn it in presentation tool. It is easy with this remote to keep your finger on the advance button and simply advance slides — or turn the screen back, at your favorite PDF viewer. 

Think like MacGyver,  to handle a difficult situation through improvisation using only available materials to do an intelligent activity...

Its Ok, lets go to the hack...

First step you need get some things:

  • Computer with Unix Like OS(at my tests i using Fedora Linux) 
  • Any TV remote control (i use a samsung model “AA59-00469A”
  • Arduino nano 12,00 USD 
  • IR recv (model “1838B”) - 2,00 USD 
  • Jumpers 1,00 USD 
  • Breadboard 2,50 USD

Total of costs is 17.50 USD, looks good  is not expensive, try following this image to assembly your hardware:




  • Green wire is GND 
  • Orange wire is 5v 
  • Yellow wire is pin 6(this is input  to make communication with arduino) 
  • USB connected at arduino(usually at mini series uses FTDI input)

Second step mapping your TV remote control:

At this step we are get some libraries, look this following:

  • $ git clone https://github.com/shirriff/Arduino-IRremote 
  • $ mv Arduino-IRremote ArduinoRemote; sudo cp -rf ArduinoRemote/ /usr/share/arduino/libraries 

At your arduino IDE tool, you can view examples of use it at tab "File", load example that show the input of serial, look this following:




The function Serial.println() shows the output of serial input. for example: when you hold the button one of TV remote control, this action shows the hexadecimal value "E13DDA28".

Done the mapping process of buttons, the next step is use syscall open() to open the file "/dev/ttyUSB0" and use  the syscall read() to get INPUTs of arduino device, remember to put diferent condition at each button input of device.

To automate keyboard hold keys, at Unix like system, you need use some libraries like libXtst and libX11, to emulate keys to turn screens of presentation, to install this libraries look the following:
$ yum install libXtst-devel libX11-devel
at deb based distros uses apt-get install pkg_name-dev

To get final code, rewrite this lines 152 and 159 with address of your button mapping,  compile it and run:

$ git clone https://github.com/CoolerVoid/arduino_ppt_walk 
$ gcc IR_remote.c -o IR_remote -lX11 -lXtst -Wall
$ ./IR_remote /dev/ttyUSB0
Look this following:

https://www.youtube.com/watch?v=Wx64BfLgxQU

Saturday, April 16, 2016

Solving the fizzbuzz problem in Assembly code

Hello ladies and gentlemen, also the loyal readers of my blog. In this post, we will not be working with optimization techniques. Instead, I will share a small challenge that I worked on. Working on a small challenge can be a good way of relieving stress at the end of the day.

For those who don't know, the problem is about replacing a number that is multiple of 3 or 5 by Fizz or Buzz,respectively. Numbers that are multiple of both 3 and 5 should be replaced by "FizzBuzz".

More information about the problem can be found  here.

This problem can be easily solved using a high-level programming language, but if you use Assembly language instead, it's harder.

That's basically what I am going to share with you. I solved fizzbuzz using x86-64 Assembly with Intel syntax.

Let's take a look at the code:

;; Author: CoolerVoid
;;
;; https://en.wikipedia.org/wiki/Fizz_buzz
;; for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz".
;; For numbers which are multiples of both three and five print "FizzBuzz".
;;
;; $ nasm -g -f elf64 fizz_buzz_game.asm -o buzz.o
;; $ ld -m elf_x86_64 buzz.o -o gamebuzz; ./gamebuzz
section .data
 tick db 'tick'
 fizz db 'fizz'
 buzz db 'buzz'
 newline db 0xA
section .bss
 three resb 1      
 five resb 1      
 zero resb 1      

section .text
global _start

_start:
 xor si, si
 mov si,      0xFF
 mov [three], byte 0x3
 mov [five],  byte 0x5

Loop:
 push si   
 mov [zero], byte 1
 sub [three], byte 1
 mov bl, [three]
 cmp [three], byte 0
 jne Zero_Fizz
 mov [three], byte 3
Zero_Fizz: 
 xor rax, rax   
 cmp bl, 0x0
 jnz Not_Fizz
 mov [zero], byte 0
 mov rax, 4              ; syscall write()
 mov rbx, 1
 mov rcx, fizz
 mov rdx, 4
 int 0x80
Not_Fizz:
 sub [five], byte 1
 mov bl, [five]

 cmp [five], byte 0
 jne Zero_Buzz
 mov [five], byte 5
Zero_Buzz: 
 xor rax, rax  
 cmp bl, 0x0
 jnz Not_Buzz
 mov [zero], byte 0
 mov rax, 4           ; syscall write()
 mov rbx, 1
 mov rcx, buzz
 mov rdx, 4
 int 0x80
Not_Buzz:
 xor rax, rax
 mov al, [zero]
 cmp al, 0x0
 jz Not_Tick
 mov rax, 4         ; syscall write()
 mov rbx, 1
 mov rcx, tick
 mov rdx, 4
 int 0x80
Not_Tick:
 push 0x0
 xor rax, rax
 mov rax, 4         ; syscall write()
 mov rbx, 1
 mov rcx, newline
 mov rdx, 1
 int 0x80
 pop rax
    
 pop si
 dec si
 jnz Loop
    
 mov rax, 1        ; syscall exit()
 mov rbx, 0
 int 0x80


If you have familiarity with Assembly, you will notice that the solution is simple. For those unfamiliar, Assembly is not hard, but it does require that the programmer pays attention to slight details.

If you have doubt you can decrease value 0xFF at line 24, and try run again...its all right in do this...

My fifty cents ! CHEERS !