Wednesday, November 11, 2015

VSFTPD - Set up your FTP server on a CentOS 6x system

Warm Diwali wishes friends! 

Was wondering as what should I do on this festive day which is already spoiled by incessant rain, then felt like lets document something useful. So, here is one;

VSFTPD! Passive or Active, too much confusion? Here is how to set up both on a CentOS-6x system (should work on RHEL, Fedora based systems as well);


A. Installation is a breeze using YUM, do it like;
# yum install vsftpd -y

B. Some custom configuration 
     You may do the following in the "/etc/vsftpd/vsftpd.conf" file;

1. No anonymous login:
anonymous_enable=NO

2. I needed the full log like connection details of clients:

xferlog_std_format=NO

3. Add this;
log_ftp_protocol=YES

4. The following is to restrict FTP users to their directories. Not a good
           thing to allow them to peep into others' :-)

chroot_local_user=YES

6. I wanted specific users to have FTP access, thus I listed the users in
           "/etc/vsftpd/user_list" commenting the default ones;

           userlist_deny=NO
           (to make use of the file /etc/vsftpd/user_list, include only those users
           who needs FTP service)

7. Active OR Passive?

A. Specific to Active FTP:

pam_service_name=vsftpd
userlist_enable=YES
userlist_deny=NO
tcp_wrappers=YES
pasv_enable=NO


B. Specific to Passive FTP (open the passive port range in the
                    firewall):

##For passive ftp mode

pam_service_name=vsftpd
userlist_enable=YES
userlist_deny=NO
tcp_wrappers=YES

pasv_enable=YES
pasv_min_port=50000
pasv_max_port=50999
port_enable=YES
pasv_addr_resolve=YES
pasv_address=xxx.xxx.xxx.xxx   (Public IP of your FTP server,
                   may be it is needed as this Openstack instance is behind a NAT)


8. SELinux !
          (Modify the SELinux Boolean if you encounter "500 OOPS: cannot 
          change directory:/home/ Login failed.")

A. Grab the values:

# getsebool -a | grep ftp
allow_ftpd_anon_write --> off
allow_ftpd_full_access --> off
allow_ftpd_use_cifs --> off
allow_ftpd_use_nfs --> off
ftp_home_dir --> off
ftpd_connect_db --> off
ftpd_use_fusefs --> off
ftpd_use_passive_mode --> on
httpd_enable_ftp_server --> off
tftp_anon_write --> off
tftp_use_cifs --> off
tftp_use_nfs --> off

B. Change the Home directory specific boolean value:

                # setsebool -P ftp_home_dir On
                (Do a man page for options)


C. Test the FTP server

         Create a FTP user (a system user) and set his login shell as /sbin/nologin (to
        deny him SSH access). Test your FTP server using command line FTP
        client or GUI based Filezilla (or any other client of your choice)

Monday, August 31, 2015

Multi Hopping SSH Tunnel


Let's assume you have two remote systems (System A and System B) of which one (System A) is accessible by its Public IP but the other does not have the Public IP or it may be behind the firewall. This situation prevents you from accessing the second system directly from your home.

You can access (SSH) the second system (System B) in two steps.

1. From your home, Log into System A
2. From System A, Log into System B

But, what if you want to access System B directly from your home? 

[Note: HostName, UserName, Keys, IP Address used here are only for example]

Multi-Hop SSH Tunnel

Here, we would use a built in SSH feature known as SSH Hopping using an Intermediate Host (System-A in this case);

ssh -t user@Intermediate Host ssh user@Destination Host

-t switch creates a pseudo terminal to execute some commands. (in this case it executes the ssh to System B)

For example;

# ssh -i id_rsa -t centos@xxx.xxx.xxx.xxx ssh -i id_rsa_private centos@172.16.20.12
Last login: Mon Aug 31 13:05:40 2015 from 172.16.20.13
[centos@ins-2 ~]$

Let's understand what it is doing; 

1. ssh -i id_rsa -t centos@xxx.xxx.xxx.xxx
It opens an ssh connection to server at xxx.xxx.xxx.xxx IP. The "-t " switch actually creates an
        pseudo terminal on that server to execute the following command;

[Note:  The private key "id_rsa" is stored under the current path of execution of the ssh
        command]

2. ssh -i id_rsa_private centos@172.16.20.12
[Note: The private key "id_rsa_private" is stored under the home directory of user "centos" on
        "System A with Pub IP xxx.xxx.xxx.xxx" ]

How about doing the following from your home system?
ssh centos@172.16.20.12

Lets tweak it further, for this we would be requiring NC (Netcat) package on our intermediate host(s).

1. Start an SSH agent on our Home system and store the "Private Key"

# eval $(ssh-agent -s)
Agent pid 3067

# ssh-add id_rsa
Identity added: id_rsa (id_rsa)

.2 Put the following contents in the file ~/.ssh/config 

Host someserver
  HostName xxx.xxx.xxx.xxx
User centos
Port 22

Host 172.16.20.12
HostName 172.16.20.12
User centos
ForwardAgent yes
Port 22

ProxyCommand ssh -q xxx.xxx.xxx.xxx nc %h %p

3. Now, from your home system do a direct SSH to System B i.e. 172.16.20.12 as shown 
        below;

# ssh centos@172.16.20.12
Last login: Mon Aug 31 16:07:18 2015 from 172.16.20.13
[centos@ins-2 ~]$

Thursday, July 16, 2015

Recovering deleted files in Linux ! The ext4magic ...


I was wondering if I could find any tool that would undelete files from ext3/ext4 partitions. While searching I came across this tool which did the job I wanted. I tested it on an old Fedora-14 (32 bit) system;


[Source:   
]


Following are the steps;

1. Download URL;
http://rpms.plnet.rs/plnet-centos6-i386/RPMS.plnet-downloaded/ext4magic-0.3.1-1.2.i686.rpm
http://rpms.plnet.rs/plnet-centos6-x86_64/RPMS.plnet-downloaded/ext4magic-0.3.1-1.2.x86_64.rpm

2. Install;
# yum install ext4magic-0.3.1-1.2.i686.rpm --nogpgcheck
(I could not find the gpg key so I avoided checking the same while installing)

3. I deleted some of the files from "/LVM-1" directory which was acting as the mount point for
        /dev/mapper/vg1-lv--1

4. Stop using the filesystem that needs recovery and unmount it;
# umount /LVM-1

5. Copy partition;
(dd if=/dev/DEVICE of=/BACKUPPATH/DEVICE.img)
# dd if=/dev/mapper/vg1-lv--1 of=/BACKUP/vg1-lv--1.img

6. Examine the directory structure once. I created a separate directory for recovered files;
# tree BACKUP/
BACKUP/
├── RECOVERED
└── vg1-lv--1.img

7. Run ext4magic on the copy/dd-image to recover all deleted files (-m switch for files and 
        -M if entire filesystem needs recovery);

(ext4magic /BACKUPPATH/DEVICE.img -m -j /BACKUPPATH/journal.copy)

# ext4magic /BACKUP/vg1-lv--1-NEW.img -M -d /BACKUP/RECOVERED/
Warning: Activate magic-scan or disaster-recovery function, may be some command line options
         ignored
"/BACKUP/RECOVERED/"  accept for recoverdir
Filesystem in use: /BACKUP/vg1-lv--1-NEW.img

Using  internal Journal at Inode 8
Activ Time after  : Wed Jul 15 14:03:20 2015
Activ Time before : Wed Jul 15 14:07:04 2015
Inode 2 is allocated
-------- /BACKUP/RECOVERED//lost+found
-------- /BACKUP/RECOVERED//Dir-1
-------- /BACKUP/RECOVERED//Dir-2
-------- /BACKUP/RECOVERED//file-1
-------- /BACKUP/RECOVERED//file-2
-------- /BACKUP/RECOVERED//
MAGIC-1 : start lost directory search
MAGIC-2 : start lost file search
MAGIC-2 : start lost in journal search
MAGIC-3 : start ext4-magic-scan search
ext4magic : EXIT_SUCCESS


Bang! Files are back :) 

Wednesday, July 15, 2015

DRBD (Distributed Replicated Block Device)

DRBD (Distributed Replicated Block Device)
---------------------------------------------------------

DRBD refers to block devices which acts as to form high availability (HA) clusters on Linux systems. The process involves mirroring a whole block device over network. This is somewhat similar to network based RAID-1 where data is copied on two storage devices, failure of one results in activating the other one. 


But, there is marked difference between Network based RAID-1 and DRBD. In case of network based RAID-1, there exists a single application which access any one of the two storage devices at any point in time. The RAID layer chooses to read the other device when one fails. There is an abstraction between the application and RAID devices thus the application is not aware of which of the devices it is interacting at any given point. 

But, this is not the case with DRBD where exists two instances of the application, and each can read only from one of the two storage devices. Read more here...

Requirements

– Two disks  (preferably same size)

– Networking between machines (node1 & node2)
– Working DNS resolution  (/etc/hosts file)
– NTP synchronized times on both nodes
– Selinux Permissive (!)
– Iptables ports (7788) allowed

A. Test Environment:

– Two CentOS-6.6 systems with IP 172.16.20.46 and 172.16.20.47 designated as 

           "node1" and "node2" respectively 

– On both systems Disks are partitioned as;
  /dev/vdb1               1        2082     1049296+  83  Linux
  /dev/vdb2            2083      6241     2096136   83  Linux

– DNS resolution is done through /etc/hosts on both the systems by setting hostname 
<--> IP address 
    instead of FQDN  as;
 172.16.20.46 node1
 172.16.20.47 node2

B. SELinux and IPTABLES:


B1. Setting SELinux to permissive (Not a very good idea though!! :) )
# setenfore 0

B2. Allow DRBD port to accept connection from all (test only, change it to specific IPs 
       to your need)
# iptables -I INPUT 4 -p tcp --dport 7788 -j ACCEPT
# service iptables save
iptables: Saving firewall rules to /etc/sysconfig/iptables: [  OK  ]
 
     # service iptables restart
iptables: Setting chains to policy ACCEPT: filter           [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                               [  OK  ]
iptables: Applying firewall rules:                         [  OK  ]

C. Configuration:

Note:  Carry out the following steps on both the systems unless mentioned otherwise;

1. Setup ELRepo (not EPEL, as I could not find DRBD packages for CentOS-6.6 release) on both 

    systems;
  # wget http://www.elrepo.org/elrepo-release-6-6.el6.elrepo.noarch.rpm .
# rpm -ivh elrepo-release-6-6.el6.elrepo.noarch.rpm

2. Check the yum repositories once;

# yum repolist
repo id                 repo name                               status
base                  CentOS-6 - Base                                       6,518
datastax              DataStax Repo for Apache Cassandra                         158
elrepo                ELRepo.org Community Enterprise Linux Repository - el6        334
epel                  Extra Packages for Enterprise Linux 6 - x86_64                   11,735
extras                CentOS-6 - Extras                                         38
updates               CentOS-6 - Updates                                         1,336

3. Install the packages;

# yum install drbd83-utils kmod-drbd83

4. Now, insert DRBD module manually into Kernel on both systems (or reboot to make it 

    effective);
  # modprobe drbd
# lsmod | grep drbd
      drbd       332493  0 

5. Create the Distributed Replicated Block Device resource file (/etc/drbd.d/clusterdb.res):
resource clusterdb
{
startup {
wfc-timeout 30;
outdated-wfc-timeout 20;
degr-wfc-timeout 30;
}

net {
cram-hmac-alg sha1;
shared-secret sync_disk;
}

syncer {
rate 10M;
al-extents 257;
on-no-data-accessible io-error;
}

on node1 {
device /dev/drbd0;
disk /dev/vdb2;
address 172.16.20.46:7788;
flexible-meta-disk internal;
}
 
on node2 {
device /dev/drbd0;
disk /dev/vdb2;
address 172.16.20.47:7788;
meta-disk internal;
}
}

6. Copy DRBD configuration files (viz. /etc/drbd.d/clusterdb.res) and entries in /etc/hosts file to    

     "node2"

7. Initialize the DRBD meta data storage on both machines;

# drbdadm create-md clusterdb

--==  Thank you for participating in the global usage survey  ==--
The server's response is:

you are the 25728th user to install this version
Writing meta data...
initializing activity log
NOT initialized bitmap
New drbd meta data block successfully created.
success

8. Start the DRBD service on both systems;
# service drbd start

Starting DRBD resources: [ d(clusterdb) s(clusterdb) n(clusterdb) ]..........


       DRBD's startup script waits for the peer node(s) to appear.

       - In case this node was already a degraded cluster before the
        reboot the timeout is 30 seconds. [degr-wfc-timeout]
        - If the peer was available before the reboot the timeout will
         expire after 30 seconds. [wfc-timeout]
        (These values are for resource 'clusterdb'; 0 sec -> wait forever)
        To abort waiting enter 'yes' [  29]:
.

9. Check status as;

# service drbd status
or,
# cat /proc/drbd

10. As you can see, at the beginning both nodes are secondary, which is normal. We need to figure out   
      which one would act as a primary that will initiate the first 'full sync' between the two nodes; 

      In our case, we choose "node1", thus;
A. On node1:
# drbdadm -- --overwrite-data-of-peer primary clusterdb

11. Put a watch on the sync in progress;

# watch 'cat /proc/drbd'
Every 2.0s: cat /proc/drbd                                 Tue Jul 14 08:59:44 2015

version: 8.3.16 (api:88/proto:86-97)

GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 
      14:51:37
     0: cs:SyncSource ro:Primary/Secondary ds:UpToDate/Inconsistent C r-----
     ns:429056 nr:0 dw:0 dr:429720 al:0 bm:26 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:1666980
[===>................] sync'ed: 20.8% (1666980/2096036)K
finish: 0:03:38 speed: 7,600 (9,128) K/sec

12. Once full sync is achieved, check the status on both the nodes;

A. Node1
# cat /proc/drbd
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-
            24 14:51:37
           0: cs:Connected ro:Primary/Secondary ds:UpToDate/UpToDate C r-----
           ns:2096036 nr:0 dw:0 dr:2096700 al:0 bm:128 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0

B. Node2
[root@node2 ~]# cat /proc/drbd 
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-       
            24 14:51:37
0: cs:Connected ro:Secondary/Primary ds:UpToDate/UpToDate C r-----
           ns:0 nr:2096036 dw:2096036 dr:0 al:0 bm:128 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0

13. Create filesystem on Distributed Replicated Block Device device;

On the primary node i.e. node1:
# mkfs.ext4 /dev/drbd0

14. Now, mount DRBD device on primary node;

# mkdir /my-DRBD-Data
# mount /dev/drbd0 /my-DRBD-Data

15. Please note:  

One does not need need to mount the disk from secondary systems explicitly. All data that are 
       written on "/my-DRBD-Data" folder will be synced to the other system i.e. "node2".

16. Lets test that out;

16a. Unmount the "/my-DRBD-Data" folder from the primary node "node1". 
16b. Make the secondary node as primary node.  
16c. Mount back the "/my-DRBD-Data" on the second machine "node2", you will see the same 
                 contents in /my-DRBD-Data  folder.
17. Actual test;

17a. Create some data on Node1:
# cd /my-DRBD-Data
# mkdir bijit
# echo "hi" > test1.txt
# echo "hello" > test2.txt
 
                 [root@node1 my-DRBD-Data]# ll
total 28
drwxr-xr-x. 2 root root  4096 Jul 14 09:20 bijit
drwx------. 2 root root 16384 Jul 14 09:15 lost+found
-rw-r--r--. 1 root root     3 Jul 14 09:20 test1.txt
-rw-r--r--. 1 root root     6 Jul 14 09:21 test2.txt

17b. Unmount the data on the primary Node:

[root@node1 /]# umount /my-DRBD-Data/

17c. Make secondary node as the Primary:

[root@node1 /]# drbdadm secondary clusterdb
[root@node2 ~]# drbdadm -- --overwrite-data-of-peer primary clusterdb

17d. Mount back the "/my-DRBD-Data" on the second machine "node2";
[root@node2 ~]# mkdir /my-DRBD-Data
[root@node2 ~]# mount /dev/drbd0 /my-DRBD-Data/
 
  17e. Check the contents on Node2:
[root@node2 ~]# ll /my-DRBD-Data/
total 28
drwxr-xr-x. 2 root root  4096 Jul 14 09:20 bijit
drwx------. 2 root root 16384 Jul 14 09:15 lost+found
-rw-r--r--. 1 root root     3 Jul 14 09:20 test1.txt
-rw-r--r--. 1 root root     6 Jul 14 09:21 test2.txt

Now, delete and add some contents on the "node2" which now acts as primary. 

Unmount it and make it secondary. Switch to "node1" and make it as primary and mount it back. Check if the changes are replicated !