Friday 7 April 2017

High Availability with IREDMAIL Integrated with Active Directory




This is step by step guide for Centos 7. Server1 will be the Active node and Server2 will be the failover node. After failover when Server 1 comes back online all service will be restored to Server1.

A floating IP 10.21.202.110 will be used for the cluster config


To start with disable Firewall and Selinux on both servers and install prerequisites

#yum install vim wget bzip2 telnet pcs pacemaker corosync cman wget -y

Server 1
10.21.202.108
hostname: mail.example.com

Server 2
10.21.202.109
hostname: mail.example.com


Step 1: Make host file entries

Server1
$vim /etc/hosts
10.21.202.108   master1.example.com   master1
10.21.202.109   master2.example.com   master2
10.21.202.108   mail.example.com

Server2
$vim /etc/hosts
10.21.202.108   master1.example.com   master1
10.21.202.109   master2.example.com   master2
10.21.202.109   mail.example.com

Step 2: Install Mariadb On Both Servers. 

The mysql root password and other user password should be the same on both servers in order for HA to work with iRedMail/Roundcube.
#yum install mariadb-server -y



Step 3: Start Mariadb Multi-Master Replication Between The Two Servers

Insert the following configuration for replication. Create the file and paste the below

Server1:
#vim /etc/my.cnf.d/repl.cnf

[mysqld]
server-id               = 108
report_host             = master1
log_bin                 = /var/log/mariadb/mariadb-bin
log_bin_index           = /var/log/mariadb/mariadb-bin.index
relay_log               = /var/log/mariadb/relay-bin
relay_log_index         = /var/log/mariadb/relay-bin.index

Server2:
#vim /etc/my.cnf.d/repl.cnf

[mysqld]
server-id               = 102
report_host             = master2
log_bin                 = /var/log/mariadb/mariadb-bin
log_bin_index           = /var/log/mariadb/mariadb-bin.index
relay_log               = /var/log/mariadb/relay-bin
relay_log_index         = /var/log/mariadb/relay-bin.index

Restart Mariadb on both servers and run the following commands to initialize Mariadb

#systemctl restart mariadb.service
#systemctl enable mariadb.service
# mysql_secure_installation

Set the same root password on both servers. Now login to mysql and create the replication user.

Server1:
#mysql -u root -p<pass>
> create user 'replusr'@'%' identified by '<password>';
> grant replication slave on *.* to 'replusr';

To check Master status
>show master status;
Make a note of bin file name and position

Server2:
#mysql -u root -p<pass>
> create user 'replusr'@'%' identified by '<password>';
> grant replication slave on *.* to 'replusr';

To start replication on Server 2
>stop slave;
>change master to master_host='master1', master_user='replusr', master_password='<pass>’,
master_log_file='<bin file name>', master_log_pos=<pos>;
>start slave;

To check status use the following command
>show slave status;
Now check master status in Server2 and get bin file name and position
>show master status;

Server1
>stop slave;
>change master to master_host='master2', master_user='replusr', master_password='<pass>',
master_log_file='<bin file name>', master_log_pos=<pos>;
>start slave;
>show slave status;

Now both servers have Mariadb installed and multi-master replication is enabled.


Step 4: Install Remi And EPEL Repo On Both Servers

#yum install epel-release -y

#rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

Now enable remi repo for php5.5 on both servers
#vim /etc/yum.repos.d/remi.repo
-----------------------------------------------------------
[remi-php55]
name=Remi's PHP 5.5 RPM repository for Enterprise Linux 7 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/7/php55/$basearch/
#mirrorlist=https://rpms.remirepo.net/enterprise/7/php55/httpsmirror
mirrorlist=http://rpms.remirepo.net/enterprise/7/php55/mirror
# NOTICE: common dependencies are in "remi-safe"
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi
--------------------------------------------------------------

Step 5: Install iRedMail With Openladap Backend On Server 1

Server 1:
#wget https://bitbucket.org/zhb/iredmail/downloads/iRedMail-0.9.6.tar.bz2
#tar xjvf iRedMail-0.9.6.tar.bz2
#cd iRedMail-0.9.6 && chmod +x iRedMail.sh
Note: Do not apply iRedMail's mysql settings













Step 6: Installing Calendar Plugin For RoundCube

#yum install composer -y

Comment this line in php.ini
#vim /etc/php.ini
;disable_functions=(.....)

#cd /tmp

#git clone https://git.kolab.org/diffusion/RPK/roundcubemail-plugins-kolab.git
 
#cd /tmp/roundcubemail-plugins-kolab/plugins
#mv calendar/ libcalendaring/ /var/www/roundcubemail/plugins/
#cd /var/www/roundcubemail/
#mv composer.json-dist composer.json

Now install dependancy for calendar plugin
#composer require "sabre/vobject" "~3.3.3"
Initialize the calendar database tables
# mysql -uroot -p<pass> roundcubemail < /var/www/roundcubemail/plugins/calendar/drivers/database/SQL/mysql.initial.sql

Enable the calendar plugin
#vim /var/www/roundcubemail/config/config.inc.php

Add 'calendar' to the list of active plugins:
$config['plugins'] = array((...)    'calendar',  );

Step 7: Installing Skins For Roundcube

Harry Skin
#mkdir /root/skins
#cd /root/skins
#git clone https://github.com/beliys/harry.git
#cd harry
#rm -rf .git

Barry Skin
#cd /root/skins
#wget http://indexnl.com/barry.zip
#unzip barry.zip

#mv harry barry /var/www/roundcubemail/skins/

Step 8: Restart And Enable All Services


systemctl enable amavisd.service
systemctl enable fail2ban.service
systemctl enable nginx.service
systemctl enable php-fpm.service
systemctl enable uwsgi.service
systemctl enable mariadb.service

systemctl restart amavisd.service
systemctl restart fail2ban.service
systemctl restart nginx.service
systemctl restart php-fpm.service
systemctl restart uwsgi.service
systemctl restart mariadb.service
systemctl restart iredapd

Step 9: Integrate iRedMail And Roundcube With Active Directory

Create an account "vmail" in AD with a strong password. Password should be set to never expire.

Disable unused iRedMail special settings:
postconf -e virtual_alias_maps=''
postconf -e sender_bcc_maps=''
postconf -e recipient_bcc_maps=''
postconf -e relay_domains=''
postconf -e relay_recipient_maps=''
postconf -e sender_dependent_relayhost_maps=''
Add your mail domain name in smtpd_sasl_local_domain and virtual_mailbox_domains:
postconf -e smtpd_sasl_local_domain='example.com'
postconf -e virtual_mailbox_domains='example.com'
Change transport maps setting:
postconf -e transport_maps='hash:/etc/postfix/transport'

Enable AD query. Note: We will create these 3 files later.
  • Verify SMTP senders
postconf -e smtpd_sender_login_maps='proxy:ldap:/etc/postfix/ad_sender_login_maps.cf'
  • Verify local mail users
postconf -e virtual_mailbox_maps='proxy:ldap:/etc/postfix/ad_virtual_mailbox_maps.cf'
  • Verify local mail lists/groups.
postconf -e virtual_alias_maps='proxy:ldap:/etc/postfix/ad_virtual_group_maps.cf'
  • Create/edit file: /etc/postfix/transport.
example.com dovecot
Notedovecot used here is a Postfix transport defined in /etc/postfix/master.cf, used to deliver received emails to local user mailboxes.
Run postmap so that postfix can read it:
# postmap hash:/etc/postfix/transport
  • Create file: /etc/postfix/ad_sender_login_maps.cf:
server_host     = ad.example.com
server_port     = 389
version         = 3
bind            = yes
start_tls       = no
bind_dn         = vmail
bind_pw         = password_of_vmail
search_base     = cn=users,dc=example,dc=com
scope           = sub
query_filter    = (&(userPrincipalName=%s)(objectClass=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))
result_attribute= userPrincipalName
debuglevel      = 0
  • Create file: /etc/postfix/ad_virtual_mailbox_maps.cf:
server_host     = ad.example.com
server_port     = 389
version         = 3
bind            = yes
start_tls       = no
bind_dn         = vmail
bind_pw         = passwd_of_vmail
search_base     = cn=users,dc=example,dc=com
scope           = sub
query_filter    = (&(objectclass=person)(userPrincipalName=%s))
result_attribute= userPrincipalName
result_format   = %d/%u/Maildir/
debuglevel      = 0
Note: Here, we hard-code user's mailbox path in [domain]/[username]/Maildir/ format (result_format parameter). for example:example.com/postmaster/Maildir/.
  • Create file: /etc/postfix/ad_virtual_group_maps.cf:
server_host     = ad.example.com
server_port     = 389
version         = 3
bind            = yes
start_tls       = no
bind_dn         = vmail
bind_pw         = password_of_vmail
search_base     = cn=users,dc=example,dc=com
scope           = sub
query_filter    = (&(objectClass=group)(mail=%s))
special_result_attribute = member
leaf_result_attribute = mail
result_attribute= userPrincipalName
debuglevel      = 0
Note:
  • If your user have email address in both mail and userPrincipalName, you will get duplicate result. Comment out leaf_result_attribute line will fix it.
  • If your mail group account doesn't contain attribute mail and userPrincipalName, please try query_filter = (&(objectClass=group)(sAMAccountName=%u)) instead.
Also, we need to remove iRedAPD related settings in Postfix:
  1. Open Postfix config file /etc/postfix/main.cf
  2. Remove setting check_policy_service inet:127.0.0.1:7777.

Verify LDAP query with AD in Postfix

We can now use command line tool postmap to verify AD integration in postfix. Before testing, we have to create two testing mail accounts first:
  1. Create a mail user in AD. e.g. user@example.com.
  2. Create a mail group in AD. e.g. testgroup@example.com, then assign mail user user@example.com as group member.
  3. Query mail user account with below command:
# postmap -q user@example.com ldap:/etc/postfix/ad_virtual_mailbox_maps.cf
example.com/user/Maildir/
If nothing returned by the command, it means LDAP query doesn't get expected result. Please set debuglevel = 1 file /etc/postfix/ad_virtual_mailbox_maps.cf, then query again, it now will print detailed debug message. If you're not familiar with LDAP related info, please post the debug message in our online support forum to get help.
Verify sender login check:
# postmap -q user@example.com ldap:/etc/postfix/ad_sender_login_maps.cf
user@example.com
Verify mail group
# postmap -q testgroup@example.com ldap:/etc/postfix/ad_virtual_group_maps.cf
user@example.com
NOTEpostmap return nothing if:
  1. mail group doesn't exist
  2. mail group doesn't have any members

Remove iRedAPD integration in Postfix

iRedAPD relies on iRedMail LDAP scheme, so it's useless if you integrate iRedMail with Active Directory. We should remove the integration in Postfix to save some system resource.
To disable iRedAPD, please read tutorial: Manage iRedAPD.

Enable Active Directory integration in Dovecot

To query AD instead of local LDAP server, we have to modify Dovecot config file /etc/dovecot/dovecot-ldap.conf like below:
hosts           = ad.example.com:389
ldap_version    = 3
auth_bind       = yes
dn              = vmail
dnpass          = passwd_of_vmail
base            = cn=users,dc=example,dc=com
scope           = subtree
deref           = never
user_filter     = (&(userPrincipalName=%u)(objectClass=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))
pass_filter     = (&(userPrincipalName=%u)(objectClass=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))
pass_attrs      = userPassword=password
default_pass_scheme = CRYPT
user_attrs      = =home=/var/vmail/vmail1/%Ld/%Ln/Maildir/,=mail=maildir:/var/vmail/vmail1/%Ld/%Ln/Maildir/
Restart dovecot service to make it work.
Note: we don't have per-user quota limit here, you can set a hard-coded quota for all users in /etc/dovecot/dovecot.conf. For example:
plugin {
    [... omit other settings here ...]

    # Format: integer number + M/G/T (M -> MB, G -> GB, T -> TB).
    quota_rule = *:storage=1G
}
Now use command telnet to verify AD query after restarted Dovecot service:
# telnet localhost 143                     # <- Type this
* OK [...] Dovecot ready.

. login user@example.com password_of_user  # <- Type this. Do not miss the dot in the beginning
. OK [...] Logged in

^]                                         # <- Quit telnet with "Ctrl+]", then type 'quit'.
Note: Do NOT miss the dot character before login command. if it returns Logged in, then dovecot + AD works.


Step 10: Integrate Roundcube with AD for address book lookup

# vim /var/www/roundcubemail/config/config.inc.php

Delete all lines after the plugin config line and insert the below.
Modify the connection and user details as per the requirement

-----------------------------------------------------------------------------
#
# "sql" is personal address book stored in roundcube database.
# "global_ldap_abook" is the new LDAP address book for AD, we will create it below.
#
$config['autocomplete_addressbooks'] = array("sql", "global_ldap_abook");

# Enable setting below if Roundcube returns 'user@127.0.0.1' as email address
#$config['mail_domain'] = '%d';

#
# Global LDAP Address Book with AD.
#
$config['ldap_public']["global_ldap_abook"] = array(
    'name'          => 'Global Address Book',
    'hosts'         => array("ad.example.com"), // <- Set AD hostname or IP address here.
    'port'          => 389,
    'use_tls'       => false,   // <- Set to true if you want to use LDAP over TLS.
    'ldap_version'  => '3',
    'network_timeout' => 10,
    'user_specific' => false,

    'base_dn'       => "dc=example,dc=com", // <- Set base dn in AD
    'bind_dn'       => "vmail",             // <- bind dn
    'bind_pass'     => "<pass>", // <- bind password
    'writable'      => false,               // <- Do not allow mail user write data back to AD.
    'search_fields' => array('mail', 'cn', 'sAMAccountName', 'displayname', 'sn',
givenName'),

    // mapping of contact fields to directory attributes
    'fieldmap' => array(
        'name'        => 'cn',
        'surname'     => 'sn',
        'firstname'   => 'givenName',
        'title'       => 'title',
        'email'       => 'mail:*',
        'phone:work'  => 'telephoneNumber',
        'phone:mobile' => 'mobile',
        'phone:workfax' => 'facsimileTelephoneNumber',
        'street'      => 'street',
        'zipcode'     => 'postalCode',
        'locality'    => 'l',
        'department'  => 'departmentNumber',
        'notes'       => 'description',
        'photo'       => 'jpegPhoto',
    ),
    'sort'          => 'cn',
    'scope'         => 'sub',
    'filter'        => "(|(&(objectclass=group)(!(groupType:1.2.840.113556.1.4.803:=2147483648)))(&(objectclass=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2))))",
    'fuzzy_search'  => true,
    'vlv'           => false,   // Enable Virtual List View to more
                                // efficiently fetch paginated data
                                // (if server supports it)
    'sizelimit'     => '0',     // Enables you to limit the count of
                                // entries fetched. Setting this to 0
                                // means no limit.
    'timelimit'     => '0',     // Sets the number of seconds how long
                                // is spend on the search. Setting this
                                // to 0 means no limit.
    'referrals'     => false,   // Sets the LDAP_OPT_REFERRALS option.
                                // Mostly used in multi-domain Active
                                // Directory setups
);
-------------------------------------------------------------------------------------

Save and close the file

Step 11: Now Drop all databases created mysq iRedmail in Server 1



Step 12: Install iRedmail in server 2 with openLDAP backend



Note: copy config file from server 1 to server 2 before starting the installation. The config file contains the random db user passwords created for installation. They should be the same on both servers.

#scp /root/iRedMail-0.9.6/config root@server2:/root/iRedMail-0.9.6/config

Install iredmail with openldap backend and install the calendar plugin just like how we did for server1. Install the skins as well

Step 13: Install unision on both server. 

We will use unison to sync email, postfix  and dovecot config files

#yum install ocaml ocaml-camlp4-devel ctags ctags-etags -u
#cd ~
#wget http://www.seas.upenn.edu/~bcpierce/unison//download/releases/stable/unison-2.40.102.tar.gz
#tar xvfz unison-2.40.102.tar.gz
#cd unison-2.40.102
#make
#sudo cp -v unison /usr/local/sbin/
# sudo cp -v unison /bin/unison

Now enable shell access for vmail user and enable passwordless SSH for this user between the two servers. Emails are stored in /var/vmail/vmail1 directory and user "vmail" is the owner of the directory

On Server 1
Switch to user vmail and create the below crontab entry to sync mails across the two servers

#crontab -e
*/2 * * * *           /bin/unison -batch /var/vmail/vmail1 ssh://master2//var/vmail/vmail1

Now as root user
#crontab -e
0 5 * * *               /bin/unison -batch /etc/postfix ssh://master2//etc/postfix          
0 6 * * *               /bin/unison -batch /etc/dovecot ssh://master2//etc/dovecot

Step 14: Cluster configuration

On Server 1 and 2 set the same password for hacluster user

#passwd hacluster

Start PCSD service and enable it at startup
#systemctl start pcsd
#systemctl enable pcsd
#mkdir /etc/cluster

Server1

Now on server1 authorize the cluster nodes
#pcs cluster auth master1 master2

Now create the cluster and start the cluster
#pcs cluster setup --name MAILCLUSTER master1 master2
#pcs cluster start --all

Now disable STONITH and quorum as it is not required for a two node setup
#pcs property set stonith-enabled=false
#pcs property set no-quorum-policy=ignore

Now add the resources. We need a virtual IP 
#pcs resource create VirtualIP ocf:heartbeat:IPaddr2 ip=x.x.x.x cidr_netmask=24  op monitor interval=30s

Now we need a mail alert when ever failover happens
# pcs resource create MailTo ocf:heartbeat:MailTo email="admin@example.com" subject="MailServerFailOver" op monitor timeout="10" interval="10"

Now add postfix and dovecot as resources
# pcs resource create POSTFIX ocf:heartbeat:postfix op monitor interval=30s
# pcs resource create DOVECOT systemd:dovecot op monitor interval=30s

Now set a constraint so that they all run on the same server
# pcs constraint colocation set VirtualIP MailTo POSTFIX DOVECOT

Server1 is going to act as the active server and so we need to make sure that the services sticks to server1
# pcs constraint location VirtualIP prefers master1
# pcs constraint location MailTo prefers master1
# pcs constraint location DOVECOT prefers master1
# pcs constraint location POSTFIX prefers master1

Now stop and start the cluster
# pcs cluster stop --all
# pcs cluster start --all

Now we have iRedmail with High Availability


Thursday 3 November 2016

Install and Configure Nagios on Cent OS 7 with remote NRPE host

In this tutorial, we will set up a nagios server and a remote NRPE host.

Lets install the prerequisites first

$sudo yum install -y gcc glibc glibc-common gd gd-devel make net-snmp openssl-devel xinetd unzip mailx httpd php5 php5-gd postfix

We must create a user and group that will run the Nagios process. Create a "nagios" user and "nagcmd" group, then add the user to the group with these commands

$sudo useradd nagios
$sudo groupadd nagcmd
$sudo usermod -a -G nagcmd nagios

Install Nagios Core

$curl -L -O https://assets.nagios.com/downloads/nagioscore/releases/nagios-4.1.1.tar.gz
$tar xvf nagios-*.tar.gz
$cd nagios-*
$./configure --with-command-group=nagcmd
$make all
$sudo make install
$sudo make install-commandmode
$sudo make install-init
$sudo make install-config
$sudo make install-webconf
$sudo usermod -G nagcmd apache

Now lets install the nagios plugins
$cd ..
$curl -L -O http://nagios-plugins.org/download/nagios-plugins-2.1.1.tar.gz
$tar xvf nagios-plugins-*.tar.gz
$cd nagios-plugins-*
$./configure --with-nagios-user=nagios --with-nagios-group=nagios --with-openssl
$make
$sudo make install

Now lets install NRPE
$cd ..
$curl -L -O http://downloads.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.15/nrpe-2.15.tar.gz
$tar xvf nrpe-*.tar.gz
$cd nrpe-*
$./configure --enable-command-args --with-nagios-user=nagios --with-nagios-group=nagios --with-ssl=/usr/bin/openssl --with-ssl-lib=/usr/lib/x86_64-linux-gnu
$make all
$sudo make install
$sudo make install-xinetd
$sudo make install-daemon-config

Now lets edit the start-up script 
$sudo vi /etc/xinetd.d/nrpe

Modify the only_from line by adding the private IP address of the your Nagios server to the end (substitute in the actual IP address of your server):

only_from = 127.0.0.1 x.x.x.x

Restart the xinetd service to start NRPE:

$sudo service xinetd restart

Now let's perform the initial Nagios configuration. You only need to perform this section once, on your Nagios server.

$sudo vi /usr/local/nagios/etc/nagios.cfg

Now find an uncomment this line

#cfg_dir=/usr/local/nagios/etc/servers

Now create the directory that will store the configuration file for each server that you will monitor:

$sudo mkdir /usr/local/nagios/etc/servers

Open the Nagios contacts configuration in your favorite text editor. We'll use vi to edit the file:

$sudo vi /usr/local/nagios/etc/objects/contacts.cfg

Find the email directive, and replace its value (the highlighted part) with your own email address:

email                           nagios@localhost        ; <<***** CHANGE THIS TO YOUR EMAIL ADDRES

Let's add a new command to our Nagios configuration:

$sudo vi /usr/local/nagios/etc/objects/commands.cfg

Add the following to the end of the file:

define command{
        command_name check_nrpe
        command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$
}

For mail Notification

We have to change the command "notify-host-by-email" and "notify-service-by-email" as below inorder for the mail notification to work

$sudo vim /usr/local/nagios/etc/objects/commands.cfg

define command{
        command_name    notify-host-by-email
        command_line    /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n" | /usr/bin/mail -s "** $NOTIFICATIONTYPE$ Host Alert: $HOSTNAME$ is $HOSTSTATE$ **" $CONTACTEMAIL$
        }

# 'notify-service-by-email' command definition
define command{
        command_name    notify-service-by-email
        command_line    /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\n\nService: $SERVICEDESC$\nHost: $HOSTALIAS$\nAddress: $HOSTADDRESS$\nState: $SERVICESTATE$\n\nDate/Time: $LONGDATETIME$\n\nAdditional Info:\n\n$SERVICEOUTPUT$\n" | /usr/bin/mail -s "** $NOTIFICATIONTYPE$ Service Alert: $HOSTALIAS$/$SERVICEDESC$ is $SERVICESTATE$ **" $CONTACTEMAIL$
        }


Configure Apache

Use htpasswd to create an admin user, called "nagiosadmin", that can access the Nagios web interface:

$sudo htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin

Enter a password at the prompt. Remember this login, as you will need it to access the Nagios web interface.

Nagios is ready to be started. Let's do that, and restart Apache:

$sudo systemctl start nagios.service
$sudo systemctl restart httpd.service

To enable Nagios to start on server boot, run this command:

$sudo systemctl enable nagios.service

Open your favorite web browser, and go to your Nagios server

http://nagios_server_ip/nagios


#################################################################################

Monitor a CentOS 7 Host with NRPE


On a server that you want to monitor, install the EPEL repository:

$sudo yum install epel-release

Now install Nagios Plugins and NRPE:

$sudo yum install nrpe nagios-plugins-all

Now, let's update the NRPE configuration file. Open it in your favorite editor (we're using vi):

$sudo vi /etc/nagios/nrpe.cfg

Find the allowed_hosts directive, and add the private IP address of your Nagios server to the comma-delimited list (substitute it in place of the highlighted example):

allowed_hosts=127.0.0.1,x.x.x.x

Restart NRPE to put the change into effect:

$sudo systemctl start nrpe.service
$sudo systemctl enable nrpe.service


Add Host to Nagios Configuration

On your Nagios server, create a new configuration file for each of the remote hosts that you want to monitor in /usr/local/nagios/etc/servers/. Replace the highlighted word, "yourhost", with the name of your host:

$sudo vi /usr/local/nagios/etc/servers/yourhost.cfg


Add in the following host definition, replacing the host_name value with your remote hostname ("web-1" in the example), the alias value with a description of the host, and the address value with the private IP address of the remote host:

define host {
        use                             linux-server
        host_name                       client1.example.com
        alias                           Monitor 1
        address                         x.x.x.x
        max_check_attempts              5
        check_period                    24x7
        notification_interval           30
        notification_period             24x7
contacts                        nagiosadmin
}


With the configuration file above, Nagios will only monitor if the host is up or down. If this is sufficient for you, save and exit then restart Nagios. If you want to monitor particular services, read on.

Add any of these service blocks for services you want to monitor. Note that the value of check_command determines what will be monitored, including status threshold values. Here are some examples that you can add to your host's configuration file:

Ping:

define service {
        use                             generic-service
        host_name                       yourhost
        service_description             PING
        check_command                   check_ping!100.0,20%!500.0,60%
}

SSH 

define service {
        use                             generic-service
        host_name                       yourhost
        service_description             SSH
        check_command                   check_ssh
        notifications_enabled           0
}


$sudo systemctl reload nagios.service

HTTP
define service {
        use                             generic-service
        host_name                       client1.example.com
        service_description             HTTP
        check_command                   check_http
        notifications_enabled           1
}

Port Check: We are going to check the availablility of port 80 with a check interval of 10 seconds

define service {
        use                             generic-service
        host_name                       client1.example.com
        service_description             HTTP_PORT_CHECK
        check_command                   check_tcp!80
        check_interval                  0.2
        notifications_enabled           1
}

Note:
check_interval 1 = 60 seconds
check_interval .5 = 30 seconds


To check memory utilization on the remote host

Download the Memory check Plugin

$wget https://raw.githubusercontent.com/justintime/nagios-plugins/master/check_mem/check_mem.pl

$sudo mv check_mem.pl /usr/lib64/nagios/plugins/check_mem
chmod +x /usr/lib64/nagios/plugins/check_mem

You can check whether the script generates output properly by manually running the following command on localhost. When used with NRPE, this command is supposed to check free memory, warn when free memory is less than 20%, and generate critical alarm when free memory is less than 10%.

$/usr/lib64/nagios/plugins/check_mem -f -w 20 -c 10

OK - 34.0% (2735744 kB) free.|TOTAL=8035340KB;;;; USED=5299596KB;6428272;7231806;; FREE=2735744KB;;;; CACHES=2703504KB;;;;

If you see something like the above as an output, that means the command is working okay.

Now that the script is ready, we define the command to check RAM usage for NRPE. As mentioned before, the command will check free memory, warn when free memory is less than 20%, and generate critical alarm when free memory is less than 10%.

$sudo vim /etc/nagios/nrpe.cfg
command[check_mem]=/usr/lib64/nagios/plugins/check_mem  -f -w 20 -c 10



Now in the Nagios server add the following section to the /usr/local/nagios/etc/servers/yourhost.cfg


define service{
        use                            generic-service
        host_name                      client1.example.com
        service_description            Check RAM
        check_command                  check_nrpe!check_mem
}


Restart the nrpe service in the remote host

Restart the nagios service in the Nagios server

Nagios should start checking RAM usage of a remote-server using NRPE. If you are having any problem, you could check the following.

Make sure that NRPE port is allowed all the way to the remote host. Default NRPE port is TCP 5666.
You could try manually checking NRPE operation by executing the check_nrpe command: /usr/local/nagios/libexec/check_nrpe -H remote-server
You could also try to run the check_mem command manually: /usr/local/nagios/libexec/check_nrpe -H remote-server –c check_mem



Tuesday 25 October 2016

Use LFTP command line to transfer files from ftp server

Use LFTP command line to transfer files from ftp server


Example source server
Host: host.example.com
username: exampleuser
password: examplepass
Source folder: /public_html
To install lftp in ubuntu
#apt-get install lftp
Usage
To connect to the ftp server use
#lftp -u exampleuser,examplepass host.example.com -e ‘set ftp:ssl-allow no;’
Once your are connected you will see the below prompt
lftp exampleuser@host.example.com:~>
Use ls command to list files and directories
To copy the entire public_html directory use the following command
lftp exampleuser@host.example.com:~>mirror public_html /destination-path
Note: Lftp will not automatically create the destination-path. The destination path should exist

Monday 29 August 2016

Kerberos-Based Apache SSO with Active Directory

Apache SSO with Active Directory


In this tutorial we will be setting up Active directory - Kerberos based sso with Apache.


Requirements

1. Active directory Server - Windows server 2008 R2
2. Apache server - Cent OS 7
3. mod_auth_kerb module in apache

Active Directory details

Domain Name : example.com
Domain Controller name: dc.example.com
IP address  : 192.168.0.100


Cent OS server details

Hostname : server.example.com
IP address: 192.168.0.101
DNS address: 192.168.0.100

Lets begin by installing apache with mod_auth_kerb module

#yum install httpd mod_auth_kerb krb5-workstation

Now lets configure and verify kerberos

#vim /etc/krb5.conf

------------------------------------------------------------------------
[logging]
 default = FILE:/var/log/krb5libs.log
 kdc = FILE:/var/log/krb5kdc.log
 admin_server = FILE:/var/log/kadmind.log

[libdefaults]
 dns_lookup_realm = false
 ticket_lifetime = 24h
 renew_lifetime = 7d
 forwardable = true
 rdns = false
 default_realm = EXAMPLE.COM
 default_ccache_name = KEYRING:persistent:%{uid}
 default_tkt_enctypes = rc4-hmac
 default_tgs_enctypes = rc4-hmac
 permitted_enctypes = rc4-hmac

[realms]
 EXAMPLE.COM = {
  kdc = dc.example.com
  admin_server = dc.example.com
 }

[domain_realm]
.example.com = EXAMPLE.COM
 example.com = EXAMPLE.COM

--------------------------------------------------------------------------


Now lets verify with the following command



For every kerberized host you have to create a service principal on the KDC. Lets create a service principle in the Command prompt on the windows server.

Before we create a service principal, we need to create a user account with any name which will be used for creating the service ticket. Le the name of the user be "krb5@example.com"

Use the below command to create the service principal

C:\>ktpass -princ HTTP/server.example.com@EXAMPLE.COM -mapuser krb5@EXAMPLE.COM -crypto RC4-HMAC-NT -ptype KRB5_NT_PRINCIPAL -pass long$longp2ass3word -out c:\temp\krb5.keytab


The ktpass command creates the pricipal HTTP/server.example.com@EXAMPLE.COM, maps it to AD account "krb5" and exports it's key to the keytabfile c:\temp\krb5.keytab. Copy that file to Centos server(apache server).


Check if the KDC sends correct tickets (kvno) by getting a serviceticket and using klist:

#kvno HTTP/server.example.com@EXAMPLE.COM
#klist -e

check this values against keytab krb5.keytab

#klist -e -k -t krb5.keytab

#kinit -k -t krb5.keytab HTTP/server.example.com

If this doesn't work then there is a problem with the Kerberos config.

Now lets create a test site with Apache and configure kerberos authentication

Copy the keytab file to /etc/httpd and change the ownership of the file to apache:apache

-------------------------------------------------
<VirtualHost *:80>

ServerName server.example.com

DocumentRoot /var/www/html/server.example.com

<Directory "/var/www/html/server.example.com">
AuthType  Kerberos
KrbAuthRealms EXAMPLE.COM
KrbServiceName HTTP
Krb5Keytab /etc/httpd/krb5.keytab
KrbMethodNegotiate on
KrbMethodK5Passwd off
require valid-user
</Directory>


</VirtualHost>
------------------------------------------------


Now lets enable Windows integrate authentication in Internet Explorer using the below link

https://docs.secureauth.com/display/KBA/Enable+Integrated+Windows+Authentication+(IWA)+in+Internet+Explorer


Now lets configure Firefox for sso

1. In the address bar of Firefox, type about:config to display the list of current configuration options.
2. In the Filter field, type negotiate to restrict the list of options.
3. Double-click the network.negotiate-auth.trusted-uris entry to display the Enter string value dialog box.
4. Enter the name of the domain against which you want to authenticate, for example, .example.com.
5. Repeat the above procedure for the network.negotiate-auth.delegation-uris entry, using the same domain.

Use the following link to enable Windows Integrated Authentication with chrome

https://www.specopssoft.com/configuring-chrome-and-firefox-for-windows-integrated-authentication/















Saturday 21 November 2015

Installing HA-Proxy on Cent OS 7



This example assumes that firewall and selinux is disabled. We are going to use the following three servers.

Apache1: 192.168.124.2 apache1.example.com
Apache2: 192.168.124.3 apache2.example.com
HAProxy: 192.168.124.10 haproxy.example.com



All three servers should be able to reach each other. Enter the following in the /etc/hosts file in all three nodes

192.168.124.2 apache1.example.com apache1
192.168.124.3 apache2.example.com apache2
192.168.124.10 haproxy.example.com haproxy

Now install apache service on the two apache nodes using the following command

#yum install httpd -y

Create a sample HTML file in the apache nodes in differentiate them and start the httpd service

#systemctl start httpd.service


Install and enable Epel repository on the haproxy node

#yum install epel-release -y

Install HA proxy

#yum install haproxy -y

The default configuration file haproxy.cfg is located in /etc/haproxy/

Lets make a backup of the original file

#cd /etc/haproxy

#cp haproxy.cfg haproxy.cfg.bkp


Now lets edit the configuration file. We need to clear the existing frontend/backend config and create our own config

Delete the following lines in haproxy.cfg

------------------------------------------------------------------------
frontend  main *:5000
    acl url_static       path_beg       -i /static /images /javascript /stylesheets
    acl url_static       path_end       -i .jpg .gif .png .css .js

    use_backend static          if url_static
    default_backend             app

backend static
    balance     roundrobin
    server      static 127.0.0.1:4331 check

backend app
    balance     roundrobin
    server  app1 127.0.0.1:5001 check
    server  app2 127.0.0.1:5002 check
    server  app3 127.0.0.1:5003 check
    server  app4 127.0.0.1:5004 check
------------------------------------------------------------------------

Now add the following lines
-------------------------------------------------------------------------
#webapp1 is the name we give for our frontend
frontend webapp1
#Makes the haproxy service listen on port number 80
bind *:80
#defining the backen name
default_backend webapp1_servers
#send X-Forwarded-For header
option  forwardfor


#Backend configuration
backend webapp1_servers
#Load balencing protocol
balance     roundrobin
server  apache1 192.168.124.89:80 check
server  apache2 192.168.124.51:80 check
-------------------------------------------------------------------------

Note: The X-Forwarded-For request header helps you identify the IP address of a client when you use an HTTP or HTTPS load balancer. Because load balancers intercept traffic between clients and servers, your server access logs contain only the IP address of the load balancer.





Save the config file and restart haproxy service

#systemctl restart haproxy.service


Now hit the haprosy node's IP address in the browser and it should direct us to one of the web servers.

High Availability with IREDMAIL Integrated with Active Directory

This is step by step guide for Centos 7. Server1 will be the Active node and Server2 will be the failover node. After failover when ...