Board index Linux Linux - Tips&Tricks

Moderator: chandranjoy

Tips & Tricks

Postby chandranjoy » Sun Apr 04, 2010 12:49 am

Download Linux hardening guide:
http://innovationframes.com/phpbb/download/Linux-Hardening.pdf

TIP 1:
NTP
Is NTP Working?

STEP 1 (Test the current server):

Try issuing the following command:

$ ntpq -pn


remote refid st t when poll reach delay offset jitter
===================================================
tock.usno.navy 0.0.0.0 16 u - 64 0 0.000 0.000 4000.00

The above is an example of a problem.
Compare it to a working configuration.

$ ntpq -pn


remote refid st t when poll reach delay offset jitter
========================================================
+128.4.40.12 128.4.40.10 2 u 107 128 377 25.642 3.350 1.012
127.127.1.0 127.127.1.0 10 l 40 64 377 0.000 0.000 0.008
+128.91.2.13 128.4.40.12 3 u 34 128 377 21.138 6.118 0.398
*192.5.41.41 .USNO. 1 u 110 128 377 33.69 9.533 3.534

STEP 2 (Configure the /etc/ntp.conf):

$ cat /etc/ntp.conf


# My simple client-only ntp configuration.
server timeserver1.upenn.edu
# ping -a timeserver1.upenn.edu shows the IP address 128.91.2.13
# which is used in the restrict below
restrict 128.91.2.13
server tock.usno.navy.mil
restrict 192.5.41.41
server 128.4.40.12
restrict 128.4.40.12
server 127.127.1.0 # local clock
fudge 127.127.1.0 stratum 10
driftfile /etc/ntp/drift
restrict default ignore
restrict 127.0.0.0 mask 255.0.0.0
authenticate no

STEP 3 (Configure /etc/ntp/step-tickers):

The values for server above are placed in the "/etc/ntp/step-tickers" file

$ cat /etc/ntp/step-tickers


timeserver1.upenn.edu
tock.usno.navy.mil
128.4.40.12

The startup script /etc/rc.d/init.d/ntpd will grab the servers in this
file and execute the ntpdate command as follows:

/usr/sbin/ntpdate -s -b -p 8 timeserver1.upenn.edu

Why? Because if the time is off ntpd will not start. The command above set the
clock. If System Time deviates from true time by more than 1000 seconds, then,
the ntpd daemon will enter panic mode and exit.

STEP 4 (Restart the service and check):

Issue the restart command

/etc/init.d/ntpd restart


check the values for "ntpq -pn",
which should match step 1.
ntpq -pn



TIP 2:


cpio works like tar, only better.

STEP 1 (Create two directories with data ../dir1 an ../dir2)
mkdir -p ../dir1
mkdir -p ../dir2
cp /etc/*.conf ../dir1/.
cp /etc/*.cnf ../dir2/.


Which will backup all your cnf and conf files.

STEP 2 (Piping the files to tar)

cpio works like tar but can take input
from the "find" command.
$ find ../dir1/ | cpio -o --format=tar > test.tar
or
$ find ../dir1/ | cpio -o -H tar > test2.tar


Same command without the ">"

$ find ../dir1/ | cpio -o --format=tar -F test.tar
or
$ find ../dir1/ | cpio -o -H tar -F test2.tar


Using append

$ find ../dir1/ | cpio -o --format=tar -F test.tar
or
$ find ../dir2/ | cpio -o --format=tar --append -F test.tar


STEP 3 (List contents of the tar file)

$ cpio -it < test.tar
or
$ cpio -it -F test.tar

STEP 4 (Extract the contents)

$ cpio -i -F test.tar



TIP 3:

Working with tar. The basics with encryption.

STEP 1 (Using the tar command on the directory /stuff)

Suppose you have a directory /stuff
To tar everything in stuff to create a ".tar" file.

$ tar -cvf stuff.tar stuff


Which will create "stuff.tar".

STEP 2 (Using the tar command to create a ".tar.gz" of /stuff)

$ tar -czf stuff.tar.gz stuff


STEP 3
(List the files in the archive)
$ tar -tzf stuff.tar.gz
or
$ tar -tf stuff.tar


STEP 4
(A way to list specific files)

Note, pipe the results to a file and edit

$ tar -tzf stuff.tar.gz > mount


Then, edit mout to only include the files you want

$ tar -T mout -xzf stuff.tar.gz


The above command will only get the files in mount.
Of course, if you want them all

$ tar -xzf stuff.tar.gz


STEP 5 (ENCRYPTION)

$ tar -zcvf - stuff|openssl des3 -salt -k secretpassword | dd of=stuff.des3


This will create stuff.des3...don't forget the password you
put in place of secretpassword. This can be done interactively as
well.

$ dd if=stuff.des3 |openssl des3 -d -k secretpassword|tar zxf -


NOTE: above there is a "-" at the end... this will extract everything.

Special Notes:
Extracting Specific Files

Extract a file called /etc/default/sysstat from config.tar.gz tarball:
$ tar -ztvf config.tar.gz
$ tar -zxvf config.tar.gz etc/default/sysstat
$ tar -xvf {tarball.tar} {path/to/file}

Some people prefers following syntax:
tar --extract --file={tarball.tar} {file}


Extract a directory called css from cbz.tar:
$ tar --extract --file=cbz.tar css


Wildcard based extracting
You can also extract those files that match a specific globbing pattern (wildcards). For example, to extract from cbz.tar all files that begin with pic, no matter their directory prefix, you could type:
$ tar -xf cbz.tar --wildcards --no-anchored 'pic*'


To extract all php files, enter:
$ tar -xf cbz.tar --wildcards --no-anchored '*.php'


Where,
* -x: instructs tar to extract files.
* -f: specifies filename / tarball name.
* -v: Verbose (show progress while extracting files).
* -j : filter archive through bzip2, use to decompress .bz2 files.
* -z: filter archive through gzip, use to decompress .gz files.
* --wildcards: instructs tar to treat command line arguments as globbing patterns.
* --no-anchored: informs it that the patterns apply to member names after any / delimiter.


TIP 4:

Creating a Virtual File System and Mounting it with a Loopback Device.

STEP 1 (Construct a 10MB file)

$ dd if=/dev/zero of=/tmp/disk-image count=20480


By default dd uses block of 512 so the size will be 20480*512

STEP 2 (Make an ext2 or ext3 file system) -- ext2 shown here.

$ mke2fs -q


or if you want ext3

$ mkfs -t ext3 -q /tmp/disk-image


yes, you can even use reiser, but you'll need to create a bigger
disk image. Something like "dd if=/dev/zero of=/tmp/disk-image count=50480".

$ mkfs -t reiserfs -q /tmp/disk-image


Hit yes for confirmation. It only asks this because it's a file


STEP 3 (Create a directory "virtual-fs" and mount. This has to be done as root)
$ mkdir /virtual-fs
$ mount -o loop=/dev/loop0 /tmp/disk-image /virtual-fs


SPECIAL NOTE: if you mount a second device you will have to increase the
loop count: loop=/dev/loop1, loop=/dev/loop2, ... loop=/dev/loopn

Now it operates just like a disk. This virtual filesystem can be mounted
when the system boots by adding the following to the "/etc/fstab" file. Then,
to mount, just type "mount /virtual-fs".

/tmp/disk-image /virtual-fs ext2 rw,loop=/dev/loop0 0 0

STEP 4 (When done, umount it)

$ umount /virtual-fs



SPECIAL NOTE: If you are using Fedora core 2, in the /etc/fstab you can take
advantage of acl properties for this mount. Note the acl next to the
rw entry. This is shown here with ext3.

/tmp/disk-image /virtual-fs ext3 rw,acl,loop=/dev/loop1 0 0


Also, if you are using Fedora core 2 and above, you can mount the file
on a cryptoloop.

$ dd if=/dev/urandom of=disk-aes count=20480
$ modprobe loop
$ modprobe cryptoloop
$ modprobe aes

$ losetup -e aes /dev/loop0 disk-aes
$ mkfs -t ext2 /dev/loop0
$ mount -o loop,encryption=aes disk-aes <mount point>


HELPFUL INFORMATION: It is possible to bind mount partitions, or associate the
mounted partition to a directory name.

# mount --bind /virtual-fs /home/mchirico/vfs


Also, if you want to see what filesystems are currently mounted, "cat" the
file "/etc/mtab"

$ cat /etc/mtab


Also see TIP 91.



TIP 5:

Setting up 2 IP address on "One" NIC. This example is on ethernet.

STEP 1 (The settings for the initial IP address)

$ vi /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=static
BROADCAST=192.168.99.255
IPADDR=192.168.1.155
NETMASK=255.255.252.0
NETWORK=192.168.1.0
ONBOOT=yes


STEP 2 (2nd IP address: )

$ vi /etc/sysconfig/network-scripts/ifcfg-eth0:1
DEVICE=eth0:1
BOOTPROTO=static
BROADCAST=192.168.99.255
IPADDR=192.168.1.182
NETMASK=255.255.252.0
NETWORK=192.168.1.0
ONBOOT=yes


Then
ifup eth0 up


SUMMARY Note, in STEP 1 the filename is "ifcfg-eth0", whereas in
STEP 2 it's "ifcfg-eth0:1" and also not the matching
entries for "DEVICE=...". Also, obviously, the
"IPADDR" is different as well.


TIP 6:


Sharing Directories Among Several Users.

Several people are working on a project in "/home/share"
and they need to create documents and programs so that
others in the group can edit and execute these documents
as needed. Also see (TIP 186) for adding existing users
to groups.
$ /usr/sbin/groupadd share
$ chown -R root.share /home/share
$ /usr/bin/gpasswd -a <username> share
$ chmod 2775 /home/share
$ ls -ld /home/share
drwxrwsr-x 2 root share 4096 Nov 8 16:19 /home/share
^---------- Note the s bit, which was set with the chmod 2775
$ cat /etc/group
...
share:x:502:chirico,donkey,zoe
... ^------- users are added to this group.


The user may need to login again to get access. Or, if the user is currently
logged in, they can run the following command:

$ su - <username>


Note, the above step is recommended over "newgrp - share" since currently
newgrp in FC2,FC3, and FC4 gets access to the group but the umask is not
correctly formed.

As root you can test their account.

$ su - <username> "You need to '-' to pickup thier environment '$ su - chirico' "


Note: SUID, SGID, Sticky bit. Only the left most octet is examined, and "chmod 755" is used
as an example of the full command. But, anything else could be used as well. Normally
you'd want executable permissions.

Octal digit Binary value Meaning Example usage
0 000 all cleared $ chmod 0755 or chmod 755
1 001 sticky $ chmod 1755
2 010 setgid $ chmod 2755
3 011 setgid, sticky $ chmod 3755
4 100 setuid $ chmod 4755
5 101 setuid, sticky $ chmod 5755
6 110 setuid, setgid $ chmod 6755
7 111 setuid, setgid, sticky $ chmod 7755


A few examples applied to a directory below. In the first example all users in the group can
add files to directory "dirA" and they can delete their own files. Users cannot delete other
user's files.

Sticky bit:
$ chmod 1770 dirA


Below files created within the directory have the group ID of the directory, rather than that
of the default group setting for the user who created the file.

Set group ID bit:
$ chmod 2755 dirB




TIP 7:

Getting Information on Commands

The "info" is a great utility for getting information about the system.
Here's a quick key on using "info" from the terminal prompt.

'q' exits.
'u' moves up to the table of contents of the current section.
'n' moves to the next chapter.
'p' moves to the previous chapter.
'space' goes into the selected section.

The following is a good starting point:

$ info coreutils


Need to find out what a certain program does?

$ whatis open

open (2) - open and possibly create a file or device
open (3) - perl pragma to set default PerlIO layers for input and output
open (3pm) - perl pragma to set default PerlIO layers for input and output
open (n) - Open a file-based or command pipeline channel

To get specific information about the open commmand

$ man 2 open


also try 'keyword' search, which is the same as the apropos command.
For example, to find all the man pages on selinux, type the following:

$ man -k selinux


or the man full word search. Same as whatis command.

$ man -f <some string>


This is a hint once you are inside man.

space moves forward one page
b moves backward
y scrolls up one line "yikes, I missed it!"
g goes to the beginning
q quits
/<string> search, repeat seach n
m mark, enter a letter like "a", then, ' to go back
' enter a letter that is marked.

To get section numbers

$ man 8 ping


Note the numbers are used as follows
(This is OpenBSD)

1 General Commands
2 System Calls and Error Numbers
3 C Libraries
3p perl
4 Devices and device drivers
5 File Formats and config files
6 Game instructions
7 Miscellaneous information
8 System maintenance
9 Kernel internals

To find the man page directly, "ls" command:

$ whereis -m ls

ls: /usr/share/man/man1/ls.1.gz /usr/share/man/man1/ls.1 /usr/share/man/man1p/ls.1p

To read this file directly, do the following:

$ man /usr/share/man/man1/ls.1.gz


If you want to know the manpath, execute manpath.

$ manpath

/usr/share/man:/usr/X11R6/man:/usr/local/share/man:/usr/local/pgsql/man:/usr/man:/usr/local/man


TIP 8:


How to Put a "Running Job" in the Background.

You're running a job at the terminal prompt, and it's taking
a very long time. You want to put the job in the backgroud.

"CTL - z" Temporarily suspends the job
$ jobs This will list all the jobs
$ bg %jobnumber (bg %1) To run in the background
$ fg %jobnumber To bring back in the foreground


Need to kill all jobs -- say you're using several suspended
emacs sessions and you just want everything to exit.

$ kill -9 `jobs -p`


The "jobs -p" gives the process number of each job, and the
kill -9 kills everything. Yes, sometimes "kill -9" is excessive
and you should issue a "kill -15" that allows jobs to clean-up.
However, for exacs session, I prefer "kill -9" and haven't had
a problem.

Sometimes you need to list the process id along with job
information. For instance, here's process id with the listing.

$ jobs -l


Note you can also renice a job, or give it lower priority.

$ nice -n +15 find . -ctime 2 -type f -exec ls {} \; > last48hours
^z
$ bg


So above that was a ctl-z to suppend. Then, bg to run it in
the background. Now, if you want to change the priority lower
you just renice it, once you know the process id.
$ jobs -pl
[1]+ 29388 Running nice -n +15 find . -ctime 2 -exec ls -l {} \; >mout &
$ renice +30 -p 29388
29388: old priority 15, new priority 19

19 was the lowest priority for this job. You cannot increase
the priority unless you are root.


TIP 9:


Need to Delete a File for Good -- not even GOD can recover.

You have a file "secret". The following makes it so no one
can read it. If the file was 12 bytes, it's now 4096 after it
has been over written 100 times. There's no way to recover this.

$ shred -n 100 -z secret


Want to remove the file? Use the "u" option.

$ shred -n 100 -z -u test2


It can be applied to a device

$ shred -n 100 -z -u /dev/fd0



CAUTION: Note that shred relies on a very important assumption: that the file system overwrites data
in place. This is the traditional way to do things, but many modern file system designs do not sat-
isfy this assumption. The following are examples of file systems on which shred is not effective, or
is not guaranteed to be effective in all file system modes:

* log-structured or journaled file systems, such as those supplied with

AIX and Solaris (and JFS, ReiserFS, XFS, Ext3, etc.)



TIP 10:


Need a WWW Browser for the Terminal Session? Try lynx or elinks.
$ lynx


Or to read all these tips, with the latest updates




Or, better yet elinks.

$ elinks http://somepage.


You can get elinks at the following site:

/

TIP 11:

Keep Logs Longer with Less Space.

Normally logs rotate monthly, over writing all the old data. Here's a
sample "/etc/logrotate.conf" that will keep 12 months of backup
compressing the logfiles

$ cat /etc/logrotate.conf


# see "man logrotate" for details
# rotate log files weekly
#chirico changes to monthly
monthly

# keep 4 weeks worth of backlogs
# keep 12 months of backup
rotate 12

# 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 wtmp -- we'll rotate them here
/var/log/wtmp {
monthly
create 0664 root utmp
rotate 1
}

# system-specific logs may be also be configured here.



TIP 12:


SSH - How to Generate the Key Pair.

On the local server

$ ssh-keygen -t dsa -b 2048


This will create the two files:

.ssh/id_dsa (Private key)
.ssh/id_dsa.pub (Public key you can share)

Next insert ".ssh/id_dsa.pub" on the remote server
in the file ".ssh/authorized_keys" and ".ssh/authorized_keys2"
and change the permission of each file to (chmod 600). Plus, make
sure the directory ".ssh" exists on the remote computer with 700 rights.
Ok, assuming 192.168.1.155 is the remote server and "donkey" is the
account on that remote server.

$ ssh donkey@192.168.1.155 "mkdir -p .ssh"
$ ssh donkey@192.168.1.155 "chmod 700 .ssh"
$ scp ./.ssh/id_dsa.pub donkey@192.168.1.155:.ssh/newkey.pub


Now connect to that remote server "192.168.1.155" and add .ssh/newkey.pub
to both "authorized_keys" and "authorized_keys2". When done, the permission
on
(This is on the remote server)

$chmod 600 .ssh/authorized_key*


Next, go back to the local server and issue the following:

$ ssh-agent $SHELL
$ ssh-add


The "ssh-add" will allow you to enter the passphrase and it will
save it for the current login session.

You don't have to enter a password when running "ssh-keygen" above. But,
remember anyone with root access can "su - <username>" and then connect
to your computers. It's harder, however, not impossible, for root to do
this if you have a password.


Below is a quick shell command to distribute ssh keys. I find
this command to be very useful.

$ cat ~/.ssh/id_dsa.pub|ssh remoteserver "cat - >> ~/.ssh/authorized_keys"



TIP 13:

Securing the System: Don't allow root to login remotely. Instead,
the admin could login as another account, then, "su -". However,
root can still login "from the local terminal".

In the "/etc/ssh/sshd_config" file change the following lines:
Protocol 2
PermitRootLogin no
PermitEmptyPasswords no


Then, restart ssh

/etc/init.d/sshd restart


Why would you want to do this? It's not possible for anyone to guess
or keep trying the root account. This is especially good for computers
on the Internet. So, even if the "root" passwords is known, they can't
get access to the system remotely. Only from the terminal, which is locked
in your computer room. However, if anyone has a account on the server,
then, they can login under their account then "su -".

Suppose you only want a limited number of users: "mchirico" and "donkey".
Add the following line to "/etc/ssh/sshd_config". Note, this allows access
for chirico and donkey, but everyone else is denied.

# Once you add AllowUsers - everyone else is denied.
AllowUsers mchirico donkey



TIP 14:

How to make a File "immutable" or "unalterable" -- it cannot be changed
or deleted even by root. Note this works on (ext2/ext3) filesystems.
And, yes, root can delete after it's changed back.

As root:
$ chattr +i filename


And to change it back:
$ chattr -i filename


List attributes
$ lsattr filename



TIP 15:


Kill a User and All Their Current Processes.

#!/bin/bash
# This program will kill all processes from a
# user. The user name is read from the command line.
#
# This program also demonstrates reading a bash variable
# into an awk script.
#
# Usage: kill9user <user>
#

kill -9 `ps aux|awk -v var=$1 '$1==var { print $2 }'`


or if you want want to create the above script the command
below will kill the user "donkey" and all of his processes.

$ kill -9 `ps aux|awk -v var="donkey" '$1==var { print $2 }'`


Check their cron jobs and "at" jobs, if you have a security issue.

$ crontab -u <user> -e


Lock the account:
$ passwd -l <user>


Remove all authorized_keys
$ rm /home/user/.shosts
$ rm /home/user/.rhosts
$ rm -rf /home/user/.ssh
$ rm /home/user/.forward


or consider
$ mv /home/user /home/safeuser


Change the shell
$ chsh -s /bin/true <user>


Do an inventory

$ find / -user <user> > list_of_user_files


To see all users, except the current user. Do not use the
dash "ps -aux" is wrong but the following is correct:

$ ps aux| awk '!/'${USER}'/{printf("%s \n",$0)}'


or (ww = wide, wide output)

$ ps auwwx| awk '!/'${USER}'/{printf("%s \n",$0)}'



The following codes may be useful:

D Uninterruptible sleep (usually IO)
R Running or runnable (on run queue)
S Interruptible sleep (waiting for an event to complete)
T Stopped, either by a job control signal or because it is being traced.
W paging (not valid since the 2.6.xx kernel)
X dead (should never be seen)
Z Defunct ("zombie") process, terminated but not reaped by its parent.


For BSD formats and when the stat keyword is used, additional
characters may be displayed:

< high-priority (not nice to other users)
N low-priority (nice to other users)
L has pages locked into memory (for real-time and custom IO)
s is a session leader
l is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)
+ is in the foreground process group



TIP 16:

Record Eveything Printed on Your Terminal Screen.
$ script -a <filename>


Now start doing stuff and "everything" is appended to <filename>.
For example
$ script installation

$ (command)

$ (result)

$ ...

$ ...

$ (command)

$ (result)

$ exit

The whole session log is in the installation file that you can later
read and/or cleanup and add to a documentation.

This command can also be used to redirect the contents to another user,
but you must be root to do this.

Step 1 - find out what pts they are using.

$ w


Step 2 - Run script on that pts. After running this command below
everything you type will appear on their screen.

$ script /dev/pts/4




TIP 17:


Monitor all Network Traffic Except Your Current ssh Connection.

$ tcpdump -i eth0 -nN -vvv -xX -s 1500 port not 22


Or to filter out port 123 as well getting the full length of the packet
(-s 0), use the following:

$ tcpdump -i eth0 -nN -vvv -xX -s 0 port not 22 and port not 123


Or to filter only a certain host say 81.169.158.205

$ tcpdump -i eth0 -nN -vvv -xX port not 22 and host 81.169.158.205


Just want ip addresses and a little bit of data, then,
use this. The "-c 20" is to stop after 20 packets.

$ tcpdump -i eth0 -nN -s 1500 port not 22 -c 20


If you're looking for sign of DOS attacks, the following show just the SYN
packets on all interfaces:

$ tcpdump 'tcp[13] & 2 == 2'




TIP 18:


Setting or Changing the Library Path.

The following contains the settings to be added or deleted

/etc/ld.so.conf

After this file is edited, you must run the following:

$ ldconfig

See "man ldconfig" for more information.

TIP 19:

Need to Keep Secrets? Encrypt it.

To Encrypt:

$ openssl des3 -salt -in file.txt -out file.des3


The above will prompt for a password, or you can put it in
with a -k option, assuming you're on a trusted server.

To Decrypt

$ openssl des3 -d -salt -in file.des3 -out file.txt -k mypassword


Need to encrypt what you type? Enter the following, then start typing
and ^D to end.

$ openssl des3 -salt -out stuff.txt




TIP 19:


Using the "find" Command.

List only directories, max 2 nodes down that have "net" in the name

$ find /proc -type d -maxdepth 2 -iname '*net*'


Find all *.c and *.h files starting from the current "." position.

$ find . \( -iname '*.c' -o -iname '*.h' \) -print


Find all, but skip what's in "/CVS" and "/junk". Start from "/work"


$ find /work \( -iregex '.*/CVS' -o -iregex '.*/junk' \) -prune -o -print

Note -regex and -iregex work on the directory as well, which means
you must consider the "./" that comes before all listings.

Here is another example. Find all files except what is under the CVS, including
CVS listings. Also exclude "#" and "~".

$ find . -regex '.*' ! \( -regex '.*CVS.*' -o -regex '.*[#|~].*' \)


Find a *.c file, then run grep on it looking for "stdio.h"

$ find . -iname '*.c' -exec grep -H 'stdio.h' {} \;
sample output --> ./prog1.c:#include <stdio.h>
./test.c:#include <stdio.h>


Looking for the disk-hog on the whole system?

$ find / -size +10000k 2>/dev/null


Looking for files changed in the last 24 hours? Make sure you add the
minus sign "-1", otherwise, you will only find files changed exactly
24 hours from now. With the "-1" you get files changed from now to 24
hours.


$ find . -ctime -1 -printf "%a %f\n"
Wed Oct 6 12:51:56 2004 .
Wed Oct 6 12:35:16 2004 How_to_Linux_and_Open_Source.txt

Or if you just want files.

$ find . -type f -ctime -1 -printf "%a %f\n"


Details on file status change in the last 48 hours, current directory. Also note "-atime -2").

$ find . -ctime -2 -type f -exec ls -l {} \;

NOTE: if you don't use -type f, you make get "." returned, which
when run through ls "ls ." may list more than what you want.

Also you may only want the current directory

$ find . -ctime -2 -type f -maxdepth 1 -exec ls -l {} \;


To find files modified within the last 5 to 10 minutes

$ find . -mmin +5 -mmin -10



For more example "find" commands, reference the following looking
for the latest version of "bashscripts.x.x.x.tar.gz":

http://sourceforge.net/project/showfile ... e_id=80711

for examples of find using the inode feature. " $ find . -inum <inode> -exec rm -- '{}' \; "

If you don't want error messages, or need to redirect error messages "> /dev/null 2>&1"


TIP 20:

Limits: file size, open files, pipe size, stack size, max memory size cpu time, plus others.

To get a listing of current limits:

$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) unlimited
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 8179
virtual memory (kbytes, -v) unlimited

Note as a user you can decrease your limits in the current
shell session; but, you cannot increase. This can be ideal
for testing programs. But, first you may want to create
another shell "sh" so that you can "go back to where started".

$ ulimit -f 10


Now try

$ yes >> out

File size limit exceeded

To set limits on users, make changes to "/etc/security/limits.conf"

bozo - maxlogins 1


Will keep bozo from loging in more than once.

To list hard limits:

$ ulimit -Ha


To list soft limits:

$ ulimit -Sa


To restrict user access by time, day make changes to
"/etc/security/time.conf"

Also take a look at "/etc/profile" to see what other changes
can be made, plus take a look under "/etc/security/*.conf" for
other configuration files.

TIP 21:

Guard against SYN attacks and "ping".

As root do the following:

echo 1 > /proc/sys/net/ipv4/tcp_syncookies


Want to disable "ping" ?

echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all


Disable broadcast/multicast "ping" ?

echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts


And to enable again:

echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all

TIP 22:

Generating Random Numbers.
$ od -vAn -N4 -tu4 < /dev/urandom
3905158199



TIP 23:


RPM Usage Summary.

Install. Full filename is needed.

$ rpm -ivh Fedora/RPMS/postgresql-libs-7.4.2-1.i386.rpm


To view list of files installed with a particular package.

$ rpm -ql postgresql-libs
/usr/lib/libecpg.so.4
/usr/lib/libecpg.so.4.1
/usr/lib/libecpg_compat.so.1
/usr/lib/libecpg_compat.so.1.1
/usr/lib/libpgtypes.so.1
...

Or, to get the file listing from a package that is not installed use the
"-p" option.

$ rpm -pql /iso0/Fedora/RPMS/libpcap-0.8.3-7.i386.rpm

/usr/share/doc/libpcap-0.8.3/CHANGES
/usr/share/doc/libpcap-0.8.3/LICENSE
/usr/share/doc/libpcap-0.8.3/README
/usr/share/man/man3/pcap.3.gz

Note, you can also get specific listing. For example, suppose you
want to view the changelog

$ rpm -q --changelog audit

* Tue Jan 13 2009 Steve Grubb <sgrubb@redhat.com> 1.7.11-2
- Add crypto event definitions

* Sat Jan 10 2009 Steve Grubb <sgrubb@redhat.com> 1.7.11-1
- New upstream release

Or, maybe you want to see what scripts are installed.

$ rpm -q --scripts audit

postinstall scriptlet (using /bin/sh):
/sbin/chkconfig --add auditd
preuninstall scriptlet (using /bin/sh):
if [ $1 -eq 0 ]; then
/sbin/service auditd stop > /dev/null 2>&1
/sbin/chkconfig --del auditd
fi
postuninstall scriptlet (using /bin/sh):
if [ $1 -ge 1 ]; then
/sbin/service auditd condrestart > /dev/null 2>&1 || :
fi

For dependencies listing, use the "R" option.

$ rpm -qpR /iso0/Fedora/RPMS/libpcap-0.8.3-7.i386.rpm

/sbin/ldconfig
/sbin/ldconfig
kernel >= 2.2.0
libc.so.6
libc.so.6(GLIBC_2.0)
libc.so.6(GLIBC_2.1)
libc.so.6(GLIBC_2.1.3)
libc.so.6(GLIBC_2.3)
openssl
rpmlib(CompressedFileNames) <= 3.0.4-1
rpmlib(PayloadFilesHavePrefix) <= 4.0-1


To check the integrity, use the "-K" option.

$ rpm -K /iso0/Fedora/RPMS/libpcap-0.8.3-7.i386.rpm

/iso0/Fedora/RPMS/libpcap-0.8.3-7.i386.rpm: (sha1) dsa sha1 md5 gpg OK

To list all packages installed.

$ rpm -qa


To find out which file a package belongs to.

$ rpm -qf /usr/lib/libecpg.so.4.1


To find the source. (See Tip 246 for more detail)

$ rpm -qi sysstat


To uninstall a package

$ rpm -e

For building rpm packages reference the following:
http://www-106.ibm.com/developerworks/library/l-rpm1/

To verify md5 sum so that you know it downloaded ok

$ rpm -K *.rpm


TIP 24:

How to generate random password?

Below given command provides 10 passwords which contains 9 characters.

cat /dev/urandom|tr -dc "a-zA-Z0-9-_\$\?"|fold -w 9|head -10
openssl rand 12 -base64


TIP 25:
RPM commands lock up or freeze

Sounds like the RPM database has been corrupted.

1. cd /var/lib/rpm
2. db_verify Packages (only salvagable if this is ok)
3. rm -f __db.*
4. rpm -vv --rebuilddb


Cool :)

TIP 26:
Adding new TrueType fonts(TTF) in Linux

1. Make a new directory, say /usr/X11R6/lib/X11/fonts/MyTTFdir
2. Copy your .ttf font files into there
3. cd /usr/X11R6/lib/X11/fonts/MyTTFdir
4. ttmkfdir to make the fonts.scale file
5. mkfontdir to make the fonts.dir file (needed for TTF fonts?)
6. chkfontpath --add=/usr/X11R6/lib/X11/fonts/MyTTFdir (or manually by editing /etc/X11/fs/config)
7. service xfs restart (or /etc/init.d/xfs restart)
8. chkfontpath --list to see if MyTTFdir was added
9. xfontsel to browse/view available fonts


TIP 27:

CD Burning in Linux

* cdrecord -scanbus to find out the SCSI ID X,Y,Z of your burner (usually 0,0,0)
* cdrecord -v dev=0,0,0 blank=fast to fast blank a CD-RW
* cdrecord -v dev=0,0,0 blank=all to thoroughly blank a CD-RW
* mkisofs -v -J -r -o mysrcdir.iso mysrcdir to create an ISO image of all files in directory mysrcdir
* mount -t iso9660 -o ro,loop mysrcdir.iso /mnt/cdrom to check that the ISO image is OK before burning
* mkisofs -v dev=0,0,0 speed=10 -data mysrcdir.iso to burn ISO image at 10x speed
* cdrecord -dummy ... will do a dummy write for testing
* cdrecord driveropts=burnproof will turn on 'burnproof' settings
* mkisofs -v -J -r . | cdrecord -v driveropts=burnproof speed=10 dev=0,0,0 - will avoid creating an intermediate ISO file
* mount /mnt/cdrom to mount the CD
* cdrecord -v speed=10 dev=0,0,0 -pad -audio *.wav will burn an audio CD of .wav files


Enjoy :)
chandranjoy
Site Admin
 
Posts: 283
Joined: Fri Oct 23, 2009 11:19 pm

Return to Linux - Tips&Tricks

Who is online

Users browsing this forum: No registered users and 1 guest


cron