Friday, June 10, 2022

The magic of bits

 Before the long tale to the course of magic bits, let's gonna for a little walk in the world of C language.

Variable of type int has 4 bytes, so 32bits. 

If you do it:

"int var = 3;"

You can see this schema:

4bytes = 32bits

Looking to this context, each octet is a byte, half an octet can be called a nibble.

“…00000000 00000000 00000011

Each place of binary number counts as one bit.

The bit is nothing but a mnemonic for “Binary digiT

To know the number of bytes, we use the “sizeof(var)” operator, which returns the value in bytes of the variable. If we want to know the binary value of a number, we divide by 2

and as long as the remainder of the division is different from “1”, we divide the end. We take the leftovers in reverse to be the final result

For example number 12

12 | 2
12 +------                   1100 -- reverse result
 0  6    | 2              -------------
    0      3  | 2
          1     1

going on, there's another better way to do it, but no
it's time to address this now.

#include <stdio.h>
int main()
 int bin[8],num=0,counter=0;
 puts("Dec2Bin\n digite um numero");


 printf("\nResultado: ");
 return 0;
Introduction to "Bitwise"

When we say bitwise, it is a mere reference to work
to manipulate bits to get specific results. Staff who work
with microcontrollers, AVR and PIC often have to do such
manipulation. When we want bitwise performance, we can
also help, although the compiler already optimizes many tasks. Another
use is in image processing and manipulation. OpenCV
even forces you to use it whenever there is no ready-made solution.

Bit shifting

Shifting a bit is nothing more than changing the bit from its original position.
to get a specific result, we call this technique bit shift
is a mnemonic of the assembly “shl,shr”(shifting left, shifting right),
Let's look at an example of shifting to the left:

int var = 3;
var <<= 1;
So the 3
recv left shift

The result is “6”, which can give an illusion of product arithmetic or
addition by itself, but it was the result of displacement, form
Correct according to the K&R math textbook to explain our expression
an example would be “2*3¹”.

Now look that following a shift to the right:

int var = 100;
So you can see 1100100
var >>= 2;
remove last two digits

The result gives us “25” the mathematical form for this is the following “(100/2)²”.
You tell me 25 thousand. Where are the zeros? As I said, remove the last two digits.

Bit mask


Let's go to the “|” operator with the “OR” mnemonic in assembly. Let's go to understand its impact.

| 10011
  11011   ==  27


Now the “&” mnemonic with “AND” in assembly.

& 10011
  10010 == 18


The "~" is mnemonic with "NOT"; that is, it is a negation, making an inverse effect
of its loaded value, where one is, it becomes zero and vice versa.


the result would be -27, Like but why not 5 ? remember that I said an "int" is 4 bytes equals 32bits, so look at the following:

0000 0000 0001 1010

1111 1111 1110 0101

I did it in a nibble, so I don't have to write too much.


The “^” is a mnemonic for XOR.

^ 10011
  01001  == 9

So look at that table in the following:

| a | b |  a ^ b |  pode-se fazer SWAP sem usar uma terceira variável
|---|---|--------|  exemplo:
| 0 | 0 |   0    |
| 0 | 1 |   1    |  int A=4,B=7;
| 1 | 0 |   1    |  A^=B; B^=A; A^=B;
| 1 | 1 |   0    |  // "A" agora vale 7
 alguns usam XOR em criptografia também...

The magic of the bits

Let's use bitwise to get "performance" let's go to get 
some bitwise code snips.

// check if a value is even or odd
main(int argc,char *argv[]){printf("%s\x0a",(!((atoi(argv[1]))&1))?"odd":"even");}
// This "x&1" same effect like "x%2"
// num is multiple
resto = num & (divisor - 1);
x = 122 % 6;
// maybe faster
x = 122 & (6 - 1);
casting float to Int
"x = int(3.142)" try to "x=3.142>>0;" can be improve the performance
// ternary operation
i = x < 0 ? -x : x;
// try
i = (x ^ (x >> 31)) - (x >> 31);
// compare ints
x = a * b > 0;
// or try
x = a ^ b >= 0;
//Compare two vars
gamma = y ^ ((x ^ y) & -(x < y)); // equivalent to gamma=menor(x, y)
gamma = x ^ ((x ^ y) & -(x < y)); // equivalent to  gamma=maior(x, y)
//check 2 potence
x = v && !(v & (v - 1));

//average number to integer
int a=6,b=8; printf("%d\n",((a&b)+(a^b)>>1));
// check if exist position "n" in bit "1"
if( n & 1 << i ) 

So remember our simple code to convert decimal to binary? Let's make one using bitwise 🙂

char * dec2bin(int n, char * string)
 int i;
 static int size = 8 * sizeof(int);
  for(i = size - 1; i >= 0; i--, n >>= 1)
   string[i] = (01 & n) + '0';
 string[size] = '\0';
 return string;

The square root calc, following bitwise path:

// header beer.h
int bit_sqrt(int num)
//so 32 is sizeof(int)<<3 -1="" bit_sqrt="" error="" if="" int="" num0="num,result=0,tbit=1<<((sizeof(int)<<3)-2);" num="" printf="" return="" tbit="" while="">num0)
 return result;

This function cannot be compared to APIs such as GMP and OpenSSL
even because it is a simple function, much less “math.h”
it was more to illustrate.
Can I use bitwise on strings?
If it is a pointer, why not?

// return reverse string
char *strrev(char *str)
 char *p1, *p2;
 if(! str || ! *str)
  return str;
 for(p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
  *p1 ^= *p2;
  *p2 ^= *p1;
  *p1 ^= *p2;
 return str;

So this second example is a simple benchmark following CPU cyles to compare arithmetic division using bitwise and common resource.

Author: Cooler_
Contact: c00f3r[at]gmail[dot]com

Compares arithmetic division with bitwise and  without... 
test CPU cycles...

$ gcc -o code code.c; ./code 
#include <stdio.h>
#include <stdlib.h>
#include <x86intrin.h>
#include <cpuid.h>
#include <inttypes.h>
#define LAST "\033[0m"
#define RED "\033[22;31m"
void mul()
 int x=50,y=0;
void leftshift()
 register int x=50,y=0;
  y=x<<1 bit_div7="" div7="" n="" num="" register="" return="" unsigned="" x--="" x="(num" y="">>1)+(num>>4);
 y=num-((x<<3 return="" x="" y="">>3);
unsigned div3(unsigned n)
 return n/3;
unsigned bit_div3(unsigned num)
 register unsigned x,y;
 y=num-((x<<2 ficou="" return="" ruim="" x="" y="">>5);
// ruim  return x+( (y+5+(y<<2>>4);
 return x+( (((y+1)<<2 y="">>4);
int main(void)
  int x=0;
  uint32_t a=0, b=0, c=0, d=0;
  register uint64_t y=0;
  x = 0;
  do {
    __cpuid(0, a, b, c, d);
    y = _rdtsc();
    y = _rdtsc() - y;
  } while (++x < 2);
  printf("::: left shift: %s  %lld %s cicles\n",RED, y,LAST);
  x = 0;
  do {
    __cpuid(0, a, b, c, d);
    y = _rdtsc();
    y = _rdtsc() - y;
  } while (++x < 2);
  printf("::: mul: %s %lld %s cicles\n", RED,y,LAST);
  unsigned int z=0;
  x = 0;
  do {
    __cpuid(0, a, b, c, d);
    y = _rdtsc();
    printf("result: %d\n",z);
    y = _rdtsc() - y;
  } while (++x < 2);
  printf("::: div7: %s %lld %s cicles\n", RED,y,LAST);
  x = 0;
  do {
    __cpuid(0, a, b, c, d);
    y = _rdtsc();
    printf("result: %d\n",z);
    y = _rdtsc() - y;
  } while (++x < 2);
  printf("::: bit_div7:  %s %lld %s cicles\n",RED, y,LAST);
  x = 0;
  do {
    __cpuid(0, a, b, c, d);
    y = _rdtsc();
    printf("result: %d\n",z);
    y = _rdtsc() - y;
  } while (++x < 2);
  printf("::: div3:  %s %lld %s cicles\n",RED, y,LAST);
  x = 0;
  do {
    __cpuid(0, a, b, c, d);
    y = _rdtsc();
    printf("result: %d\n",z);
    y = _rdtsc() - y;
  } while (++x < 2);
  printf("::: bit_div3:  %s %lld %s cicles\n", RED,y,LAST);

This subject is huge. I'll stop here for the end
I suggest you read it to delve deeper into the subject.
by bitwise, the following book “hacker’s delight.”

Thursday, November 15, 2018

mtg to relieve my cortisol

Follow Wikipedia:

There's a lot of strategic depth to Magic or MTG. There is usually a pretty good variety of top-tier decks you can play. From my perspective, you can generally find a tier that fits your playstyle or color preference and is still competitive.

Do you believe that games can relieve stress levels?
So, I choice play mtg to do that.

The cool thing is, if you stop playing for a year or four, it's not like your deck becomes obsolete. If you were playing standard, you could switch to modern legacy, and that's that.

Here "brazil" have devir call events and challenges

If you have some curiosity to view my strategy's look that following:

Open Source simulators:  

Saturday, December 23, 2017

Firefox tunnel

A crucial element of the Red Team's task is stealth in the attack. Success is its ability to espouse an aggressive mindset. If the red team wins, an absolute cracker's point of view can help construct a better defence for the Blue Team in the future. Don't bear this content. All content here has a practical purpose.

This blog post is about a different attack approach to remote control the machine and bypasses the firewall. We have many weapons to work in that perspective, something like veil framework, msfvenom. But sometimes, following a different path will generally bring good results.

 The attack aims to use firefox to communicate between client and server. Using hooks to do that is not impossible, but DLL injection sometimes is boring to implement and can be harder to turn in portable. Do you know that? x32 and x64, each architecture needs a different approach to develop(in the future, I discovered that the easy hook API could solve that). Another day I was studying the firefox internals, reading something about the use of SQLite to work with cookies that gave me a different focus.
Look at the following:

That is a complete plan to create a program to use firefox with the tunnel. I going to explain in each step:

1- Programm of tunnel call firefox browser in hidden mode, sending a URL, URL has a malicious server, that malicious server sends a cookie with command.

2- The tunnel gets a cookie of evil server in the cookie.SQLite uses that in the command shell.

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

4- Programm open wrote HTML in hidden mode to send CMD to the malicious server.

 Now you can look at the following:

For a satisfactory conclusion, I wrote the code and recorded the proof of concept. The incredible fact of the empirical point turns all into reality. You can view all staff at the following:

Future insights:

Insert persistence, using function RegOpenKeyEx() to open path: 


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 to 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 wrong domain or hosts, that can use a blocklist to find and uses DELETE query to remove the 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 the Black & Scholes model.

This study resulted in the creation of OptionsCat, an open-source tool to work with European options. I faced many Arithmetic-related security pitfalls when writing this tool, which motivated me to study it and write a blog post.  


 I always develop my implementations for the algorithms presented throughout the finance books. That's because the writers are often careless about security pitfalls. From this article's perspective, this is a problem or dragon that can 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. An integer overflow may occur when computing the memory size to allocate a buffer, often leading to a buffer overflow.


 Look at the following quote: 

 "Integer overflows cannot be detected after they have happened, so there is no way for an application to tell if a result it has calculated previously is correct. This action can get dangerous if the calculation has to do with a buffer's size 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 bug classes, 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 the use of the 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 considerable length can cause Denial of service. The use of Integers is not hard to find in the stock markets. But double is then expected and can bring 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 it, it returns something like "1799999999999999916112.*(dirts...)". You ask me, "why to return it ?" you don't validate the operation and pass the carrying limit. This action can cause undefined behaviour and overflow.

Killing dragons in integers 

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



 Some operating systems have solutions at libraries to mitigate the problem. For example, OSX has 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. */

Another way to mitigate this way is from OpenBSD:

#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t)*4))
// based in OpenBSD reallocarray() function
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 different ways to write safe code with integers, sometimes calling each function safe_add()safe_sub(), safe_mul(), and safe_div() is very dull when having significant expressions, and thinking about it I wrote a solution, look my project Here!

Killing dragons in double

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

At inputs, don't use the atof() function. Replace to strtod(), and double look the following code here.

Thank you for reading.

The magic of bits

 Before the long tale to the course of magic bits, let's gonna for a little walk in the world of C language. Variable of type int has 4 ...