Monday, 17 September 2012


* The Shell is a command line interpreter that executes commands read from the standard input device such as keyboard or from a file.
* In other forms, it is a user program or it is an environment provided for user interaction.
* We can start using the shell by opening the console(terminal).
* The shell is not a part of system kernel, but it uses the system to execute programs.
* The various shells available for linux are:
  • BASH (Bourne-Again SHell) – Most common shell in Linux. It is an Opensource software.
  • CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming language.
  • KSH (Korn SHell) – Created by David Korn at AT & T Bell Labs. The Korn Shell also was the base for the POSIX Shell standard specifications.
  • TCSH – It is an enhanced but completely compatible version of the Berkeley UNIX C shell (CSH).
What is a shell script ?
* A shell script is series of commands stored in a plain text file.
* Shell scripts are a fundamental part of the UNIX and Linux programming environment.
* Scripts are useful for automating the processes repeatedly at the command line.
* Linux users involved with system administraton and troubleshooting often work with the shell scripts.
/etc/profile is the system-wide user login script which runs whenever a user logs into the system.
Each shell script consists of
• Shell keywords such as if..else, do..while.
• Shell commands such as pwd, test, echo, continue, type.
• Linux binary commands such as w, who, free etc..
• Text processing utilities such as grep, awk, cut.
• Functions – add frequent actions together via functions. For example, /etc/init.d/functions file contains functions
to be used by most or all system shell scripts in the /etc/init.d directory.
• Control flow statments such as if..then..else or shell loops to preform repeated actions.
Each script has purpose
• Specific purpose – For example, backup file system and database to NAS server.
• Act like a command – Each shell script is executed like any other command under Linux.
• Script code usability – Shell scripts can be extended from existing scripts. Also, you can use functions files to
package frequently used tasks.
Why shell scripting?
• Shell scripts can take input from a user or file and output them to the screen.
• Whenever you find yourself doing the same task over and over again you should use shell scripting, i.e., repetitive
task automation.
• Creating your own power tools/utilities.
• Automating command input or entry.
• Customizing administrative tasks.
• Creating simple applications.
• Since scripts are well tested, the chances of errors are reduced while configuring services or system
administration tasks such as adding new users.
Realtime usage of shell scripts where it is actively used:
• Monitoring Linux system.
• Data backup and creating snapshots.
• Dumping Oracle or MySQL database for backup.
• Creating email based alert system.
• Find out what processes are eating up our system resources.
• Find out available and free memory.
• Find out all logged in users and what they are doing.
• Find out if all necessary network services are running or not. For example if web server failed then send an alert
to system administrator via a pager or an email.
• Find out all failed login attempt, if login attempt are continue repeatedly from same network IP automatically
block all those IPs accessing your network/service via firewall.
• User administration as per our own security policies.
• Find out information about local or remote servers.
• Configure server such as BIND (DNS server) to add zone entries.
Advantages
• Easy to use.
• Quick start, and interactive debugging.
• Time Saving.
• Sys Admin task automation.
• Shell scripts can execute without any additional effort on nearly any modern UNIX / Linux / BSD / Mac OS X
operating system as they are written an interpreted language.
Disadvantages
• Compatibility problems between different platforms.
• Slow execution speed.
• A new process launched for almost every shell command executed.

Wednesday, 12 September 2012


9 Examples To Generate Random Password In Linux

  
You may have noted that Many times when you create an account on some website, you are provided with a random password. How can we generate this random data (or passwords in our case) on Linux? This can be done in a number of ways. Let’s see how?

Generating Random Passwords

Linux has a powerful way of chaining commands together, that we will use here to generate random data.Date command prints out date and time of the day. As we know that time keeps on changing, so we use this changing data to create random passwords. So, first, lets have a look at the output of ‘date’ command.
raghu@raghu-Inspiron-1440:~$ date
Thu Jun 28 15:56:02 IST 2012
with +%s, it displays total number of seconds passed since January 01, 1970:
raghu@raghu-Inspiron-1440:~$ date +%s
1340879165

Example 1.

Both of these commands can be used as input to ‘md5sum’ command, which creates 128 bit checksum(and we know that this checksum looks quite random).
raghu@raghu-Inspiron-1440:~$ date | md5sum
746b59da100daa4137d91de95c052793 -

Example 2.

The pipe symbol, “|” is used to chain the commands, i.e. the output of the left command becomes the input of the right command. And the output with “date +%s”,
raghu@raghu-Inspiron-1440:~$ date +%s | md5sum
f751a65f32a1e0cf52c513a7cf23a451 -

Example 3.

Here, instead of using “md5sum”, “sha256sum” or “sha512sum” can also be used to generate 256 or 512 bit output.
raghu@raghu-Inspiron-1440:~$ date | sha256sum
3a96b9feb1e7d869ed98b101a2e5cc5169e9f8d348712c1fb56196f877e23b8e -
raghu@raghu-Inspiron-1440:~$ date +%s | sha512sum
4f2f1e1863c243fea1dd7082006256211b16d0cb747968cd03ab77abc8f2a01b5c0cac7d9ca078e73d2dadf41959ff9cd2b1b8373dec803ab5967f007b19a5aa -
As you have seen that these commands create quite large output, but sometimes, fixed length output (for example 8 character long) might be needed. The head command prints out first few lines (10 by default) of a file. But with -c option, it can be used to display first few characters.

Example 4.

So, in the above commands, if we pipe the output further into “head -c 10” command, then it will generate only 10 characters of output.
raghu@raghu-Inspiron-1440:~$ date +%s | md5sum | head -c 10 ; echo
c398d742c4
raghu@raghu-Inspiron-1440:~$ date | sha256sum | head -c 8 ; echo
d3b1b029
Here, echo command is used just for a return after the output. Otherwise, output will attach itself with the prompt.
There is a file /dev/urandom, that provides an interface to kernel’s random number generator, means, it can be used for random number generation. This file can produce a lot of random characters. Before we see how to use this file, we will have a look at a text processing tool, “tr”. “tr” command can be used to translate the characters from one range to another (for example, from lowercase to uppercase). We won’t go into much details of this command, but will confine ourselves with only what is needed for random numbers generation. “echo ‘Hello World’ | tr a-z A-Z” will convert all small letters in the message into capitals.
raghu@raghu-Inspiron-1440:~$ echo ‘Hello World’ | tr a-z A-Z
HELLO WORLD
“tr -cd a-z” will truncate (-d option, delete) everything except (-c option, compliment) the letters in the given range (a-z here):
raghu@raghu-Inspiron-1440:~$ echo ‘Hello World’ | tr -cd a-z; echo
elloorld
Here, H and W are removed because they do not belong to range a-z.

Example 5.

Now lets get back to generating random numbers. If you need the random numbers in alphabets only, use “tr -cd [:alpha:] < /dev/urandom”. But be careful, it will fill the screen with random alphabets until you press ctrl+c. (The input redirection symbol, < in above command means that the file /dev/random is the input file of the command on its left side, tr here.) So we will use head command for first few characters.
raghu@raghu-Inspiron-1440:~$ tr -cd [:alpha:] < /dev/urandom | head -c 15 ; echo
QdUAwqfKrCBOnVG

Example 6.

Here, [:alpha:] is a predefined character range for alphabets. “tr -cd A-Za-z “ could also be used for the same effect. If all letters and numbers are required, [:alnum:] (or alternatively A-Za-z0-9 or [alpha]0-9) is used.
raghu@raghu-Inspiron-1440:~$ tr -cd [:alnum:] < /dev/urandom | head -c 10 ; echo
TRIJR4YTZC

Example 7.

To include all characters, such as punctuation marks etc, use:
raghu@raghu-Inspiron-1440:~$ tr -cd [:alnum:][:punct:] < /dev/urandom | head -c 20 ; echo
8ejcWS{kk%`p~Zm5JNfC

Example 8.

This output can be further given to md5sum or sha256sum command:
raghu@raghu-Inspiron-1440:~$ tr -cd [:alnum:] < /dev/urandom | head -c 10 | md5sum | head -c 10; echo
805d13817e

Example 9.

If you want more randomness in password, or if want to complicate more, you can use random number of bits as input to md5sum command (instead of fixed 10).
raghu@raghu-Inspiron-1440:~$ tr -cd [:alnum:] < /dev/urandom | head -c $(tr -cd 0-9 < /dev/urandom | head -c 1) | md5sum | head -c 10; echo
d41d8cd98f
Here, $() substitutes the result of for its place. And here, we have generated a random number using “tr -cd 0-9 < /dev/urandom | head -c 1”. So this command inputs a random number of characters (less than 10) to md5sum command.

Linux Fdisk Tool 


 Simple Enough to Create Partitions


Here what I am trying to do is creating a partition on the disk (ProLiant SmartArray RAID controller – /dev/cciss) You can choose the option “n” to create new partition and “p” to list available partitions. On the below output (7253-8920, default 8920) mean cylinder 7253 upto 8920 is available now.
# fdisk /dev/cciss/c0d0
The number of cylinders for this disk is set to 8920.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)
Command (m for help): m
Command action
a toggle a bootable flag
b edit bsd disklabel
c toggle the dos compatibility flag
d delete a partition
l list known partition types
m print this menu
n add a new partition
o create a new empty DOS partition table
p print the partition table
q quit without saving changes
s create a new empty Sun disklabel
t change a partition’s system id
u change display/entry units
v verify the partition table
w write table to disk and exit
x extra functionality (experts only)
Command (m for help): n
First cylinder (7253-8920, default 7253): ==> PRESS ENTER TO ACCEPT DEFAULT
Using default value 7253
Last cylinder or +size or +sizeM or +sizeK (7253-8920, default 8920): +5G
Command (m for help): p
Disk /dev/cciss/c0d0: 73.3 GB, 73372631040 bytes
255 heads, 63 sectors/track, 8920 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks Id System
/dev/cciss/c0d0p1 * 1 12 96358+ 83 Linux
/dev/cciss/c0d0p2 13 2101 16779892+ 83 Linux
/dev/cciss/c0d0p3 2102 4190 16779892+ 82 Linux swap
/dev/cciss/c0d0p4 4191 8920 37993725 5 Extended
/dev/cciss/c0d0p5 4191 5234 8385898+ 83 Linux
/dev/cciss/c0d0p6 5235 5756 4192933+ 83 Linux
/dev/cciss/c0d0p7 5757 5881 1004031 83 Linux
/dev/cciss/c0d0p8 5882 6006 1004031 83 Linux
/dev/cciss/c0d0p9 6007 7252 10008463+ 83 Linux
/dev/cciss/c0d0p10 7253 7861 4891761 83 Linux
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table.
The new table will be used at the next reboot.
Syncing disks.
The partprobe command will informs the operating system kernel of partition table changes. So no need for reboot. /* CAREFUL : partprobe MAY CAUSE A REBOOT(Not Always, only precaution) – Arrange downtime on live systems*/
# partprobe /dev/cciss/c0d0
Below file displays the available disk partitions. So the newly created partitions would be there in this list. You can run this command before and after the disk partition.
# cat /proc/partitions
major minor #blocks name
104 0 71652960 cciss/c0d0
104 1 96358 cciss/c0d0p1
104 2 16779892 cciss/c0d0p2
104 3 16779892 cciss/c0d0p3
104 5 8385898 cciss/c0d0p5
104 6 4192933 cciss/c0d0p6
104 7 1004031 cciss/c0d0p7
104 8 1004031 cciss/c0d0p8
104 9 10008463 cciss/c0d0p9
104 10 4891761 cciss/c0d0p10
Next step would be to format the partition with required filesystem.
# /sbin/mkfs -t ext3 /dev/cciss/c0d0p10
mke2fs 1.35 (28-Feb-2004)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
611648 inodes, 1222940 blocks
61147 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=1254096896
38 block groups
32768 blocks per group, 32768 fragments per group
16096 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736
Writing inode tables: done
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 33 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
You can set new label name for the filesystem using the e2label command.
# e2label /dev/cciss/c0d0p10 /mydatadisk
You can edit fstab file to update new label (filesystem) information.
# vi /etc/fstab
# This file is edited by fstab-sync – see ‘man fstab-sync’ for details
LABEL=/ / ext3 defaults 1 1
LABEL=/boot /boot ext3 defaults 1 2
none /dev/pts devpts gid=5,mode=620 0 0
none /dev/shm tmpfs defaults 0 0
LABEL=/mlextras /mlextras ext3 defaults 1 2
none /proc proc defaults 0 0
none /sys sysfs defaults 0 0
LABEL=/var /var ext3 defaults 1 2
LABEL=SW-cciss/c0d0p3 swap swap defaults 0 0
LABEL=/itrs /itrs ext3 defaults 1 2
LABEL=/mqmsw /mqmsw ext3 defaults 1 2
LABEL=/mktdata /mktdata ext3 defaults 1 2
LABEL=/mydatadisk /tools ext3 defaults 1 2
/dev/vx/dsk/dg_apps/apps /apps vxfs suid 1 2
/dev/hda /media/cdrecorder auto pamconsole,exec,noauto,managed 0 0
You are now set ready to create folder and mount the partition
# mkdir /tools
# mount /dev/cciss/c0d0p10 /tools
To confirm we can list the mount points with below commands
# df -h /tools
Filesystem Size Used Avail Use% Mounted on
/dev/cciss/c0d0p10 4.6G 42M 4.4G 1% /tools
# mount -l | grep tools
/dev/cciss/c0d0p10 on /tools type ext3 (rw) [/tools]

Disable User Accounts In Linux With Examples

     
Linux systems allow you to disable access to particular user account without changing anything from the account. This might be useful if you do not want to remove user account permanently but, you just want it disabled and no longer able to use the system. The disabled user will still receive emails for example, but he will not be able to login and check them out.
Linux distributions use /etc/shadow file to store the encrypted user passwords.
A user account can be temporarily disabled or permanently removed.

Temporary disable user account

First method Editing /etc/shadow

You can disable or lock a user account temporarily by just putting an asterisk “*” at the beginning of the second field in the file /etc/shadow. This means that “*” won’t permit login for this account. Whenever you want to enable the account, just erase the asterisk and the user account is back in operation, with its old password.
For example you want to disable user “Tom” then you can do this as follows.
#vi /etc/shadow
Tom:*$1$narMEFm6$fhA1puOU422HiSL5aggLI/:11193:0:99999:7:-1:-1:134539228
Here, the second field is the encrypted password.
You can replace the password with “*” or “!”. This will render user account inaccessible and it will mean that no login is permitted for the user.
#vi /etc/shadow
Tom:*:13852:0:99999:7:::
However, main disadvantage of this method is that the password will be lost in the case we will want to re-enable it again later.

Second method using passwd command

Passwd command can be used to disable the user account.
#passwd Tom –l
Output
“Password changed.”
Above command changes the shadow file and adds “!” in front of the user password:
Tom:!$1$eFd7EIOg$EeCk6XgKktWSUgi2pGUpk.:13852:0:99999:7:::
Now in case If you want enable the account just unlock it using –u option as follows
#passwd Tom -u
You can also enable account by removing manually the “!” character from the user’s password line in /etc/shadow.

Permanently Remove User Account

You can permanently remove the user just run userdel command.
#userdel Tom
Or
#userdel -r Tom
Make sure to check home of the user before running this command.

Record / Log Failed Login Attempt In Linux


A system administrator needs to monitor the unusual activities on the system. Unauthorized user may try to access the system by trying out different passwords. A utility in Linux that can be used to monitor these failed login attempts is “faillog” utility. “faillog” command displays any failed login attempts by any user. If there are too many unsuccessful attempts, then the account can be disabled using “faillog”. This can be used to lock down the account for a few seconds after a user fails to login.

Faillog command syntax

These failures are stored in a file named “faillog” present in /var/log directory. “faillog” command uses this file (/var/log/faillog) for displaying the failed logins. “faillog” command entered on its own prints out any unsuccessful attempts by any user.
[root@localhost ~]# faillog
Login Failures Maximum Latest On
student 1 0 06/28/12 15:27:27 +0530 tty1
After a failed login, the user can be locked for a specified time with -l option. To lock an account (say student) for 1 minute (60 seconds), use:
[root@localhost ~]# faillog -l 60 -u student
[root@localhost ~]# faillog
Login Failures Maximum Latest On
student 2 0 06/28/12 15:28:32 +0530 tty1 [51s left]
As you can see, the remaining time since failed login is displayed on the last column. The -u option is used to specify a username (whose account needs to be locked). Further, maximum limit on login attempts can be set by -m option.
[root@localhost ~]# faillog -m 0 -u student
This command will disable the student account after 3 unsuccessful logins.

pam_tally.so:

If you read carefully, “faillog” does not log the failures, it just displays them. The actual surveillance of such attempts is the responsibility of pam_tally.so module. Now before going into the details of this module, lets have a quick overview of PAM.

Pluggable Authentication Modules (PAM):

As the name suggests, PAM performs all the authentication tasks in Linux. But these modules are ‘pluggable’: it means that it can be used with other applications. PAM is not any “program or utility” that provides authentication functions, it is a module, that helps all the utilities that need authentication functions. For example, when we login to any terminal (the prompt that looks like: “localhost login: “) on Linux system, the utility that is running in background is ‘login’ utility. This utility uses PAM modules. Other utilities such as ssh(used for remote login), su(to switch users), at, cron (both used for scheduling tasks) etc. also use PAM modules for authentication.
So, returning to our discussion about pam_tally.so module. This module counts the failed login attempts and stores them in /var/log/faillog file. If your system is not configured to use this module, “faillog” will not work. So to configure the system to use this module, we need to edit /etc/pam.d/system-auth file. Add these 2 lines in the file:
auth required pam_tally.so
account required pam_tally.so
My /etc/pam.d/system-auth file looks like this (you can see these lines surrounded by comments, in bold and italics):
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth required pam_env.so
auth sufficient pam_unix.so nullok try_first_pass
auth requisite pam_succeed_if.so uid >= 500 quiet
auth required pam_deny.so
###———Added by Raghu———###
auth required pam_tally.so
###——————————–###
account required pam_unix.so
account sufficient pam_succeed_if.so uid < 500 quiet
account required pam_permit.so
###---------Added by Raghu---------###
account required pam_tally.so
###--------------------------------###
password requisite pam_cracklib.so try_first_pass retry=3
password sufficient pam_unix.so md5 shadow nullok try_first_pass use_authtok
password required pam_deny.so
session optional pam_keyinit.so revoke
session required pam_limits.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required pam_unix.so

Authenticating HTTP Users Using htpasswd and .htaccess


htpasswd is used to create and update the flat-files used to store usernames and password for basic authentication of HTTP users. htpasswd encrypts passwords using either a version of MD5 modified for Apache, or the system’s crypt() routine.
htpasswd returns a zero status (“true”) if the username and password have been successfully added or updated in the password file. htpasswd returns 1 if it encounters some problem accessing files, 2 if there was a syntax problem with the command line, 3 if the password was entered interactively and the verification entry didn’t match, 4 if its operation was interrupted, 5 if a value is too long (username, filename, password, or final computed record), 6 if the username contains illegal characters (see the Restrictions section), and 7 if the file is not a valid password file.
Following steps will guide you to create password protected directories in Apache.

1. Create a password file for user ‘ganesh’ using htpasswd command

htpasswd -c /home/user/.htpasswd ganesh
This will create a new file and stores a record in it for user ganesh. The user is prompted for the password. If the file exists and cannot be read, or cannot be written, it is not altered and htpasswd will display a message and return an error status.

2. Add/modify password for ganesh

htpasswd /home/user/.htpasswd ganesh
The user is prompted for the password which will get added to the password file.
In order to implement web based authentication (password protected directories), you need to modify the user’s .htaccess file (if it is not available under the ‘Document Root’ of the user, you need to create it) with the following entries.
AuthType Basic
AuthName “Restricted Access”
AuthUserFile /home/user/.htpasswd
Require user ganesh
Note: If the webserver has disabled the usage of .htaccess file, you can enable it for the user, by modifying the apache configuration file (httpd.conf). Check for the <Directory> directive for the directory for which you need to enable .htaccess.
Replace,
AllowOverride None
With,
AllowOverride AuthConfig


Linux Lock / Unlock User Account : Force User Change Password Next Login

 
The most important responsibilities of any administrator are the administration and monitoring of users in Linux. System Administrator can prevent unnecessary downtime and will uncover security holes before they become a problem. The user Information is stored in the system /etc/passwd and /etc/shadow files, and that additionally; group membership information is stored in the /etc/group. There are three types of user account in Linux. 1) root user, 2) System User, 3) Normal User. Its good practice to take precaution while creating users account in Linux.

Example: 1 Creating normal user account and setting password for in Linux

[root@mailserver ~]# adduser aloft
[root@mailserver ~]# passwd aloft
Changing password for user aloft.
New UNIX password:

Example: 2 Locking and unlocking the user accounts using password command.

Below command Lock the account
[root@mailserver ~]# passwd -l aloft
Locking password for user aloft.
passwd: Success
Below command Unlock the account
[root@mailserver ~]# passwd -u aloft
Unlocking password for user aloft.
passwd: Success.
Below Command removes the Password
[root@mailserver ~]# passwd -d aloft
Removing password for user aloft.
passwd: Success

Example: 3 Locking the user accounts using usermod command.

Below Command locks the password.
[root@mailserver ~]# usermod -L aloft
Below Command unlocks the Password
[root@mailserver ~]# usermod -U aloft

Example: 4 Force Users to change Password at first login

This will force user to change password at first login
[root@mailserver ~]# chage -d 0 aloft
Prompt like below
You are required to change your password immediately (root enforced)
Changing password for aloft
(current) UNIX password:
They have to enter their CURRENT password first before having to enter a new one.

Example: 5 Set Password Expire date

The -E option is used to set a date on which the users account will no longer be accessible.
[root@mailserver ~]# usermod -e 03/08/2012 aloft

Linux File Encrypt / Decrypt Using Emcrypt Command

Mcrypt is a replacement command of one of the popular Unix Crypt command. Crypt in UNIX was one of the file encryption tools which were using one of the popular algorithms similar to World War II enigma cipher. Mcrypt is also the similar command and it provides same functionality. So, we can say Mcrypt is a simplest type of modern crypting program. It uses today’s modern algorithms like AES to encrypt the data. Libmcrypt is called a companion. This is a kind of library code which holds all encryption functions that can be easily used. We can implement different kind of cryptographic algorithms and most of them are stream ciphers and block ciphers. Most common algorithms used by Mcrypt program are blowfish, arcfour, enigma, GOST, LOKI97, RC2, serpent, twofish, threeway, XTEA and wake.
Mcrypt also allows us to make use of different types of functions for encryptions and they don’t need to make any changes in the coding part. It also helps users to encrypt the data without making use of cryptographers. When we actually encrypt or decrypt any file, a new file with .nc extension is created. This file will have a mode 0600. This new file will have the same modification date like the original one. Even we can also delete the original file by specifying –u option in the command. If you don’t specify any filename in this command then by default standard input value will be encrypted and the result will be printed on the standard output.

Syntax and Examples of mcrypt

This option will list the entire available encryption algorithm.
root@LinuxServer Desktop] # mcrypt –list
This command will encrypt the given file with new name filename.nc. It will make use of blowfish algorithm. It will also ask us to enter passphrase 2 times.
root@LinuxServer Desktop] # mcrypt –a blowfish filename
This command will decrypt the file filename.txt.nc to filename.txt.
root@LinuxServer Desktop] # mcrypt –d filename.txt.nc
This command will display the help for the whole mcrypt command with all its options.
root@LinuxServer Desktop] # mcrypt –-help
Example:
If you want to encrypt the data.txt file then following command will be used.
root@LinuxServer Desktop] # mcrypt data.txt
[Output]…
Enter the passphrase (maximum of 512 characters)
Please use the combination of upper and lower case letters and numbers.
Enter passphrase:
Enter passphrase:
Once, this command is executed it will create a new encrypted file with extension .nc. So, the name of the new file would be data.txt.nc. You can view the same file with following command:
# ls data.txt.nc
or
# cat data.txt.nc
If you want to decrypt the file then you can use the following command.
# mcrypt –d data.txt.nc
[Output]…
Enter passphrase:
File data.txt.nc was decrypted.
If you want to delete the input file after your encryption or decryption process is successful then you can use the following command.
root@LinuxServer Desktop] # mcrypt –u data.txt
or
root@LinuxServer Desktop] # mcrypt –u –d data.txt.nc
While encrypting or decrypting any file with this command it will ask us to enter passphrase. Make sure that the passphrase we enter should have 512 characters maximum length. When the file is encrypted, this passphrase is generally transformed with the help of some key generation algorithm. The output of this is normally used as the key for it.

Simple Examples To Explain Linux File Permissions

Linux Permissions

Linux File Permissions

In Linux operating system, everything is organized in the form of files and directories. By setting permissions on files and directories, one can make sure that only authorized users are allowed to access a specific data. Each file in Linux is owned by a user and group. The user is the one that creates the file and group is the one to which the user (owner of the file) belongs to.
For example, you can list the files under the directory /home/sam as follows.
ls –l /home/sam
drwxrwxrwx 3 sam admin 80 2012-08-20 21:37 tmp
-rw-rw-r– 1 sam admin 8187 2012-08-25 13:35 file1
-rwxr-x— 1 sam admin 10348 2012-08-21 20:31 file2
Here, the first field shows the file permissions, third column shows the owner (user) of the file and the fourth column shows the group of the file. We can check the file permission field in detail.
To understand the file permissions easily, we can divide the permission bits into 4 parts.
[d][rwx][rwx][rwx]
The first part can have any of the following value.
d : directory
- : regular file
l : symbolic link
p : named pipe
s : Unix domain socket
c : character device file
b : block device file
The second part shows the allowed permissions for the user (owner of the file/directory). Third part shows the allowed permissions for the users that belong to the group of the file/directory and the fourth part shows the permissions for everybody else (who doesn’t belong to the user or group).
Permissions need to be set for the following modes.

• r : read permission

For a file ‘r’ means you will be able to read the file.
For a directory, the permission ‘r’ means you will be able to list the contents of the directory.

• w: write permission

For a file ‘w’ means you will be able to edit the file.
For a directory, the permission ‘w’ means you will be able to add, delete or rename files in that directory.

• x : execute permission

For a file ‘x’ means you will be able to execute the program or shell script of that file.
For a directory, the permission ‘x’ means you will be able to move to that directory (cd to the directory).
So, the permission “drwxrwxrwx” on ‘tmp’ directory sets read, write and execute permissions for user, group and others. And the permission ‘-rw-rw-r—‘ on file1 permits the user sam to read and edit the file, all users belong to the group admin can also read and write the file and everybody else can just read the file but not write or execute it.

Changing File permissions

The linux command chmod can be used to change the permission of a file or directory. The basic syntax of ‘chmod’ command is as follows.
chmod [option] OCTAL-MODE filename
The value of OCTAL-MODE is basically a 3 digit number where first digit refers to the permissions for the ‘user’, second digit refers to the permissions for the ‘group’ and third digit refers to the permissions for ‘others (anybody other than the user and group)’. Each digit can be calculated using the following table
r (Read) 4
w (write) 2
x (execute) 1
-(no permission) 0

Example 1:

If you want to set the permission of a file such that the user should be able to read, write and execute the file, group and others should only be read and execute the file, the permission should be like ‘-rwxr-xr-x’.
We can now find the OCTAL-MODE need to be used for setting the permission ‘-rwxr-xr-x’.
For user part -> rwx = 4+2+1 = 7
For Group -> r-x = 4+0+1 = 5
For others -> r-x = 4+0+1 = 5
Hence, the command should be,
chmod 755 filename

Example 2:

If you want to set the permission of a file such that the user should be able to read and write the file, the group should be able to read the file and others should not have any access to the file, permission should be like ‘-rw-r—–‘.
For user -> rw- = 4+2 = 6
For group -> r– = 4+0+0 =4
For others -> — = 0+0+0 =0
Hence the command should be,
chmod 640 filename

Example 3:

If you want to temporarily disable a file, you need to set the permission of the file such that nobody will be able to access the file. In order to set this permission ‘———-‘, you need to execute the command,
chmod 000 filename

Example 4:

If you want to give full permissions (rwxrwxrwx) to a directory and all sub directories and files in it, you can use chmod recursively as follows.
chmod –R 777 dir_name


Apache ( httpd.conf ) Directives That A Web Server Admin Should Know

Apache Web Server Directives

Apache web server is the most popular web server designed for unix like operating system. It has become the dominating one over the other web servers because of its high flexibility and performance. Apache functionality can be extended with the help of compiled modules. Apache directives can be defined as the instruction to the web server on how to run. Apache configuration file is ‘httpd.conf’.
In this article, we will go through the important directives that an administrator should know for configuring apache and for performance tuning. These directives can be divided into three sections.

Section 1: Global Environment
The directives in this section affect the overall operation of Apache, such as the number of concurrent requests it can handle.
Sample Segment
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
MinSpareServers 5
MaxSpareServers 10
StartServers 5
MaxClients 150
MaxRequestsPerChild 1000
a. Timeout
Amount of time the server will wait for certain events before failing a request. The default value is 300. Reducing this value to a very low number may cause a long running script to terminate earlier than expected. Also, it should not be set to too high for better performance.
b. KeepAlive
This defines whether the server allows more than one request per connection. Default value is “On”. When this directive is set to “on”, the client is allowed to serve multiple resources over the same connection. This will be very useful while serving web sites that have multiple images and you will see that the web page has been served so fast. But for high volume or load balanced servers, this should be set to ‘off’ for high connection throughput.
c. MaxKeepAliveRequests
This directive limits the number of requests allowed per connection while “KeepAlive” is “On”. Default value is 100.
d. KeepAliveTimeout
This refers to the number of seconds Apache will wait for a subsequent request before closing the connection. Default value is 15 seconds. For heavily loaded servers, this value may need to be reduced; otherwise child may sit idle waiting for new request on a connection that may not arrive which in turn increase the memory usage.
e. MinSpareServers
This defines the minimum number of idle child server processes. An idle process is one which is not handling a request. If there are fewer than ‘MinSpareServers’ idle, then the parent process creates new children at a maximum rate of 1 per second. Default value is 5. Setting the value to a higher value is always a bad idea as the memory will be used up for nothing.
f. MaxSpareServers
It sets the desired maximum number of idle child server processes. An idle process is one which is not handling a request. If there are more than MaxSpareServers idle, then the parent process will kill off the excess processes. It is better to set this value as double as ‘MinSpareServers’. If
you set it to equal or lesser than the ‘MinSpareServers’ value, Apache will automatically adjust it to MinSpareServers + 1.
g. StartServers
It sets the number of child server processes created on startup. It usually set to the same as ‘MinSpareServers’ value. Default is 5 for prefork MPM and 3 for worker MPM.
h. MaxClients
It sets the limit on the number of simultaneous requests that will be served. Any connection attempts over the MaxClients limit will normally be queued. Once a child process is freed at the end of a different request, the connection will then be serviced. Default is 256. Setting this limit to a high value will result in using up of whole memory and cause high swap usage. The limit can be found by diving the ‘amount of memory reserved for Apache’ by ‘Average size of a single Apache process (usually between 15M to 20M).
i. MaxRequestsPerChild
It sets the limit on the number of requests that an individual child server process will handle. After MaxRequestsPerChild requests, the child process will die. This should not be too low or too high. If it is set to too high, it will increase the risk of memory leaks. So, the child processes should be killed after serving reasonable amount of requests. When a client uses a Keep-Alive connection it will be counted as a single “request” for the MaxRequestsPerChild directive, regardless of how many requests are sent using the connection.
j. LoadModule
This is used to load a module which was built as a DSO, so the directives contained in it are actually available before they are used.
Example:
LoadModule foo_module libexec/mod_foo.so

Section 2: Main Server Configuration
In this section, we will see the directives used by the ‘main’ server, which responds to any requests that aren’t handled by adefinition. If these directives are available inside thedirective, default settings will be overridden for the virtual host being defined.
a. Listen
The Listen directive tells the server to accept incoming requests on the specified port or address-and-port combination. If only a port number is specified, the server listens to the given port on all interfaces. If an IP address is given as well as a port, the server will listen on the given port and interface.
Multiple Listen directives may be used to specify a number of addresses and ports to listen to. The server will respond to requests from any of the listed addresses and ports. Multiple Listen directives for the same ip address and port will result in an “Address already in use” error message.
Listen 80
b. <Directory>
This is called a sectional directive as it encloses a group of directives that applies to the specified directory.
Example:
<Directory “/var/www/htdocs”>
Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
We can now go through the directives included above.
1. Options
Options allows you to define specific options to be available for a defined directory. Now, you can use ‘+’ to tell Apache to add the option or ‘-’ to remove an option. This directive can take any of the following or in combinations,
a. All : All options other than “MultiViews”
b. None
c. Includes : for enabling SSI (Server Side Includes)
d. Indexes : If a URL which maps to a directory is requested, and there is no DirectoryIndex (e.g., index.html) in that directory, then mod_autoindex will return a formatted listing of the directory.
e. FollowSymLinks : The server will follow symbolic links in this directory. This is the default setting.
f. ExecCGI : Execution of CGI scripts using mod_cgi is permitted.
g. Multiviews : Support for multilanguage pages
2. AllowOverride
This defines the directives that are allowed in .htaccess files. The value ‘None’ will disable the .htaccess usage and “All” will allow all directives. You can specifically mention the directive types too.
3. Allow, Deny Directives
These directives will help to restrict access to the particular directory. You can mention the IP address or Hostname which need to be granted/denied access.

Section 3 : Virtual Hosts
1.<VirtualHost>
This sectional directive contains directives that apply only to a specific hostname or IP address.
Example:
<VirtualHost 10.1.2.3:80>
ServerAdmin webmaster@host.example.com
DocumentRoot /www/docs/host.example.com
ServerName host.example.com
ErrorLog logs/host.example.com-error_log
TransferLog logs/host.example.com-access_log
</VirtualHost>
We can now check the enclosed directives.
a. ServerAdmin : It sets the e-mail address that the server includes in any error messages it returns to the client.
b. DocumentRoot : This directive sets the directory from which httpd will serve files. Unless matched by a directive like ‘Alias’, the server appends the path from the requested URL to the document root to make the path to the document.
That is,
DocumentRoot /usr/web
Then, access to http://www.my.host.com/index.html refers to /usr/web/index.html.
c. ServerName: Hostname and port that the server uses to identify itself.
d. ErrorLog: The ErrorLog directive sets the name of the file to which the server will log any errors it encounters. If the file-path is not absolute then it is assumed to be relative to the ‘ServerRoot’.
These are the main directives that help apache administrators to configure it properly.