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

Thursday, November 19, 2020

Understanding the Apache Access Logs

Description: Log is an extremely important thing for Developer and System Administrator to troubleshoot any issue. Here I have explained how to setup Apache log and different options to get more details from Apache

For instance, when someone visits your website, a log is recorded and stored to provide the Apache webserver administrator with information such as the IP address of the visitor, what pages they were viewing, status codes, browser used, etc.

How to setup Access log file for Apache

  • Open HTTP configuration file [Located on /etc/httpd/conf/httpd.conf] and paste below configuration 
# vi /etc/httpd/conf/httpd.conf

LogFormat "%h %t \"%r\" %>s %b %O %T/%D \"%{Referer}i\" \"%{User-Agent}i\"" combined

CustomLog logs/access_log combined

  • After saving configuration restart Apache service 
    # service httpd restart

Below are the options for the custom log which we can use for Access Log 
%% The percent sign
%a Remote IP-address
%A Local IP-address
%B Size of response in bytes, excluding HTTP headers.
%b Size of response in bytes, excluding HTTP headers. In CLF format, i.e. a '-' rather than a 0 when no bytes are sent.
%{Foobar}C The contents of cookie Foobar in the request sent to the server.
%D The time taken to serve the request, in microseconds.
%{FOOBAR}e The contents of the environment variable FOOBAR
%f Filename
%h Remote host
%H The request protocol
%{Foobar}i The contents of Foobar: header line(s) in the request sent to the server.
%l Remote logname (from identd, if supplied). This will return a dash unless mod_ident is present and IdentityCheck is set On.
%m The request method
%{Foobar}n The contents of note Foobar from another module.
%{Foobar}o The contents of Foobar: header line(s) in the reply.
%p The canonical port of the server serving the request
%P The process ID of the child that serviced the request.
%{format}P The process ID or thread id of the child that serviced the request. Valid formats are pid, tid, and hextid. hextid requires APR 1.2.0 or higher.
%q The query string (prepended with a ? if a query string exists, otherwise an empty string)
%r First line of request
%s Status. For requests that got internally redirected, this is the status of the *original* request --- %>s for the last.
%t Time the request was received (standard english format)
%{format}t The time, in the form given by format, which should be in strftime(3) format. (potentially localized)
%T The time taken to serve the request, in seconds.
%u Remote user (from auth; may be bogus if return status (%s) is 401)
%U The URL path requested, not including any query string.
%v The canonical ServerName of the server serving the request.
%V The server name according to the UseCanonicalName setting.
%X Connection status when response is completed:
X = connection aborted before the response completed.
+ = connection may be kept alive after the response is sent.
- = connection will be closed after the response is sent.
(This directive was %c in late versions of Apache 1.3, but this conflicted with the historical ssl %{var}c syntax.)
%I Bytes received, including request and headers, cannot be zero. You need to enable mod_logio to use this.
%O Bytes sent, including headers, cannot be zero. You need to enable mod_logio to use this.


Below are the example of Access log after setup above configuration in Http configuration file
104.244.168.11 [19/Nov/2020:10:56:24 +0000] "POST /boaform/admin/formLogin HTTP/1.1" 400 278 473 **60/60059969** "http://104.211.139.152:80/admin/login.asp" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:71.0) Gecko/20100101 Firefox/71.0
103.251.217.65 [19/Nov/2020:11:01:20 +0000] "GET /favicon.ico HTTP/1.1" 502 341 573 **60/60043967** "http://104.211.139.152/balancer-manager" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"

Below are the option used on the above example 
%h = Requestor IP/address
%t = Date time of the request 
%r = Request type and resource being requested
%s = HTTP response status code
%b = Size of response in bytes, excluding HTTP headers
%O = Size of object returned    
%T = The time taken to serve the request, in seconds    Response time
%D = The time taken to serve the request, in microsecond


Thursday, November 5, 2020

Deny access to files with Specific extension in Apache

 Description: Here I have explain how to deny specific extension in Apache using .htaccess file or httpd.conf file

Procedure:

  • For the demo purpose I have blocked "mp3, avi, flv, pdf " extensions. Open .htaccess or httpd.conf file and use Files Directives to block extension 
  • Open httpd configuration file using below command

# vi /etc/httpd/conf/httpd.conf

  • Add below Files Directives under virtual host then save file. 

<Files ~ "\.(mp3|avi|flv|pdf)$">

Deny from all

</Files> 

  • Restart httpd service and verify by access pdf file in URL

Tuesday, July 14, 2020

How to use Apache reverse proxy as A Load Balancer

Description: Here I have explained how to use Apache Reverse Proxy as Load Balancer. In this link I have explained, how to configure reverse proxy to hide Backend application and port number. I have covered redirection part, In this tutorial I will explained how can we use reverse proxy as Loadbalancer.

Procedure: 
  • As a Pre requisite we need to install Apache server with Apache Proxy Modules like mod_proxy, mod_proxy_http, mod_proxy_balancer and mod_lbmethod_byrequests
  • You can verify by using httpd -M command
  • You can also find modules in apache configuration file
# vi /etc/httpd/conf/httpd.conf
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_h
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
  • Restart apache server to after enable it. 
Configuring Backend Server: I have created 3 application server with same App directory as follow.
http://10.0.0.1:5000/App
http://10.0.0.2:5000/App
http://10.0.0.3:5000/App

Configuring the Reverse Proxy: To configure apache reverse proxy load balancer we need to add some configuration in apache configuration file.


# vi /etc/httpd/conf/httpd.conf
<VirtualHost *:80>

<Proxy balancer://cluster>

BalancerMember http://10.0.0.1:5000/App
BalancerMember http://10.0.0.2:5000/App
BalancerMember http://10.0.0.3:5000/App


ProxyPreserveHost On
ProxyPass / balancer://cluster/
ProxyPassReverse / balancer://cluster/

</VirtualHost>

Here ‘<Proxy balancer://cluster>’ is part where we mention the all the instances and 'ProxyPass' is handle all redirection. After making changes restart apache service.

# systemctl restart httpd

Friday, July 10, 2020

Prevent DNS Manager to Overwriting /etc/resolv.conf

Description: Here I have explained how to prevent DNS Manager to Overwriting /etc/resolv.conf after reboot server.

Procedure: In Centos 7 any custom dns store in /etc/resolv.conf, However if we simply add it in file we notice that after server reboot entries overwrite by NetworkManager. 

  • First we configure in NetworkManager for not to overwrite this file. Then, we will go and configure nameserver in  /etc/resolv.conf 
  • Network Configuration file located on /etc/NetworkManager/NetworkManager.conf Open this file on your editor like vi, vim or gedit.
  • Search for [main] section in this file and add entry as follow
  [main]
dns=none
  • Save file and restart network manager service
 # systemctl restart NetworkManager.service
  • Now add your Name Server to /etc/resolv.conf 
 nameserver 8.8.8.8
nameserver 4.4.4.4

  • Verify entries after  restart your server.


Sunday, April 26, 2020

How to Disable Directory browsing in Apache

Description: Here I have explained how to disable directory browsing in Apache.

Procedure: 

  • Open http configuration file on given path /etc/httpd/conf/httpd.conf
  • Remove "indexes" word and save the file 

Options Includes Indexes FollowSymLinks MultiViews
TO

Options Includes FollowSymLinks MultiViews


  • Save Configuration file and Restart service

Monday, April 20, 2020

How to Configure Apache Reverse Proxy on CentOS

Description: Here I have explained what is Apache Reverse Proxy and How to configure it.

What is Reverse Proxy: 
A reverse proxy accepts connections and then routes them to an appropriate path.

For example, if we have any application running on port 5000, we can configure a reverse proxy to accept connections on HTTP or HTTPS, which can then transparently proxy requests to the application backend.

Configure Reverse Proxy.
  1. Verify Proxy module using below command
# httpd -M

Output


proxy_module (shared)


lbmethod_byrequests_module (shared)


proxy_balancer_module (shared)


proxy_http_module (shared


      2. Configure Virtual Host as follow: [We’ll use example application running on 127.0.0.1:5000 as the backend service that we want to reverse proxy requests to]

 


<VirtualHost *:443>


        # The ServerName directive sets the request scheme, hostname and port that


        # the server uses to identify itself. This is used when creating


        # redirection URLs. In the context of virtual hosts, the ServerName


        # specifies what hostname must appear in the request's Host: header to


        # match this virtual host. For the default virtual host (this file) this


        # value is not decisive as it is used as a last resort host regardless.


        # However, you must set it for any further virtual host explicitly.


        #ServerName www.example.com


        ProxyPreserveHost On


        ProxyPass /api http://127.0.0.1:5000


        ProxyPassReverse /api http://127.0.0.1:5000


         ServerAdmin webmaster@localhost


        ServerName app1.demo.com


        ServerAlias app1.demo.com


        DocumentRoot /var/www/html/demoapp


SSLEngine on


SSLCertificateFile /var/www/html/certs/demo.crt


SSLCertificateKeyFile /var/www/html/certs/demo.key


SSLCertificateChainFile /var/www/html/certs/demo_CA.crt




        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,


        # error, crit, alert, emerg.


        # It is also possible to configure the loglevel for particular


        # modules, e.g.


        #LogLevel info ssl:warn




        ErrorLog ${APACHE_LOG_DIR}/error.log


        CustomLog ${APACHE_LOG_DIR}/access.log combined




        # For most configuration files from conf-available/, which are


        # enabled or disabled at a global level, it is possible to


        # include a line for only one particular virtual host. For example the


        # following line enables the CGI configuration for this host only


        # after it has been globally disabled with "a2disconf".


        #Include conf-available/serve-cgi-bin.conf


</VirtualHost>


  • Restart httpd service and verify. 
# systemctl start httpd

Thursday, November 14, 2019

Run Script in Screen Mode on Startup

Description: Here I have explained, How to run script on Startup

Procedure: 
  • Create one script as below which will run in screen mode

 #!/bin/sh
screen -d -m -S SessionName /home/script/run.sh

  • To run script on startup open crontab and define schedule as follow.
 @reboot /bin/sh /home/script/run.sh 

  • After define in schedule restart crontab service and test by restart server.

Tuesday, July 3, 2018

Install and Configure FirewallD on Centos 7

Description: FirewallD is a firewall management tool available on CentOS 7 servers. Basically, it is a wrapper around iptables and it comes with graphical configuration tool firewall-config and command line tool firewall-cmd. With the iptables service, every change requires flushing of the old rules and reading the new rules from the '/etc/sysconfig/iptables' file, while with firewalld only differences are applied.

Procedure: 
  • Install FirewallD using yum 
# yum install firewalld 

FirewallD Zones: FirewallD uses services and zones instead of iptables rules and chains. By default the following zones are available

  1. Drop: Drop all incoming network packets with no reply, only outgoing network connections are available.
  2. Block: Reject all incoming network packets with an icmp-host-prohibited message, only outgoing network connections are available.
  3. Public: Only selected incoming connections are accepted, for use in public areas
  4. External: For external networks with masquerading enabled, only selected incoming connections are accepted.
  5. DMZ: DMZ demilitarized zone, publicly-accessible with limited access to the internal network, only selected incoming connections are accepted.
  6. work: For computers in your home area, only selected incoming connections are accepted.
  7. home: For computers in your home area, only selected incoming connections are accepted.
  8. internal: For computers in your internal network, only selected incoming connections are accepted.
  9. trusted: All network connections are accepted.
  • To list all available zones 
# firewall-cmd --get-zones

work drop internal external trusted home dmz public block
  • To list default zone
#firewall-cmd --get-default-zone
public
  • To change the default zone:
# firewall-cmd --set-default-zone
# firewall-cmd --get-default-zone
dmz
  • Add and allow service in DMZ zone 
# firewall-cmd --zone=dmz --add-service=http --permanent
# firewall-cmd --zone=dmz --add-service=https --permanent
# firewall-cmd --zone=dmz --add-service=imap --permanent
# firewall-cmd --zone=dmz --add-service=imaps --permanent
# firewall-cmd --zone=dmz --add-service=pop3 --permanent
# firewall-cmd --zone=dmz --add-service=pop3s --permanent
  • Remove service and add custom port 
# firewall-cmd --remove-service=ssh --permanent
# firewall-cmd --add-port=7022/tcp --permanent
  • Reload Firewall configuration 
# firewall-cmd --reload
  • List Firewall Rules 
# firewall-cmd --list-all
dmz
target: default
icmp-block-inversion:
interfaces
sources
services: http https imap imaps pop3 pop3s smtp smtps
ports: 7022/tcp
protocols
masquerade: no
forward-ports
sourceports
icmp-blocks
rich rules

Wednesday, June 27, 2018

Install Samba on Centos 7 for file sharing on Windows

Description: In this article I have explain how we can sharing files between windows and Centos

Procedure: 

  • Install Samba in Centos 7 using below command
# yum install samba samba-client samba-common
  • After installation need to add in firewall 
# firewall-cmd --permanent --zone=public --add-service=samba
# firewall-cmd --reload
  • Check windows system work group settings. Before configure samba need to check work group in windows PC.  We can check from My Computer -- Properties -- Advance System settings -- Computer Name
  • After checking work group configure Samba on centos 7. The configuration file of samba is /etc/samba/smb.conf  with pre-configuration settings. But make sure to take backup before made any changes. 
  • First create any directory that you want to share like "Testdirectory"  and set appropriate permission on it.
# mkdir -p /srv/samba/Testdirectory
# chmod -R 0775 /srv/samba/Testdirectory
# chown -R nobody:nobody /srv/samba/Testdirectory
  • You need to set SELinux security context for shared directory
# chcon -t samba_share_t /srv/samba/Testdirectory
  • After creating directory open smb configuration directory and add as following 
# useradd authuser
# vi /etc/samba/smb.conf
[global]
workgroup = WORKGROUP
netbios name = centos
security = user

[Testdirectory]
comment = Test Directory
path = /srv/samba/Testdirectory
browsable =yes
writable = yes
guest ok = yes
read only = no
force user = nobody
  • Now test configuration using below command 
# useradd authuser
# testparm

Load smb config files from /etc/samba/smb.conf
rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
Processing section "[homes]"
Processing section "[printers]"
Processing section "[print$]"
Processing section "[Anonymous]"
Loaded services file OK.
Server role: ROLE_STANDALONE
Press enter to see a dump of your service definitions
# Global parameters

[global]
netbios name = centos
printcap name = cups
security = USER
idmap config * : backend = tdb
cups options = raw

[homes]
comment = Home Directories
browseable = No
inherit acls = Yes
read only = No
valid users = %S %D%w%S

[printers]
comment = All
Printers
path = /var/tmp
browseable = No
printable = Yes
create mask = 0600
[print$]
comment = Printer
Drivers
path = /var/lib/samba/drivers
create
mask = 0664
directory mask = 0775
write list = root
[Testdirectory]
comment = Anonymous File Server Share
path = /srv/samba/Testdirectory
force user = nobody
guest ok = Yes
read only = No
  • Now start samba service and enable it during boot process
# systemctl enable smb.service
# systemctl enable nmb.service
# systemctl start smb.service
# systemctl start nmb.service
  • Now test from your windows client by using \\ipaddress_of_server 
Setup Secure Samba in Centos 7 
  • First create samba group, then add user and set password for them.
# groupadd smbgrp
# usermod systalk -aG smbgrp
# smbpasswd -a systalk
  • Then create a secure directory where the shared files will be kept and set the appropriate permissions on the directory with SELinux security context for the samba.
# mkdir -p /srv/samba/secure
# chmod -R 0770 /srv/samba/secure
# chown -R root:smbgrp /srv/samba/secure
# chcon -t samba_share_t /srv/samba/secure
  • Open samba configuration file and add samba group for appropriate sharing 
# vi /etc/samba/smb.conf
[Secure]
comment = Secure File Server Share
path =  /srv/samba/secure
valid users = @smbgrp
guest ok = no
writable = yes
browsable = yes
  • After configuration run testparm to test configuration and restart service 
# systemctl restart smb.service
# systemctl restart nmb.service
  • Now test secure samba file sharing it will prompt for password. 

Tuesday, June 26, 2018

Configure NFS [Network File System] in Centos 7

Description: 
Network File System (NFS) is a popular distributed file system protocol that enables users to mount remote directories on their server. NFS lets you leverage storage space in a different location and allows you to write onto the same space from multiple servers or clients in an effortless manner.

Procedure:

NFS Server side:
  • First step to install NFS using yum using below command 
# yum install nfs-utils
  • Now create directory that need to share using NFS 
# mkdir /data
  • Change permission on directory as follow
# chmod -R 755 /data
# chown nfsnobody:nfsnobody /data
  • Need to start service and enable them as boot time

# systemctl enable rpcbind
# systemctl enable nfs-server
# systemctl enable nfs-lock
# systemctl enable nfs-idmap
# systemctl start rpcbind
# systemctl start nfs-server
# systemctl start nfs-lock
# systemctl start nfs-idmap
  • Share directory over network using following
# vi /etc/exports

/var/nfsshare    * (rw,sync,no_root_squash,no_all_squash)
/home            10.10.10.10 (rw,sync,no_root_squash,no_all_squash)

Note : 10.10.10.10 is the IP of client machine, if you wish that any other client should access it you need to add the it IP wise other wise you can add "*" instead of IP for all IP access.
  • Restart NFS service 
# systemctl restart nfs-server
  • After restart service need to allow NFS port in firewall 

# firewall-cmd --permanent --zone=public --add-service=nfs
# firewall-cmd --permanent --zone=public --add-service=mountd
# firewall-cmd --permanent --zone=public --add-service=rpc-bind
# firewall-cmd --reload

NFS Client Side:
  • Install nfs-util using below command 
# yum install nfs-utils
  • Create directory to  mount from NFS
# mkdir /mnt/nfsshare
# mkdir /mnt/home
  • After creating directory now mount from NFS using below command:
# mount -t nfs 10.10.10.1:/var/nfsshare /mnt/nfsshare
# mount -t nfs 10.10.10.1:/home /mnt/home
  • After mount check storage using below command 
# df -kh

Filesystem                             Size     Used   Avail   Use%   Mounted on
/dev/mapper/centos-root       39G      1.1G    38G    3%       /
devtmpfs                                488M    0        488M   0%       /dev
tmpfs                                     494M     0        494M   0%      /dev/shm
tmpfs                                     494M    6.7M   487M   2%     /run
tmpfs                                     494M     0        494M    0%      /sys/fs/cgroup
/dev/mapper/centos-home    19G      33M    19G      1%      /home
/dev/sda1                               497M  126M   372M    26%    /boot
10.10.10.1:/var/nfsshare       49G    980M   48G     3%      /mnt/nfsshare 
10.10.10.1:/home                   19G   33M     19G      1%      /mnt/home
  • Now we are connecting NFS shared drive, please check by create test file 
# touch  /mnt/nfsshare/testfile

Permanent  NFS Mounting
  • We need to remount after every reboot, so to mount them as permanent by adding NFS share in fstab as follow:
# vi /etc/fstab
Add entries as follow 
10.10.10.1:/var/nfsshare   /mnt/nfsshare  nfs defaults 0 0
Save file using :wq 
  • Now check by reboot client machine and directory mounted or not.


How to add user and grant Root Privileges in centos 7

Description: To assign root privileges to another user on centos 7

Procedure: 

  • First add user using below command 
# adduser testuser1

  • Set password to user 
# passwd testuser1

  • Grant privileges to user using below command 
# visudo

## find the following content
root ALL=(ALL) ALL
## Add following content
testuser1 ALL=(ALL) ALL


  • Then save and exit file using :wq command
  • To test privileges login with testuser1 and use below command to take previleges
$ sudo su
password prompt for testuser1 now testuser1 can run all commands as a root. 

Thursday, June 21, 2018

Install and Configure Apache in Centos 7

Description:  Apache is most widely usable Web Server Application in the world. It supports multiple features like compiled as a separate modules and extend its functionality. Virtual hosting is one feature which allow single server to server multiple number of different website.  
Here I have explained how to install and configure Apache in Centos 7 and setup virtual hosting using different method. 

Procedure:
  • You can install via default package manager using below command
# yum -y install httpd
  • After installation you need to start and enable service 
# systemctl  enable httpd.service
# systemctl start httpd.service

Install Apache from Source: You can also install Apache from source using below method. Download source in  /usr/local/src folder
# cd /usr/local/src
# gzip -d httpd-2.2.26.tar.gz
# tar xvf httpd-2.2.26.tar
# httpd-2.2.26
#./configure --help
#./configure –prefix=/usr/local/apache –enable-so
# make
# make install

  • In order to see all configuration option available for Apache, you can use ./configure –help option.  The most common configuration option is –prefix={install directory name}
    
      
     
     
      
      
  • Configure firewall to allow httpd traffic using below command 
# firewall-cmd --zone=public --permanent --add-service=http
# firewall-cmd --zone=public --permanent --add-service=https
# firewall-cmd --reload
  • Test your installation by browse default page in browser 
http://SERVER_DOMAIN_NAME_OR_IP


Virtual Host:  An apache server can host multiple website on Same server. You do not  need to have multiple machine and apache software in each server. This can achieved by using virtualhost or vhost

Types Of  Apache Virtual Host

  • Name-based virtual host 
  • Address-based  or IP based virtual host

Name-based virtual host: It is use to host multiple virtual sites on single address.
  • First create vhost.conf file under /etc/httpd/conf.d/ to store multiple vhost configuration 
# vi /etc/httpd/conf.d/vhost.conf

Add the following example virtual host directive template for website testdomain.com, make sure to change the necessary values for your own domain


NameVirtualHost *:80

<10.0.0.1:80>
ServerAdmin master@testdomain.com
ServerName testdomain1.com
ServerAlias www.testdomain1.com
DocumentRoot /var/www/html/testdomain1.com/
ErrorLog /var/log/httpd/testdomain1.com/error.log
CustomLog /var/log/httpd/testdomain1.com/access.log
</VirtualHost>

######## Additional Domain ################

<10.0.0.1:80>
ServerAdmin master@testdomain2.com
ServerName testdomain2.com
ServerAlias www.testdomain2.com
DocumentRoot /var/www/html/testdomain2.com/
ErrorLog /var/log/httpd/testdomain2.com/error.log
CustomLog /var/log/httpd/testdomain2.com/access.log
</VirtualHost>


  • Save file after make changes 
  • You can Check syntax of configuration file by using httpd -t
# httpd -t 
  • You can add more virtual host as you require. 
  • Make sure to create error log and custom log folder as defined in virtual host file.
  • Restart httpd service after chagnes
# systemctl restart httpd.service 

  • Now you can visit to testdomain1.com  and testdomain2.com

IP-based virtual host: In order to setup IP based virtual hosting, you need more than one IP address configured on your server.  So the number of virtual host will require number of IP address. i.e If you have 10 Virtual Host you require 10 IP Address.


# vi /etc/httpd/conf.d/vhost.conf

Add the following example virtual host directive template for website testdomain.com and testdomain2.com, make sure to change the necessary values for your own domain


Listen 10.0.0.3:80

<VirtualHost 10.0.0.1:80>
ServerAdmin master@testdomain.com
ServerName testdomain1.com
ServerAlias www.testdomain1.com
DocumentRoot /var/www/html/testdomain1.com/
ErrorLog /var/log/httpd/testdomain1.com/error.log
CustomLog /var/log/httpd/testdomain1.com/access.log
</VirtualHost>

######## Additional Domain ################

<VirtualHost 10.0.0.2:80>
ServerAdmin master@testdomain2.com
ServerName testdomain2.com
ServerAlias www.testdomain2.com
DocumentRoot /var/www/html/testdomain2.com/
ErrorLog /var/log/httpd/testdomain2.com/error.log
CustomLog /var/log/httpd/testdomain2.com/access.log
</VirtualHost>



Setup Apache Password Protected Directory with htpasswd
  • By default Apache does not allow the use of .htaccess files in CentOS 7. You will need to set up Apache to allow .htaccess based authentication. You can do this by editing the Apache config file
# vi /etc/httpd/conf/httpd.conf
Find the section that begins with <Directory "/var/www/html">. Change the line from AllowOverride none to AllowOverride AuthConfig

AllowOverride AuthConfig
  • Create a password file with htpasswd
# htpasswd -c /etc/httpd/.htpasswd user1

You will be asked to supply and confirm a password for user1.

.htpasswd file created  and it looks like as follow
 user1:$apr1$0r/2zNGG$jopiWY3DEJd2FvZxTnugJ/

  • Now, you need to allow the apache user to read the .htpasswd file.
# chown apache:apache /etc/httpd/.htpasswd
# chmod 0660 /etc/httpd/.htpasswd

Now you need to create a .htaccess file in the web directory you wish to restrict.
For this example, we will create the .htaccess file in the /var/www/html/ directory to restrict the entire document root.

vi /var/www/html/.htaccess

Add the following content:

AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/httpd/.htpasswd
Require valid-user
  • Save file and restart service. 
  • Test it by browse URL in browser. You will prompt for username and password

Monday, June 18, 2018

Install and configure FTP and SFTP in Centos

Description: Here I have explained how to configure FTP and SFTP in centos

Procedure:

Setup FTP on Centos 
  • Enable epel repository by using below command

[root@localhost ~] # wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-6.noarch.rpm

[root@localhost ~] # rpm -ivh epel-release-7-6.noarch.rpm
  • Install ftp by using below command
[root@localhost ~] # yum install vsftpd
  • Open /etc/vsftpd/vsftpd.conf to configure ftp server. Made below changes in server
[root@localhost ~] # vi /etc/vsftpd/vsftpd.conf

anonymous_enable=NO
local_umask=022
chroot_local_user=YES  #(this property used to limit the users to their home directories.)
local_enable=YES
write_enable=YES
  • Enable and start service

[root@localhost ~] # systemctl start vsftpd
[root@localhost ~] # systemctl enable vsftpd
  • Verify installation by browse ftp://IP_ADDR
Setup SFTP on Centos 

Description: SFTP is the FTP service built into Secure Shell [SSH]

  • SFTP Directory: The First thing you need to create a directory to host your FTP data.
# mkdir /data
# chmod 701 /data
  • Create SFTP user and group: Now we are creating user and group to access ftp 
# groupadd sftp_users
# useradd -g sftp_users -d /data -s /sbin/nologin USERNAME

Where USERNAME is the name of user. Now set password to user 

# passwd USERNAME

  • Create new user SFTP directory: We will create new directory to store data and assigned permission to user. 
# mkdir -p /data/USERNAME/upload
# chown -R root:sftp_users /data/USERNAME
# chown -R username: sftp_users /data/USERNAME/upload
  • Configure sshd configuration file and add below content to the end of file.
# vi /etc/ssh/sshd_config
Match Group sftp_users
ChrootDirectory /data/%u
ForceCommand internal-sftp

  • Save and close file. Restart ssh service for effect.
# systemctl restart sshd
  • Check user by login using sftp USERNAME@IP_ADDR

Install KVM Virtualization on Centos 7 and RHEL 7


Description: KVM is an open source hardware virtualization software through which we can create and run multiple Linux based and windows based virtual machines simultaneously. KVM known as Kernel based Virtual Machine because when we install KVM package then KVM module is loaded into the current kernel and turns our Linux machine into a hyper-visor.

Before installation, we need to check CPU supports Hardware Virtualization. To check use below command:
[root@localhost ~] # grep -E '(vmx|svm)' /proc/cpuinfo
Output should be either vmx or svm, Otherwise CPU does not support Virtualization

Procedure:
First install KVM and its associate packages 
[root@localhost ~] # yum install qemu-kvm qemu-img virt-manager libvirt libvirt-python libvirt-client virt-install virt-viewer bridge-utils

After installation enable and start libvirtd service
[root@localhost ~] # systemctl start libvirtd
[root@localhost ~] # systemctl enable libvirtd 

Verify KVM Installation:
[root@localhost ~] # lsmod | grep -i kvm
kvm_intel             162153  0
kvm                   525409  1 kvm_intel

Configure Bridge Interface: Before start creating VM you need to configure bridge interface is required if you want to access virtual machine from outside of your network

[root@localhost ~]# cd /etc/sysconfig/network-scripts/
[root@localhost network-scripts]# cp ifcfg-eth0 ifcfg-br0

Edit the Interface file and set followings:

[root@localhost network-scripts]# vi ifcfg-eth0
TYPE=Ethernet
BOOTPROTO=static
DEVICE=eth0
ONBOOT=yes
BRIDGE=br0

Edit the Bridge file (ifcfg-br0) and set the followings:

[root@localhost network-scripts] # vi ifcfg-br0
TYPE=Bridge
BOOTPROTO=static
DEVICE=br0
ONBOOT=yes
IPADDR=10.10.10.1
NETMASK=255.255.255.0
GATEWAY=10.10.10.11
DNS1=10.10.10.11

Replace the IP address and DNS server details as per your setup.
After making changes Restart network service 
[root@localhost ~] # systemctl restart network

Check the Bridge interface using below command :
[root@localhost ~] # ip addr show br0

Start creating virtual machine using by 'virt-install' or virt-manager [GUI Tool]
Go to file option, Click on "New Virtual Machine"




Specify ISO file location and provide RAM and CPU as per your requirement. 





Click on Finish to create Virtual Machine

Creating a virtual Machine from Command Line:

[root@localhost ~] # virt-install --name=Ubuntu-16-04 --file=/var/lib/libvirt/images/ubuntu16-04.dsk --file-size=20 --nonsparse --graphics spice --vcpus=2 --ram=2048 --cdrom=ubuntu-16.04-server-amd64.iso --network bridge=br0 --os-type=linux --os-variant=generic
Starting install...
Allocating 'ubuntu16-04.dsk'               | 20 GB 00:00:00
Creating domain...

Thursday, February 15, 2018

SSL Certificate Installation - Tomcat Server

Procedure:


Create a New Keystore:

  • You will be using the keytool command to create and manage your new Keystore file. You may need to add the java /bin/ directory to your PATH before the keytool command is recognized. When you are ready to create your keystore go to the directory where you plan to manage your Keystore and certificates. Enter the following command in command prompt:


           keytool -genkey -alias server -keyalg RSA -keysize 2048 -keystore your_site_name.jks

  • You will be prompt to choose a password for your keystore. You will then be prompt to enter your Organization information.
  • When it asks for first and last name, this is NOT your first and last name, but rather it is your Fully Qualified Domain Name for the site you are securing (example: www.yourdomain.com). If you are ordering a Wildcard Certificate this must begin with the * character. (example: *.yourdomain.com)
  • After you have completed the required information, confirm that the information is correct by entering 'y' or 'yes' when prompted. Next, you will be ask for your password to confirm. Make sure to remember the password you choose. Your keystore file named your_site_name.jks is now create in your current working directory.

Generate a CSR from Your New Keystore:

  • Next, you will use keytool to create the Certificate Signing Request (CSR) from your Keystore. Enter the following command:
         keytool -certreq -alias server -file csr.txt -keystore your_site_name.jks


  • Type the keystore password that you chose earlier and hit Enter.
  • Once CSR generated upload it to Certificate Authority and generate SSL certificate.
  • Install Certificate on Tomcat Server
  • Depending on the certificate format in which you received the certificate from the Certificate Authority, there are different ways of importing the files into the keystore. 
PKCS#:   
  • If the certificate you received is in PKCS#7 format (the extension of the certificate file will be .p7b or .cer), it already includes the necessary intermediate and root certificates. Additionally, a certificate with .p7b extension can be download in the user account. Run the following command to import it into the keystore:
         keytool -import -trustcacerts -alias server -keystore example.jks -file example.p7b
  • If the certificate was imported successfully, you will see the message 'Certificate reply was installed in keystore'. You can check the details of the certificate that was imported to the keystore with a command:
         keytool -list -keystore example.jks 

PEM: 
  • If you received the certificate in the PEM format ( files will be with the .crt extension), you will need to import the root certificate, intermediate certificates and the certificate issued for your domain name to the keystore separately starting from a root certificate and ending with the certificate for your domain name. To import a root certificate, run the following command
        keytool -import -alias root -keystore example.jks -trustcacerts -file root.crt
  • To import an intermediate certificate
        keytool -import -alias intermediate -keystore example.jks -trustcacerts -file intermediate.crt
  • After the successful import you need to edit Tomcat configuration file. As a rule, it is called server.xml and usually can be found in Home_Directory/conf folder. Please change in configuration file as follow:

        <Connector port="443" protocol="HTTP/1.1"
          SSLEnabled="true"
          scheme="https" secure="true" clientAuth="false"
          sslProtocol="TLS" keystoreFile="/your_path/yourkeystore.jks"
          keystorePass="password_for_your_key_store" />

  • Save the changes and restart Tomcat web service.

Thursday, October 26, 2017

LVM [Logical Volume Manager]

Description:


LVM is a tool for logical volume management, which includes allocating disks, striping, mirroring and resizing logical volumes. LVM allow you to manage disk space more effectively. With LVM, we can create logical partitions that can span across one or more physical hard drives. First, the hard drives are divided into physical volumes, then those physical volumes are combined together to create the volume group and finally the logical volumes are created from volume group.

Configure Logical Volume:


First create three partitions using fdisk or gdisk. In this example I have create 3 partition /dev/sda5, /dev/sdb1 and /dev/sdc1

After create partition need to convert to physical volume using below command:
        # pvcreate /dev/sda5 /dev/sdb1 /dev/sdc1
            Physical volume "/dev/sda5" successfully created
            Physical volume "/dev/sdb1" successfully created
            Physical volume "/dev/sdc1" successfully created

Once physical volume created you need to create volume group of all three partition using below command:
       # vgcreate vg0 /dev/sda5 /dev/sdb1 /dev/sdc1
           Volume group "vg0" successfully created
           You can use the vgs command to display the attributes of the new volume group

Now you can create logical volume  from volume group using below command:
      # lvcreate –L  100 G –n lv0 vg0
          Logical volume "lv0" created
          Note :  lv0 is logical volume name

Create a file system on the logical volume using below command
      # mkfs –t ext4 /dev/vg0/lv0

Mount logical volume to directory
      # mount /dev/vg0/lv0 /storage

Extending a logical volume:


Extend logical volume using below command.

     # lvextend -L12G /dev/vg0/lv0
        lvextend -- extending logical volume "/dev/vg0/lv0" to 12 GB
        lvextend -- doing automatic backup of volume group "vg0"
        lvextend -- logical volume "/dev/vg0/lv0" successfully extended

    # lvextend -L+1G /dev/vg0/lv0
       lvextend -- extending logical volume "/dev/vg0/lv0" to 13 GB
       lvextend -- doing automatic backup of volume group "vg0"
       lvextend -- logical volume "/dev/vg0/lv0" successfully extended

After you have extended the logical volume, it is necessary to increase the file system size to match.

     # umount /dev/vg0/lv0
     # resize2fs /dev/vg0/lv0
     # mount /dev/vg0/lv0 /storage

Reducing a Logical Volume:


First, unmount partition using below command
# umount /storage

Check file system for error using e2fsck command
# e2fsck –f /dev/vg0/lv0

Note: In the above command e2fsck, we use the option ‘-f’ to forcefully check the file system, even if the file system is clean.

Reduce or Shrink the size of /storage to desire size
# resize2fs /dev/vg0/lv0 10G
Now reduce the size using lvreduce command.
# lvreduce -L 10G /dev/vg0/lv0
For the safer side, now check the reduced file system for errors
# e2fsck -f /dev/vg0/lv0
Mount the file system and verify its size.
# mount /dev/vg0/lv0 /storage

Thursday, September 21, 2017

SSL issue in CentOS

Error: SSL issue in yum repository during  yum update

Solution: 

  • Access server using ssh console
  • Open /etc/yum.conf and change configuration as follow:

            sslverify = false 
  • Add below line in all active repositories 
             sslverify = 0
Error: curl: (77) pbm with the SSL CA cert (path? access rights?)

Solution: 
  • Run following command to reinstall ca certificate and copy it to ca-bundle directory
  # yum reinstall ca-certificates openssl
  # mkdir /usr/src/ca-certificates && cd /usr/src/ca-certificates
 # wget ftp://ftp.rediris.es/volumes/sites/scientificlinux.org/scientific/6.7/i386/updates/fastbugs/ca-certificates-2015.2.6-65.0.1.el6_7.noarch.rpm
 # rpm2cpio ca-certificates-2015.2.6-65.0.1.el6_7.noarch.rpm| cpio –idmv
 # cp -pi ./etc/pki/tls/certs/ca-bundle.* /etc/pki/tls/certs/

Friday, April 7, 2017

Mount ISO Image in Linux/CentOS/Fedora

Procedure:
  • First create folder to mount ISO
  • # mkdir /mnt/isodata
  • After created mount point use mount command to mount iso file to /mnt/isodata folder
  • mount -t iso9660 -o loop /home/Data/data.iso /mnt/isodata
Options:
  1. -t: This option is use to indicate given file system type
  2. ISO 9660: It defines standard file system type structure to be used for CD/DVD ROMs
  3. -o:  Options are necessary with a -o argument followed by a separated comma string of options.
  4. loop: The loop device is a pseudo-device that often used for mounting CD/DVD ISO image and makes those files accessible as a block device
  • After mount image check data in folder
  • For permanent mounting enter below entry in /etc/fstab file as follow:
    /home/Data/data.iso  /mnt/isodata  iso9660  loop  0  0
  • Restart server and check permanent mount is working or not



Thursday, April 6, 2017

Partitioning in Linux

Description:
  • This section shows you how to actually partition your hard drive with the fdisk utility. Linux allows only 4 primary partitions. You can have a much larger number of logical partitions by sub-dividing one of the primary partitions. Only one of the primary partitions can be sub-divided.
  • If partition size is more than 2 TB than you need to gdisk instead of fdisk. You need to convert from MBR to GPT you can do so (use caution with this) using gdisk.
Fdisk usage
  • fdisk is started by typing (as root) fdisk device at the command prompt. device might be something like /dev/hda or /dev/sda
  • The basic fdisk commands you need are:
  1. pprint the partition table
  2. ncreate a new partition
  3. ddelete a partition
  4. qquit without saving changes
  5. wwrite the new partition table and exit
  • Create New Partition on Linux
  1. Start a terminal.
  2. Start fdisk using the following command:
    # fdisk /dev/sda
  3. In fdisk, to create a new partition, type the following command:
    n
          1. When prompted to specify the Partition type, type p to create a primary partition or e to create an extended one. There may be up to four primary partitions. If you want to create more than four partitions, make the last partition extended, and it will be a container for other logical partitions
          2. When prompted for the Number, in most cases, type 3 because a typical Linux virtual machine has two partitions by default.
          3. When prompted for the Start cylinder, type a starting cylinder number or press Return to use the first cylinder available.
          4. When prompted for the Last cylinder, press Return to allocate all the available space or specify the size of a new partition in cylinders if you do not want to use all the available space.
          5. By default, fdisk creates a partition with a System ID of 83. If you're unsure of the partition's System ID, use the
            l
            Command to check it.
          6. Use the
            w
            Command to write the changes to the partition table.
             
  1. Create a file system on the new partition. We recommend that you use the same file system as on the other partitions. In most cases it will be either the Ext4 or ReiserFS file system. For example, to create the Ext4 file system, enter the following command:
    # mkfs.ext4 /dev/sda3
       Or
    # mkfs -t ext4 /dev/sda3
  2. Create a directory that will be a mount point for the new partition and mount partition in that directory. For example, to name it data, enter:
    # mkdir /data
    # mount /dev/sda3  /data
  3. Make changes in your static file system information by editing the /etc/fstab file in any of the available text editors. For example, add the following string to this file:
    /dev/sda3 /data ext4 defaults 0 0
    Save /etc/fstab file after making changes
Gdisk Usage:
  • Gdisk is use to create more than 2 TB partition because fdisk support up to 2 TB.
  • The basic fdisk commands you need are:
  1. pprint the partition table
  2. ncreate a new partition
  3. ddelete a partition
  4. qquit without saving changes
  5. wwrite the new partition table and exit
  • Method of create new partition will be same as fdisk.