Friday, February 3, 2017

[Quick Tips: Prevent Accidental Deletion]: Prevent Files And Folders From Accidental Deletion Or Modification In Linux

Prevent Files And Folders From Accidental Deletion Or Modification In Linux


Data protection is one of the main job of a System administrator. There are numerous free and commercial data protection softwares are available on the market. But, as you might know, there is a simple, yet useful commandline utility called “chattr” (abbreviation of Change Attribute) which can be used to prevent files and folders from accidental deletion in Unix-like distributions. It applies certain attributes to a file or folder in your Linux system. So the users can’t delete or modify the files and folders either accidentally or intentionally, even as root user. Sounds useful, isn’t it?

By default, Chattr is available in most modern Linux operating systems. Let us see some examples.
The default syntax of chattr command is:
chattr [operator] [switch] [filename]
chattr has the following operators.
  • The operator ‘+’ causes the selected attributes to be added to the
    existing attributes of the files;
  • The operator ‘-‘ causes them to be removed;
  • The operator ‘=’ causes them to be the only attributes that the files have.
Chattr has different attributes namely – aAcCdDeijsStTu. Each letter applies a particular attributes to a file.
  • a – append only,
  • A – no atime updates,
  • c – compressed,
  • C – no copy on write,
  • d – no dump,
  • D – synchronous directory updates,
  • e – extent format,
  • i – immutable,
  • j – data journalling,
  • P – project hierarchy,
  • s – secure deletion,
  • S – synchronous updates,
  • t – no tail-merging,
  • T – top of directory hierarchy,
  • u – undeletable.
In this tutorial, we are going to discuss the usage of two attributes, namely ai which are used to prevent the deletion of files and folders.

Prevent files from accidental deletion

I am going to create a file called file.txt in my current directory.
touch file.txt
Now, I am going to apply “i” attribute which makes the file immutable. It means you can’t delete, modify the file, even if you’re the file owner and the root user.
sudo chattr +i file.txt
You can check the file attributes using command:
sudo lsattr file.txt
Sample output:
----i---------e---- file.txt
Now, try to remove the file either as a normal user or with sudo privileges.
rm file.txt
Sample output:
rm: cannot remove 'file.txt': Operation not permitted
Let me try with sudo command:
sudo rm file.txt
Sample output:
rm: cannot remove 'file.txt': Operation not permitted
Let us try to append some contents in the text file.
echo 'Hello World!' >> file.txt
Sample output:
bash: file.txt: Operation not permitted
Try with sudo privilege:
sudo echo 'Hello World!' >> file.txt
Sample output:
bash: file.txt: Operation not permitted
As you noticed in the above outputs, We can’t delete or modify the file even as root user.
To revoke attributes, just use “-i” switch as shown below.
sudo chattr -i file.txt
Now, the immutable attribute has been removed. You can now delete or modify the file.
rm file.txt
Similarly, you can restrict the directories from accidental deletion or modification as described in the next section.

Prevent folders from accidental deletion and modification

Create a directory called dir1 and a file called file.txt inside this directory.
mkdir dir1 && touch dir1/file.txt
Now, make this directory and its contents (file.txt) immutable using command:
sudo chattr -R +i dir1
Where,
  • -R – will make the dir1 and its contents immutable recursively.
  • +i – makes the directory immutable.
Now, try to delete the directory either as normal user or using sudo user.
rm -fr dir1
sudo rm -fr dir1
You will get the following output:
rm: cannot remove 'dir1/file.txt': Operation not permitted
Try to append some contents in the file using “echo” command:
See? You can’t modify it either.
To revoke the attributes back, run:
sudo chattr -R -i dir1
Now, you can delete or modify the contents of this directory as usual.

Prevent files and folders from accidental deletion, but allow modification

We know now how to prevent files and folders from accidental deletion and modification. Next, we are going to prevent files and folders from deletion, but allow modification.
To do so, run the following command:
For files:
sudo chattr +a file.txt
For directories: 
sudo chattr -R +a dir1
The “+a” option will allow you to modify the file or folder, but you can’t delete it.
Add some contents to the file(s) to check whether it works or not.
echo 'Hello World!' >> file.txt
echo 'Hello World!' >> dir1/file.txt
Check the file contents using cat command:
cat file.txt
cat dir1/file.txt
Sample output:
Hello World!
You will see that you can now be able to append the contents. It means we can modify the files and folders.
Let us try to delete the file or folder now.
rm file.txt
Output:
rm: cannot remove 'file.txt': Operation not permitted
Let us try to delete the folder:
rm -fr dir1/
Sample output:
rm: cannot remove 'dir1/file.txt': Operation not permitted
To remove the attributes, run the following commands:
For files:
sudo chattr -R -a file.txt
For directories: 
sudo chattr -R -a dir1/
Now, you can delete or modify the files and folders as usual.
For more details, refer the man pages.
man chattr
That’s all for now. You know now how to apply file attributes to files and folders using chattr command, and how to prevent them from accidental deletion or modification. This can be useful to protect the important system files and data in your Linux system.
Cheers!

[Quick Tips: SSH Allow/ Deny]: Allow Or Deny SSH Access To A Particular User Or Group In Linux

Allow Or Deny SSH Access To A Particular User Or Group In Linux

openSSH configuration file has two directives for both allowing and denying SSH access to a particular user(s) or a group.

Allow SSH Access to a user or group

First, we will see how to allow SSH access for a particular user, for example sk.
Please note that all commands should be run as root user.
Go to your remote server, and edit sshd_config file:
vi /etc/ssh/sshd_config
Add or edit the following line. Replace “sk” with your username.
AllowUsers sk
You can also specify more than one user as shown below.
AllowUsers sk ostechnix
To allow an entire group, say for example root, add/edit the following line:
AllowGroups root
Those who are in the “root” group are can able to ssh to the remote server.
Save and quit the SSH config file. Restart SSH service to take effect the changes.
systemctl restart sshd
Now, the users sk, ostechnix or all the users under the group “root” are allowed to ssh into your remote server. The other users (except sk, ostechnix and users of “root” group) can’t ssh to the remote server.
If you try to ssh in to the remote server using any one of non-allowed user, you will get the following message:
Permission denied, please try again.
Now, let us go ahead and see how to deny/disable ssh access to a particular user or group.

Deny SSH Access to a user or group

To disable or deny SSH access to any user or group, you need to add/edit the following directives in your remote server’s sshd_config file.
To deny SSH access to specific user called “sk”, edit sshd_config file:
vi /etc/ssh/sshd_config
Add/edit the following line in sshd_config file.
DenyUsers sk
Similarly, To deny SSH access to multiple users, specify the usernames with comma separated as shown below.
DenyUsers sk ostechnix
To deny SSH access to an entire group, add:
DenyGroups root
Save and quit the ssh config file. Restart ssh service to take effect the changes.
systemctl restart sshd
if you try to ssh to server using denied users, for example sk:
ssh sk@192.168.1.150
You will get the following message:
sk@192.168.1.150's password: 
Permission denied, please try again.
sk@192.168.1.150's password:
More importantly you should disable Root user login too. Root ssh access is considered a bad practice in terms of security.
To disable root ssh login, edit sshd_config file:
vi /etc/ssh/sshd_config
Find the following line, Uncomment it, and set the value to no.
PermitRootLogin no
Restart SSH service. Congrats! You have just disabled the ssh root login.

[Quick Tips: SSH Keybased Authentication]: How To Configure SSH Key-based Authentication In Linux

How To Configure SSH Key-based Authentication In Linux

What is SSH Key-based authentication?

As we all know, SSH, also known as Secure Shell, is the cryptographic network protocol that allows you to securely communicate/access a remote system over unsecured network, for example Internet. Whenever you send a data over an unsecured network using SSH, the data will be automatically encrypted in the source system, and decrypted in the destination side. SSH provides four authentication methods namely password-based authenticationkey-based authentication, Host-based authentication, and Keyboard authentication. The most commonly used authentication methods are password-based and key-based authentication.
In password-based authentication, all you need is the password of the remote system’s user. If you know the password of remote user, you can access the respective system using “ssh user@remote-system-name”. On the other hand, in key-based authentication, you need to generate SSH key pairs and upload the SSH public key to the remote system in order to communicate it via SSH. Each SSH key pair consists of a private key and public key. The private key should be kept within the client system, and the public key should uploaded to the remote SSH server. You shouldn’t not disclose the private key to anyone. Hope you got the basic idea about SSH and its authentication methods.
In this brief tutorial, we will be discussing how to configure SSH key-based authentication in Linux.

Configure SSH Key-based Authentication In Linux

For the purpose of this guide, I will be using CentOS 7 as SSH server and Ubuntu 16.04 LTS as client system.
SSH Server details:
  • OS : CentOS 7 64-bit minimal edition
  • IP address : 192.168.1.150/24
SSH client details:
  • OS : Ubuntu 16.04 LTS 64-bit minimal system
  • IP address : 192.168.1.103/24

Client side configuration

Like I said already, in SSH key-based authentication method, the public key should be uploaded to the remote system that you want to access via SSH. The public keys will usually be stored in a file called ~/.ssh/authorized_keys in the remote SSH systems.
Important note: Do not generate key pairs as root, as only root would be able to use those keys. Create key pairs as normal user.
Now, let us create the SSH key pair in the client system. To do so, run the following command in your client system.
ssh-keygen
The above command will create 2048 bit RSA key pair. Enter the passphrase twice. More importantly, Remember your passphrase. You’ll need it later.
Sample output:
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ostechnix/.ssh/id_rsa): 
Created directory '/home/ostechnix/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/ostechnix/.ssh/id_rsa.
Your public key has been saved in /home/ostechnix/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gCswMvywVrbhuVsExLb9WpwpUTd20N9T0jTPkiVJLb0 ostechnix@ubuntuserver
The key's randomart image is:
+---[RSA 2048]----+
| .. .o .oBo|
|. .o . . + o +=B|
|=o.=+ o o o . +o=|
|.+B.=+ . . E |
| o.=..+ S .|
|. .o. * |
| . .+ |
| o. |
| . |
+----[SHA256]-----+
In case you have already created the key pair, you will see the following message. Just type “y” to create overwrite the existing key .
/home/username/.ssh/id_rsa already exists.
Overwrite (y/n)?
Now, we have created the key pair in the client system. Now, copy the SSH public key to your remote SSH server using command:
ssh-copy-id sk@192.168.1.150
Here, I will be copying the client (Ubuntu 16.04 LTS) system’s public key to the remote SSH server (CentOS 7 in my case). Technically speaking, the above command will copy the contents of client system’s ~/.ssh/id_rsa.pub key into remote system’s ~/.ssh/authorized_keys file. Clear? Good.
Type yes to continue connecting to your remote SSH server. And, then Enter the root user’s password of the remote system.
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/ostechnix/.ssh/id_rsa.pub"
The authenticity of host '192.168.1.150 (192.168.1.150)' can't be established.
ECDSA key fingerprint is SHA256:U7I0O1OOzzbHFlhIG0HoGDr1usHzLBju6Jmr6bUB9Es.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
sk@192.168.1.150's password:

Number of key(s) added: 1

Now try logging into the machine, with: "ssh 'root@192.168.1.150'"
and check to make sure that only the key(s) you wanted were added.
We have successfully added the SSH public key to the remote SSH server. No, let us disable the password-based authentication completely. Because, we have configured key-based authentication, so we don’t need password-base authentication anymore.

Server side configuration

You need to perform the following commands as root user.
To disable password-based authentication, go to your remote server’s console and edit /etc/ssh/sshd_config configuration file using any editor:
vi /etc/ssh/sshd_config
Find the following line. Uncomment it and set its as no.
PasswordAuthentication no
Restart ssh service to take effect the changes.
systemctl restart sshd

Access SSH server from Client system

Go to your Client system and SSH into your remote server using command:
ssh sk@192.168.1.150
Enter the passphrase.
Sample output:
Enter passphrase for key '/home/ostechnix/.ssh/id_rsa': 
Last login: Tue Jan 31 19:01:43 2017 from sk
[sk@server1 ~]#
Now, you’ll be able to SSH into your remote system. As you noticed, we have logged-in to the remote system’s account using passphrase, not using the actual account’s password.
If you try to ssh from another client system, you will get this error message. Say for example, I am tried to SSH into my CentOS 7 server from my Arch Linux using command:
ssh sk@192.168.1.150
Sample output:
The authenticity of host '192.168.1.150 (192.168.1.150)' can't be established.
ECDSA key fingerprint is 67:fc:69:b7:d4:4d:fd:6e:38:44:a8:2f:08:ed:f4:21.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.150' (ECDSA) to the list of known hosts.
Permission denied (publickey).
As you see in the above output, I can’t SSH into my remote CentOS 7 server from any other systems, except the Ubuntu client.

Adding more Client system’s keys to SSH server

This is very important. Like I said already, you can’t access the remote system via SSH, except the one you configured (In our case it’s Ubuntu). I want to give permissions to more clients to access the remote SSH server. What should I do? Simple. You need to generate the SSH key pair in your client systems and copy the ssh public key manually to the remote server that you want to access via SSH.
To create SSH key pair, run:
ssh-keygen
Enter the passphrase twice. Now, the ssh key pair is generated. You need to copy the public ssh key (not private key) to your remote server manually.
Display the pub key using command:
cat ~/.ssh/id_rsa.pub
You should an output something like below.
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCt3a9tIeK5rPx9p74/KjEVXa6/OODyRp0QLS/sLp8W6iTxFL+UgALZlupVNgFjvRR5luJ9dLHWwc+d4umavAWz708e6Na9ftEPQtC28rTFsHwmyLKvLkzcGkC5+A0NdbiDZLaK3K3wgq1jzYYKT5k+IaNS6vtrx5LDObcPNPEBDt4vTixQ7GZHrDUUk5586IKeFfwMCWguHveTN7ykmo2EyL2rV7TmYq+eY2ZqqcsoK0fzXMK7iifGXVmuqTkAmZLGZK8a3bPb6VZd7KFum3Ezbu4BXZGp7FVhnOMgau2kYeOH/ItKPzpCAn+dg3NAAziCCxnII9b4nSSGz3mMY4Y7 ostechnix@ubuntuserver
Copy the entire contents and go to your remote server’s console. Create a directory called ssh in the home directory as shown below. You need to execute the following commands as root user.
mkdir -p ~/.ssh
Now, append the your client system’s pub key which you generated in the previous step in a file called
echo {Your_public_key_contents_here} >> ~/.ssh/authorized_keys
Restart ssh service on the remote system. Now, you’ll be able to SSH to your server from the new client.
That’s it. SSH Key-based authentication provides an extra layer protection from brute-force attacks. Configuring key-based authentication is not that difficult either.

[Quick Tips: Installed Apps Info]: How To Find Installed Applications With Installed Size In Linux

How To Find Installed Applications With Installed Size In Linux

There might be many ways to do this, but I prefer the following three.

1. Find installed applications with size using Synaptic package manager

In Ubuntu and its derivatives, we can easily find it using Synaptic package manager. If your system don’t have synaptic, install it as shown below.
sudo apt-get install synaptic
Once installed, go to Settings -> Preferences and click on “Columns and Fonts” tab. Then, check the column boxes named “Size” and “Download size”.
After enabling those columns, go back to the main screen of Synaptic, and click on Status tab on the left and choose “Installed” option. You will there see the installed applications along with their size.

2. Find installed applications with size From Terminal

On Debian, Ubuntu, Linux Mint:
sudo dpkg-query -Wf '${Installed-size}\t${Package}\n' | column -t
Sample output:
140 xserver-xorg-video-siliconmotion
98 xserver-xorg-video-sisusb
87 xserver-xorg-video-tdfx
161 xserver-xorg-video-trident
50 xserver-xorg-video-vesa
.
.
.
157 zeitgeist-datahub
350 zenity
1716 zenity-common
573 zip
157 zlib1g
On RHEL, CentOS, Fedora, run:
sudo rpm -qa --queryformat '%10{size} - %-25{name} \t %{version}\n' | sort -n
Here, the “%10{size}” indicates that the size should be aligned right and padded by 10 characters. The “%-25{name}” sets the package name to be aligned left and padded to 25 characters. Finally, “sort” will sort the result line as per the specified numeric value (-n).
Sample output:
This command will display the installed packages by size. Largest packages packages will be displayed last.
 0 - basesystem 10.0
 0 - filesystem 3.2
 0 - gpg-pubkey 352c64e5
 0 - gpg-pubkey f4a80eb5
 0 - libreport-filesystem 2.1.11
 180 - selinux-policy 3.13.1
 599 - rootfiles 8.1
 .
 .
 .
 120273417 - glibc-common 2.17
 132737027 - kernel 3.10.0
 132756803 - kernel 3.10.0
 142671431 - kernel 3.10.0
 142686493 - kernel 3.10.0

3. Find installed applications with size using Pacgraph

Pacgraph visualizes the installed applications in a pretty graph. It was originally developed for Arch Linux and its derivatives. Now, it is ported to other distros as well.
To install it in Arch Linux and its derivatives, run:
sudo pacman -S pacgraph
On Ubuntu 16.04:
sudo apt-get install pacgraph
Well, we have installed pacgraph. Let us now see how to find the installed applications withe disk space consumed by them using command:
sudo pacgraph -c
Sample output:
Here is the sample output from my Arch Linux desktop. The largest packages will be shown first.
Autodetected Arch.
Loading package info
warning: ttf-font found in ['ttf-dejavu-ib', 'ttf-liberation-ib', 'ttf-oxygen'], assuming ttf-dejavu-ib
Total size: 6968MB
563MB qt5-examples
541MB libreoffice-fresh
337MB virtualbox
206MB go-tools
.
.
.
27648B which
27648B acpi
24576B caja-open-terminal
5120B systemd-sysvcompat
If your system has graphical DE, you can easily display the graph of all installed packages by running:
pacgraph-tk

[Quick Tips: Copy 1File to Multiple DIR]: How To Copy A File To Multiple Directories In Command Line On Linux

How To Copy A File To Multiple Directories In Command Line On Linux

Today, I wanted to copy a movie to two different folders in my Arch Linux desktop. As you already know, We can easily do it by right-clicking on the movie file, select Copy option and paste it on the destination directory/folder. However, I was curious to know that is there any other option to copy the file into multiple directories in one go. I thought It would help when I want to copy a single file into number of different directories at once. I dug a little bit in Google and found this solution. In this brief guide, I will be explaining how to copy a file to multiple directories in command line on Linux.

Copy A File To Multiple Directories In Command Line On Linux

I have text file called ostechnix.txt in my home directory, and I wanted to copy it to two different directories called Downloads and Documents in one go. It’s not that difficult. Here is some simple methods to accomplish this task.

Method 1 – Using tee command

Tee is a Unix and Linux utility used to read from standard input and write to standard output and files.
Now, let us copy the ostechnix.txt file into two different directories called /home/sk/Downloads and /home/sk/Documents.
To do so, just run the following command from the Terminal:
tee /home/sk/Downloads/ostechnix.txt /home/sk/Documents/ostechnix.txt < /home/sk/ostechnix.txt
The above command copied the ostechnix.txt file from home directory to Downloads and Documents directory.
Please note that tee command will also write the input to the standard output. If you don’t want tee command to do this, just redirect the standard output to /dev/null as shown below.
tee /home/sk/Downloads/ostechnix.txt /home/sk/Documents/ostechnix.txt < /home/sk/ostechnix.txt >/dev/null
Please be mindful that if there is any file already present with the same same (i.e ostechnix.txt), the above commands will overwrite the existing file.

Method 2: Using find command

We can copy a single file to multiple directories at once using find command. It is a Unix and Linux command to search for files in a directory hierarchy.
Let us see how to use this command to accomplish this task.
find Downloads/ Documents/ -type d -exec cp ostechnix.txt {} \;
The above command will copy ostechnix.txt file into  Downloads, Documents directories and also into their sub-directories as well.
If you only want to copy ostechnix.txt file to Downloads and Documents directories, and not in their sub-directories, run the following command with -maxdepth 0 option :
find Downloads/ Documents/ -maxdepth 0 -type d -exec cp ostechnix.txt {} \;
The above command will copy ostechnix.txt file to the specified directories, not in their sub-directories.
That’s it. There might be other ways to copy a file to multiple directories at once. But, I believe these commands are very simple and easy to use. If you’re new to Linux, I always suggest you to test these commands in any test machines before start using them in the production. This will prevent the unnecessary loss of data.