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.