Pages

Sunday, December 5, 2010

"Hello, World!" first shellcode - Part 1

Simple C program to print "Hello, World!". Compiled with gcc version 3.3.6 on Ubuntu 7.04

#include <stdio.h>

char SHELLCODE[]="\xeb\x13\x59\x31\xc0\xb0\x04\x31\xdb\x43\x31\xd2"
                 "\xb2\x0f\xcd\x80\xb0\x01\x4b\xcd\x80\xe8\xe8\xff"
                 "\xff\xff\x48\x65\x6c\x6c\x6f\x2c\x20\x77\x6f\x72"
                 "\x6c\x64\x21\x0a\x0d";

typedef void (*func_ptr)();

int main() {
    func_ptr f = (func_ptr)SHELLCODE;
    f();
}
To compile the source:
$ gcc my_shellcode.c
$ ./a.out 
Hello, world!
The char array represents position-independent instructions, that, when injected into a process, will be executed. But where did that came from?  Here's an .asm source to generate position-independent code that prints something:
BITS 32             ; tell nasm this is 32-bit code

jmp short one       ; jump down to a call at the end

two:
; ssize_t write(int fd, const void *buf, size_t count);
  pop ecx           ; pop the return address (string ptr) into ecx
  xor eax, eax      ; zero out full 32-bits of eax register
  mov al, 4         ; write syscall #4 to the low byte of eax
  xor ebx, ebx      ; zero out ebx
  inc ebx           ; increment ebx to 1, STDOUT file descriptor
  xor edx, edx
  mov dl, 15        ; length of the string
  int 0x80          ; do syscall: write(1, string, 14)

; void _exit(int status);
  mov al, 1        ; exit syscall #1, the top 3 bytes are still zeroed
  dec ebx          ; decrement ebx back down to 0 for status = 0   
  int 0x80         ; do syscall:  exit(0)

one:
  call two   ; call back upwards to avoid null bytes
  db "Hello, world!", 0x0a, 0x0d  ; with newline and carriage return bytes

Some things to pay attention to:
  • the jmp technique with 2 labels (the call in the second label will jump back, will avoid \x00 bytes)
  • xor eax, eax, to zero a register (xor instruction does not modify the flags registry, so it's better than something like for example sub eax, eax that also clears eax.)
  • inc, dec,  instructions that take less machine bytes than mov, so the size of the shellcode  is reduced
  • system calls number can be found in /usr/include/asm-i386/unistd.h (found out with find command ls /usr/include/ -name "*.h" |xargs grep execve , for example)
The asm source cannot be linked into an elf executable. But it can be compiled into machine instructions:
$ nasm shell.asm
$ hexdump -C shell
$ ndisasm shell
The output shows the actual machine code, interpreted as instructions. 
To be continued..

Tuesday, November 30, 2010

Base .. powered by Apache

From a shell,
telnet presidency.ro 80
HEAD / HTTP/1.0

Date: Tue, 30 Nov 2010 08:50:10 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT

Or you can see the response headers (and many many others) with the Web Developer plugin for Chrome or Firefox:
Date: Tue, 30 Nov 2010 08:50:10 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
...

First question: is it for real? :) Has he really gone free software?
Second,  is it good/bad, why.......

Set key bindings for C shell

To bind a sequence of keys to a particular shell command (for example use Ctrl+R, to search the history backwards, as in bash, or other useful functions) add the following to ~/.cshrc :

# Nice key bindings
bindkey -b ^r history-search-backward
bindkey -b ^w backward-delete-word
bindkey -b ^u backward-kill-line
bindkey -b ^b backward-word     # Ctrl + b
bindkey -b ^f forward-word      # Ctrl + f
bindkey '^[OD' backward-word    # Ctrl + Left
bindkey '^[OC' forward-word     # Ctrl + Right
bindkey '\e[1;5D' backward-word # ~ for xterm
bindkey '\e[1;5C' forward-word  # ~

How to obtain the key sequence from a function key, or combination of keys: use the read command. 
Example for pressing Ctrl + Left sequence:
$ read
^[[1;5D
Example for pressing Esc sequence:
$ read
^[
Make sure you write the key sequence as \e[1;5D  rather than ^[[1;5D. The ^[ sequence is equivalent to the [Esc] key, which is represented by \e in the shell. So, for instance, if the key sequence was ^[[OP the resulting bind code to use would be \e[OP.
The same key sequence for a function key or combination can be obtained by pressing Ctrl+V and then the key or sequence.

Sunday, November 21, 2010

Memory Segmentation

Writing down what you think you know is a good way of finding out what you don’t.

    When debugging a program, we have seen address of variables differ, whether it's a local variable or global, static or not, initialized or not, dynamically allocated....The memory of a compiled program is composed of 5 segments: text, data, bss, heap and stack. Each one contains specific things and has different properties. 
  1. The Text Segment:
    • also know as code segment. Here are located the program instructions (assembled machine code)
    • execution of instructions from here is non-linear, controlled by the EIP (instruction pointer) register. After an instruction is read, EIP is incremented with the byte length of the instruction and the instruction is executed.
    • write permission is disabled (prevent modifications of the code). If modification is attempted, an alert is generated and program is killed. 
    • being read-only, can be shared by multiple copies of the program running simultaneously
    • has a fixed size (does not need to change)
  2. The Data Segment:
    • used to store static and global variables
    • contains initialized global & static variables
    • is writable
    • has fixed size
  3. The BSS Segment:
    • used to store uninitialized global and static variables
    • is writable (same as data segment)
    • has fixed size (same as data segment)
  4. The Heap Segment:
    • can be directly controlled 
    • programmer can allocate blocks from this segment
    • it's not fixed, it can grow or shrink as needed
    • the memory here is managed by the allocator/deallocator algorithms 
    • it grows toward higher addresses (downward by convention)
  5. The Stack Segment:
    • has variable size
    • stores variables and contexts  (stack frame) for every function
    • a stack frame contains:
      • the variables that are passed to the functon
      • the location the EIP should point after the function finishes
      • all the local variables used by the function
    • LIFO (last-in first-out) structure containing all the stack frames [1]
An image of the program memory:
An example to show variables addresses in different segments of memory. This shows how the variables are placed in the memory, according to the picture. An execution with gdb reveals also the address where the instructions are to be the lowest.
#include 

int global_var;

int global_initialized_var = 5;

void function() {  
   int stack_var; // This variable has the same name as the one in main() !

   printf("the function's stack_var is at address 0x%08x\n", &stack_var);
}

int main() {
   int stack_var; // Same name as the variable in function()
   static int static_initialized_var = 5;
   static int static_var;
   int *heap_var_ptr;

   heap_var_ptr = (int *) malloc(4);

   printf("These variables are in the data segment.\n");
   printf("global_initialized_var is at address 0x%08x\n", &global_initialized_var);
   printf("static_initialized_var is at address 0x%08x\n\n", &static_initialized_var);

   printf("These variables are in the bss segment.\n");
   printf("static_var is at address 0x%08x\n", &static_var);
   printf("global_var is at address 0x%08x\n\n", &global_var);

   printf("This variable is in the heap segment.\n");
   printf("heap_var is at address 0x%08x\n\n", heap_var_ptr);

   printf("These variables are in the stack segment.\n");
   printf("stack_var is at address 0x%08x\n", &stack_var);
   function(); 
}

References:
  1. The call stack  (Wikipedia)
  2. Jon Erickson - Hacking: The Art of Exploitation, 2nd Edition
  3. Toby Opferman - Debug Tutorial Part 2: The Stack  (on  Codeproject) 

Saturday, November 20, 2010

Customize blog description display (javascript + css)


How to use a javascript function to display something in the blog
description section on my blogspot blog:


  1. Save a backup copy of the original template
    (Download Full Template option from Design->Edit HTML template)

  2. Find the section that deals with the description in the HTML code for the template:
    • Go to Design -> Edit HTML, check "Expand Widget Templates"
    • Search for the code <data:description/>. This is the one that will print the description.
    • Search for something like
      descriptionwrapper {
          padding-left: $(header.padding);
          padding-right: $(header.padding);
      }
      .
      This is the CSS part that deals with the style of the description. (Note that it could be the same style for the title (titlewrapper{...}) and for the description. In this case, separate the two into 2 different blocks {..}).

  3. Add some code that prints a random quote every time, instead of the description. Replace <data:description/> with:
    <p id="description">
       <script language="javascript">
         var quotes = new Array ();
         quotes[0] = "Text string one";
         quotes[1] = "Text string two";
         quotes[2] = "Text string three";
         quotes[3] = "Text string four";
         quotes[4] = "Text string five";
         quotes[5] = "Text string six";
         quotes[6] = "Text string seven";
         var random_i = Math.floor(7*Math.random());
         document.write(quotes[random_i]);
       </script>
    </p> 
    <noscript><data:description/></noscript>
    
  4. Explanations:
    • any number of strings can be added to the array. The Math.Random() javascript funtion returns an integer between 0 and 1 (exclusive). So you multiply that result with your number of items in the array, and then round the result with Math.Floor() and you get a number between [0, N) that it's used as the index.
    • The original description is still kept after the script.
      
      
      for the crowlers(lke Google bot) that search for the description and also for the browsers that dont support Javascript, or it's disabled by the user (
      HTML noscript tag
      )
  5. Customize CSS style for the description:
    • Find the section
      .header-inner .Header.descriptionwrapper {...} and add as many styles as you like.
    • Here you can choose how to modify the fonts, and look and feel :) of the text.
    • And from here you can add a nice border if you like. There are other nice options there, for margins, padding, background. Very nice. I customized my css style like this:
      .header-inner .Header.descriptionwrapper {
        padding-left: $(header.padding);
        padding-right: $(header.padding);
        border-style: outset;
        font-size: 17px;
        font-family: sans-serif; 
        font-weight: bolder;
      }
      

  6. Other great links:

Friday, November 19, 2010

Have some green tea!

The Little Book of Semaphores by Allen B. Downey

is a free (in both senses of the word - as in "free speech" and also as in "free beer") textbook that introduces the principles of synchronization for concurrent programming. The site also contains a 1 hour introduction to semaphores presented at Northeastern University by the author. Theory, examples, exercises, puzzles, that's the way a good CS course should be.
"The approach of this book is to identify patterns that are useful for a variety of synchronization problems and then show how they can be assembled into solutions. After each problem, the book offers a hint before showing a solution, giving students a better chance of discovering solutions on their own."

Tuesday, November 16, 2010

Online WYSIWYG HTML editor

TinyMCE is a Javascript HTML WYSIWYG editor control released as Open Source under LGPL.
Very very cool :)