Monday, March 1, 2010

nis

root@ns ~]#
yum -y install ypserv


[root@ns ~]#
ypdomainname server-linux.info

// set domain name

[root@ns ~]#
vi /etc/sysconfig/network


NETWORKING=yes
NETWORKING_IPV6=yes
HOSTNAME=ns.server-linux.info
GATEWAY=192.168.0.1
NISDOMAIN=server-linux.info
// add at the bottom of file


[root@ns ~]#
vi /var/yp/Makefile


# MERGE_PASSWD=true|false
MERGE_PASSWD=
false
// line 42: change

#
# MERGE_GROUP=true|false
MERGE_GROUP=
false
// line 46: change

#
all: passwd
shadow
group hosts rpc services netid protocols
// line 109: add


[root@ns ~]#
vi /var/yp/securenets


host
127.0.0.1

255.255.255.0
192.168.0.0


// create a directory for web site automatically when a user is added in the system

[root@ns ~]#
mkdir /etc/skel/public_html

[root@ns ~]#
chmod 711 /etc/skel/public_html


// create a directory for email automatically when a user is added in the system

[root@ns ~]#
mkdir -p /etc/skel/Maildir/cur

[root@ns ~]#
mkdir -p /etc/skel/Maildir/new

[root@ns ~]#
mkdir -p /etc/skel/Maildir/tmp

[root@ns ~]#
chmod -R 700 /etc/skel/Maildir/


[root@ns ~]#
useradd cent

[root@ns ~]#
passwd cent

Changing password for user cent.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

[root@ns ~]#
/usr/lib/yp/ypinit -m

At this point, we have to construct a list of the hosts which will run NIS servers. ns.server-linux.info is in the list of NIS server hosts. Please continue to add the names for the other hosts, one per line. When you are done with the list, type a .
next host to add: ns.server-linux.info
next host to add:
// push Ctrl + D keys

The current list of NIS servers looks like this:

ns.server-linux.info

Is this correct? [y/n: y]
y
// input 'y' and push Enter key

We need a few minutes to build the databases...
Building /var/yp/server-linux.info/ypservers...
Running /var/yp/Makefile...
gmake[1]: Entering directory `/var/yp/server-linux.info'
Updating passwd.byname...
Updating passwd.byuid...
Updating group.byname...
Updating group.bygid...
Updating hosts.byname...
Updating hosts.byaddr...
Updating rpc.byname...
Updating rpc.bynumber...
Updating services.byname...
Updating services.byservicename...
Updating netid.byname...
Updating protocols.bynumber...
Updating protocols.byname...
Updating mail.aliases...
gmake[1]: Leaving directory `/var/yp/server-linux.info'

ns.server-linux.info has been set up as a NIS master server.

Now you can run ypinit -s ns.server-linux.info on all slave server.

[root@ns ~]#
/etc/rc.d/init.d/portmap start

Starting portmap:
[ OK ]

[root@ns ~]#
/etc/rc.d/init.d/ypserv start

Starting YP server services:
[ OK ]

[root@ns ~]#
/etc/rc.d/init.d/yppasswdd start

Starting YP passwd service:
[ OK ]

[root@ns ~]#
chkconfig portmap on

[root@ns ~]#
chkconfig ypserv on

[root@ns ~]#
chkconfig yppasswdd on


// It's neccessary to update NIS database with following way if new user is added again

[root@ns ~]#
cd /var/yp

[root@ns yp]#
make

Sunday, February 28, 2010

LVM setup

* The LVM is not currently configured or in used. Having say that, this is the LVM tutorial if you’re going to setup LVM from the ground up on a production Linux server with a new SATA / SCSI hard disk.

* Without a luxury server hardware, I tested this LVM tutorial on PC with the secondary hard disk dedicated for LVM setup. So, the Linux dev file of secondary IDE hard disk will be /dev/hdb (or /dev/sdb for SCSI hard disk).

* This guide is fully tested in Red Hat Enterprise Linux 4 with Logical Volume Manager 2 (LVM2) run-time environment (LVM version 2.00.31 2004-12-12, Library version 1.00.19-ioctl 2004-07-03, Driver version 4.1.0)!


How to setup Linux LVM in 3 minutes at command line?

1. Login with root user ID and try to avoid using sudo command for simplicity reason.

2. Using the whole secondary hard disk for LVM partition:
fdisk /dev/hdb

At the Linux fdisk command prompt,
1. press n to create a new disk partition,
2. press p to create a primary disk partition,
3. press 1 to denote it as 1st disk partition,
4. press ENTER twice to accept the default of 1st and last cylinder – to convert the whole secondary hard disk to a single disk partition,
5. press t (will automatically select the only partition – partition 1) to change the default Linux partition type (0×83) to LVM partition type (0×8e),
6. press L to list all the currently supported partition type,
7. press 8e (as per the L listing) to change partition 1 to 8e, i.e. Linux LVM partition type,
8. press p to display the secondary hard disk partition setup. Please take note that the first partition is denoted as /dev/hdb1 in Linux,
9. press w to write the partition table and exit fdisk upon completion.


3. Next, this LVM command will create a LVM physical volume (PV) on a regular hard disk or partition:
pvcreate /dev/hdb1

4. Now, another LVM command to create a LVM volume group (VG) called vg0 with a physical extent size (PE size) of 16MB:
vgcreate -s 16M vg0 /dev/hdb1

Be properly planning ahead of PE size before creating a volume group with vgcreate -s option!

5. Create a 400MB logical volume (LV) called lvol0 on volume group vg0:
lvcreate -L 400M -n lvol0 vg0

This lvcreate command will create a softlink /dev/vg0/lvol0 point to a correspondence block device file called /dev/mapper/vg0-lvol0.

6. The Linux LVM setup is almost done. Now is the time to format logical volume lvol0 to create a Red Hat Linux supported file system, i.e. EXT3 file system, with 1% reserved block count:
mkfs -t ext3 -m 1 -v /dev/vg0/lvol0

7. Create a mount point before mounting the new EXT3 file system:
mkdir /mnt/vfs

8. The last step of this LVM tutorial – mount the new EXT3 file system created on logical volume lvol0 of LVM to /mnt/vfs mount point:
mount -t ext3 /dev/vg0/lvol0 /mnt/vfs


To confirm the LVM setup has been completed successfully, the df -h command should display these similar message:

/dev/mapper/vg0-lvol0 388M 11M 374M 3% /mnt/vfs

Some of the useful LVM commands reference:

vgdisplay vg0

To check or display volume group setting, such as physical size (PE Size), volume group name (VG name), maximum logical volumes (Max LV), maximum physical volume (Max PV), etc.

pvscan

To check or list all physical volumes (PV) created for volume group (VG) in the current system.

vgextend

To dynamically adding more physical volume (PV), i.e. through new hard disk or disk partition, to an existing volume group (VG) in online mode. You’ll have to manually execute vgextend after pvcreate command that create LVM physical volume (PV).

Saturday, July 18, 2009

How to create FTP SERVER AND USER

[root@deep ] /# mkdir /home/ftp
[root@deep ] /# useradd -d /home/ftp/ftpadmin/ -s /dev/null ftpadmin > /dev/null 2>&1
[root@deep ] /# passwd ftpadmin



Changing password for user ftpadmin
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully

Monday, July 13, 2009

How to Extend LVM

lvextend -L +54 /dev/vg01/lvol10 /dev/sdk3

Thursday, July 2, 2009

LVM CREATION IN LINUX

Changing hostname on RHEL
1. Change the HOSTNAME line in /etc/sysconfig/network
2. Change the hostname (FQDN and alias) in /etc/hosts
3. Run /bin/hostname new_hostname for the hostname change to take effect immediately.
4. Run /sbin/service syslog restart for syslog to log using the new hostname.
A reboot is not required to change the system hostname.

How to enable SSH in Linux: -
#chkconfig -list sshd
#chkconfig –level 345 sshd on

How to enable mouse in Linux: -
#vi /etc/X11/xorg.conf
Section “device” (add the below line)
Option “HWCursor” “off”
#gdm restart

How to make a iso image: -
#mkisofs -o /tmp/file_name.iso /u01/software_contents_folder_name


1. for firewall enable/disable:-
chkconfig iptables off
chkconfig ip6tables off
Or
system-config-securitylevel

2. to network services:-

service network restart
service network start
service network stop
or
/etc/init.d/network start
/etc/init.d/network restart
/etc/init.d/network stop

3. nmap localhost: - it will display the port details, which are all opened for this Box.


4. nautilus – it’ll work in putty. It will display all the windows in the Linux server.

1.rsync –a / root@: :- to copy the files from one Linux system to another.
How to create a symbolic link in Linux: - $ ln –s target_filename symlink_filename
xstart
gdmstart

Tar:-

1. To tar the one or more files:-

$ tar –cvzf <.tar.gz file name with path> < source file name or Directory> . . . .

To un-tar the .tar.gz file:-

$ gunzip <.tar.gz file name>
$ tar –xvf <.tar file name>

How to increase the swap space in Linux:-

1.First check free space in file system.
$df -h

2.And find out the free space in one file system, and create swap space in that file system.
$dd if=/dev/zero of=//swap bs=1024 count=value_in_bytes
3.Change the permission :- $ chmod 600 swapfile
4. Setup the swap file with the command : - $ mkswap swapfile
5. To enable the swap file immediately but not automatically at boot time: -
$ swapon swapfile_name
6.To enable it at boot time, edit /etc/fstab to include: -
/swap_file_location swap swap defaults 0 0
(When time the system boots, it will enable the new swap file.)
7. After adding the new swap file and enabling it, make sure it is enabled by viewing the output of the command cat /proc/swaps or free.
How to change the partition name in Linux:-
1.First create a required directory under the / partition:-
$mkdir /oracle
2.Edit the /etc/fstab file:-
Old entre: - LABEL=/ora /ora ext3 defaults 1 2
New entre: - LABEL=/ora /oracle ext3 defaults 1 2
3.Then unmount the old partition & mount the new partition:-
$umount /ora
$mount /oracle
$rm –rf /ora (deleting the old partition)
4.To check the progress:-
$df –h
Use free space to create logical volume on LVM partition:-

[root@igloo ~]# vgdisplay
--- Volume group ---
VG Name VolGroup00
System ID
Format lvm2
Metadata Areas 1
Metadata Sequence No 5
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 2
Open LV 2
Max PV 0
Cur PV 1
Act PV 1
VG Size 74.41 GB
PE Size 32.00 MB
Total PE 2381
Alloc PE / Size 193 / 6.03 GB
Free PE / Size 2188 / 68.38 GB
VG UUID JoY5DH-S0HV-Q5Dw-b2wC-Rpe0-XeaR-QFbG75

[root@igloo ~]# lvscan
ACTIVE '/dev/VolGroup00/LogVol00' [5.03 GB] inherit
ACTIVE '/dev/VolGroup00/LogVol01' [1.00 GB] inherit

[root@igloo ~]# lvcreate -l 2188 VolGroup00 -n LogVol02
Logical volume "LogVol02" created

[root@igloo ~]# lvscan
ACTIVE '/dev/VolGroup00/LogVol00' [5.03 GB] inherit
ACTIVE '/dev/VolGroup00/LogVol01' [1.00 GB] inherit
ACTIVE '/dev/VolGroup00/LogVol02' [68.38 GB] inherit

[root@igloo ~]# mkfs -t ext3 /dev/VolGroup00/LogVol02
mke2fs 1.36 (05-Feb-2005)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
8962048 inodes, 17924096 blocks
896204 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=20971520
547 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
4096000, 7962624, 11239424

Writing inode tables: done
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 21 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.

[root@igloo ~]# e2label /dev/VolGroup00/LogVol02 /oracle

[root@igloo ~]# cat /etc/fstab
# This file is edited by fstab-sync - see 'man fstab-sync' for details
/dev/VolGroup00/LogVol00 / ext3 defaults 1 1
LABEL=/boot /boot ext3 defaults 1 2
LABEL=/realvar /realvar ext3 defaults 1 2
none /dev/pts devpts gid=5,mode=620 0 0
none /dev/shm tmpfs defaults 0 0
none /proc proc defaults 0 0
none /sys sysfs defaults 0 0
/dev/VolGroup00/LogVol01 swap swap defaults 0 0
/dev/VolGroup00/LogVol02 /oracle ext3 defaults 1 2
/dev/hdc /media/cdrom auto pamconsole,exec,noauto,managed 0 0
/dev/fd0 /media/floppy auto pamconsole,exec,noauto,managed 0 0

Create the partition name with required name in / and mount it:-
[root@igloo ~]#mkdir /oracle
[root@igloo ~]#mount /oracle
Check with the df –h command.

Run Level’s in Linux:-
Run Level
Generic
Fedora Core
Slackware
Debian
0
Halt
Halt
Halt
Halt
1
Single-user mode
Single-user mode
Single-user mode
Single-user mode
2
Basic multi-user mode (without networking)
User definable (Unused)
User definable - configured the same as runlevel 3
Multi-user mode
3
Full (text based) multi-user mode
Multi-user mode
Multi-user mode - default Slackware runlevel

4
Not used
Not used
X11 with KDM/GDM/XDM (session managers)
Multi-user mode
5
Full (GUI based) multi-user mode
Full multi-user mode (with an X-based login screen) - default runlevel
User definable - configured the same as runlevel 3
Multi-user mode
6
Reboot
Reboot
Reboot
Reboot


The script below will display all files that are greaten then one megabyte in size. Note that the size parameter is specified in K-bytes.
root> find . -size +1024 –print
./prodsid_ora_22951.trc
Of course, you can easily append the xargs of –exec command to automatically remove the large file:
root> find . -size +1024 –print|xargs –i rm \;
This find command will do a "stats" on all files in a directory structure, showing the total size of all files in the directory. You can also incorporate the "df -k" command"
find ${START_DIR} -mtime -${DAYS} |xargs stat -c "%s"|awk '{sum += $1}END{print sum}'


select sid, serial# from v$session s, dba_datapump_sessions d where s.saddr = d.saddr;
select sid, serial#, sofar, totalwork from v$session_longops;
rman> list backup;
rman> list backup of database;
rman> list backup summary;
rman> list incarnation;
rman> list backup by file;
rman> list copy of database archivelog all;
rman> list copy of datafile 1, 2, 3;
rman> list backup of datafile 11 summary;
rman> list backup of archivelog from sequence 1234;
rman> list controlfilecopy "/u01/app/oracle/ctrl1.cpy";
rman> list backupset of datafile 1;

select
session_key, db_name,
min(r.start_time) start_rman,
min(c.checkpoint_time) start_controlfile,
min(d.checkpoint_time) start_datafile,
min(a.first_time) start_archivelog,
max(a.next_time) end_archivelog,
min(b.start_time) start_set,
max(b.completion_time)
end_set, min(p.start_time)
start_piece, max(p.completion_time) end_piece
from
rman.rc_backup_controlfile_details c
join
rman.rc_backup_datafile_details d
on c.session_key = d.session_key
join
rman.rc_backup_archivelog_details a
on c.session_key = a.session_key
join
rman.rc_backup_set_details b
on c.session_key = b.session_key
join
rman.rc_backup_piece_details p
on c.session_key = p.session_key
join
rman.rc_rman_backup_job_details r
on c.session_key = r.session_key
where
db_key =
(select db_key
from rman.rc_database
where name = 'alice1')
and
c.checkpoint_time >sysdate-14
and
d.checkpoint_time >sysdate-14
and
r.start_time >sysdate-14
and
a.first_time >sysdate-14
and
b.start_time >sysdate-14
and
p.start_time >sysdate-14
and
a.next_time >sysdate-14
and
b.completion_time >sysdate-14
and
p.completion_time >sysdate-14
group by
session_key,
db_name;

Cleanup trace files more than 7 days old: -
root> find $DBA/$ORACLE_SID/bdump/*.trc -mtime +7 -exec rm {} \;
root> find $DBA/$ORACLE_SID/udump/*.trc -mtime +7 -exec rm {} \;
root> find $DBA/$ORACLE_SID/cdump/*.trc -mtime +7 -exec rm {} \;

Cleanup redo log files that are more than 7 days old: -
root> find $DBA/$ORACLE_SID/arch/*.log -mtime +7 -exec rm {} \;

You can query v$session and join into v$sql to see session and SQL information. This will show the SID for the session that is holding a PL/SQL package: -

select x.sid from v$session x, v$sqltext y
where x.sql_address = y.address and y.sql_text like '%%';



Display distinct multiple columns with SQL: -

select deptno, loc, job, sal, ename from lsc_emp
join lsc_dept
using (deptno)
order by deptno,loc,job,sal,ename;

The fuser command will show all UNIX process ID’s that are accessing any Oracle data file: -
root> fuser –u /u01/app/oracle/myfile.dbf

/u01/app/oracle/myfile.dbf 1234(user1) 2345(user2) 5678(user3)

db uptime :-

select
'Hostname : ' || host_name
,'Instance Name : ' || instance_name
,'Started At : ' || to_char(startup_time,'DD-MON-YYYY HH24:MI:SS') stime
,'Uptime : ' || floor(sysdate - startup_time) || ' days(s) ' ||
trunc( 24*((sysdate-startup_time) -
trunc(sysdate-startup_time))) || ' hour(s) ' ||
mod(trunc(1440*((sysdate-startup_time) -
trunc(sysdate-startup_time))), 60) ||' minute(s) ' ||
mod(trunc(86400*((sysdate-startup_time) -
trunc(sysdate-startup_time))), 60) ||' seconds' uptime
from
sys.v_$instance;

(or)

select to_char(logon_time,'DD/MM/YYYY HH24:MI:SS') from v$session
where sid=1;


How to display your Oracle session ID number: -

select sys_context('USERENV','SID') from dual;

select sid from v$mystat where rownum <=1;

select to_number(substr(dbms_session.unique_session_id,1,4),'XXXX') mysid from dual;

select distinct sid from v$mystat;



How to share and Access file on Solaris machine
In this example I will share a file from jupiter machine and then access it on neptune machine. Both machine uses Solaris platform.
1)On jupiter machine,

bash-3.00$ hostname
jupiter

Log on as a root user,
bash-3.00$ su
Password:

Change shell to bash
# bash

To make share persistence (after reboot is will also show) edit /etc/dfs/dfstab entry. Here I want to share directory /export/home/oracle and sharing option is read write.
# vi /etc/dfs/dfstab
share -F nfs -o rw /export/home/oracle

rw means read write permission You can also want to give ro (read only) instead of read write.

If you want it temporary you can do,
# share -F nfs -o rw /export/home/oracle
Restart your nfs server.
# /etc/init.d/nfs.server stop
# /etc/init.d/nfs.server start

Have a look at whether nfs server is running or not.
# ps -ef | grep nfs
daemon 317 1 0 Oct 10 ? 0:00 /usr/lib/nfs/lockd
daemon 311 1 0 Oct 10 ? 0:00 /usr/lib/nfs/statd
daemon 313 1 0 Oct 10 ? 0:03 /usr/lib/nfs/nfsmapid
daemon 291 1 0 Oct 10 ? 0:00 /usr/lib/nfs/nfs4cbd
root 12741 12424 0 03:20:34 pts/4 0:00 grep nfs

This must show statd and lockd running. In fact The statd and lockd must be running on server and
client.

Have a look at which file is shared and it's mode.
# share
- /export/home/oracle rw ""

2)On Saturn machine log on as a root user
oracle@neptune ~$ su -
Password:

Create a directory where you mount the network location.
root@neptune /# mkdir /export/home/oracle/remote

Mount the network drive
root@neptune /# mount -F nfs jupiter:/export/home/oracle /export/home/oracle/remote

Or, with more options issue,
# mount -o rw,bg,hard,nointr,rsize=32768,wsize=32768,tcp,vers=3,timeo=600,actimeo=0 jupiter:/export/home/oracle /export/home/oracle/remote
See whether it is mounted.
root@neptune /# df -h
.
.

jupiter:/export/home/oracle
20G 7.6G 12G 39% /export/home/oracle/remote

Friday, June 26, 2009

Linux admin interview questions

Configure and Use System Log Files
Information
These notes were originally written in the year 2000 as part of a set of LPI
Exam 101 training materials. The LPI training course at Bromley College was
subsequently discontinued and some of the sections of the notes modified and
incorporated into our one-day System Administration Courses. The remainder
of the notes have now been made publicly available on the
linuxtraining.org.uk website.
If you are a beginner please do not be put off of training courses by these
notes, as they are rather technical. On the other hand if you are a more
experienced Linux user we hope you find the coverage of this topic
refreshingly clear.
For full details of our current Linux training please visit the site:
http://ce.bromley.ac.uk/linux
If you have reached this page from a search engine and wish to see the full
contents list for the published notes please visit the site:
http://www.linuxtraining.org.uk
We hope you find these notes useful, but please remember that they apply to
the 2.2 kernel. I will update them when I have the time.
Clive Gould - 21st December 2004
C.R.Gould Section E Objective 3 Page 1 Linux Administration
Configure and Use System Log Files
Objective 3
Configure and use system log files to meet administrative and security
needs: Configure the type and level of information logged, manually scan log
files for notable activity, arrange for automatic rotation and archiving of
logs, track down problems noted in logs. Involves editing /etc/syslog.conf
Understanding Log Files
Many processes record an event log automatically. These logs can be
invaluable in tracing system problems and security violations. Log files are
typically stored in the directory /var/log and its associated subdirectories.
When a log file reaches its maximum size it is renamed and the original file is
overwritten with fresh log data. Log files can be distribution specific. Some of
the main log files you may encounter are listed below:
Filename Description
/var/log/boot.log Contains information on all the processes started and stopped
when the system starts up or shuts down. (A copy of what you
see on the screen during boot or reboot). The contents of this
log are controlled by the syslogd process.
/var/log/cron Contains status messages from cron, a process which
automatically runs scheduled jobs on a timed basis.
/var/log/dmesg Contains messages recorded by the kernel during boot.
/var/log/httpd This directory contains the access and error log files maintained
by the Apache server
/var/log/lastlog This file is similar to wtmp and contains login times for users.
Can be accessed using the lastlog command. Used by finger to
determine when a user was last logged on.
/var/log/maillog Logs all mail messages in one place. The contents of this log
are controlled by the syslogd process.
/var/log/messages A general purpose log file to which many programs record
messages. The contents of this log are controlled by the syslogd
process.
C.R.Gould Section E Objective 3 Page 2 Linux Administration
Configure and Use System Log Files
Filename Description
/var/log/news This directory contains log files associated with the news
server. Some of these log files are controlled by the syslogd
process.
/var/log/secure Records the date and time of local and remote logins and
sessions. The contents of this log are controlled by the syslogd
process.
/var/log/samba This directory contains log files associated with the samba
server, including machine, user and nmb logs.
/var/log/spooler Contains mail and news errors of level err and higher. The
contents of this log are controlled by the syslogd process.
/var/run/utmp This is a binary file containing information on currently logged
on users. Used by the who, w and finger commands. The
format of this file may vary from one system to another.
/var/log/wtmp This is a binary file containing log times and durations for each
user. Can be accessed using the last command. The format of
this file may vary from one system to another.
The commands less, tail and grep are very useful with log files
The use of the grep command with the secure log file is illustrated below:
[root@redhat log]# grep student1 secure.*
secure.4:Aug 2 10:14:43 redhat login: LOGIN ON 3 BY student1
FROM redhat
The use of the grep command with the messages log file is illustrated below:
[root@redhat log]# grep SCSI messages
Aug 29 10:26:47 redhat kernel: (scsi0) Ultra SCSI host adapter> found at PCI 9/0
Aug 29 10:26:47 redhat kernel: (scsi0) Wide Channel, SCSI ID=7, 16/255 SCBs
Aug 29 10:26:47 redhat kernel: (scsi0) in the Adaptec SCSI BIOS by hitting CTRLA
when prompted
Aug 29 10:26:47 redhat kernel: scsi0 : Adaptec AHA274x/284x/294x (EISA/VLB/PCIFast
SCSI) 5.1.15/3.2.4
Aug 29 10:26:47 redhat kernel: Ultra SCSI host adapter>
Aug 29 10:26:47 redhat kernel: Type: DirectAccess
ANSI SCSI revision: 02
Aug 29 10:26:47 redhat kernel: SCSI device sda: hdwr sector= 512 bytes. Sectors= 17824700 [8703 MB] [8.7
GB]
C.R.Gould Section E Objective 3 Page 3 Linux Administration
Configure and Use System Log Files
The use of the tail command with the samba log file for machine rm113_10 is
illustrated below:
[root@redhat samba]# tail log.rm113_10
[2000/07/06 12:07:48, 1] smbd/service.c:close_cnum(514)
rm113_10 (172.16.32.119) closed connection to service netlogon
[2000/07/06 12:10:16, 1] smbd/service.c:close_cnum(514)
rm113_10 (172.16.32.119) closed connection to service common
[2000/07/06 12:10:16, 1] smbd/service.c:close_cnum(514)
rm113_10 (172.16.32.119) closed connection to service student10
[2000/07/06 13:31:48, 1] smbd/password.c:pass_check_smb(528)
smb_password_check failed. Invalid password given for user 'student10'
[2000/07/06 13:47:50, 1] smbd/password.c:pass_check_smb(528)
smb_password_check failed. Invalid password given for user 'alfredd'
Linux System Logging Utilities syslogd
The syslogd process logs selected kinds of system activity, such as error
messages from the news server and warnings printed by the kernel. Syslogd
runs as a daemon and is started in one of the rc files at boot time. Syslogd can
also log the activity of remote hosts over a network.
The syntax for the syslogd process is shown below:
syslogd option(s)
Common syslogd options are:
Option Explanation
f
CONFIG_FILE Specify an alternative CONFIG_FILE instead
of /etc/syslog.conf, which is the default and is read at startup.
m
INTERVAL The syslogd logs a mark timestamp regularly. The
default interval between two marked lines is 20
minutes. This INTERVAL can be changed with this option.
The interval is often set to to zero which turns this feature
off entirely.
Note: There are a number of additional options available with syslogd, but
these are concerned with remote logging and are beyond the scope of this
course.
C.R.Gould Section E Objective 3 Page 4 Linux Administration
Configure and Use System Log Files
The file /etc/syslog.conf is used to control where syslogd records its
information. Such a file might look like the following:
[root@redhat /root]# cat /etc/syslog.conf
# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.* /dev/console
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;news.none;authpriv.none /var/log/messages
# The authpriv file has restricted access.
authpriv.* /var/log/secure
# Log all the mail messages in one place.
mail.* /var/log/maillog
# Everybody gets emergency messages, plus log them on another
# machine.
*.emerg *
# Save mail and news errors of level err and higher in a
# special file.
uucp,news.crit /var/log/spooler
# Save boot messages also to boot.log
local7.* /var/log/boot.log
# INN
news.=crit /var/log/news/news.crit
news.=err /var/log/news/news.err
news.notice /var/log/news/news.notice
The first field of each line lists the kind of messages that should be logged, and
the second field indicates where they should be logged to. The first field is of
the format:
facility.level;facility.level....
Where facility is the system application or facility generating the message, and
level is the level of severity. e.g. facility can be mail for the mail process, kern
for the kernel, or authpriv for authentication programs such as login.
Listed in order of increasing severity, level can be : debug, info, notice,
warning, err, crit, alert or emerg.
C.R.Gould Section E Objective 3 Page 5 Linux Administration
Configure and Use System Log Files
In the above example we can see that:
• All levels (*) of kernel messages are logged to the screen.
• All messages of level info and higher (.info), apart from those generated by
mail, news and authentication (.none) are logged to /var/log messages.
• All levels of login authentication messages are logged to the file /var/log
secure. For security this file is read and write only by the root.
• All levels of mail messages are logged to the file /var/log/maillog.
• All messages of level emerg are sent to all users (* in the second field).
• All news messages of just level crit (=crit) are logged to the file news.err
By default all messages of the specified level and higher are logged. The = is
used to log only messages of the specified level and != can be used to exclude
messages of a particular level from being logged.
The messages logged by syslogd usually contain the date, an indication of what
process or facility delivered the message, and the message itself, all on a single
line. An example of this taken from the /var/log/secure file is illustrated below:
[root@redhat log]# tail -2 /var/log/secure
Aug 31 13:52:27 redhat login: LOGIN ON tty1 BY clive
Aug 31 13:53:11 redhat login: ROOT LOGIN ON tty1
Log files can be important in tacking down system problems. If a log file grows
too large you can delete it using rm. It will automatically be recreated by
syslogd.
Your distribution probably comes equipped with a running syslogd and a
properly configured /etc/syslog.conf file. However it is important to know
where your log files are and what programs they represent. For example, you
might want to log debug level messages from the kernel, which can be very
verbose, by adding an appropriate line in /etc/syslog.conf. After you have done
this you will need to send the syslogd process the -HUP signal to tell it to reread
its configuration file.
C.R.Gould Section E Objective 3 Page 6 Linux Administration
Configure and Use System Log Files
Rotates, Compresses, and Mails System Logs logrotate
The logrotate command is designed to ease administration of systems that
generate large numbers of log files. It allows automatic rotation, compression,
removal, and mailing of log files. Each log file may be handled daily, weekly,
monthly, or when it grows too large.
Normally, logrotate is run as a daily cron job and thus reads its configuration
file(s) daily. Any number of configuration files may be specified on the
command line. Later configuration files may override the options given in
earlier files, so the order in which the logrotate configuration files are listed in
is important.
An example of an /etc/logrotate.conf configuration file is illustrated below:
[root@redhat samba]# cat /etc/logrotate.conf
# rotate log files weekly
weekly
# keep 4 weeks worth of backlogs
rotate 4
# send errors to root
errors root
# create new (empty) log files after rotating old ones
create
# uncomment this if you want your log files compressed
#compress
# RPM packages drop log rotation information into this directory
include /etc/logrotate.d
# no packages own lastlog or wtmp -- we'll rotate them here
/var/log/wtmp {
monthly
create 0664 root utmp
rotate 1
/var/log/lastlog {
monthly
rotate 1
# system-specific logs may be configured here
C.R.Gould Section E Objective 3 Page 7 Linux Administration
Configure and Use System Log Files
Both global options, which apply to all log files, and local options, which apply
to specific log files, can be set in the /etc/logrotate.conf file. Any local options
override global ones. Directives used in the above logrotate.conf file are
explained in the table below:
Directive Explanation
weekly This global option ensures that all log files are rotated
once a week.
rotate COUNT
rotate 4
This global option ensures that all logs are rotated
COUNT times before being removed or mailed. If
count is 0, old versions are removed rather then rotated.
errors ADDRESS
errors root
This global option ensures that any errors that occur
during log file processing are mailed to the given
ADDRESS
create MODE OWNER GROUP
create
This global option controls the permissions, owner and
group which will be applied to all new log files. If these
are omitted the log file will assume the attributes of the
original log file.
compress
#compress
If this global option is enabled it causes all old versions
of log files to be compressed with gzip.
include
include /etc/logrotate.d
Includes additional logrotate configuration files
containing local settings. This is commonly used to
specify logrotate directives for individual applications.
The options associated with the sections of the file dealing with /var/log/wtmp
and /var/log/lastlog are local rather than global. Both of these are rotated
monthly rather than weekly and only one old log file is kept.
Below you can see a couple of log files maintained on a typical system:
-rw------- 1 root root 828 Aug 31 15:42 secure
-rw------- 1 root root 0 Aug 20 04:02 secure.1
-rw------- 1 root root 299 Aug 18 17:47 secure.2
-rw------- 1 root root 253 Aug 11 09:29 secure.3
-rw------- 1 root root 266 Aug 2 10:15 secure.4
-rw-rw-r-- 1 root utmp 1152 Sep 1 10:16 wtmp
-rw-rw-r-- 1 root utmp 246144 Aug 31 16:03 wtmp.1
You can see that the secure log file is rotated four times, on a weekly basis,
before being removed, whereas the wtmp log file is only rotated once, on a
monthly basis, before removal.
C.R.Gould Section E Objective 3 Page 8 Linux Administration
Configure and Use System Log Files
Archiving Logs - Prerotate and Postrotate
You need to decide how long you want to keep old log files for. In some
instances, such as the log files for the Apache server, you might want to keep
six months worth of log files, or your organisation might want to keep records
of when users log in or log out for several years.
One way to keep logs for long periods of time would just be to increase the
count. However this could easily fill up your disk, especially if you want to
keep several years worth of logs. This can be solved by moving log files to
nearline or offline storage.
When logrotate rotates a particular log it automatically discards the oldest log
and renames all the existing log files. By placing lines containing appropriate
shell command(s) between the prerotate and endscript directives in your
logrotate.conf configuration file, you can move your oldest log to somewhere
safe before the logs are rotated and the log is overwritten and it contents lost.
By placing a shell command(s) between the postrotate and endscript directives
in your logrotate.conf configuration file, you can execute the shell command
after the logs have been rotated. This is typically used to tell a process, such as
syslogd or httpd, to re-read its configuration file after the logs have been
rotated. An example of use of postrotate is illustrated below:
[clive@redhat clive]$ cd /etc/logrotate.d
[clive@redhat logrotate.d]$ cat cron
/var/log/cron {
missingok #Go on to next log file is this one is empty
notifempty #Do not compress an empty log file
postrotate
/usr/bin/killall -HUP crond
endscript
C.R.Gould Section E Objective 3 Page 9 Linux Administration

Linux Commands

1.What command should you use to check your filesystem?
Answer: fsck
2. The fsck command is used to check the integrity of the filesystem on your disk.
3.You want to print out a text file called vacations however the lines are of varying length. What text filter could you use to even out the length of the lines?
Answer: fmt
4.The fmt text utility attempts to make all the lines the same lenght by joining or splitting lines.
You need to locate a file called salesdata that one of your user’s created in his home directory but you do not know which one. How could you use the find command to locate this file?
Answer: find /home -name salesdata
When using the find command to locate a file by name you must specify the starting place in the directory heirarchy and the -name option to specify the file to search for.
What command would you type to use the cpio to create a backup called backup.cpio of all the users’ home directories?
Answer: find /home | cpio -o > backup.cpio
The find command is used to create a list of the files and directories contained in home. This list is then piped to the cpio utility as a list of files to include and the output is saved to a file called backup.cpio.
You want to create a compressed backup of the users’ home directories so you issue the command gzip /home/* backup.gz but it fails. The reason that it failed is that gzip will only compress one _______ at a time.
Answer: file
The gzip utility cannot compress multiple files in a single operation.
You have three files in the /home/ben/memos directory called letters, tom, betty. How could you determine each file’s type by issuing only one command?
Answer: file letters tom betty
The file utility will display the file’s type for each filename that is passed as an argument.
In order to display the last five commands you have entered using the fc command, you would type ___________.
Answer: fc -5
The fc command can be used to edit or rerun commands you have previously entered. To specify the number of commands to list, use -n.
Each command has two types of output. There are standard output and standard __________.
Answer: error
By default, each command sends its result as standard output and any error messages as standard error.
What can you type at a command line to determine which shell you are using?
Answer: echo $SHELL
The name and path to the shell you are using is saved to the SHELL environment variable. You can then use the echo command to print out the value of any variable by preceding the variable’s name with $. Therefore,
typing echo $SHELL will display the name of your shell.
What type of local file server can you use to provide the distribution installation materials to the new machine during a network installation?
A) Inetd
B) FSSTND
C) DNS
D) NNTP
E) NFS
Answer: E – You can use an NFS server to provide the distribution installation materials to the machine on which you are performing the installation. Answers a, b, c, and d are all valid items but none of them are file servers. Inetd is the superdaemon which controls all intermittently used network services. The FSSTND is the Linux File System Standard. DNS provides domain name resolution, and NNTP is the transfer protocol for usenet news.
What would you type to send the last 20 lines of a text file to STDIN?
A) end -n 20 filename
B) last -n 20 filename
C) head -20 filename
D) end -20 filename
E) tail -20 filename
Answer: E – Use the command tail -20 filename to see the last 20 lines of a file. The answers for a and d both point to an invalid command. The answer for b points to a valid command. Typing this answer in with a valid file name will even give you some output. However, the last command tells you who is logged in, it does not actually list the contents of any file named in the command. The answer for c, the head command, is used to look at the beginning of a file, not the end.
Which command works in almost all distributions to create a boot disk?
A) mkboot
B) make bootdsk
C) make boot
D) mkbootdsk
E) mkbootdisk
Answer: E – The mkbootdisk command creates a boot disk. Answers b and c are incorrect. The make package is used to compile software, not create boot disks. Answers a and d point to invalid commands.
Which command do you use to change runlevels?
A) initlevel
B) runlevel
C) level
D) run
E) init
Answer: E – The command used to change runlevels is init. Answers a, c, and d point to invalid commands. Answer b is a valid command, but does not set the current runlevel. The runlevel command displays the current runlevel, and the one that was used directly before entering this one.
You have a new, empty hard drive that you will use for Linux. What is the first step you use.
Choose one:
a. Create an extended partition to be used for data.
b. Format the hard drive to use the ext2 filesystem.
c. Create a swap partition of type 82.
d. Create a primary partition using fdisk.
Answer: d
You must always first create a primary partition. Operating systems, including Linux, can only be booted from a primary partition.
You have configured logrotate to rotate your logs weekly and keep them for eight weeks. You are running our of disk space. What should you do?
Choose one:
a. Quit using logrotate and manually save old logs to another location.
b. Reconfigure logrotate to only save logs for four weeks.
c. Configure logrotate to save old files to another location.
d. Use the prerotate command to run a script to move the older logs to another location.
Answer: d
You can use the prerotate command to run a script before logs are rotated. You could have this script move the older logs to another location before rotation occurs.
If you type the command cat dog &> cat what would you see on your display?
Choose one:
a. Any error messages only.
b. The contents of the file dog.
c. The contents of the file dog and any error messages.
d. Nothing as all output is saved to the file cat.
Answer: d
When you use &> for redirection, it redirects both the standard output and standard error. The output would be saved to the file cat.
You have a directory with the following permissions
drw-rw–w- 1 root admin 7202 Sep 17 9:10 administration
and need to give everyone except root read only access to it. Which of the following commands will accomplish this?
Choose one:
a. chmod uo=r administration
b. chmod ug+r administration
c. chmod uo+r administration
d. chmod ug=r administration
Answer: d
When using symbols, the equal sign explicitly sets permissions and revokes any pre-existing permissions.
You want to know how much space is being occupied by your user’s home directories. Which of the following will provide you with this information?
Choose one:
a. du -l /home
b. du -b /home
c. du -m /home
d. du -c /home
Answer: d
Using the -c option with the du command will show the grand total of used space for the designated directory.
You have entered the following cronjob. When will it run? 15 * * * 1,3,5 myscript
Choose one:
a. at 15 minutes after every hour on the 1st, 3rd and 5th of each month.
b. at 1:15 am, 3:15 am, and 5:15 am every day
c. at 3:00 pm on the 1st, 3rd, and 5th of each month
d. at 15 minutes after every hour every Monday, Wednesday, and Friday
Answer: d
This would run at 15 minutes after the hour on every Monday, Wednesday, and Friday of every month no matter what the date.
You need to see the last fifteen lines of the files dog, cat and
horse. What command should you use?
Answer: tail -15 dog cat horse
The tail utility displays the end of a file. The -15 tells tail to
display the last fifteen lines of each specified file.
Who owns the data dictionary?
Answer: The SYS user owns the data dictionary. The SYS and SYSTEM
users are created when the database is created.
You routinely compress old log files. You now need to examine a log
from two months ago. In order to view its contents without first
having to decompress it, use the _________ utility.
Answer: zcat
The zcat utility allows you to examine the contents of a compressed
file much the same way that cat displays a file.
You suspect that you have two commands with the same name as the
command is not producing the expected results. What command can you
use to determine the location of the command being run?
Answer: which
The which command searches your path until it finds a command that
matches the command you are looking for and displays its full path.
You locate a command in the /bin directory but do not know what it
does. What command can you use to determine its purpose.
Answer: whatis
The whatis command displays a summary line from the man page for the
specified command.
You wish to create a link to the /data directory in bob’s home
directory so you issue the command ln /data /home/bob/datalink but the
command fails. What option should you use in this command line to be
successful.
Answer: Use the -F option
In order to create a link to a directory you must use the -F option.
When you issue the command ls -l, the first character of the
resulting display represents the file’s ___________.
Answer: type
The first character of the permission block designates the type of
file that is being displayed.
What utility can you use to show a dynamic listing of running processes?
Answer: top
The top utility shows a listing of all running processes that is
dynamically updated.
Where is standard output usually directed?
Answer: to the screen or display
By default, your shell directs standard output to your screen or display.
You want to create a compressed backup of the users’ home
directories. What utility should you use?
Answer: tar
You can use the z modifier with tar to compress your archive at the
same time as creating it.
You wish to restore the file memo.ben which was backed up in the
tarfile MyBackup.tar. What command should you type?
Answer: tar xf MyBackup.tar memo.ben
This command uses the x switch to extract a file. Here the file
memo.ben will be restored from the tarfile MyBackup.tar.
You need to view the contents of the tarfile called MyBackup.tar.
What command would you use?
Answer: tar tf MyBackup.tar
The t switch tells tar to display the contents and the f modifier
specifies which file to examine.
What daemon is responsible for tracking events on your system?
Answer: syslogd
The syslogd daemon is responsible for tracking system information and
saving it to specified log files.
You have a file called phonenos that is almost 4,000 lines long.
What text filter can you use to split it into four pieces each 1,000
lines long?
Answer: split
The split text filter will divide files into equally sized pieces. The
default length of each piece is 1,000 lines.
You would like to temporarily change your command line editor to be
vi. What command should you type to change it?
Answer: set -o vi
The set command is used to assign environment variables. In this case,
you are instructing your shell to assign vi as your command line
editor. However, once you log off and log back in you will return to
the previously defined command line editor.
What account is created when you install Linux?
Answer: root
Whenever you install Linux, only one user account is created. This is
the superuser account also known as root.
What command should you use to check the number of files and disk
space used and each user’s defined quotas?
Answer: repquota
The repquota command is used to get a report on the status of the
quotas you have set including the amount of allocated space and amount
of used space.
In order to run fsck on the root partition, the root partition must
be mounted as ___________.
Answer: readonly
You cannot run fsck on a partition that is mounted as read-write.
In order to improve your system’s security you decide to implement
shadow passwords. What command should you use?
Answer: pwconv
The pwconv command creates the file /etc/shadow and changes all
passwords to ‘x’ in the /etc/passwd file.
Bob Armstrong, who has a username of boba, calls to tell you he
forgot his password. What command should you use to reset his command?
Answer: passwd boba
The passwd command is used to change your password. If you do not
specify a username, your password will be changed.
When you look at the /etc/group file you see the group kmem listed.
Since it does not own any files and no one is using it as a default
group, can you delete this group?
Answer: no
The kmem group manages direct access to kernel memory and is necessary
for your system’s health.
What text filter can you use to display a multi-page file and place
numbers at the beginning of each line.
DirContents
Using the > will redirect the output of the ls /etc command to the
file DirContents.
What file defines the levels of messages written to system log files?
Answer: kernel.h
To determine the various levels of messages that are defined on your
system, examine the kernel.h file.
You have two files each ten lines long. What text filter could you
use to combine the two files so that each line of the output contains
the corresponding line from each file?
Answer: join
The join text filter will display one line for each pair of input
lines from two files.
You have two files in two different directories with the same
inode. What type of link is involved?
“,1] ); //–>
Answer: nl
The nl text filter will divide a file into logical pages and number each line.
Question The top utility can be used to change the priority of a
running process? Another utility that can also be used to change
priority is ___________?
Answer: nice
Both the top and nice utilities provide the capability to change the
priority of a running process.
In order to apply a filesystem to your new partitions you must
format them. What command would you use to create the ext2 filesystem?
Answer: mke2fs
The mke2fs command creates the new filesystem on your partition.
What command should you type to see all the files with an
extension of ‘mem’ listed in reverse alphabetical order in the
/home/ben/memos directory.
Answer: ls -r /home/ben/memos/*.mem
The -c option used with ls results in the files being listed in
chronological order. You can use wildcards with the ls command to
specify a pattern of filenames.
In order to create a file called DirContents containing the
contents of the /etc directory you would type ____________.
Answer: ls /etc > DirContents
Using the > will redirect the output of the ls /etc command to the
file DirContents.
What file defines the levels of messages written to system log files?
Answer: kernel.h
To determine the various levels of messages that are defined on your
system, examine the kernel.h file.
You have two files each ten lines long. What text filter could you
use to combine the two files so that each line of the output contains
the corresponding line from each file?
Answer: join
The join text filter will display one line for each pair of input
lines from two files.
You have two files in two different directories with the same
inode. What type of link is involved?
/interview-questions/type.asp?iType\u003d83&offset\u003d20
“,0] ); D(["ma",[1,"
Linux JOB Interview questions.doc
61K View as HTML Scanning for viruses...

","10b484103aee0819"] ] ); D(["ce"]); //–>
Answer: hard
Hard links all have the same inode number, unlike symbolic links.
What command is used to remove the password assigned to a group?
Answer: gpasswd -r
The gpasswd command is used to change the password assigned to a
group. Use the -r option to remove the password from the group.



mysql databases backup script on cpanel servers
July 23, 2008
Daily mysql backup with 7 days retention period.
root@server1 [~]# cat /scripts/mbak.sh
#!/bin/bash
Time=`date “+%Y.%m.%d-%A”`
baksrc=/var/lib/mysql
bakdst=/backup/mysqlbackup
dumpdb=/usr/bin/mysqldump
yum -y dialog nmap ncurses
mkdir -p $bakdst/$Time
{ for I in 10 20 30 40 50 60 70 80 90 100 ; do
echo $I
sleep 1
done
echo; } | dialog –gauge ” Starting to backup all databases ” 6 70 0
ls -lhd $baksrc/*_* | awk {’print $9}’ | cut -d/ -f5 | grep -v ib_* > /root/mysqldd-list
for db in `cat /root/mysqldd-list` ;
do
{ for I in 10 50 100 ; do
echo $I
sleep 1
done
echo; } | dialog –gauge ” Creating backup of $db ” 6 70 0
$dumpdb $db > $bakdst/$Time/$db.sql 2> $bakdst/$Time/error.log
{ for I in 10 50 100 ; do
echo $I
sleep 1
done
echo; } | dialog –gauge ” Database : $db backup completed ” 6 70 0
echo ” …………….. $db backed up on `date “+%Y.%m.%d.%T-%A”` …………………………
.. “
sleep 3
echo ” …………….. working on the next db backup ………………………”
sleep 3
echo ” ……………… Taking some rest before that ……………………….”
sleep 3
done
$dumpdb mysql > $bakdst/$Time/mysql.sql 2> $bakdst/$Time/error.log
echo ” All Databases backup up successfully to folder $bakdst/$Time/ “
echo ” Check for any errors at : $bakdst/$Time/error.log “
wall ” All Databases backup up successfully to folder $bakdst/$Time/ “
wall ” Check for any errors at : $bakdst/$Time/error.log or the database backup “
echo ” removing older backups”
sleep 2
echo ” hold on, let me work for 3 to 10 mins”
/usr/bin/find $bakdst -type d -maxdepth 1 -mtime +7 -exec rm -fr {} \;
echo ” …………….. Finishing up the entire process “
sleep 3
echo ” …………….. Successfully Done ……………………….”
wall ” ***** Note Again **** Check for any errors at : $bakdst/$Time/error.log or the database backup “
exit 0
root@server1 [~]#
root@server1 [~]# chmod +x /scripts/mbak.sh ( make the script executable )
root@server1 [~]# /bin/sh /scripts/mbak.sh (run script to make database backups )
Posted in Backup, Linux Administration, Linux:- Tips & Tricks, Mysql | Leave a Comment »

Prevent non-root users from logging
May 9, 2007
Prevent non-root users from logging
Imagine that for some reason (i.e. maintenance tasks) you want to prevent non-root users from logging into the system. The next tip is a very simple way to achieve this goal.
If a file called /etc/nologin exists login will disable the begin of a session in this system. If you put some text into the file, users will be shown this text and their login attempts will be refused.
vi /etc/nologin
Server under maintenance. No access allowed at this moment.
Posted in Backup, Linux Administration, Linux General, Linux Security, Linux:- Tips & Tricks, Tuning Linux | Leave a Comment »

How to install CVS
July 21, 2006
Installation:
Compile it from source
Download from ftp://ftp.cvshome.org/pub/
$ gunzip cvs-x.x.tar.gz $ tar -xvf cvs-x.x.tar $ cd cvs-x.x/ $ ./configure $ ./make $ su -l (enter password) #switch user to root # ./make install
check to make certain CVS is installed:
$ which cvs /usr/bin/cvs
Create the cvsroot for a user and master repository:
You can choose to place your cvsroot almost wherever you want. I’ve historically placed it in /home/ to make regular backups easier. You might have your own reasons to place it where you want.
$ su -l # adduser cvs # rm -rf /home/cvs # mkdir /home/cvs
It can be convenient to enable user permissions by creating a ‘cvs’ group in /etc/group, and then adding various users to that group. While adding permissions to the cvsroot directories to the group ‘cvs’.
Set a CVSROOT:
You need to set the environment variables, so that CVS knows where to find the root library.
$ export CVSROOT=/home/cvs/ #for bash users > setenv CVSROOT '/home/cvs' #for csh, or tcsh users # this can also be added to /etc/profile for system-wide access
This can also be set automatically upon login by adding a line to your ~/.bashrc file (or whichever stores your shell environment variables).
Check to make sure that it’s set properly:
$ echo $CVSROOT /home/cvs/
As you may have noticed, the CVSROOT variable is set by the client, and not the server. This enables you to easily use multiple CVSROOTs, based on permissions, partitioning, etc.
Remote access:
The CVS slient can also be configured to use a cvsroot on a remote server, and to tunnel through SSH. The remote client needs to have these entered at the command line, or read in from the .bashrc file:
export CVSROOT="user@host.domain.tld:/pathto/cvsroot" export CVS_RSH="/usr/bin/ssh"
All commands should operate as usual, but each will require a password in order to proceed.
Bad CVSROOT error:
A common, and frustrating error to run into while using this method, because it’s not well documented.
cvs checkout: is set for a remote access method but your cvs checkout: CVS executable doesn't support it cvs [checkout aborted]: Bad CVSROOT.
Your problem most likely exists with the client version of the cvs binary. It’s probably version 1.11.1 or previous, upgrading to 1.11.2 should take care of this.
Posted in Backup, Linux Administration, Linux General | Leave a Comment »

Backup: Using Rsync and SSH
June 10, 2006
Using Rsync and SSH
Keys, Validating, and Automation
This document covers using cron, ssh, and rsync to backup files over a local network or the Internet. Part of my goal is to ensure no user intervention is required when the computer is restarted (for passwords, keys, or key managers).
I like to backup some logging, mail, and configuration information sometimes on hosts across the network and Internet, and here is a way I have found to do it. You’ll need these packages installed:
• rsync
• openssh
• cron (or vixie-cron)
Please note these instructions may be specific to Red Hat Linux versions 7.3, 9, and Fedora Core 3, but I hope they won’t be too hard to adapt to almost any *NIX type OS. The man pages for ’ssh’ and ‘rsync’ should be helpful to you if you need to change some things (use the “man ssh” and “man rsync” commands).
First, I’ll define some variables. In my explanation, I will be synchronizing files (copying only new or changed files) one way, and I will be starting this process from the host I want to copy things to. In other words, I will be syncing files from /remote/dir/ on remotehost, as remoteuser, to /this/dir/ on thishost, as thisuser.
I want to make sure that ‘rsync’ over ’ssh’ works at all before I begin to automate the process, so I test it first as thisuser:
$ rsync -avz -e ssh remoteuser@remotehost:/remote/dir /this/dir/
and type in remoteuser@remotehost’s password when prompted. I do need to make sure that remoteuser has read permissions to /remote/dir/ on remotehost, and that thisuser has write permissions to /this/dir/ on thishost. Also, ‘rsync’ and ’ssh’ should be in thisuser’s path (use “which ssh” and “which rsync”), ‘rsync’ should be in remoteuser’s path, and ’sshd’ should be running on remotehost.
Configuring thishost
If that all worked out, or I eventually made it work, I am ready for the next step. I need to generate a private/public pair of keys to allow a ’ssh’ connection without asking for a password. This may sound dangerous, and it is, but it is better than storing a user password (or key password) as clear text in the script. And I can put some limitations on what connections made with this key can do. Anyway, I generate the key I will use on thishost (as thisuser):
$ ssh-keygen -t dsa -b 2048 -f /home/thisuser/cron/thishost-rsync-key
Generating public/private dsa key pair.
Enter passphrase (empty for no passphrase): [press enter here]
Enter same passphrase again: [press enter here]
Your identification has been saved in /home/thisuser/cron/thishost-rsync-key.
Your public key has been saved in /home/thisuser/cron/thishost-rsync-key.pub.
The key fingerprint is:
2e:28:d9:ec:85:21:e7:ff:73:df:2e:07:78:f0:d0:a0 thisuser@thishost
and now we have a key with no password in the two files mentioned above [1]. Make sure that no other unauthorized user can read the private key file (the one without the ‘.pub’ extension).
This key serves no purpose until we put the public portion into the ‘authorized_keys’ file [2] on remotehost, specifically the one for remoteuser:
/home/remoteuser/.ssh/authorized_keys
I use scp to get the file over to remotehost:
$ scp /home/thisuser/cron/thishost-rsync-key.pub remoteuser@remotehost:/home/remoteuser/
and then I can prepare things on remotehost.
Configuring remotehost
I ’ssh’ over to remotehost:
$ ssh remoteuser@remotehost remoteuser@remotehost’s password: [type correct password here] $ echo I am now $USER at $HOSTNAME I am now remoteuser at remotehost
to do some work.
I need to make sure I have the directory and files I need to authorize connections with this key [3]:
$ if [ ! -d .ssh ]; then mkdir .ssh ; chmod 700 .ssh ; fi
$ mv thishost-rsync-key.pub .ssh/
$ cd .ssh/
$ if [ ! -f authorized_keys ]; then touch authorized_keys ; chmod 600 authorized_keys ; fi
$ cat thishost-rsync-key.pub >> authorized_keys
Now the key can be used to make connections to this host, but these connections can be from anywhere (that the ssh daemon on remotehost allows connections from) and they can do anything (that remoteuser can do), and I don’t want that. I edit the ‘authorized_keys’ file (with vi) and modify the line with ‘thishost-rsync-key.pub’ information on it. I will only be adding a few things in front of what is already there, changing the line from this:
ssh-dss AAAAB3NzaC1kc3MAAAEBAKYJenaYvMG3nHwWxKwlWLjHb77CT2hXwmC8Ap+fG8wjlaY/9t4u
A+2qx9JNorgdrWKhHSKHokFFlWRj+qk3q+lGHS+hsXuvta44W0yD0y0sW62wrEVegz+JVmntxeYc0nDz
5tVGfZe6ydlgomzj1bhfdpYe+BAwop8L+EMqKLS4iSacNjoPlHsmqHMnbibn3tBqJEq2QJjEPaiYj1iP
5IaCuYBhuTKQGa+oyH3mXEif5CKdsIKBj46B0tCy0/GC7oWcUN92QdLrUyTeRJZsTWsxKpRbMliD2pBh
4oyX/aXEf8+HZBrO5vQjDBCfTFQA+35Xrd3eTVEjkGkncI0SAeUAAAAVAMZSASmQ9Pi38mdm6oiVXD55
Kk2rAAABAE/bA402VuCsOLg9YS0NKxugT+o4UuIjyl6b2/cMmBVWO39lWAjcsKK/zEdJbrOdt/sKsxIK
1/ZIvtl92DLlMhci5c4tBjCODey4yjLhApjWgvX9D5OPp89qhah4zu509uNX7uH58Zw/+m6ZOLHN28mV
5KLUl7FTL2KZ583KrcWkUA0Id4ptUa9CAkcqn/gWkHMptgVwaZKlqZ+QtEa0V2IwUDWS097p3SlLvozw
46+ucWxwTJttCHLzUmNN7w1cIv0w/OHh5IGh+wWjV9pbO0VT3/r2jxkzqksKOYAb5CYzSNRyEwp+NIKr
Y+aJz7myu4Unn9de4cYsuXoAB6FQ5I8AAAEBAJSmDndXJCm7G66qdu3ElsLT0Jlz/es9F27r+xrg5pZ5
GjfBCRvHNo2DF4YW9MKdUQiv+ILMY8OISduTeu32nyA7dwx7z5M8b+DtasRAa1U03EfpvRQps6ovu79m
bt1OE8LS9ql8trx8qyIpYmJxmzIdBQ+kzkY+9ZlaXsaU0Ssuda7xPrX4405CbnKcpvM6q6okMP86Ejjn
75Cfzhv65hJkCjbiF7FZxosCRIuYbhEEKu2Z9Dgh+ZbsZ+9FETZVzKBs4fySA6dIw6zmGINd+KY6umMW
yJNej2Sia70fu3XLHj2yBgN5cy8arlZ80q1Mcy763RjYGkR/FkLJ611HWIA= thisuser@thishost
to this [4]:
from=”10.1.1.1″,command=”/home/remoteuser/cron/validate-rsync” ssh-dss AAAAB3Nza
C1kc3MAAAEBAKYJenaYvMG3nHwWxKwlWLjHb77CT2hXwmC8Ap+fG8wjlaY/9t4uA+2qx9JNorgdrWKhH
SKHokFFlWRj+qk3q+lGHS+hsXuvta44W0yD0y0sW62wrEVegz+JVmntxeYc0nDz5tVGfZe6ydlgomzj1
bhfdpYe+BAwop8L+EMqKLS4iSacNjoPlHsmqHMnbibn3tBqJEq2QJjEPaiYj1iP5IaCuYBhuTKQGa+oy
H3mXEif5CKdsIKBj46B0tCy0/GC7oWcUN92QdLrUyTeRJZsTWsxKpRbMliD2pBh4oyX/aXEf8+HZBrO5
vQjDBCfTFQA+35Xrd3eTVEjkGkncI0SAeUAAAAVAMZSASmQ9Pi38mdm6oiVXD55Kk2rAAABAE/bA402V
uCsOLg9YS0NKxugT+o4UuIjyl6b2/cMmBVWO39lWAjcsKK/zEdJbrOdt/sKsxIK1/ZIvtl92DLlMhci5
c4tBjCODey4yjLhApjWgvX9D5OPp89qhah4zu509uNX7uH58Zw/+m6ZOLHN28mV5KLUl7FTL2KZ583Kr
cWkUA0Id4ptUa9CAkcqn/gWkHMptgVwaZKlqZ+QtEa0V2IwUDWS097p3SlLvozw46+ucWxwTJttCHLzU
mNN7w1cIv0w/OHh5IGh+wWjV9pbO0VT3/r2jxkzqksKOYAb5CYzSNRyEwp+NIKrY+aJz7myu4Unn9de4
cYsuXoAB6FQ5I8AAAEBAJSmDndXJCm7G66qdu3ElsLT0Jlz/es9F27r+xrg5pZ5GjfBCRvHNo2DF4YW9
MKdUQiv+ILMY8OISduTeu32nyA7dwx7z5M8b+DtasRAa1U03EfpvRQps6ovu79mbt1OE8LS9ql8trx8q
yIpYmJxmzIdBQ+kzkY+9ZlaXsaU0Ssuda7xPrX4405CbnKcpvM6q6okMP86Ejjn75Cfzhv65hJkCjbiF
7FZxosCRIuYbhEEKu2Z9Dgh+ZbsZ+9FETZVzKBs4fySA6dIw6zmGINd+KY6umMWyJNej2Sia70fu3XLH
j2yBgN5cy8arlZ80q1Mcy763RjYGkR/FkLJ611HWIA= thisuser@thishost
where “10.1.1.1″ is the IP (version 4 [5]) address of thishost, and “/home/remoteuser/cron/validate-rsync” is a script that looks something like this [6] [7]:
#!/bin/sh
case “$SSH_ORIGINAL_COMMAND” in
*\&*)
echo “Rejected”
;;
*\(*)
echo “Rejected”
;;
*\{*)
echo “Rejected”
;;
*\;*)
echo “Rejected”
;;
*\<*)
echo “Rejected”
;;
*\`*)
echo “Rejected”
;;
rsync\ –server*)
$SSH_ORIGINAL_COMMAND
;;
*)
echo “Rejected”
;;
esac
If thishost has a variable address, or shares it’s address (via NAT or something similar) with hosts you do not trust, omit the ‘from=”10.1.1.1″,’ part of the line (including the comma), but leave the ‘command’ portion. This way, only the ‘rsync’ will be possible from connections using this key. Make certain that the ‘validate-rsync’ script is executable by remoteuser on remotehost and test it.
PLEASE NOTE: The private key, though now somewhat limited in what it can do (and hopefully where it can be done from), allows the possessor to copy any file from remotehost that remoteuser has access to. This is dangerous, and I should take whatever precautions I deem necessary to maintain the security and secrecy of this key. Some possibilities would be ensuring proper file permissions are assigned, consider using a key caching daemon, and consider if I really need this process automated verses the risk.
ALSO NOTE: Another security detail to consider is the SSH daemon configuration on remotehost. This example focuses on a user (remoteuser) who is not root. I recommend not using root as the remote user because root has access to every file on remotehost. That capability alone is very dangerous, and the penalties for a mistake or misconfiguration can be far steeper than those for a ‘normal’ user. If you do not use root as your remote user (ever), and you make security decisions for remotehost, I recommend either:
PermitRootLogin no
or:
PermitRootLogin forced-commands-only
be included in the ‘/etc/ssh/sshd_config’ file on remotehost. These are global settings, not just related to this connection, so be sure you do not need the capability these configuration options prohibit. [8].
Troubleshooting
Now that I have the key with no password in place and configured, I need to test it out before putting it in a cron job (which has it’s own small set of baggage). I exit from the ssh session to remotehost and try:
$ rsync -avz -e “ssh -i /home/thisuser/cron/thishost-rsync-key” remoteuser@remotehost:/remote/dir /this/dir/
If this doesn’t work, I will take off the “command” restriction on the key and try again. If it asks for a password, I will check permissions on the private key file (on thishost) and on ‘authorized_keys’ and (on remotehost). If some cryptic ‘rsync’ protocol error occurs mentioning the ‘validate-rsync’ script, I will make sure the permissions on ‘validate-rsync’ (on remotehost) allow remoteuser to read and execute it. Hopefully, it will always just work flawlessly so I never have to extend the troubleshooting information listed here [9].
Cron Job Setup
The last step is the cron script. I use something like this:
#!/bin/sh
RSYNC=/usr/bin/rsync
SSH=/usr/bin/ssh
KEY=/home/thisuser/cron/thishost-rsync-key
RUSER=remoteuser
RHOST=remotehost
RPATH=/remote/dir
LPATH=/this/dir/
$RSYNC -az -e “$SSH -i $KEY” $RUSER@$RHOST:$RPATH $LPATH
because it is easy to modify the bits and pieces of the command line for different hosts and paths. I will usually call it something like ‘rsync-remotehost-backups’ if it contains backups. I test the script too, just in case I carefully inserted an error somewhere.
When I get the script running successfully, I use ‘crontab -e’ to insert a line for this new cron job:
0 5 * * * /home/thisuser/cron/rsync-remotehost-backups
for a daily 5 AM sync, or:
0 5 * * 5 /home/thisuser/cron/rsync-remotehost-backups
for a weekly (5 AM on Fridays). Monthly and yearly ones are rarer for me, so look at “man crontab” or here for advice on those.
Alright! Except for the everyday “keeping up with patches” thing, the insidious “hidden configuration flaws” part, and the unforgettable “total failure of human logic” set of problems, my work here is done. Enjoy!
Notes:
[1] If remotehost only has SSH1 installed, you may need to use another key type. Instead of ‘dsa’ you will need to use ‘rsa1′. You can use ‘rsa’ instead of ‘dsa’, but it will still only be useful for a SSH2 connection. SSH2 connections are more secure than SSH1 connections, but you’ll have to look elsewhere for the details on that (”man ssh-keygen” and Google).
[2] Some configurations use the file ‘authorized_keys2′ instead of ‘authorized_keys’. Look for “AuthorizedKeysFile” in ‘/etc/ssh/sshd_config’.
[3] If you use a shell other than ‘bash’ (or other bourne compatible shell), like ‘csh’ or ‘tcsh’, the commands listed may not work. Before executing them, start up a ‘bash’ (or ’sh’, or ‘ksh’, or ‘zsh’) shell using the ‘bash’ (or ’sh’, or ‘ksh’, or ‘zsh’) command. After completing the commands, you will have to exit the ‘bash’ shell, and then exit the shell your host spawns normally.
[4] Remember not to insert any newlines into the “authorized_keys” file. The key information, and the inserted commands associated with that key, should all be on one line. The key you generate (the nonsensical stuff on the key line) will be different from the one here.
[5] I have seen one host ignore a properly presented IPv4 address and instead see the incoming connection as a IPv6-ish sort of address (”::fff:10.1.1.1″). I found the address in ‘/var/log/messages’ on a Fedora Core 3 Linux host, and it does allow connections from that host with the IPv6-ish version in the ‘authorized_keys’ file.
[6] Another option for validation (and more) is the perl script located here: http://www.inwap.com/mybin/miscunix/?rrsync, though it is more complicated.
[7] By the time the ‘validate-rsync’ script runs, a SSH connection has been made with the SSH key you associated with this command in the ‘authorized_keys’ file. The script basically tries to return ‘Rejected’ to anything other than a command that starts with “rsync –server”, which is what rsync over ssh does on the other end of the connection (I found this out by running ‘ps auxw | grep rsync’ on the remote end of the connection after initialing a long running rsync job). The first six ‘Rejected’ lines try to elimate shell symbols that will allow a person to execute more than one command within a session (for example, a short rsync and some naughty command you don’t want running remotely).
[8] “PermitRootLogin no” does what it says: the root user is not allowed to login via SSH. “PermitRootLogin forced-commands-only” requires that all connections, via SSH as root, need to use public key authentication (with a key like ‘thishost-rsync-key.pub’) and that a command be associated with that key (like ‘validate-rsync’). For more explanation, use the “man sshd_config” command.
[9] Not likely.
Links:
• Rsync
• Rsync Tutorial
• OpenSSH
• SSH, The Definitive Guide
• OpenSSH Key Management, Part 1 Part 2 Part 3
• Rsync + Stunnel 4.x (for another way to secure rsync)
• Using Rsnapshot and SSH
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license should be available here and here.
The current copy of this document should be available here.




iptables string match to drop malicious urls
August 5, 2008
iptables string match to drop malicious urls
==================================
Usually modsecurity rules can help filter many malicious url attack patterns combined with apache on apache port (http|https). But what if a malicious attack using a vulnerable url pattern, that exposes or tries to break into your system is coming onto another port?
This is where iptables string match comes in handy.
/usr/local/sbin/iptables -I INPUT -p tcp -s 0.0.0.0/0 -m string –string “download?file=%2e%2e” –algo bm -j DROP
[root@server ~]# iptables -L -v | grep STR
73 49908 DROP tcp – any any anywhere anywhere STRING match “download?file=%2e%2e” ALGO name bm TO 65535
[root@server ~]#
The above iptable rule will block any url that has the string “download?file=%2e%2e” on any port on your server.
Note: your iptables binary path may be /sbin/iptables
Say http://yourserverIP:9132/blah/download?file=%2e%2e
Posted in Advanced Commands, Linux Administration, Linux General, Linux Security, Linux:- Tips & Tricks, Tuning Linux, iptables | 2 Comments »

How do I Drop or block attackers IP with null routes?
July 4, 2006
Someone might attack on your system. You can drop attacker IP using IPtables. However one of our sr. sys admin highlighted something new for me. You can nullroute (like some time ISP do prevent your network device from sending any data to a remote system.) stopping various attacks coming from a single IP (read as spammers or hackers):
Suppose that bad IP is 65.21.34.4, type following command at shell:
# route add 65.21.34.4 127.0.0.1
You can verify it with following command:
# netstat -nr
This is cool, as you do not have to play with iptables rules.
Posted in Linux Administration, Linux General, Linux Security, Linux:- Tips & Tricks, Tuning Linux, iptables | Leave a Comment »

Server Security with Advanced Policy Firewall and Antidos
July 2, 2006
LinuxAPF is a policy based iptables firewall system designed for ease of use and configuration. APF is ideal for deployment in many server environments based on Linux.
Below are notes on installing, configuring and running APF.
1. Download the latest tarball via rfxnetworks.com
2. Extract and install it:
3. # tar -xvzf apf-current.tar.gz
4.
5. # cd apf*
6.
# ./install.sh
7. Check the port that you need to protect with `ifconfig`. Usually it is “eth0″ but if it’s something else, change it in the “conf.apf” file or you’ll risk locking yourself from the server.
8. Edit “/etc/apf/conf.apf” and enable D-Shield block list of top networks exhibiting suspicious activity, and activate Antidos also.
9. USE_DS="1"
10.
USE_AD="1"
11. Open the common inbound and outboud ports.
12. IG_TCP_CPORTS="20,21,22,25,53,80,110,143,443"
13.
14. IG_UDP_CPORTS="53"EGF="1"
15.
16. EG_TCP_CPORTS="21,22,25,43,53,80,110,443"
17.
EG_UDP_CPORTS="20,21,53"
18. Edit “/etc/apf/ad/conf.antidos”:
19. LP_KLOG="1"USR_ALERT="1"
20.
USR="root"
21. Add antidos to “/etc/crontab”:
22. # Antidos
23.
*/2 * * * * root /etc/apf/ad/antidos -a >> /dev/null 2>&1
24. Star the firewall via `apf –s`.
25. If you are not locked out of SSH, disable development mode in “conf.apf” file.
DEVM="0"
26. Restart with `apf -r` and verify that firewall is up and protecting the server using `iptables -L -n`.
________________________________________
Notes:
• APF uses init files and is automatically set to startup at boot time. Check with `chkconfig –list apf`.
• The apf and antidos logs are rotated via the conf files present in “/etc/logrotate.d”.
• Remember to add your IP address in “/etc/apf/allow_hosts.rules” and “/etc/apf/ad/ignore.hosts” files to avoid being locked out of the server.
________________________________________
Posted in Linux Administration, Linux General, Linux Networking, Linux Security, Linux:- Tips & Tricks, Tuning Linux, iptables | Leave a Comment »

Writing Linux firewall rules w/ IPTables
July 2, 2006


The Linux kernel, since version 2.0, has included the capabilities to act as a firewall. In those days, the kernel module was called ipfwadm and was very simple. With the 2.2 kernel, the firewall module became called ipchains and had greater capabilities than its predecessor. Today, we have IPTables, the firewall module in the kernel since the 2.4 days. IPTables was built to take over ipchains, and includes improvements that now allow it to compete against some of the best commercial products available in the market. This guide will give you some background on IPTables and how to use it to secure your network.
Getting to know some important terminology
IPTables can be used in three main jobs: NAT, Packet Filtering, and Routing.
• NAT stands Network Address Translation, and it is used to allow the use of one public IP address for many computers.
• Packet Filteringstateless firewall and the other is stateful firewall. Stateless firewalls do not have the ability to inspect incoming packets to see if the packet is coming from a known connection originating at your computer. Stateful firewalls have the ability to inspect each packet to see if it’s part of a known connection, and if the packet is not part of a known, established connection then the packet is “dropped” or not allowed to pass through the firewall.
• Routing is used to route various network packets to different ports, which are similar to Airport gates, or different IP addresses depending on what is requested. For example, if you have a web server somewhere in your network that uses port 8080, you can use Linux’s packet routing to route port 80 packets to your server’s port 8080. More on all this this later on.
A word on tables
There are three table types: filter, NAT, and mangle.
• Filter – this is the default table type and contains most of the chains including input, output, and forward.
• NAT – this table is used when new connections are created. It contains only three chains: prerouting, output, and postrouting.
• Mangle – is used to alter packets.
The importance of chains…
There are three built-in chains that are part of IPTables.
• The INPUT chain is used for packets comming into the Linux box. This chain can be used to stop certain packets from coming into the network or system, so for example, if would prevent another computer from pinging your network.. I will talk more about stopping ping attacks later.
• The OUTPUT chain is used for packets coming out of your Linux box. This chain can be used to stop certain packets that you do not want to leave your network or system.
• The FORWARD chain is used for packets passing through the network’s firewall. This chain will be used to set our NAT rules. I will go into the syntax of a basic NAT filter later in this article.
• The PREROUTING chain is for changing packets as they come in
• The POSTROUTING chain is for changing packets as they leave
Every chain in IPTables is either user-defined or built-in and will have a default policy, which can be either ACCEPT or DROP. ACCEPT and DROP will be discussed in the next section.
Packet targets
IPTables has targets which denotes what happens to all packets. There are four built-in targets:
• ACCEPT – denotes if the packet should be allowed to move on.
• DROP – denotes if the packet should be dropped and ignored.
• QUEUE – denotes if the packet should be passed to userspace.
• RETURN – denotes if the packet should be passed to the previous chain. Should this happen, then the packet is governed by the default policy of the previous chain.
For the most part I will be using ACCEPT and DROP targets for the sake of simplicity. These two targets are also more than enough to create your firewall rules. Please note that while there are predefined chains, they can also be a user-defined.
NAT, one IP for them all
NAT is one of the best tricks for networking; it allows one IP address to be used by many computers so they can all access the internet. NAT on your network would work through the rewriting the packet by changing the source IP address to read your internet IP address as it passes out of your network. When a packet needs to return to the source, the packet’s destination IP address is changed back to the computer’s IP address inside your network. For example, if your computer with an IP address of 192.168.1.2 needed to get to Google, whose IP address is 216.239.57.99, the NAT firewall would change 192.168.1.2 to something like 64.199.1.83 and would then be passed throught the internet to Google. When Google sends a response, the IP address is changed from 64.199.1.83 to 192.168.1.2 and is received at your computer inside the network.
To write IPTables rules you will need to open a command prompt, but there are some graphical apps to help you out. One application that makes writing IPTables rules simple is Firestarter for GNOME. KDE users can benefit from an application like knetfilter.

Some notes on IPTables syntax
IPTables chain syntax can be confusing, particularly for beginners, but once you have the basics down, anyone can learn to write their own firewall rules; be patient, it just takes time. It took me about 3 months to figure out how to write a rule to block ICMP packets which are used to ping computers. IPTables syntax looks like this: iptables -t filter -A INPUT -p icmp -i eth0 -j DROP.
• The -t filter specifies that this rule will go into the filter table. If you wanted to write a NAT rule you would type -t nat.
• The -A INPUT specifies that the rule is going to be appended to the INPUT chain. Other possible syntax would be -A OUTPUT, -A FORWARD, -A PRETROUTING, and-A POSTROUTING.
• The -p icmp specifies that the packet has be from the ICMP protocol. The other two options are -p tcp used for TCP packets, and -p udp used for UDP packets.
• The -i eth0 specifies that the packet has to be coming in via the eth0 interface or your first network device.
• The -j DROP that if the packet matches it should be dropped. This rule is to stop people from using finger (used to see who else is on the system) , ping (used to check if a server is responding), or other methods to discover your network.
The next two rules are going to do the work of blocking connections not originating from inside your network.

iptables -A FORWARD -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
The -m state --state ESTABLISHED,RELATED was used to match the state of the packet coming in via eth0 (your ethernet device) and if the packet matches, then the packet is accepted. The -m is used to match on a specific option. Some possible options are -m limit --limit which looks for a limited rate, -m tos --tos used to match the TOS IP header field on a packet, -m unclean which is used to match packets that look “suspicious”.
The next rule is going to do source NAT, which will allow your network to connect using one IP address.

iptables -t nat -A POSTROUTING -o eth0

Depending on if you have a Static IP or Dynamic IP you would type: -j SNAT --to-source 1.2.3.4 for Static IP, and -j MASQUERADE for Dynamic IP at the end of the above code. As a bonus, i’ll tell you how to do destination NAT, which will allow you to put a server behind the firewall at the expense of security.

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport www -j DNAT --to-dest 192.168.1.2
The --dport www denotes that the destination port is port 80. You can use text like www (port 80) or ftp (port 21) or simply use port numbers. The -j DNAT part of the rule is the target, similar to -j DROP or -j ACCEPT in previous examples. --to-dest 192.168.1.2 tells IPTables where you want the packet to go. --sport 8080 is just like --dport www.
For three years i have writen my own firewall rules. IPTables saved my computer from MyDoom and Sasser worms/viruses. Hopefully, now you too can write your own firewall rules. IPTables is a usefull tool in the Linux user’s tool belt, for protecting Linux and Windows computers.
Posted in Linux Administration, Linux Networking, Linux Security, Linux:- Tips & Tricks, Tuning Linux, iptables | 9 Comments »

netfilter’s geoip match
June 19, 2006
Introduction
netfilter and iptables are building blocks of a framework inside the Linux 2.4.x and 2.6.x kernel. This framework enables packet filtering, network addresss [and port] translation (NA[P]T) and other packet mangling. It is the re-designed and heavily improved successor of the previous Linux 2.2.x ipchains and Linux 2.0.x ipfwadm systems. To learn more about iptables/netfilter you should visit www.netfilter.org.
what is iptables/netfilter’s geoip match?
This framework is modular and easily let you extend the features. This is exactly what geoip is : an extension to iptables/netfilter that allows you to filter, nat or mangle packets based on the country’s destination or provenance.
Installation
There’s some minor steps to go through before using this match.
The geoip’s database
In order to efficiently filter on a country basis, we obviously need a subnet-to-country database. Fortunately, there’s a free one available at http://www.maxmind.com.
However, this database is big and unsorted. Loading this database into memory would eat up too much ressources than what we really need. Also, seeking through unsorted database takes ages. This is why you need a tool called ‘csv2bin’ to strip, sort and compile your database.
csv2bin is available at http://people.netfilter.org/peejix/geoip/tools/
An alternative to creating your own up-to-date database is downloading a prebuilt but possibly outdated database from http://people.netfilter.org/peejix/geoip/database/.
You’ll now have to copy `geoipdb.bin’ and its index file `geoipdb.idx’ into /var/geoip/. The reason on why we do this is that iptables’s geoip shared library is statically reading both files from that path. If you ever need to change that path, take a look at extensions/libipt_geoip.c and suit it for your needs.
Applying patch-o-matic
Just like other “official” patches, geoip is part of patch-o-matic-ng. As a new match, we’ve put it into Testing state and Extra repository, so start ‘runme’ accordingly.
#> tar xfz patch-o-matic-ng-XXXXXX.tar.gz
#> cd patch-o-matic-ng
#> IPTABLES_DIR=/usr/src/iptables KERNEL_DIR=/usr/src/linux ./runme geoip
Do not forget to :
o recompile iptables;
o enable geoip into your kernel config;
o recompile your kernel or compile geoip as a module;
o boot the new kernel or modprobe ipt_geoip.
NOTE: If you had to change the database path into libipt_geoip.c, you MUST do it before compiling.
Examples
If you want to block all Anonymous Proxies and Satellite Providers, you can enter something like that: (I assume that your linux box acts as a router, else you can provide `-A INPUT’ instead.)
#> iptables -A FORWARD -m geoip –src-cc A1,A2 -j DROP
If you only plan to accept connections from your country.
#> iptables -P INPUT DROP
#> iptables -A INPUT -m geoip ! –src-cc CA -j DROP
Some people likes to know which countries are hitting obscure or well-known security risk ports.
Create a dedicated accounting custom chain
#> iptables -N SSH_GEOIP
Feed that chain with your targeted countries (below are for exemple means only)
#> iptables -A SSH_GEOIP -m geoip –src-cc CA
#> iptables -A SSH_GEOIP -m geoip –src-cc DE
#> iptables -A SSH_GEOIP -m geoip –src-cc US
#> iptables -A SSH_GEOIP -m geoip –src-cc JP
#> iptables -A SSH_GEOIP -m geoip –src-cc FR
The sixth rule will match all other countries
#> iptables -A SSH_GEOIP -m geoip ! –src-cc CA,DE,US,JP,FR
Then call the chain for a specific situation
#> iptables -A INPUT -p tcp –dport 22 -j SSH_GEOIP
Motivation
This patch has been provided for fun and as a challenge only. Please do not consider this patch as an anti-spam approach. There is much better uses of this patch than such a racist-routing.
Thanks
Thanks to
Charles Michaud, for giving us the project’s idea.
Arthur Ouellet, for giving us ideas and bugs report.
Martin Josefsson, for answering our technicals questions.
Tarek W. Said for jiggling his butt when we succeed.
Sean Donner for testing and writing the geoip_update.sh
and all the netfilter core team, you’re working like a big mama.
Posted in Linux Administration, Linux General, Linux Networking, Linux Security, Linux:- Tips & Tricks, iptables | Leave a Comment »

Autoblock IPs with failed SSH logins
June 1, 2006
automatic blocking of systems after a number of failed login-try’s
________________________________________
some general things first…
first of all i would like to announce, i know there are tools like ‘denyhosts’ or ‘pam_abl’ (which i use too) but the problem is: i just wan’t a system to be ignored and not justed blocked…otherwise the system can still continue attacking my system via http, ftp or other services i’m running or just waste my system performance.
for this purpose i setup a script which automaticly adds the hosts identified by ‘pam_abl’ (http://www.hexten.net/pam_abl/ by Andy Armstrong) to iptables, which drops every traffic of this system.
this howto is just an english translation out of this documentation: http://nimue/doc/?doc=032-abl_iptab…_abl%20iptables
now, heres the howto….
————————————-
install, configure and activate ‘pam_abl’
under fedora its soo easy…just
Code:
yum install pam_abl
next configure pam_abl in ‘/etc/security/pam_abl.conf’.
with a configuration like this:
Code:
# /etc/security/pam_abl.conf
host_db=/var/lib/abl/hosts.db
host_purge=5d
host_rule=*:5/1h,20/1d
pam_abl will deny every system (host_rule=*:…), which gives 5 times per hour or 20 times per day an invalid user/password token.
for further information about configuring ‘pam_abl’ consider the official docs at http://www.hexten.net/assets/pam_abl_doc/index.html
after this, enable ‘pam_abl’ like its described in ‘/usr/share/doc/pam_abl-*/README.fedora’. i would advice you to add the ‘pam_abl’-rule before a sufficient pam-rule, otherwise it is possible for a system to go around this rule…
and be aware of changing pam-configuration, make a backup-copy first!
using ‘pam_abl’
now you have the ‘pam_abl’ module (called pam_abl.so) and the command-line tool ‘pam_abl’. this enables you to manually edit the database of so called ‘crackers’.
Code:
pam_abl -p
this purges old hosts in your database (means, hosts which are longer in database than defined in your config). we do this, cause we’ll be blocking ip-adresses via iptables and in most cases these ip-adresses were dynamically distributed by an isp.
changes to iptables
that we can automatically update our iptables rules with ‘crackers’ we must create a chain and then insert a rule into our current iptables rules (or firewall script):
Code:
iptables -t filter --new crackers
iptables -A INPUT -j crackers
it’s important to insert the rule at the top of iptables, otherwise a rule can allow a system before we can check if its a cracker identified by pam_abl (if you use iptables -I INPUT -j crackers, its inserted at top).
blocking the systems identified by ‘pam_abl’
now, we just need to update the ‘crackers’ chain with the systems attacking our system:
Code:
#!/bin/bash
#
# script: update_firewall.sh - updates crackers reported by pam_abl (http://www.hexten.net/pam_abl/) in the firwall

# initalitaion
#
# define variables
chain_name=crackers
iptables=/sbin/iptables
abl_hostdb=/var/lib/abl/hosts.db

# check access to iptables
if [ ! -x $iptables ]; then
echo "cannot execute iptables!"
echo "please correct iptables-variable in $0"
exit
fi

# check access to read-db-script
if [ ! -x $read_dbscript ]; then
echo "cannot execute read-db-script!"
echo "please correct read_dbscript-variable in $0"
exit
fi

# check if defined chain exist in current iptable-rules
if [ -z "`$iptables -n -L | grep -i "chain $chain_name"`" ]; then
echo "chain $chain_name is not defined in your iptable rules!"
echo "cannot add a rule into a non-existing chain. please update your iptables-config."
exit
fi

# checks ok, go on...
#
# purge old hosts from pam_abl
/usr/sbin/pam_abl -p

# flush crackers chain
$iptables -t filter -F $chain_name

# reload chain with actual crackers
for i in `/usr/sbin/pam_abl | grep -v hosts: | grep -v ocking | awk '{print $1}'`; do
$iptables -t filter -A $chain_name -s $i -j DROP
done
this script does all for you, it cleans the ‘pam_abl’-databse and the chain and finally adds every system identified by ‘pam_abl’ to iptables.
if you then add this script to your crontab (for example every 10minutes) a cracker system has max. 10minutes of time after blocked by pam_abl to attack another service or wasting your system performance…




There could also be a problem with the server’s session.save_path
June 9, 2009

New joomla install would show following:
An error has occurred.:Cookies do not appear to be enabled on your browser client. You will not be able to install the application with this feature disabled. Alternatively, there could also be a problem with the server’s session.save_path. If this is the case, please consult your hosting provider if you don’t know how to check or fix this yourself.
and
existing admin login to joomla installations were not authenticating.

Soln=====>
Compare the following in php.ini
Working configuration
#############################
[root@server root]# grep session. /usr/local/lib/php.ini
session.save_handler = files
; variable in order to use PHP’s session functions.
; session.save_path = “N;/path”
; where N is an integer. Instead of storing all the session files in
; store the session data in those directories. This is useful if you
; a more efficient layout for servers that handle lots of sessions.
; You can use the script in the ext/session dir for that purpose.
; use subdirectories for session storage
;session.save_path = /tmp
session.use_cookies = 1
; attacks which involve passing session ids in URLs; defaults to 0.
; session.use_only_cookies = 1
; Name of the session (used as cookie name).
session.name = PHPSESSID
; Initialize session on request startup.
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.serialize_handler = php
; on every session initialization.
session.gc_probability = 1
session.gc_divisor = 100
session.gc_maxlifetime = 1440
; NOTE: If you are using the subdirectory option for storing session files
; (see session.save_path above), then garbage collection does *not*
; setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
; cd /path/to/sessions; find -cmin +24 | xargs rm
; to initialize a session variable in the global scope, albeit register_globals
session.bug_compat_42 = 1
session.bug_compat_warn = 1
; HTTP_REFERER has to contain this substring for the session to be
session.referer_check =
session.entropy_length = 0
; Specified here to create the session id.
session.entropy_file =
;session.entropy_length = 16
;session.entropy_file = /dev/urandom
session.cache_limiter = nocache
session.cache_expire = 180
; – User may send URL contains active session ID
; – URL that contains active session ID may be stored
; – User may access your site with the same session ID
session.use_trans_sid = 0
[root@server root]#
Things to check for
##########################
1) check that the above are set and check that:
2) /tmp has permissions 1777
3) /dev/urandom exists, if not create it with following commands:
mknod -m 644 /dev/urandom c 1 9
chown root:root /dev/random /dev/urandom
4) uncomment
;session.save_path = /tmp
in php.ini , if the sessions folder is not /tmp ( by default for cpanel server installation it is /tmp , however if php/apache is installed on a plain server, the sessions folder is usually /var/lib/php/sessions or something)
Posted in Apache, Linux Administration, Linux General, Linux:- Tips & Tricks, php | Leave a Comment »

Install Latest postgresql using yum from pgsqlrpms
September 29, 2008
##################################################
[root@server ~]# yum erase postgresql postgresql-server
[root@server ~]# wget http://yum.pgsqlrpms.org/reporpms/8.3/pgdg-centos-8.3-4.noarch.rpm
[root@server ~]# rpm -ivh pgdg-centos-8.3-4.noarch.rpm
[root@server ~]# yum install postgresql postgresql-server
[root@server ~]# chkconfig postgresql on
[root@server ~]# service postgresql initdb
[root@server ~]# chkconfig postgresql on && service postgresql start
[root@server ~]# /usr/bin/postgres –version
postgres (PostgreSQL) 8.3.4
[root@server ~]#
Set port and the interface to bind to
#########################################
vi /var/lib/pgsql/data/postgresql.conf
# – Connection Settings -
listen_addresses = ‘*’
port = 5432
Posted in Advanced Commands, Linux Administration, Linux General, Linux:- Tips & Tricks, postgres, postgresql, sql, yum | Leave a Comment »

NMAP
September 23, 2008
echo ” ========== Installing NMAP network Scanner ================= “
echo “…………………………………………………………………………………………………………………..”
echo “…………………………………………………………………………………………………………………..”
echo “Cleaning old nmap installation, if any “
yum -y remove nmap
echo “…………………………………………………………………………………………………………………..”
echo “Install beings “
yum -y install nmap
if [ -f /usr/bin/nmap ]
then
echo ” Nmap successfully installed”
sleep 2
echo ” Testing Nmap “
echo ” ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++”
sleep 3
/usr/bin/nmap localhost -v
sleep 5
else
echo ” Nmap faield to install”
fi
echo ” =========== Install NMAP network Scanner process completed ===============”
echo “…………………………………………………………………………………………………………………..”
echo “…………………………………………………………………………………………………………………..”
echo “…………………………………………………………………………………………………………………..”
Posted in Advanced Commands, Linux Administration, Linux General, Linux Security, Linux:- Tips & Tricks | Leave a Comment »

MySQL ERROR 1045 (28000): Access denied for user ‘root’@'localhost’ (using password: YES)
August 25, 2008
The other day I got this error on one of our servers. Fantastico module in cpanel was showing the error: Unable to connect to mysql database. While mysql service was running fine, the root user was unable to login to mysql database. I initially tried to reset the mysql root password like http://rhcelinuxguide.wordpress.com/2008/08/08/reset-mysql-root-password/ but that did not help. The real issue was permission on the folder /var/lib/mysql/mysql . It is supposed to be 711 , while it was 751. That fixed it.
==================================================================
root@server1 [~]# mysql
ERROR 1045 (28000): Access denied for user ‘root’@'localhost’ (using password: YES)
root@server1 [~]#
root@server1 [/var/lib/mysql/mysql]# ls -lhd /var/lib/mysql
drwxr-x–x 179 mysql mysql 12K Aug 25 01:44 /var/lib/mysql/
root@server1 [/var/lib/mysql/mysql]# chmod 711 /var/lib/mysql/mysql
root@server1 [/var/lib/mysql/mysql]# ls -lhd /var/lib/mysql/mysql
drwx–x–x 2 mysql mysql 4.0K Aug 25 01:32 /var/lib/mysql/mysql/
root@server1 [/var/lib/mysql/mysql]# service mysql restart
Shutting down MySQL..
[ OK ]
Starting MySQL [ OK ]
root@server1 [/var/lib/mysql/mysql]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.51a-community MySQL Community Edition (GPL)Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.
mysql> quit
Bye
root@server1 [/var/lib/mysql/mysql]#
==================================================================
Worked for me !
Posted in Advanced Commands, Linux Administration, Linux:- Tips & Tricks, Mysql | 1 Comment »

Virtuozzo Upgrade : Upgrading from Virtuozzo3 to Virtuozzo4
August 18, 2008
Upgrading from Virtuozzo 3 to Virtuozzo 4
================================
First of all refer to : http://www.parallels.com/en/products/virtuozzo/easy-upgrade/ for detailed explanation. When I decided to upgrade, there was not much available except the above docs. I used the inbuilt vzup2date for the upgrade purpose.
First of all apply all updates on your current Virtuozzo 3 using vzup2date , by selecting udate for virtuozzo 3.0.x only. Once updates are applied, it also does a kernel upgrade. It will finally ask if you want to reboot. Just select finish, and dont reboot. It is better to reboot manually, so that you can swith back to old kernel, in case the new kernel panics or hang up during boot.
Step 1
===================================================
[root@vpsMainNode virtuozzo]# vzup2date
Apply all updates on your current Virtuozzo 3.
Select option reboot manually and dont hit the reboot option, just select finish.
Next,
Edit /etc/grub.conf and change the option
default=0 to default=1 , so that the current kernel is selected in grub , instead of the new kernel , that was just installed.
Next we configure grub to boot the new kernel only for the next reboot. If the reboot does not go well and the system does not boot properly, do a hard reset ( ask your DC, if
reqd. ) and you will successfully boot into the last working kernel.
[root@vpsMainNode virtuozzo]# grub shell
Probing devices to guess BIOS drives. This may take a long time.
GNU GRUB version 0.95 (640K lower / 3072K upper memory)
[ Minimal BASH-like line editing is supported. For the first word, TAB
lists possible command completions. Anywhere else TAB lists the possible
completions of a device/filename.]
grub> savedefault –default=0 –once
grub> quit
[root@vpsMainNode virtuozzo]#
Reboot the server. If all goes fine, and the server comes up with the new kernel, edit /etc/grub.conf and change the option
default=1 to default=0
Next,
Run vzup2date again and select updates for Virtuozzo 3 , and go next , next to finish install ( select option manual reboot )
[root@vpsMainNode virtuozzo]# vzup2date
If all Virtuozzo 3 are already applied, you will see no more update available message.
Now that Virtuozzo 3 has all its latest stuff in its version, we will update Virtuozzo 3 to Virtuozzo 4.
Run vzup2date again,
[root@vpsMainNode virtuozzo]# vzup2date
This time, select Virtuozzo 4 for upgrades, do the usual next , next to apply updates. ( select option manual reboot )
This process will take some time depending on speed. Usually 20 to 60 minutes.
Again this will install a newer kernel, so
Next we configure grub to boot the new kernel only for the next reboot. If the reboot does not go well and the system does not boot properly, do a hard reset ( ask your DC, if
reqd. ) and you will successfully boot into the last working kernel.
[root@vpsMainNode virtuozzo]# grub shell
Probing devices to guess BIOS drives. This may take a long time.
GNU GRUB version 0.95 (640K lower / 3072K upper memory)
[ Minimal BASH-like line editing is supported. For the first word, TAB
lists possible command completions. Anywhere else TAB lists the possible
completions of a device/filename.]
grub> savedefault –default=0 –once
grub> quit
[root@vpsMainNode virtuozzo]#
Reboot the server. If all goes fine, and the server comes up with the new kernel, edit /etc/grub.conf and change the option
default=1 to default=0
Voila ! you have upgraded your server from Virtuozzo 3 to Virtuozzo 4. You will see that all nodes will work properly, start the nodes, if any active node is down in the usual
way.
[root@vpsMainNode virtuozzo]# vzctl start VE_ID
Note VE_ID is now also called as CT_ID ( container ID )
You will find that the Service VE ( now called as Service Container ) will fail to start. If not, then fine. You have nothing left to do , except running a vzup2date again and
apply any newer updates for one more time. If any new kernel is installed , then modify grub.conf as already discussed, while rebooting.
In case Service VE ( now called as Service Container ) fails to start or does not start, you will be unable to access your virtuozzo control panel.
Note , I destroyed old Service VE and recreated it, if for any reason, you want backup of old service , you might chose to make a backup of it.
Here is what I did to install the service CT
###############################################
[root@vpsMainNode virtuozzo]# vzctl destroy 1
[root@vpsMainNode virtuozzo]# cd /root/
[root@vpsMainNode virtuozzo]# wget http://download.parallels.com/virtuozzo/virtuozzo4.0/linux/iso/lin-i386.iso
[root@vpsMainNode virtuozzo]# mkdir /mnt/iso
[root@vpsMainNode virtuozzo]# mount -o loop lin-i386.iso /mnt/iso
[root@vpsMainNode virtuozzo]# vzsveinstall -D /mnt/iso -s xx.yy.zz.IP
[root@vpsMainNode virtuozzo]# vzlist -a | grep CT
CTID NPROC STATUS IP_ADDR HOSTNAME
1 77 running xx.yy.zz.IP ServiceCT
[root@vpsMainNode virtuozzo]#
[root@vpsMainNode virtuozzo]# lsof -i :4643
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
vzaproxy 531 root 4u IPv4 10286471 TCP *:4643 (LISTEN)
vzcp 591 root 4u IPv4 10286403 TCP *:4643 (LISTEN)
vzcp 595 apache 4u IPv4 10286403 TCP *:4643 (LISTEN)
vzcp 596 apache 4u IPv4 10286403 TCP *:4643 (LISTEN)
vzcp 3004 apache 4u IPv4 10286403 TCP *:4643 (LISTEN)
[root@vpsMainNode virtuozzo]#
[root@vpsMainNode virtuozzo]# vzctl restart 1
Restart Container
Stopping Container …
Container was stopped
[ OK ] down vzagent: [ OK ]
[ OK ] vzagent: [ OK ]
Container is unmounted
Starting Container …
Starting vzagent: [ OK ]
Starting vzagent: [ OK ]
Container is mounted
Setting devperms 20006 dev 0×7d00
Adding IP address(es): xx.yy.zz.IP
Hostname for Container set: ServiceCT
File resolv.conf was modified
Container start in progress…
[root@vpsMainNode virtuozzo]# vzlist -a | grep CT
CTID NPROC STATUS IP_ADDR HOSTNAME
1 77 running xx.yy.zz.IP ServiceCT
[root@vpsMainNode virtuozzo]#
[root@vpsMainNode log]# cd /root/
[root@vpsMainNode ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 9.9G 4.1G 5.3G 44% /
/dev/sda1 494M 81M 388M 18% /boot
none 4.0G 0 4.0G 0% /dev/shm
/dev/sda3 448G 267G 158G 63% /vz
/dev/sdb1 459G 123G 313G 29% /backup
/root/lin-i386.iso 582M 582M 0 100% /mnt/iso
[root@vpsMainNode ~]# mkdir /root/virt4_source
[root@vpsMainNode ~]# cp -r /mnt/iso/* /root/virt4_source/
[root@vpsMainNode ~]# umount /mnt/iso
[root@vpsMainNode ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 9.9G 4.7G 4.8G 50% /
/dev/sda1 494M 81M 388M 18% /boot
none 4.0G 0 4.0G 0% /dev/shm
/dev/sda3 448G 267G 158G 63% /vz
/dev/sdb1 459G 123G 313G 29% /backup
[root@vpsMainNode ~]#
Congrats !!! , now that you have got the Service Container Up and Running, time to explore/enjoy the new looks in Virtuozzo 4 control panel.
Posted in Advanced Commands, Linux Administration, Linux General, Linux Installation, Linux:- Tips & Tricks, Tuning Linux, Virtuozzo, upgrade virtuozzo, virtuozzo 3 to 4, virtuozzo 3 to virtuozzo 4, virtuozzo 3 upgrade, virtuozzo upgrade, virtuozzo version upgrade | Leave a Comment »

Reset MySQL Root Password
August 8, 2008
[root@dedicated08 ~]# lsof -i :3306
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
mysqld 31792 mysql 3u IPv4 434089 TCP *:mysql (LISTEN)
[root@dedicated08 ~]# kill -9 31792
[root@dedicated08 ~]# /etc/init.d/mysql start
Mysql Started
[root@dedicated08 ~]# mysql
Access denied for user ‘root’@'localhost’ (using password: NO)
[root@dedicated08 ~]# /etc/init.d/mysql stop
[root@dedicated08 ~]# mysqld_safe –skip-grant-tables &
[root@dedicated08 ~]#
[root@dedicated08 ~]# mysql -u root
mysql>
mysql> use mysql;
mysql> update user set password=PASSWORD(”NEW-ROOT-PASSWORD”) where
User=’root’;
mysql> flush privileges;
mysql> quit
NEW-ROOT-PASSWORD above is whatever password you want to set.
[root@dedicated08 ~]# # /etc/init.d/mysql stop
[root@dedicated08 ~]# lsof -i :3306
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
mysqld 31792 mysql 3u IPv4 434089 TCP *:mysql (LISTEN)
[root@dedicated08 ~]# kill -9 31792
[root@dedicated08 ~]# fuser -k /usr/bin/mysqld_safe ( in
case you see mysql process is still running )
[root@dedicated08 ~]# vi /root/.my.cnf
[root@dedicated08 ~]# cat /root/.my.cnf
[client]
user=”root”
pass=”NEW-ROOT-PASSWORD”
[root@dedicated08 ~]#
[root@dedicated08 ~]# service mysql restart
[root@dedicated08 ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.21-standard-log
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.
mysql> quit
Bye
[root@dedicated08 ~]#
Posted in Advanced Commands, Linux Administration, Linux:- Tips & Tricks, Mysql | Leave a Comment »

hwclock – query and set the hardware clock
August 5, 2008
set the system time from the hardware clock
============================================
root@s1 [~]# /sbin/hwclock –hctosys
root@s1 [~]#
set the hardware clock to the current system time
============================================
root@s1 [~]# /sbin/hwclock –systohc
root@s1 [~]#
root@s1 [~]# /sbin/hwclock –help
hwclock – query and set the hardware clock (RTC)
Usage: hwclock [function] [options...]
Functions:
–help show this help
–show read hardware clock and print result
–set set the rtc to the time given with –date
–hctosys set the system time from the hardware clock
–systohc set the hardware clock to the current system time
–adjust adjust the rtc to account for systematic drift since
the clock was last set or adjusted
–getepoch print out the kernel’s hardware clock epoch value
–setepoch set the kernel’s hardware clock epoch value to the
value given with –epoch
–version print out the version of hwclock to stdout
Options:
–utc the hardware clock is kept in coordinated universal time
–localtime the hardware clock is kept in local time
–directisa access the ISA bus directly instead of /dev/rtc
–badyear ignore rtc’s year because the bios is broken
–date specifies the time to which to set the hardware clock
–epoch=year specifies the year which is the beginning of the
hardware clock’s epoch value
–noadjfile do not access /etc/adjtime. Requires the use of
either –utc or –localtime
Posted in Advanced Commands, Linux Administration, Linux General, Linux:- Tips & Tricks | Leave a Comment »

iptables string match to drop malicious urls
August 5, 2008
iptables string match to drop malicious urls
==================================
Usually modsecurity rules can help filter many malicious url attack patterns combined with apache on apache port (http|https). But what if a malicious attack using a vulnerable url pattern, that exposes or tries to break into your system is coming onto another port?
This is where iptables string match comes in handy.
/usr/local/sbin/iptables -I INPUT -p tcp -s 0.0.0.0/0 -m string –string “download?file=%2e%2e” –algo bm -j DROP
[root@server ~]# iptables -L -v | grep STR
73 49908 DROP tcp – any any anywhere anywhere STRING match “download?file=%2e%2e” ALGO name bm TO 65535
[root@server ~]#
The above iptable rule will block any url that has the string “download?file=%2e%2e” on any port on your server.
Note: your iptables binary path may be /sbin/iptables
Say http://yourserverIP:9132/blah/download?file=%2e%2e
Posted in Advanced Commands, Linux Administration, Linux General, Linux Security, Linux:- Tips & Tricks, Tuning Linux, iptables | 2 Comments »

Rename a username , groupname and its homedirectory with usermod
August 5, 2008
Rename user 7777777 ’s name, groupname and homedir to 88888888 with usermod
root@server1 [/home]# useradd 7777777
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/passwd
7777777:x:32147:32148::/home/
7777777:/bin/bash
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/group
7777777:x:32148:
root@server1 [/home]#
root@server1 [/home]# usermod -d /home/88888888 7777777
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/passwd
7777777:x:32147:32148::/home/88888888:/bin/bash
root@server1 [/home]#
************************************************************************************************************
root@server1 [/home]# rm -fr /home/7777777/ OR you can mv /home/7777777 /home/88888888, if you want
************************************************************************************************************
root@server1 [/home]# usermod -l 88888888 7777777
failed to rename mailbox: File exists
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/passwd
root@server1 [/home]# grep 88888888 /etc/passwd
88888888:x:32147:32148::/home/88888888:/bin/bash
root@server1 [/home]#
root@server1 [/home]# groupmod -n 88888888 7777777
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/group
root@server1 [/home]#
root@server1 [/home]# grep 88888888 /etc/group
88888888:x:32148:
root@server1 [/home]#
Posted in Advanced Commands, Linux Administration, Linux General, Linux:- Tips & Tricks | Leave a Comment »

create a directory with different permission mode
July 29, 2008
—————————————————————
[root@server ~]# mkdir /root/test1 -v -m 1777
mkdir: created directory `/root/test1′
[root@server ~]# ls -lhd /root/test1
drwxrwxrwt 2 root root 4.0K Jul 29 01:42 /root/test1
[root@server ~]#
v = verbose, is not mandatory though




There could also be a problem with the server’s session.save_path
June 9, 2009

New joomla install would show following:
An error has occurred.:Cookies do not appear to be enabled on your browser client. You will not be able to install the application with this feature disabled. Alternatively, there could also be a problem with the server’s session.save_path. If this is the case, please consult your hosting provider if you don’t know how to check or fix this yourself.
and
existing admin login to joomla installations were not authenticating.

Soln=====>
Compare the following in php.ini
Working configuration
#############################
[root@server root]# grep session. /usr/local/lib/php.ini
session.save_handler = files
; variable in order to use PHP’s session functions.
; session.save_path = “N;/path”
; where N is an integer. Instead of storing all the session files in
; store the session data in those directories. This is useful if you
; a more efficient layout for servers that handle lots of sessions.
; You can use the script in the ext/session dir for that purpose.
; use subdirectories for session storage
;session.save_path = /tmp
session.use_cookies = 1
; attacks which involve passing session ids in URLs; defaults to 0.
; session.use_only_cookies = 1
; Name of the session (used as cookie name).
session.name = PHPSESSID
; Initialize session on request startup.
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.serialize_handler = php
; on every session initialization.
session.gc_probability = 1
session.gc_divisor = 100
session.gc_maxlifetime = 1440
; NOTE: If you are using the subdirectory option for storing session files
; (see session.save_path above), then garbage collection does *not*
; setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
; cd /path/to/sessions; find -cmin +24 | xargs rm
; to initialize a session variable in the global scope, albeit register_globals
session.bug_compat_42 = 1
session.bug_compat_warn = 1
; HTTP_REFERER has to contain this substring for the session to be
session.referer_check =
session.entropy_length = 0
; Specified here to create the session id.
session.entropy_file =
;session.entropy_length = 16
;session.entropy_file = /dev/urandom
session.cache_limiter = nocache
session.cache_expire = 180
; – User may send URL contains active session ID
; – URL that contains active session ID may be stored
; – User may access your site with the same session ID
session.use_trans_sid = 0
[root@server root]#
Things to check for
##########################
1) check that the above are set and check that:
2) /tmp has permissions 1777
3) /dev/urandom exists, if not create it with following commands:
mknod -m 644 /dev/urandom c 1 9
chown root:root /dev/random /dev/urandom
4) uncomment
;session.save_path = /tmp
in php.ini , if the sessions folder is not /tmp ( by default for cpanel server installation it is /tmp , however if php/apache is installed on a plain server, the sessions folder is usually /var/lib/php/sessions or something)
Posted in Apache, Linux Administration, Linux General, Linux:- Tips & Tricks, php | Leave a Comment »

Install Latest postgresql using yum from pgsqlrpms
September 29, 2008
##################################################
[root@server ~]# yum erase postgresql postgresql-server
[root@server ~]# wget http://yum.pgsqlrpms.org/reporpms/8.3/pgdg-centos-8.3-4.noarch.rpm
[root@server ~]# rpm -ivh pgdg-centos-8.3-4.noarch.rpm
[root@server ~]# yum install postgresql postgresql-server
[root@server ~]# chkconfig postgresql on
[root@server ~]# service postgresql initdb
[root@server ~]# chkconfig postgresql on && service postgresql start
[root@server ~]# /usr/bin/postgres –version
postgres (PostgreSQL) 8.3.4
[root@server ~]#
Set port and the interface to bind to
#########################################
vi /var/lib/pgsql/data/postgresql.conf
# – Connection Settings -
listen_addresses = ‘*’
port = 5432
Posted in Advanced Commands, Linux Administration, Linux General, Linux:- Tips & Tricks, postgres, postgresql, sql, yum | Leave a Comment »

NMAP
September 23, 2008
echo ” ========== Installing NMAP network Scanner ================= “
echo “…………………………………………………………………………………………………………………..”
echo “…………………………………………………………………………………………………………………..”
echo “Cleaning old nmap installation, if any “
yum -y remove nmap
echo “…………………………………………………………………………………………………………………..”
echo “Install beings “
yum -y install nmap
if [ -f /usr/bin/nmap ]
then
echo ” Nmap successfully installed”
sleep 2
echo ” Testing Nmap “
echo ” ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++”
sleep 3
/usr/bin/nmap localhost -v
sleep 5
else
echo ” Nmap faield to install”
fi
echo ” =========== Install NMAP network Scanner process completed ===============”
echo “…………………………………………………………………………………………………………………..”
echo “…………………………………………………………………………………………………………………..”
echo “…………………………………………………………………………………………………………………..”
Posted in Advanced Commands, Linux Administration, Linux General, Linux Security, Linux:- Tips & Tricks | Leave a Comment »

MySQL ERROR 1045 (28000): Access denied for user ‘root’@'localhost’ (using password: YES)
August 25, 2008
The other day I got this error on one of our servers. Fantastico module in cpanel was showing the error: Unable to connect to mysql database. While mysql service was running fine, the root user was unable to login to mysql database. I initially tried to reset the mysql root password like http://rhcelinuxguide.wordpress.com/2008/08/08/reset-mysql-root-password/ but that did not help. The real issue was permission on the folder /var/lib/mysql/mysql . It is supposed to be 711 , while it was 751. That fixed it.
==================================================================
root@server1 [~]# mysql
ERROR 1045 (28000): Access denied for user ‘root’@'localhost’ (using password: YES)
root@server1 [~]#
root@server1 [/var/lib/mysql/mysql]# ls -lhd /var/lib/mysql
drwxr-x–x 179 mysql mysql 12K Aug 25 01:44 /var/lib/mysql/
root@server1 [/var/lib/mysql/mysql]# chmod 711 /var/lib/mysql/mysql
root@server1 [/var/lib/mysql/mysql]# ls -lhd /var/lib/mysql/mysql
drwx–x–x 2 mysql mysql 4.0K Aug 25 01:32 /var/lib/mysql/mysql/
root@server1 [/var/lib/mysql/mysql]# service mysql restart
Shutting down MySQL..
[ OK ]
Starting MySQL [ OK ]
root@server1 [/var/lib/mysql/mysql]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.51a-community MySQL Community Edition (GPL)Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.
mysql> quit
Bye
root@server1 [/var/lib/mysql/mysql]#
==================================================================
Worked for me !
Posted in Advanced Commands, Linux Administration, Linux:- Tips & Tricks, Mysql | 1 Comment »

Virtuozzo Upgrade : Upgrading from Virtuozzo3 to Virtuozzo4
August 18, 2008
Upgrading from Virtuozzo 3 to Virtuozzo 4
================================
First of all refer to : http://www.parallels.com/en/products/virtuozzo/easy-upgrade/ for detailed explanation. When I decided to upgrade, there was not much available except the above docs. I used the inbuilt vzup2date for the upgrade purpose.
First of all apply all updates on your current Virtuozzo 3 using vzup2date , by selecting udate for virtuozzo 3.0.x only. Once updates are applied, it also does a kernel upgrade. It will finally ask if you want to reboot. Just select finish, and dont reboot. It is better to reboot manually, so that you can swith back to old kernel, in case the new kernel panics or hang up during boot.
Step 1
===================================================
[root@vpsMainNode virtuozzo]# vzup2date
Apply all updates on your current Virtuozzo 3.
Select option reboot manually and dont hit the reboot option, just select finish.
Next,
Edit /etc/grub.conf and change the option
default=0 to default=1 , so that the current kernel is selected in grub , instead of the new kernel , that was just installed.
Next we configure grub to boot the new kernel only for the next reboot. If the reboot does not go well and the system does not boot properly, do a hard reset ( ask your DC, if
reqd. ) and you will successfully boot into the last working kernel.
[root@vpsMainNode virtuozzo]# grub shell
Probing devices to guess BIOS drives. This may take a long time.
GNU GRUB version 0.95 (640K lower / 3072K upper memory)
[ Minimal BASH-like line editing is supported. For the first word, TAB
lists possible command completions. Anywhere else TAB lists the possible
completions of a device/filename.]
grub> savedefault –default=0 –once
grub> quit
[root@vpsMainNode virtuozzo]#
Reboot the server. If all goes fine, and the server comes up with the new kernel, edit /etc/grub.conf and change the option
default=1 to default=0
Next,
Run vzup2date again and select updates for Virtuozzo 3 , and go next , next to finish install ( select option manual reboot )
[root@vpsMainNode virtuozzo]# vzup2date
If all Virtuozzo 3 are already applied, you will see no more update available message.
Now that Virtuozzo 3 has all its latest stuff in its version, we will update Virtuozzo 3 to Virtuozzo 4.
Run vzup2date again,
[root@vpsMainNode virtuozzo]# vzup2date
This time, select Virtuozzo 4 for upgrades, do the usual next , next to apply updates. ( select option manual reboot )
This process will take some time depending on speed. Usually 20 to 60 minutes.
Again this will install a newer kernel, so
Next we configure grub to boot the new kernel only for the next reboot. If the reboot does not go well and the system does not boot properly, do a hard reset ( ask your DC, if
reqd. ) and you will successfully boot into the last working kernel.
[root@vpsMainNode virtuozzo]# grub shell
Probing devices to guess BIOS drives. This may take a long time.
GNU GRUB version 0.95 (640K lower / 3072K upper memory)
[ Minimal BASH-like line editing is supported. For the first word, TAB
lists possible command completions. Anywhere else TAB lists the possible
completions of a device/filename.]
grub> savedefault –default=0 –once
grub> quit
[root@vpsMainNode virtuozzo]#
Reboot the server. If all goes fine, and the server comes up with the new kernel, edit /etc/grub.conf and change the option
default=1 to default=0
Voila ! you have upgraded your server from Virtuozzo 3 to Virtuozzo 4. You will see that all nodes will work properly, start the nodes, if any active node is down in the usual
way.
[root@vpsMainNode virtuozzo]# vzctl start VE_ID
Note VE_ID is now also called as CT_ID ( container ID )
You will find that the Service VE ( now called as Service Container ) will fail to start. If not, then fine. You have nothing left to do , except running a vzup2date again and
apply any newer updates for one more time. If any new kernel is installed , then modify grub.conf as already discussed, while rebooting.
In case Service VE ( now called as Service Container ) fails to start or does not start, you will be unable to access your virtuozzo control panel.
Note , I destroyed old Service VE and recreated it, if for any reason, you want backup of old service , you might chose to make a backup of it.
Here is what I did to install the service CT
###############################################
[root@vpsMainNode virtuozzo]# vzctl destroy 1
[root@vpsMainNode virtuozzo]# cd /root/
[root@vpsMainNode virtuozzo]# wget http://download.parallels.com/virtuozzo/virtuozzo4.0/linux/iso/lin-i386.iso
[root@vpsMainNode virtuozzo]# mkdir /mnt/iso
[root@vpsMainNode virtuozzo]# mount -o loop lin-i386.iso /mnt/iso
[root@vpsMainNode virtuozzo]# vzsveinstall -D /mnt/iso -s xx.yy.zz.IP
[root@vpsMainNode virtuozzo]# vzlist -a | grep CT
CTID NPROC STATUS IP_ADDR HOSTNAME
1 77 running xx.yy.zz.IP ServiceCT
[root@vpsMainNode virtuozzo]#
[root@vpsMainNode virtuozzo]# lsof -i :4643
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
vzaproxy 531 root 4u IPv4 10286471 TCP *:4643 (LISTEN)
vzcp 591 root 4u IPv4 10286403 TCP *:4643 (LISTEN)
vzcp 595 apache 4u IPv4 10286403 TCP *:4643 (LISTEN)
vzcp 596 apache 4u IPv4 10286403 TCP *:4643 (LISTEN)
vzcp 3004 apache 4u IPv4 10286403 TCP *:4643 (LISTEN)
[root@vpsMainNode virtuozzo]#
[root@vpsMainNode virtuozzo]# vzctl restart 1
Restart Container
Stopping Container …
Container was stopped
[ OK ] down vzagent: [ OK ]
[ OK ] vzagent: [ OK ]
Container is unmounted
Starting Container …
Starting vzagent: [ OK ]
Starting vzagent: [ OK ]
Container is mounted
Setting devperms 20006 dev 0×7d00
Adding IP address(es): xx.yy.zz.IP
Hostname for Container set: ServiceCT
File resolv.conf was modified
Container start in progress…
[root@vpsMainNode virtuozzo]# vzlist -a | grep CT
CTID NPROC STATUS IP_ADDR HOSTNAME
1 77 running xx.yy.zz.IP ServiceCT
[root@vpsMainNode virtuozzo]#
[root@vpsMainNode log]# cd /root/
[root@vpsMainNode ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 9.9G 4.1G 5.3G 44% /
/dev/sda1 494M 81M 388M 18% /boot
none 4.0G 0 4.0G 0% /dev/shm
/dev/sda3 448G 267G 158G 63% /vz
/dev/sdb1 459G 123G 313G 29% /backup
/root/lin-i386.iso 582M 582M 0 100% /mnt/iso
[root@vpsMainNode ~]# mkdir /root/virt4_source
[root@vpsMainNode ~]# cp -r /mnt/iso/* /root/virt4_source/
[root@vpsMainNode ~]# umount /mnt/iso
[root@vpsMainNode ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 9.9G 4.7G 4.8G 50% /
/dev/sda1 494M 81M 388M 18% /boot
none 4.0G 0 4.0G 0% /dev/shm
/dev/sda3 448G 267G 158G 63% /vz
/dev/sdb1 459G 123G 313G 29% /backup
[root@vpsMainNode ~]#
Congrats !!! , now that you have got the Service Container Up and Running, time to explore/enjoy the new looks in Virtuozzo 4 control panel.
Posted in Advanced Commands, Linux Administration, Linux General, Linux Installation, Linux:- Tips & Tricks, Tuning Linux, Virtuozzo, upgrade virtuozzo, virtuozzo 3 to 4, virtuozzo 3 to virtuozzo 4, virtuozzo 3 upgrade, virtuozzo upgrade, virtuozzo version upgrade | Leave a Comment »

Reset MySQL Root Password
August 8, 2008
[root@dedicated08 ~]# lsof -i :3306
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
mysqld 31792 mysql 3u IPv4 434089 TCP *:mysql (LISTEN)
[root@dedicated08 ~]# kill -9 31792
[root@dedicated08 ~]# /etc/init.d/mysql start
Mysql Started
[root@dedicated08 ~]# mysql
Access denied for user ‘root’@'localhost’ (using password: NO)
[root@dedicated08 ~]# /etc/init.d/mysql stop
[root@dedicated08 ~]# mysqld_safe –skip-grant-tables &
[root@dedicated08 ~]#
[root@dedicated08 ~]# mysql -u root
mysql>
mysql> use mysql;
mysql> update user set password=PASSWORD(”NEW-ROOT-PASSWORD”) where
User=’root’;
mysql> flush privileges;
mysql> quit
NEW-ROOT-PASSWORD above is whatever password you want to set.
[root@dedicated08 ~]# # /etc/init.d/mysql stop
[root@dedicated08 ~]# lsof -i :3306
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
mysqld 31792 mysql 3u IPv4 434089 TCP *:mysql (LISTEN)
[root@dedicated08 ~]# kill -9 31792
[root@dedicated08 ~]# fuser -k /usr/bin/mysqld_safe ( in
case you see mysql process is still running )
[root@dedicated08 ~]# vi /root/.my.cnf
[root@dedicated08 ~]# cat /root/.my.cnf
[client]
user=”root”
pass=”NEW-ROOT-PASSWORD”
[root@dedicated08 ~]#
[root@dedicated08 ~]# service mysql restart
[root@dedicated08 ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.21-standard-log
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.
mysql> quit
Bye
[root@dedicated08 ~]#
Posted in Advanced Commands, Linux Administration, Linux:- Tips & Tricks, Mysql | Leave a Comment »

hwclock – query and set the hardware clock
August 5, 2008
set the system time from the hardware clock
============================================
root@s1 [~]# /sbin/hwclock –hctosys
root@s1 [~]#
set the hardware clock to the current system time
============================================
root@s1 [~]# /sbin/hwclock –systohc
root@s1 [~]#
root@s1 [~]# /sbin/hwclock –help
hwclock – query and set the hardware clock (RTC)
Usage: hwclock [function] [options...]
Functions:
–help show this help
–show read hardware clock and print result
–set set the rtc to the time given with –date
–hctosys set the system time from the hardware clock
–systohc set the hardware clock to the current system time
–adjust adjust the rtc to account for systematic drift since
the clock was last set or adjusted
–getepoch print out the kernel’s hardware clock epoch value
–setepoch set the kernel’s hardware clock epoch value to the
value given with –epoch
–version print out the version of hwclock to stdout
Options:
–utc the hardware clock is kept in coordinated universal time
–localtime the hardware clock is kept in local time
–directisa access the ISA bus directly instead of /dev/rtc
–badyear ignore rtc’s year because the bios is broken
–date specifies the time to which to set the hardware clock
–epoch=year specifies the year which is the beginning of the
hardware clock’s epoch value
–noadjfile do not access /etc/adjtime. Requires the use of
either –utc or –localtime
Posted in Advanced Commands, Linux Administration, Linux General, Linux:- Tips & Tricks | Leave a Comment »

iptables string match to drop malicious urls
August 5, 2008
iptables string match to drop malicious urls
==================================
Usually modsecurity rules can help filter many malicious url attack patterns combined with apache on apache port (http|https). But what if a malicious attack using a vulnerable url pattern, that exposes or tries to break into your system is coming onto another port?
This is where iptables string match comes in handy.
/usr/local/sbin/iptables -I INPUT -p tcp -s 0.0.0.0/0 -m string –string “download?file=%2e%2e” –algo bm -j DROP
[root@server ~]# iptables -L -v | grep STR
73 49908 DROP tcp – any any anywhere anywhere STRING match “download?file=%2e%2e” ALGO name bm TO 65535
[root@server ~]#
The above iptable rule will block any url that has the string “download?file=%2e%2e” on any port on your server.
Note: your iptables binary path may be /sbin/iptables
Say http://yourserverIP:9132/blah/download?file=%2e%2e
Posted in Advanced Commands, Linux Administration, Linux General, Linux Security, Linux:- Tips & Tricks, Tuning Linux, iptables | 2 Comments »

Rename a username , groupname and its homedirectory with usermod
August 5, 2008
Rename user 7777777 ’s name, groupname and homedir to 88888888 with usermod
root@server1 [/home]# useradd 7777777
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/passwd
7777777:x:32147:32148::/home/
7777777:/bin/bash
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/group
7777777:x:32148:
root@server1 [/home]#
root@server1 [/home]# usermod -d /home/88888888 7777777
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/passwd
7777777:x:32147:32148::/home/88888888:/bin/bash
root@server1 [/home]#
************************************************************************************************************
root@server1 [/home]# rm -fr /home/7777777/ OR you can mv /home/7777777 /home/88888888, if you want
************************************************************************************************************
root@server1 [/home]# usermod -l 88888888 7777777
failed to rename mailbox: File exists
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/passwd
root@server1 [/home]# grep 88888888 /etc/passwd
88888888:x:32147:32148::/home/88888888:/bin/bash
root@server1 [/home]#
root@server1 [/home]# groupmod -n 88888888 7777777
root@server1 [/home]#
root@server1 [/home]# grep 7777777 /etc/group
root@server1 [/home]#
root@server1 [/home]# grep 88888888 /etc/group
88888888:x:32148:
root@server1 [/home]#
Posted in Advanced Commands, Linux Administration, Linux General, Linux:- Tips & Tricks | Leave a Comment »

create a directory with different permission mode
July 29, 2008
—————————————————————
[root@server ~]# mkdir /root/test1 -v -m 1777
mkdir: created directory `/root/test1′
[root@server ~]# ls -lhd /root/test1
drwxrwxrwt 2 root root 4.0K Jul 29 01:42 /root/test1
[root@server ~]#
v = verbose, is not mandatory though