Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

Monday, May 5, 2014

Encrypting Filesystems in Linux

If you do not have cryptsetup command you can install the package with:

# yum install cryptsetup-luks

In my case I did not have to install, I already had it.

Warning: Your data in the partition will be lost, please backup your files, if you have any.

1) Command to format the partition with the encryption
# cryptsetup -y -v luksFormat /dev/sdb1 (or any logical volume /dev/mapper/vg1-lv1)

It will ask you to enter: YES option then you will have to enter a passphrase

2) Now you will map your encrypted device 
# cryptsetup luksOpen /dev/sdb1 safefs
it will ask you for the passphrase 

You can check the mapped device after it is done with
# ls -l /dev/mapper/safefs
# cryptsetup -v status safefs

3) You will need to format the mapped device with:
# mkfs.ext4 /dev/mapper/safefs

4) Create a directory to mount the mapped filesystem 
# mkdir /safefsmount 

5) Mount the filesystem to the folder you have just created
# mount -t ext4 /dev/mapper/safefs /safefsmount

6) Please check your SELinux configurations too

7) Open cryptsetup configuration file and enter following input
# vim /etc/crypttab
safefs                  /dev/sda1               none

Above our mapping name, encrypted filesystem and third one is do not decrypt the passphrase (prompt for the password)

8) To make our mountpoint persistent to reboot enter the information to /etc/fstab file
# vim /etc/fstab
/dev/mapper/safefs   /safefsmount   ext4    defaults   0 0

9) Finally, reboot your system
# reboot (init 6)

When the system is booted it will ask you to enter the passphrase.

To unmount and secure your data you can
# umount /safefsmount
#cryptsetup luksClose safefs

You can always access to your secure information with the same open command of cryptsetup.

Disk Quotas (managing quotas for user)

Add 'usrquota' option in /etc/fstab file for /home directory
 then remount home partition

# mount -o remount /home
# mount |grep home

# quotacheck -cum /home
c = creates quota table options
u = creates aquota.user file
m = tells do not remount /home dir in read only mode

To view user's quota table run
# edquota -u user 

Limiting the space for the user 
# setquota -u user 30000 35000 0 0 /home 


Turn on quotas for the home directory 
# quotaon /home

Fill the disk with bunch of zeros

# dd if=/dev/zero of=testfile bs=1024 count=25000

Check what is the status of the user for the quotas
# edquota -u user

Copy quota settings from user to user
# edquota -up user1 user2

We can see all the users quotas with
# repquota -a

Group quotas are also similar to user quotas

In the /etc/fstab file you should enter 'grpquota' on the mount point

Then remount the filesystem you have grpquota
# mount -o remount /mountpoint
# mount |grep mountpoint (should show grpquota option on the output)

Add quota file to the location
# quotacheck -cgp /mountpoint

Turn the quota on
# quotaon /mountpoint

Set quota for the group
# setquota -g groupname 99000(99MB) 12000 0 0 /mountpoint

You can check the quotas in the all groups with
# repquota -ga

Friday, May 2, 2014

Red Hat Package Manager

RPM - RedHat Package Manager

man rpm (for more information)

Installing rpm package
$ rpm -ivh packagename.rpm - to install a package
-i - installs
-v - verbose
-h - shows progress as hash

Updating package
$ rpm -Uvh packagename (never use this command for installing kernel)

Removing package
$ rpm -e packagename

Query the rpm database of rpm (which is in /var/lib/rpm)

To query all the rpm packages
$ rpm -qa

Or grep certain package you want
$ rpm -qa |grep httpd

To look for documentation of the rpm package
$ rpm -qd packagename

To look for configuration file of the rpm package
$ rpm -qc packagename

To look for information about package
$ rpm -qi packagename

RPM will not find dependencies of the package automatically as yum does. Yum can perform exact same commands that rpm uses and can find dependencies of the package automatically.

YUM - Yellow Dog Update is commonly used installer command in RedHat
Yum must be running as root. Here is some common commands 
1) # yum install package

2) # yum remove package

3) # yum update package

4) # yum search package

5) # yum info package

6) # yum list (lists all the packages)

7) # yum whatprovides /path/filename

8) # yum update

You can find more information in depth in redhat.com website. 

Sunday, April 27, 2014

How to mount and unmount - in Linux

Here are some simple commands that you can use for mounting a device in Linux.

To mount something to the filesystem - general mount syntax
# mount -t ext4 /dev/sda2 /home

Remount syntax is
# mount -o remount /home

To make all the mount options persistent to reboot edit the /etc/fstab file. Once you have edited the fstab file you can run the the following option, which will mount all the things /etc/fstab contains.
# mount -a

To unmount the filesystem
# umount /home
# umount -a

To add permissions to the filesystem
# mount -rw -o remount /

To list all the mountpoint options you run the following
# mount
or
# mount |grep home - for individual mount points

Following command also will show all the mounted systems
# df or df -h (-h for human readable)

Forcefully unmount the system
# umount -f /mnt

You can run the fuser command to see which process is holding the mount point
# fuser -cu /mnt
# ps -ajx | grep /mnt

Mounting a cd rom device
# mount  -t iso9660 -o ro /dev/cdrom /mnt 

Wednesday, April 23, 2014

Fdisk Utility

Fdisk is the best tool to manage disk partitions. Using fdisk you can create a new partition, delete one, and change existing partitions. There are other tools you can use I found the fdisk to be easy to use.

To list all the drives in the system
# fdisk -l
# fdisk -l

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 
/dev/sda2            1960        5283    26700030    f  W95 Ext'd 
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            2662        2904     1951866   83  Linux
/dev/sda7            2905        3147     1951866   83  Linux
/dev/sda8            3148        3264      939771   82  Linux swap / Solaris
You can list particular disk drive with
# fdisk -l /dev/sdb

Warning: When you use fdisk command please be sure to backup all your data, because everything will be lost.

To create a partition to the newly added disk

1) # fdisk /dev/sdb (or whatever disk name you have)

Fdisk has simple navigation once you are inside it, as long as you know core functions in it.

Once you are inside the fdsik mode after running 1) fdisk would be offering m option for help if you need any.

m - print help menu
p - print the partition table
l - list known partitions
n - add a new partition
     When you have selected n option there are some extra steps to work on
     it will ask you to choose if it is -- extended or -- primary partition
     select whichever you like mostly (p) primary
     select partition number
     then it will prompt to minimum start size of the disk
     after selecting min size it will ask you max size of the disk

By default it will create a Linux partition 83 you can change it by option (t) and use 82 for swap so on

w - this command writes all the changes (please make sure and verify with (v) and (p) options. This would be your last chance to check before it writes all the changes you have made.

# fdisk  /dev/sda

The number of cylinders for this disk is set to 9729.
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)

After you have created the partition, now you have to format the partition
# mkfs.ext4 /dev/sdbX 

Wednesday, April 16, 2014

VIM Editor Commands

VIM Editor Commands
Vim is an editor to create or edit a text file.
There are two modes in vim. One is the command mode and another is the insert mode.
In the command mode, user can move around the file, delete text, etc.
In the insert mode, user can insert text.
Changing mode from one to another
From command mode to insert mode type a/A/i/I/o/O ( see details below)
From insert mode to command mode type Esc (escape key)
Some useful commands for VIM
Text Entry Commands (Used to start text entry)
a Append text following current cursor position
A Append text to the end of current line
i Insert text before the current cursor position
I Insert text at the beginning of the cursor line
o Open up a new line following the current line and add text there
O Open up a new line in front of the current line and add text there
The following commands are used only in the commands mode.
Cursor Movement Commands
h Moves the cursor one character to the left
l Moves the cursor one character to the right
k Moves the cursor up one line
j Moves the cursor down one line
nG or :n Cursor goes to the specified (n) line
(ex. 10G goes to line 10)
^F (CTRl F) Forward screenful
^B Backward screenful
^f One page forward
^b One page backward
^U Up half screenful
^D Down half screenful
$ Move cursor to the end of current line
0 (zero) Move cursor to the beginning of current line
w Forward one word
b Backward one word
Exit Commands
:wq Write file to disk and quit the editor
:q! Quit (no warning)
:q Quit (a warning is printed if a modified file has not been saved)
ZZ Save workspace and quit the editor (same as :wq)
: 10,25 w temp
write lines 10 through 25 into file named temp. Of course, other line
numbers can be used. (Use :f to find out the line numbers you want.

Text Deletion Commands
x Delete character
dw Delete word from cursor on
db Delete word backward
dd Delete line
d$ Delete to end of line
d^ (d caret, not CTRL d) Delete to beginning of line
Yank (has most of the options of delete)-- VI's copy commmand
yy yank current line
y$ yank to end of current line from cursor
yw yank from cursor to end of current word
5yy yank, for example, 5 lines
Paste (used after delete or yank to recover lines.)
p paste below cursor
P paste above cursor
"2p paste from buffer 2 (there are 9)
u Undo last change
U Restore line
J Join next line down to the end of the current line
File Manipulation Commands
:w Write workspace to original file
:w file Write workspace to named file
:e file Start editing a new file
:r file Read contents of a file to the workspace
To create a page break, while in the insert mode, press the CTRL key
And l. ^L will appear in your text and will cause the printer to start
A new page.


Other Useful Commands
Most commands can be repeated n times by typing a number, n, before
the command. For example 10dd means delete 10 lines.
. Repeat last command
cw Change current word to a new word
r Replace one character at the cursor position
R Begin overstrike or replace mode – use ESC key to exit
:/ pattern Search forward for the pattern
:? pattern Search backward for the pattern
n (used after either of the 2 search commands above to
continue to find next occurrence of the pattern.
:g/pat1/s//pat2/g replace every occurrence of pattern1 (pat1) with
pat2
Example :g/tIO/s//Ada.Text_IO/g
This will find and replace tIO by Ada.text_IO everywhere in the file.
:g/a/s// /g replace the letter a, by blank
:g/a/s///g replace a by nothing
note: Even this command be undone by u

Examples
Opening a New File
Step 1 type vim filename (create a file named filename)
Step 2 type i ( switch to insert mode)
Step 3 enter text (enter your Ada program)
Step 4 hit Esc key (switch back to command mode)
Step 5 type :wq (write file and exit vim)

Editing the Existing File
Step 1 type vim filename (edit the existing file named filename)
Step 2 move around the file using h/j/k/l key or any appropriate command
h Moves the cursor one character to the left
l Moves the cursor one character to the right
k Moves the cursor up one line
j Moves the cursor down one line
nG or :n Cursor goes to the specified (n) line
(ex. 10G goes to line 10)
Step 3 edit required text (replace or delete or insert)
Step 4 hit Esc key (exit from insert mode if you insert or replace text)

Step 5 type :wq

Tuesday, April 15, 2014

Network Basics in Linux

This website is very useful to learn Linux overall.

This URL is chapter about basic Networking: Please check: http://www.slackbook.org/html/basic-network-commands.html

http://www.slackbook.org/html/index.html

Monday, April 14, 2014

Linux Boot Process (6 stages)

Press the power button on your system, and after few moments you see the Linux login prompt.
Have you ever wondered what happens behind the scenes from the time you press the power button until the Linux login prompt appears?
The following are the 6 high level stages of a typical Linux boot process.

1. BIOS

  • BIOS stands for Basic Input/Output System
  • Performs some system integrity checks
  • Searches, loads, and executes the boot loader program.
  • It looks for boot loader in floppy, cd-rom, or hard drive. You can press a key (typically F12 of F2, but it depends on your system) during the BIOS startup to change the boot sequence.
  • Once the boot loader program is detected and loaded into the memory, BIOS gives the control to it.
  • So, in simple terms BIOS loads and executes the MBR boot loader.

2. MBR

  • MBR stands for Master Boot Record.
  • It is located in the 1st sector of the bootable disk. Typically /dev/hda, or /dev/sda
  • MBR is less than 512 bytes in size. This has three components 1) primary boot loader info in 1st 446 bytes 2) partition table info in next 64 bytes 3) mbr validation check in last 2 bytes.
  • It contains information about GRUB (or LILO in old systems).
  • So, in simple terms MBR loads and executes the GRUB boot loader.

3. GRUB

  • GRUB stands for Grand Unified Bootloader.
  • If you have multiple kernel images installed on your system, you can choose which one to be executed.
  • GRUB displays a splash screen, waits for few seconds, if you don’t enter anything, it loads the default kernel image as specified in the grub configuration file.
  • GRUB has the knowledge of the filesystem (the older Linux loader LILO didn’t understand filesystem).
  • Grub configuration file is /boot/grub/grub.conf (/etc/grub.conf is a link to this). The following is sample grub.conf of CentOS.
  • #boot=/dev/sda
    default=0
    timeout=5
    splashimage=(hd0,0)/boot/grub/splash.xpm.gz
    hiddenmenu
    title CentOS (2.6.18-194.el5PAE)
              root (hd0,0)
              kernel /boot/vmlinuz-2.6.18-194.el5PAE ro root=LABEL=/
              initrd /boot/initrd-2.6.18-194.el5PAE.img
  • As you notice from the above info, it contains kernel and initrd image.
  • So, in simple terms GRUB just loads and executes Kernel and initrd images.

4. Kernel

  • Mounts the root file system as specified in the “root=” in grub.conf
  • Kernel executes the /sbin/init program
  • Since init was the 1st program to be executed by Linux Kernel, it has the process id (PID) of 1. Do a ‘ps -ef | grep init’ and check the pid.
  • initrd stands for Initial RAM Disk.
  • initrd is used by kernel as temporary root file system until kernel is booted and the real root file system is mounted. It also contains necessary drivers compiled inside, which helps it to access the hard drive partitions, and other hardware.

5. Init

  • Looks at the /etc/inittab file to decide the Linux run level.
  • Following are the available run levels
    • 0 – halt
    • 1 – Single user mode
    • 2 – Multiuser, without NFS
    • 3 – Full multiuser mode
    • 4 – unused
    • 5 – X11
    • 6 – reboot
  • Init identifies the default initlevel from /etc/inittab and uses that to load all appropriate program.
  • Execute ‘grep initdefault /etc/inittab’ on your system to identify the default run level
  • If you want to get into trouble, you can set the default run level to 0 or 6. Since you know what 0 and 6 means, probably you might not do that.
  • Typically you would set the default run level to either 3 or 5.

6. Runlevel programs

  • When the Linux system is booting up, you might see various services getting started. For example, it might say “starting sendmail …. OK”. Those are the runlevel programs, executed from the run level directory as defined by your run level.
  • Depending on your default init level setting, the system will execute the programs from one of the following directories.
    • Run level 0 – /etc/rc.d/rc0.d/
    • Run level 1 – /etc/rc.d/rc1.d/
    • Run level 2 – /etc/rc.d/rc2.d/
    • Run level 3 – /etc/rc.d/rc3.d/
    • Run level 4 – /etc/rc.d/rc4.d/
    • Run level 5 – /etc/rc.d/rc5.d/
    • Run level 6 – /etc/rc.d/rc6.d/
  • Please note that there are also symbolic links available for these directory under /etc directly. So, /etc/rc0.d is linked to /etc/rc.d/rc0.d.
  • Under the /etc/rc.d/rc*.d/ directories, you would see programs that start with S and K.
  • Programs starts with S are used during startup. S for startup.
  • Programs starts with K are used during shutdown. K for kill.
  • There are numbers right next to S and K in the program names. Those are the sequence number in which the programs should be started or killed.
  • For example, S12syslog is to start the syslog deamon, which has the sequence number of 12. S80sendmail is to start the sendmail daemon, which has the sequence number of 80. So, syslog program will be started before sendmail.
There you have it. That is what happens during the Linux boot process.

Wednesday, April 2, 2014

Access Control Lists

Installation

The required package acl is a dependency of systemd, it should already be installed.

Configuration

Enabling ACL

To enable ACL, the filesystem must be mounted with the acl option. You can use fstab to make it permanent on your system.
There is a big chance that the acl option is already active as default mount option of your filesystem. Use the following command to check it for ext* formatted partitions:
# tune2fs -l /dev/sdXY | grep "Default mount options:"
Default mount options:    user_xattr acl
Also check that the default mount option is not overridden, in such case you will see noacl in /proc/mounts in the relevant line.
You can set the default mount options of a filesystem using the tune2fs -o option partition command, for example:
# tune2fs -o acl /dev/sdXY
Using the default mount options instead of an entry in /etc/fstab is very useful for external drives, such partition will be mounted with acl option also on other Linux machines. There is no need to edit /etc/fstab on every machine.
Note:
  • acl is specified as default mount option when creating an ext2/3/4 filesystem. This is configured in /etc/mke2fs.conf.
  • The default mount options are not listed in /proc/mounts.

Set ACL

To modify ACL use setfacl command. To add permissions use setfacl -m.
Add permissions to some user:
# setfacl -m "u:username:permissions"
or
# setfacl -m "u:uid:permissions"
Add permissions to some group:
# setfacl -m "g:groupname:permissions"
or
# setfacl -m "g:gid:permissions"
Remove all permissions:
# setfacl -b
Remove each entry:
# setfacl -x "entry"
To check permissions use:
# getfacl filename

Examples

Set all permissions for user johny to file named "abc":
# setfacl -m "u:johny:rwx" abc
Check permissions
# getfacl abc
# file: abc
# owner: someone
# group: someone
user::rw-
user:johny:rwx
group::r--
mask::rwx
other::r--
Change permissions for user johny:
# setfacl -m "u:johny:r-x" abc
Check permissions
# getfacl abc
# file: abc
# owner: someone
# group: someone
user::rw-
user:johny:r-x
group::r--
mask::r-x
other::r--
Remove all extended ACL entries:
# setfacl -b abc
Check permissions
# getfacl abc
# file: abc
# owner: someone
# group: someone
user::rw-
group::r--
other::r--

Output of ls command

You will notice that there is an ACL for a given file because it will exhibit a + (plus sign) after its Unix permissions in the output of ls -l.
$ ls -l /dev/audio
crw-rw----+ 1 root audio 14, 4 nov.   9 12:49 /dev/audio
$ getfacl /dev/audio
getfacl: Removing leading '/' from absolute path names
# file: dev/audio
# owner: root
# group: audio
user::rw-
user:solstice:rw-
group::rw-
mask::rw-
other::---
 
 https://www.youtube.com/watch?v=6piQXXHTmqk
 

Tuesday, April 1, 2014

Sticky Bit and Chattr attribute

What is Sticky Bit?

Sticky Bit is mainly used on folders in order to avoid deletion of a folder and its content by other users though they having write permissions on the folder contents. If Sticky bit is enabled on a folder, the folder contents are deleted by only owner who created them and the root user. No one else can delete other users data in this folder(Where sticky bit is set). This is a security measure to avoid deletion of critical folders and their content(sub-folders and files), though other users have full permissions.

Learn Sticky Bit with examples:

Example: Create a project(A folder) where people will try to dump files for sharing, but they should not delete the files created by other users.
How can I setup Sticky Bit for a Folder?
Sticky Bit can be set in two ways
  1. Symbolic way (t,represents sticky bit)
  2. Numerical/octal way (1, Sticky Bit bit as value 1)
Use chmod command to set Sticky Bit on Folder: /opt/dump/
Symbolic way:
chmod o+t /opt/dump/
or
chmod +t /opt/dump/
Let me explain above command, We are setting Sticky Bit(+t) to folder /opt/dump by using chmod command.
Numerical way:
chmod 1757 /opt/dump/
Here in 1757, 1 indicates Sticky Bit set, 7 for full permissions for owner, 5 for read and execute permissions for group, and full permissions for others.
Checking if a folder is set with Sticky Bit or not?
Use ls –l to check if the x in others permissions field is replaced by t or T
For example: /opt/dump/ listing before and after Sticky Bit set


chattr attribute is used to stop accidentally delete of files and folder. You cannot delete the files secured via chattr attribute even though you have full permission over files. This is very use full in system files like shadow and passwd files which contains all user information and passwords.
Syntax for chattr command is
 #chattr [operator] [switch] [file name] 
The operator ‘+’ causes the selected attributes to be added to the existing attributes of the files; ‘-’ causes them to be removed; and ‘=’ causes them to be the only attributes that the files have.
-R
Recursively change attributes of directories and their contents. Symbolic links encountered during recursive directory traversals are ignored.
-a
A file with the ‘a’ attribute set can only be open in append mode for writing. Only the superuser can set or clear this attribute.
-i
A file with the ‘i’ attribute cannot be modified: it cannot be deleted or renamed, no link can be created to this file and no data can be written to the file. Only the superuser can set or clear this attribute.
Let's take a simple example
Create a file from root user and set full permission on this file form chmod and verify it
#cat > test This test file
#chmod 777 test #ls –l 
cat linux commands
now secure this file with +i options
 #chattr +i test 
Now you can only read this file. All other actions excepts read will be denied including append, edit, rename or delete. chattr permission can be removed with –i options .
chattr command with i switchs
create a new file again This time we will secure this file with +a options
 #chattr +a test 
with a options you can read and append this file but all other recitations will be as it is. Main difference between a and iswitch is in i you cannot append the file while in switch you can append the file.
chattr command with a switchs
To secure entire directory use –R switch. Directory secured with -R option can be reset only with –R switch.
chattr command with a switch

Linux file permissions(Author Odil)



Basic File Permissions
Permission Groups
Each file and directory has three user based permission groups:
  • owner - The Owner permissions apply only the owner of the file or directory, they will not impact the actions of other users.
  • group - The Group permissions apply only to the group that has been assigned to the file or directory, they will not effect the actions of other users.
  • all users - The All Users permissions apply to all other users on the system, this is the permission group that you want to watch the most.

Permission Types

Each file or directory has three basic permission types:
  • read - The Read permission refers to a user's capability to read the contents of the file.
  • write - The Write permissions refer to a user's capability to write or modify a file or directory.
  • execute - The Execute permission affects a user's capability to execute a file or view the contents of a directory.

Viewing the Permissions

You can view the permissions by checking the file or directory permissions in your favorite GUI File Manager (which I will not cover here) or by reviewing the output of the \"ls -l\" command while in the terminal and while working in the directory which contains the file or folder.

The permission in the command line is displayed as: _rwxrwxrwx 1 owner:group

  1. User rights/Permissions
    1. The first character that I marked with an underscore is the special permission flag that can vary.
    2. The following set of three characters (rwx) is for the owner permissions.
    3. The second set of three characters (rwx) is for the Group permissions.
    4. The third set of three characters (rwx) is for the All Users permissions.
  2. Following that grouping since the integer/number displays the number of hardlinks to the file.
  3. The last piece is the Owner and Group assignment formatted as Owner:Group.

Modifying the Permissions

When in the command line, the permissions are edited by using the command chmod. You can assign the permissions explicitly or by using a binary reference as described below.

Explicitly Defining Permissions

To explicity define permissions you will need to reference the Permission Group and Permission Types.

The Permission Groups used are:

  • u - Owner
  • g - Group
  • o or a - All Users
The potential Assignment Operators are + (plus) and - (minus); these are used to tell the system whether to add or remove the specific permissions.

The Permission Types that are used are:

  • r - Read
  • w - Write
  • x - Execute
So for an example, lets say I have a file named file1 that currently has the permissions set to _rw_rw_rw, which means that the owner, group and all users have read and write permission. Now we want to remove the read and write permissions from the all users group.

To make this modification you would invoke the command: chmod a-rw file1
To add the permissions above you would invoke the command: chmod a+rw file1

As you can see, if you want to grant those permissions you would change the minus character to a plus to add those permissions.

Using Binary References to Set permissions

Now that you understand the permissions groups and types this one should feel natural. To set the permission using binary references you must first understand that the input is done by entering three integers/numbers.

A sample permission string would be chmod 640 file1, which means that the owner has read and write permissions, the group has read permissions, and all other user have no rights to the file.

The first number represents the Owner permission; the second represents the Group permissions; and the last number represents the permissions for all other users. The numbers are a binary representation of the rwx string.

  • r = 4
  • w = 2
  • x = 1
You add the numbers to get the integer/number representing the permissions you wish to set. You will need to include the binary permissions for each of the three permission groups.

So to set a file to permissions on file1 to read _rwxr_____, you would enter chmod 740 file1.

Owners and Groups
I have made several references to Owners and Groups above, but have not yet told you how to assign or change the Owner and Group assigned to a file or directory.

You use the chown command to change owner and group assignments, the syntax is simple chown owner:group filename, so to change the owner of file1 to user1 and the group to family you would enter chown user1:family file1.

Advanced Permissions
The special permissions flag can be marked with any of the following:
  • _ - no special permissions
  • d - directory
  • l - The file or directory is a symbolic link
  • s - This indicated the setuid/setgid permissions. This is not set displayed in the special permission part of the permissions display, but is represented as a s in the read portion of the owner or group permissions.
  • t - This indicates the sticky bit permissions. This is not set displayed in the special permission part of the permissions display, but is represented as a t in the executable portion of the all users permissions
Setuid/Setgid Special Permissions
The setuid/setguid permissions are used to tell the system to run an executable as the owner with the owner\'s permissions.

Be careful using setuid/setgid bits in permissions. If you incorrectly assign permissions to a file owned by root with the setuid/setgid bit set, then you can open your system to intrusion.

You can only assign the setuid/setgid bit by explicitly defining permissions. The character for the setuid/setguid bit is s.

So do set the setuid/setguid bit on file2.sh you would issue the command chmod g+s file2.sh.

Sticky Bit Special Permissions
The sticky bit can be very useful in shared environment because when it has been assigned to the permissions on a directory it sets it so only file owner can rename or delete the said file.

You can only assign the sticky bit by explicitly defining permissions. The character for the sticky bit is t.

To set the sticky bit on a directory named dir1 you would issue the command chmod +t dir1.

When Permissions Are Important

To some users of Mac- or Windows-based computers you don't think about permissions, but those environments don't focus so aggressively on user based rights on files unless you are in a corporate environment. But now you are running a Linux-based system and permission based security is simplified and can be easily used to restrict access as you please.

So I will show you some documents and folders that you want to focus on and show you how the optimal permissions should be set.

  • home directories - The users\' home directories are important because you do not want other users to be able to view and modify the files in another user\'s documents of desktop. To remedy this you will want the directory to have the drwx______ (700) permissions, so lets say we want to enforce the correct permissions on the user user1\'s home directory that can be done by issuing the command chmod 700 /home/user1.
  • bootloader configuration files - If you decide to implement password to boot specific operating systems then you will want to remove read and write permissions from the configuration file from all users but root. To do you can change the permissions of the file to 700.
  • system and daemon configuration files - It is very important to restrict rights to system and daemon configuration files to restrict users from editing the contents, it may not be advisable to restrict read permissions, but restricting write permissions is a must. In these cases it may be best to modify the rights to 644.
  • firewall scripts - It may not always be necessary to block all users from reading the firewall file, but it is advisable to restrict the users from writing to the file. In this case the firewall script is run by the root user automatically on boot, so all other users need no rights, so you can assign the 700 permissions.
  •  File permission symbols

    If you run the command
    Code:
    ls -l
    in your home directory, you will get a list of files that may include something like this

    Code:
    -rw-r--r--  1  Odil users  1892  Jul 10  18:30 linux_course_no
     
    Here is a table of numbers that covers all the common settings. The ones beginning with "7" are used with programs (since they enable execution) and the rest are for other kinds of files.


    Value Meaning
    777
    (rwxrwxrwx) No restrictions on permissions. Anybody may do anything. Generally not a desirable setting.
    755
    (rwxr-xr-x) The file's owner may read, write, and execute the file. All others may read and execute the file. This setting is common for programs that are used by all users.
    700
    (rwx------) The file's owner may read, write, and execute the file. Nobody else has any rights. This setting is useful for programs that only the owner may use and must be kept private from others.
    666
    (rw-rw-rw-) All users may read and write the file.
    644
    (rw-r--r--) The owner may read and write a file, while all others may only read the file. A common setting for data files that everybody may read, but only the owner may change.
    600
    (rw-------) The owner may read and write a file. All others have no rights. A common setting for data files that the owner wants to keep private.

    Directory permissions

    The chmod command can also be used to control the access permissions for directories. In most ways, the permissions scheme for directories works the same way as they do with files. However, the execution permission is used in a different way. It provides control for access to file listing and other things. Here are some useful settings for directories:


    Value Meaning
    777
    (rwxrwxrwx) No restrictions on permissions. Anybody may list files, create new files in the directory and delete files in the directory. Generally not a good setting.
    755
    (rwxr-xr-x) The directory owner has full access. All others may list the directory, but cannot create files nor delete them. This setting is common for directories that you wish to share with other users.
    700
    (rwx------) The directory owner has full access. Nobody else has any rights. This setting is useful for directories that only the owner may use and must be kept private from others.

Saturday, March 29, 2014

Linux basic commands

Basic file manipulation

Pwd = show Present Working Directory
Example: root@localhost:~#pwd
/root

man <command> = shows manual


ls = lists contents of current directory


[davr@localhost ~]$ ls
2  abc        dir1       err      file2     if.sh    Music     Templates
3  davron.sh  Documents  err.txt  hello.sh  ls.txt   Pictures  test
5  Desktop    Downloads  file1    ifq       math.sh  Public    Videos

ls –l = lists contents of current directory with extra details

ls -a = list all files and folders with hidden files
ls <folderName> = list files in folder
ls -lh = Detailed list, Human readable
ls -l *.jpg = list jpeg files only mv file.txt Documents/ = move file to a folder
ls -lh <fileName> = Result for file only


cd <folderName> = change directory 
cd /   = go to root
cd ..  = go up one folder, tip: ../../../ 
cd ~ =change directory to your home directory 
cd /  =scratch/user change directory to user on scratch 
cd -  =change directory to the last directory you were in before changing to wherever you are now.

 mkdir = create new folder

touch <fileName> = create or update a file
rm myfile removes file called myfile 
rm –f myfile removes myfile without asking you for confirmation. useful if using wildcards to remove files *** 
rm <fileName> .. = delete file (s)
rm -i <fileName> ..k = ask for confirmation each file 
rm -r <dirname> = removes the direcory 
rm –rf mydir this will delete directory mydir along with all its content without asking you for confirmation!

nano opens a text editor. see ribbon at bottom for help. ^x means CTRL-x. this will exit nano 
nano new.txt opens nano editing a file called new.txt 


cat <fileName> = show content of file (less, more)

head new.txt displays first 10 lines of new.txt 
tail new.txt displays last 10 lines of new.txt 
tail –f new.txt displays the contents of a file as it grows, starting with the last 10 lines. ctrl-c to quit. 

mv <folderName> <folderName2> = move folder in folder

mv filename.txt filename2.txt = rename file. (this will overwrite it!)
mv file.txt Documents/ = move file to a folder
mv <folderName>/ .. = move folder up in hierarchy 
mv dir subdir moves the directory called dir to the directory called subdir 
mv dir newdirname renames directory dir to newdirname  

cp image.jpg newimage.jpg = copy and rename a file

cp image.jpg <folderName>/ = copy to folder
cp image.jpg folder/sameImageNewName.jpg
cp -R stuff otherStuff = copy and rename a folder
cp *.txt stuff/ = copy all of *<file type> to folder

top = displays all the processes running on the machine, and shows available resources 
wc= word count
wc=<filename>=nbr of line, nbr of words, byte size -l (lines), -w (words), -c(byte size), -m(number of characters)

du -h: Disk usage of folders, human readable

du -ah: “ “ “ files & folders, Human readable
du -sh: only show disc usage of folders

find = the best file research tool 

find =  -name "filename"
find =  -name "text"=search for files who start with the word text

locate <text> = search the content of all the files

locate <fileName> = search for a file 
sudo updatedb = update database of files 

grep <someText> <fileName> = search for text in file

-i = Doesn't consider uppercase words
 -I = exclude binary files
grep -r <text> <folderName>/ = search for file names with occurrence of the text

With regular expressions: 

grep -E ^<text> <fileName> = search start of lines with the word text
grep -E <0-4> <fileName> =shows lines containing numbers 0-4
grep -E <a-zA-Z> <fileName> = retrieve all lines 
with alphabetical letters

sort = sort the content of files
sort <fileName> = sort alphabetically
sort -o <file> <outputFile> = write result to a file
sort -r <fileName> = sort in reverse
sort -R <fileName> = sort randomly
sort -n <fileName> = sort numbers

cut = cut a part of a file
-c --> ex: cut -c 2-5 names.txt 
(cut the characters 2 to 5 of each line)
-d (delimiter) (-d & -f good for .csv files)
-f (# of field to cut)

tar -zxf archive.tgz = this will extract the contents of the archive called archive.tgz. kind of like unzipping a zipfile. *** 
tar -zcf dir.tgz dir = this creates a compressed archive called dir.tgz that contains all the files and directory structure of dir 



Basic Terminal Shortcuts

CTRL L = Clear the terminal 

CTRL D = Logout
SHIFT Page Up/Down = Go up/down the terminal
CTRL A = Cursor to start of line 
CTRL E = Cursor the end of line
CTRL U = Delete left of the cursor 
CTRL K = Delete right of the cursor 
CTRL W = Delete word on the left 
CTRL Y = Paste (after CTRL U,K or W) 
TAB = auto completion of file or command 
CTRL R = reverse search history
!! = repeat last command
CTRL Z = stops the current command (resume with fg in foreground or bg in background)