Wednesday, January 15, 2014

How to setup Zimbra on Debian Squeeze


What is Zimbra?

Zimbra is a complete email, address book, calendar and tasks solution that can be accessed from the Zimbra Web Client, Zimbra Desktop offline client, Outlook and a variety of other standards-based email clients and mobile devices. It can be deployed as a traditional binary install on Linux, or as a software virtual appliance, commonly referred to as Zimbra appliance.There are several versions of ZCS to choose from:

    >> ZCS Network Edition
    >> ZCS hosted email by a Zimbra partner
    >> ZCS Open Source Edition (free)

Zimbra is a groupware system that provides email, calendaring, integrated antivirus and spam filtering, and more for multiple domains. Available in several editions, this guide will help you get Zimbra Collaboration Suite-Open Source Edition installed on your Debian 6 (Squeeze) Linux VPS.

Please note that Zimbra is a fairly "heavy" (resource-intensive) product compared to some other groupware offerings. We recommend a Linode 2048 or higher for best results; you may encounter issues using Zimbra with plans with less resources. Additionally, note that Zimbra works best as a standalone product on your VPS; installation alongside other software is not advised. Zimbra is deprecating support for 32-bit systems, and therefore it is assumed you have deployed the 64-bit version of Debian 6. If this is not the case, you will want to redeploy with the 64-bit version before continuing. All configuration will be performed through the terminal; please make sure you're logged into your Linode as root via SSH.

Please note that as of this writing, Zimbra is not officially supported on Debian 6. The software should function as expected but your support options may be limited by choosing to install it on Debian 6.


Please check your host record is Ok...
------------------------------------------------
    # vim /etc/hosts

====================================================
127.0.0.1       localhost
127.0.1.1       mx.mithu.com    mx
172.16.0.7     mx.mithu.com    mx

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
====================================================



Check your debian squeeze source list is Ok...
------------------------------------------------------------
  
    # vim /etc/apt/sources.list

===========================================================
deb ftp://ftp.us.debian.org/debian/ squeeze main contrib non-free
deb-src ftp://ftp.us.debian.org/debian/ squeeze main contrib non-free

deb http://security.debian.org/ squeeze/updates main
deb-src http://security.debian.org/ squeeze/updates main
===========================================================


Don't forget to update & upgrade:

    # apt-get update
    # apt-get upgrade


Download & Install several packages required by Zimbra:


    # apt-get install libpcre3 libgmp3c2 libgmp3-dev sysstat libexpat1 libidn11 perl-modules wget lzma sudo


Download Zimbra Software for Debian:


    # wget http://files2.zimbra.com/downloads/6.0.10_GA/zcs-6.0.10_GA_2692.DEBIAN5.20101215161423.tgz
    # tar -xzvf zcs*
    # cd zcs*

Now we have to edit the file util/utilfunc.sh
    # vim /root/zcs-6.0.10_GA_2692.DEBIAN5.20101215161423/util/utilfunc.sh                    [assumed that zimbra software donloaded and extracted in /root folder..    ]

=========================================================
=========================================================
Search for the first instance of the following line:

--------------------------------------------------------------------------------
PREREQ_PACKAGES="sudo libidn11 libgmp3 libstdc++6"
--------------------------------------------------------------------------------


Change it to match the following line:


------------------------------------------------------------------------------------
PREREQ_PACKAGES="sudo libidn11 libgmp3c2 libstdc++6"
------------------------------------------------------------------------------------

=========================================================
=========================================================

====================================================================
Note: while editing this file it will fire a message that... the file is read only. You have forcefully save it using (wq!).
====================================================================


Due to stricter behavior in the version supplied in Debian 6, you'll need to temporarily downgrade your dpkg binary before proceeding.
Download appropriate package depending on whether you are running 32-bit or 64-bit Debian:

Assumed that you are downloading the package in /root folder..
==========================================================
wget http://security.ubuntu.com/ubuntu/pool/main/d/dpkg/dpkg_1.15.5.6ubuntu4.5_amd64.deb [for 64bit]
wget http://security.ubuntu.com/ubuntu/pool/main/d/dpkg/dpkg_1.15.5.6ubuntu4.5_i386.deb     [for 32bit]   
==========================================================

Install the downloaded dev package with the following command:
    # dpkg -i dpkg_1.15.5.6ubuntu4.5_i386.deb

Now its time for the installation of ZIMBRA... ha ha ha
    # cd /root/zcs-6.0.10_GA_2692.DEBIAN5.20101215161423  (assumed that you extracted zimbra package in this direcotry..)
    # ./install.sh --platform-override

The install will begin, prompting you to respond to a number of questions, and consuming a moment to perform various tasks.

You can safely assume the default configuration..... (Asking prompts are as follows....)

-------------------------------------------------------------------
The system will be modified.  Continue? [N] Y
-------------------------------------------------------------------


-------------------------------------------------------------------------------------------------
DNS ERROR resolving MX for hostname.example.com
It is suggested that the domain name have an MX record configured in DNS
Change domain name? [Yes] No
--------------------------------------------------------------------------------------------------


You'll then be presented with an admin menu next.....


-------------------------------------------------------------------------------------------------------------
Main menu

   1) Common Configuration:
   2) zimbra-ldap:                                   Enabled
   3) zimbra-store:                                  Enabled
        +Create Admin User:                     yes
        +Admin user to create:                  admin@hostname.example.com
******* +Admin Password                        UNSET
        +Enable automated spam training:       yes
        +Spam training user:                           spam.5jdzb7fy@hostname.example.com
        +Non-spam(Ham) training user:          ham.vhdq0mhzo@hostname.example.com
        +Global Documents Account:             wiki@hostname.example.com
        +SMTP host:                                       hostname.example.com
        +Web server HTTP port:                     80
        +Web server HTTPS port:                   443
        +Web server mode:                             http
        +IMAP server port:                              143
        +IMAP server SSL port:                       993
        +POP server port:                               110
        +POP server SSL port:                       995
        +Use spell check server:                     yes
        +Spell server URL:                             http://hostname.example.com:7780/aspell.php
        +Configure for use with mail proxy:     FALSE
        +Configure for use with web proxy:     FALSE
        +Enable version update checks:          TRUE
        +Enable version update notifications:  TRUE
        +Version update notification email:       admin@hostname.example.com
        +Version update source email:              admin@hostname.example.com

   4) zimbra-mta:                                Enabled
   5) zimbra-snmp:                             Enabled
   6) zimbra-logger:                            Enabled
   7) zimbra-spell:                              Enabled
   8) Default Class of Service Configuration:
   r) Start servers after configuration        yes
   s) Save config to file
   x) Expand menu
   q) Quit

Address unconfigured (**) items  (? - help)
------------------------------------------------------------------------------------------------------------


Enter "3" to enter the zimbra-store menu, which will look similar to the following:

-------------------------------------------------------------------------------------------------------------
Store configuration

   1) Status:                                               Enabled
   2) Create Admin User:                           yes
   3) Admin user to create:                        admin@hostname.example.com
** 4) Admin Password                               UNSET
   5) Enable automated spam training:      yes
   6) Spam training user:                           spam.5jdzb7fy@hostname.example.com
   7) Non-spam(Ham) training user:          ham.vhdq0mhzo@hostname.example.com
   8) Global Documents Account:             wiki@hostname.example.com
   9) SMTP host:                                       hostname.example.com
  10) Web server HTTP port:                    80
  11) Web server HTTPS port:                  443
  12) Web server mode:                            http
  13) IMAP server port:                            143
  14) IMAP server SSL port:                     993
  15) POP server port:                              110
  16) POP server SSL port:                      995
  17) Use spell check server:                    yes
  18) Spell server URL:                            http://hostname.example.com:7780/aspell.php
  19) Configure for use with mail proxy:         FALSE
  20) Configure for use with web proxy:         FALSE
  21) Enable version update checks:             TRUE
  22) Enable version update notifications:     TRUE
  23) Version update notification email:        admin@hostname.example.com
  24) Version update source email:               admin@hostname.example.com

Select, or 'r' for previous menu [r] 4
-------------------------------------------------------------------------------------------------------------

You can configure various options here; but, the most important option is the one for setting the administrator password.Enter "4" to set it, choosing a strong password comprised of letters, numbers, and non-alphanumeric characters. After setting the admin password, enter "r" to return to the main menu. At this point you can enter "a" to apply the configuration that you have set, and follow this procedure. This allows Zimbra to proceed with the remaining installation steps.


Issue the following command to restore your original version of dpkg:
====================================================================
    # apt-get install dpkg

And finally don't forget restart zimber service.
    # /etc/init.d/zimbra restart



Now time to visit the Zimbra admin URL in your browser. It will be in the form of :
=====================================================================
    # https://hostname.example.com:7071/

Once you have configured the server and added accounts, users may log in using a link similar to

    # http://hostname.example.com/zimbra/mail



Note:    Default Admin Account : admin@hostname.example.com
                                      Password: as you entered during setup



Tuning:
Problem in log:

zimbra postfix/smtp[1927]: 34A2F90126: to=<email@host.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=26462, delays=26461/0.49/0.05/0.15, dsn=4.5.0, status=deferred (host 127.0.0.1[127.0.0.1] said: 451 4.5.0 Error in processing, id=32120-01, parts_decode_ext FAILED: Unix utility file(1) not available, but is needed at (eval 85) line 113. (in reply to end of DATA command))

451 4.5.0 Error in processing, id=16530-01, parts_decode_ext FAILED: Unix utility file(1) not available, but is needed at (eval 85) line 113. (in reply to end of DATA command))

Solution:

    #apt-get install file

Restart Zimbra...
    # /etc/init.d/zimbra restart

Sunday, January 12, 2014

How to install iRedMail on Debian 7 (Wheezy)

What iRedMail is?
----------------------

            >> A ZERO COST, fully fledged, full-featured mail server solution.
           All used packages are free and open source, provided by the Linux/BSD     distribution venders you trust.
           
           >> An open source project, released under GPLv2, hosted on BitBucket.

What iRedMail does?
-----------------------------
        >> Install and configure mail server related BINARY packages automatically from the official software
           repositories provided by Linux/BSD distribution venders.

What Opensource Software are Used in iRedMail ?
-----------------------------------------------------------------


            >> Postfix: SMTP service

        >> Dovecot: POP3/POP3S, IMAP/IMAPS, Managesieve service

        >> Apache: Web server

        >> MySQL/PostgreSQL: Storing application data and/or mail accounts

        >> OpenLDAP: Storing mail accounts

        >> Policyd: Postfix policy server

        >> Amavisd: An interface between Postfix and SpamAssassin, ClamAV. Used for spam and virus scanning.
   
        >> Roundcube: Webmail

            >> Awstats: Apache and Postfix log analyzer

            >> Fail2ban: scans log files (e.g. /var/log/maillog) and bans IPs that show the malicious signs
             -- too many password failures, seeking for exploits, etc.


========================================
--------------------------------------------------------
iRedMail Installation and Configuration:
-------------------------------------------------------
========================================



Please check your host record is Ok...
--------------------------------------------------
    # vim /etc/hosts

===========================================================
127.0.0.1       localhost
127.0.1.1       mx.mithu.com    mx
172.16.0.7      mx.mithu.com    mx

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
===========================================================



Check your debian squeeze source list is Ok...
---------------------------------------------------------
   
    # vim /etc/apt/sources.list

===========================================================
deb http://http.debian.net/debian wheezy main
deb-src http://http.debian.net/debian wheezy main

deb http://security.debian.org/ wheezy/updates main
deb-src http://security.debian.org/ wheezy/updates main
===========================================================


Dont forget to update & upgrade:
----------------------------------------
    # apt-get update
    # apt-get upgrade


You may need to Install the package 'bzip2' so that you can uncompress iRedMail installer.

    # sudo apt-get install bzip2


Download the latest iRedMail Package:(Supposed to be in /root directory)
------------------------------------------------------------------------------------------
    # wget https://bitbucket.org/zhb/iredmail/downloads/iRedMail-0.8.6.tar.bz2
    # cd /root/
    # tar xjf iRedMail-0.8.6.tar.bz2

=============================
Now Start iRedMail installer:
=============================

    # cd /root/iRedMail-0.8.6/
    # bash iRedMail.sh



Screens that will during installation:
--------------------------------------------

    ~ Welcom and thanks for use >> Click Yes
    ~ Specify location to store all mailboxes. Default is /var/vmail/
    ~ Choose backend used to store mail accounts. Please choose the one which you're familiar with. [I prefer MySql]
    ~ Set password of MySQL root user. MySQL is used to store data of other applications, e.g. Roundcube webmail, Policyd, Amavisd-new.
    ~ Add your first mail domain name : mithu.com [Don't be confused...Give only the domain not fqdn]
    ~ Set password of admin account of your first mail domain. [Give your desired pass $**********$ ]
    ~ Choose optional components : [Select All and press Next...]
    ~ Setup will ask for iptables config and restart the firewall ...[ Type { Y } and press enter ]


configure Mail clients (Microsoft Outlook):
====================================
User Inforamtion ~
          >> Your Name: Mehedi Hasan
          >> Email Address : mithu@imehedi.com

Server Information ~
          >> Account Type: IMAp
          >> Incomming Mail Server: 116.193.170.5
          >> Outgoing Mail Server (SMTP): 116.193.170.5


Logon Information ~
          >> User Name: mithu@imehedi.com {need [user@FullDomain] because iRedMail supports multiple virtual domains }
          >> Password:  $*********$.

Go to More Settings ~
            >> Go to Outgoing Server Tab >> Tick Mark [V] on My Outgoing Server (SMTP) requires authentication >> Select Log On using (Radio Button)
                =>> User Name: mithu@imehedi.com
                =>> Password:  $*********$.
                =>> Tick Mark [V] on Remember Password


                >> Go to Advanced Tab
                =>> Incomming Server (IMAP): 143
                =>> Use the type of encrypted connection: Choose TLS
                =>> Outgoing Server (SMTP): 25
                =>> Use the type of encrypted connection: Choose TLS


Trouble Shooting:
===============
Problem 1. Recipient address rejected: Greylisting in effect, please come back later.
-------------

Solution:  This is the way to disable Greylisting effect in iRedMail:

    # vim  /etc/cluebringer/cluebringer.conf

==========================
Change

# Greylisting module
[Greylisting]
enable=1

to

# Greylisting module
[Greylisting]
enable=0
===========================

Now the restart the serviec to take effect:
    # /etc/init.d/postfix-cluebringer restart



Problem 2. Helo command rejected: need fully-qualified hostname.
------------


Solution: 
This type  of error will appear when we try to send message from various mail clients like Outlook, thunderbird etc. To solve this problem:

Go to More Settings ~
            >> Go to Outgoing Server Tab >> Tick Mark [V] on My Outgoing Server (SMTP) requires authentication >> Select Log On using (Radio Button)
                =>> User Name: mithu@imehedi.com
                =>> Password:  $*********$.
                =>> Tick Mark [V] on Remember Password

Sunday, January 5, 2014

How to install and configure Amavis, Clamav and Spamassassin on Debian Squeeze

Concept:

In this tutorial we will show you how to install and configure Amavis-new, clamAV and Spamassassin. We also integrate these packages with Postfix for better understanding that how they works with smtpd.

Amavis-new is a wrapper that can call any number of content filtering programs for spam detection, antivirus, etc. ClamAv is world famous opensource package for content filtering and Spamassassin is for spam protection.


First of all Update Debian Squeeze Souce List (Otherwise you can't install the optional packages):


===============================================================
deb ftp://ftp.se.debian.org/debian squeeze main
deb ftp://ftp.se.debian.org/debian squeeze main contrib non-free


deb http://http.us.debian.org/debian/ squeeze main contrib non-free
deb-src http://http.us.debian.org/debian/ squeeze main contrib non-free
===============================================================


Don't forget to update & upgrade:

    # apt-get update
    # apt-get upgrade

Installation on Debian squeeze:


    # apt-get install amavisd-new spamassassin clamav-daemon


Optional packages for better spam detection:


    # apt-get install libnet-dns-perl libmail-spf-query-perl pyzor razor libmail-spf-perl


Packages to enable scanning of attached archive files:
   
        # apt-get install arj bzip2 cabextract cpio file gzip lha nomarch pax rar unrar unzip unzoo zip zoo p7zip


Configuration [Clamav]:

The default behaviour of Clamav will fit our needs. A daemon is launched (clamd) and signatures are fetched every day.

For more Clamav configuration options, check the configuration files in /etc/clamav.

Add clamav user to the amavis group and vice versa in order for Clamav to have access to scan files:

    # adduser clamav amavis
    # adduser amavis clamav


Configuration [Spamassassin]:

Spamasssassin autodetects optional components and will use them if they are present. This means that there is no need to configure dcc-client, pyzor and razor.

Edit /etc/default/spamassassin to activate the Spamassassin daemon change ENABLED=0 to:

ENABLED=1

and to enable automatic rule updates change CRON=0 at the bottom to:

CRON=1


Now start Spamassassin: (not restart)

    # /etc/init.d/spamassassin start

Configuration [Amavis]:


First, activate spam and antivirus detection in Amavis by editing /etc/amavis/conf.d/15-content_filter_mode:

=====================================================================
use strict;

# You can modify this file to re-enable SPAM checking through spamassassin
# and to re-enable antivirus checking.

#
# Default antivirus checking mode
# Uncomment the two lines below to enable it
#

@bypass_virus_checks_maps = (
   \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);


#
# Default SPAM checking mode
# Uncomment the two lines below to enable it
#

@bypass_spam_checks_maps = (
   \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);

1;  # insure a defined return
======================================================================

After configuration Amavis needs to be restarted:

    # /etc/init.d/amavis restart


Postfix integration:

For postfix integration, you need to add the content_filter configuration variable to the Postfix
configuration file /etc/postfix/main.cf.. This instructs postfix to pass messages to amavis at a given IP address and port:

    content_filter = smtp-amavis:[127.0.0.1]:10024

Alternatively you can use the following command to do the same:
    # postconf -e "content_filter = smtp-amavis:[127.0.0.1]:10024


Next edit /etc/postfix/master.cf and add the following to the end of the file:


=====================================================================
smtp-amavis     unix    -       -       -       -       2       smtp
        -o smtp_data_done_timeout=1200
        -o smtp_send_xforward_command=yes
        -o disable_dns_lookups=yes
        -o max_use=20

127.0.0.1:10025 inet    n       -       -       -       -       smtpd
        -o content_filter=
        -o local_recipient_maps=
        -o relay_recipient_maps=
        -o smtpd_restriction_classes=
        -o smtpd_delay_reject=no
        -o smtpd_client_restrictions=permit_mynetworks,reject
        -o smtpd_helo_restrictions=
        -o smtpd_sender_restrictions=
        -o smtpd_recipient_restrictions=permit_mynetworks,reject
        -o smtpd_data_restrictions=reject_unauth_pipelining
        -o smtpd_end_of_data_restrictions=
        -o mynetworks=127.0.0.0/8
        -o smtpd_error_sleep_time=0
        -o smtpd_soft_error_limit=1001
        -o smtpd_hard_error_limit=1000
        -o smtpd_client_connection_count_limit=0
        -o smtpd_client_connection_rate_limit=0
        -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks

Also add the following two lines immediately below the "pickup" transport service:
[This will prevent messages that are generated to report on spam from being classified as spam.]

         -o content_filter=
         -o receive_override_options=no_header_body_checks
======================================================================


Reload postfix:

    # /etc/init.d/postfix reload

=======================================================================
Now content filtering with spam and virus detection is enabled. Yy@aHh0o0o...Great Job MAN..Done...
=======================================================================

How to setup secure mail server on Debian Squeeze

Setup Email Services on Debian 6 Using Postfix (TLS+SASL) and Dovecot:


Concept:

Are not TLS and SSL different encryption mechanisms?

If you setup an email program you will often see separate options for “no encryption”, “SSL”, or “TLS” encryption of you transmission.  This leads one to assume that TLS and SSL are different things.

In truth, this labeling is a misnomer.  You are not actually selecting which method to use (SSL v3 or TLS v1.x) when making this choice.  You are merely selecting between options that dictate how the secure connection will be initiated.

No matter which method you choose, TLS or SSL, the same level of encryption will be obtained when talking to the server and that level is determined by the software installed on the server, how that is configured, and what your program actually supports. If the SSL vs TLS choice is not one of security, what is it?

There are two distinct ways that a program can initiate a secure connection with a server:

By Port:

Connecting to a specific port means that a secure connection should be used.  For example, port 443 for https (secure web), 993 for secure IMAP, 995 for secure POP, etc.  These ports are setup on the server ready to negotiate a secure connection first, and do whatever else you want second.

By Protocol:

These connections first begin with an insecure “hello” to the server and only then switch to secured communications after the handshake between the client and the server is successful. If this handshake fails for any reason, the connection is severed.  A good example of this is the command “STARTTLS” used in outbound email (SMTP) connections.


About Secure Mail Server:


Now a days postfix and dovecot are most famous and widely used Mailserver config packages. Postfix is used as MTA to send & receive mail and dovecot is used for poping the mail from mailbox in the server. By default postfix listens on 25 and dovecot listen 110 i.e. all  of which we know as plain text (not encrypted). As security threats are widely spreaded One problem when you administer a network is securing data that is being sent between applications across an untrusted network.

You can use TLS/SSL to authenticate servers and clients and then  use it to encrypt messages between  the  authenticated parties.

Here is a guide on getting Email services running on Debian Squeeze. I used Postfix for core services
(SMTP wtih TLS and SASL) and Dovecot for fast & secure IMAP and POP3. Both of these packages will work secure port which means
    Postfix as SMTPs-Port 465
    Dovecot as PoP3s-Port 995


Below are the checklist as prerequisite:


Please check your host record is Ok...
-----------------------------------------------
    # vim /etc/hosts

=====================================================
127.0.0.1       localhost
127.0.1.1       mx.mithu.com    mx
172.16.0.7      mx.mithu.com    mx

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
====================================================


Check your debian squeeze source list is Ok...
--------------------------------------------------------

              # vim /etc/apt/sources.list
===========================================================
deb http://ftp.debian.org/debian/ squeeze main
deb-src http://ftp.debian.org/debian/ squeeze main

deb http://security.debian.org/ squeeze/updates main
deb-src http://security.debian.org/ squeeze/updates main
===========================================================



Dont forget to update & upgrade:
-----------------------------------------
    # apt-get update
    # apt-get upgrade

Installation and Configuration:


For SSL Support in Debian SQUEEZE:
============================
    # apt-get install openssl ssl-cert sasl2-bin libsasl2 libsasl2-modules


Next, let’s take care of certificates for TLS. You will be asked several questions during this process. Fill them in as you see fit.


    # mkdir /etc/postfix/ssl
    # cd /etc/postfix/ssl/
    # openssl genrsa -des3 -rand /etc/hosts -out smtpd.key 1024
    # chmod 600 smtpd.key
    # openssl req -new -key smtpd.key -out smtpd.csr
    # openssl x509 -req -days 3650 -in smtpd.csr -signkey smtpd.key -out smtpd.crt
    # openssl rsa -in smtpd.key -out smtpd.key.unencrypted
    # mv -f smtpd.key.unencrypted smtpd.key
    # openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650


SASL Config:


Authentication will be done by saslauthd which will need to be configured to support a chrooted Postfix setup. Edit /etc/default/saslauthd and add or change the following settings so that they match:

    # vim /etc/default/saslauthd


====================================================

START=yes
OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd"

====================================================


Finish up SASL by creating the chroot directory, adding the postfix user to the sasl group
and then starting saslauthd.


    # mkdir -p /var/spool/postfix/var/run/saslauthd
    # dpkg-statoverride --add root sasl 710 /var/spool/postfix/var/run/saslauthd
    # adduser postfix sasl

and Finally restart sasl
   
    # /etc/init.d/saslauthd start




Installing & configuring Postfix for TLS and SASL:

    # apt-get install postfix

Edit the main.cf file as follows:(you should change Domain name and networks as to fit your organizational needs )


    # vim /etc/postfix/main.cf

=====================================================================

# TLS parameters

smtpd_tls_cert_file = /etc/postfix/ssl/smtpd.crt
smtpd_tls_key_file = /etc/postfix/ssl/smtpd.key
smtpd_tls_CAfile =   /etc/postfix/ssl/cacert.pem
smtpd_use_tls = yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_sasl_type = cyrus
local_recipient_maps =

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

myhostname = mx.mithu.com
alias_maps = hash:/etc/postfix/aliases
alias_database = hash:/etc/aliases
access_maps = hash:/etc/postfix/access
transport_maps = hash:/etc/postfix/transport
myorigin = /etc/mailname
mydestination = mx.mithu.com, mx, localhost.mithu.com, localhost
relayhost =
mynetworks = 127.0.0.0/8 , 10.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
html_directory = /usr/share/doc/postfix/html
smtpd_sasl_local_domain =
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination
smtpd_tls_auth_only = no
smtp_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtpd_tls_CAfile = /etc/postfix/ssl/cacert.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
mailbox_command =
=====================================================================

Now edit the master.cf file as follows:

commet out smtp and Paste smpts lines as follows:

====================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ===================================================================
#smtp      inet  n       -       -       -       -       smtpd
#submission inet n       -       -       -       -       smtpd
#  -o smtpd_tls_security_level=encrypt
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#smtps     inet  n       -       -       -       -       smtpd
smtps   inet n   -   n   - - smtpd
      -o smtpd_sasl_auth_enable=yes
#      -o smtpd_reject_unlisted_sender=yes
#      -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
      -o broken_sasl_auth_clients=yes

===================================================================


Now create a file named smptd.conf and paste the following lines:
================================================================
    # vim /usr/lib/sasl2/smtpd.conf

============================

pwcheck_method: saslauthd
mech_list: plain login

============================

Important:


Using Port 587 for Secure Submission
===========================

If you want to use port 587 as the submission port for SMTP mail rather than 25 (many ISPs block port 25)
you will need to edit /etc/postfix/master.cf and uncomment the line

----------------------------------------------------------------------
|    submission inet n      -       n       -       -       smtpd     |
----------------------------------------------------------------------


Testing:

At this point, core email services should be up and running.
Let’s make sure that you’re in good shape before moving on. First, establish a connection with the mail server.

===========================================
root@mx:/# telnet localhost 465
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 mx.mithu.com ESMTP Postfix (Debian/GNU)
ehlo mithu
250-mx.mithu.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
============================================

If you see the following lines among others, then everything is working perfectly. Type quit to exit.

=====================
250-STARTTLS
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250 8BITMIME
====================


Installing & configuring Dovecot:

    # apt-get install dovecot*

now we will configure dovecot....(Uncomment some of the following lines and change their values)

    # vim /etc/dovecot/dovecot.conf


============================================
protocols = imap imaps pop3 pop3s
auth_debug = yes
mail_location = mbox:~/mail:INBOX=/var/mail/%u
disable_plaintext_auth = yes
pop3_uidl_format = %08Xu%08Xv
============================================

~~~~~~
N.B.R.
~~~~~~

Configure Dovecot for your mailbox format use (for maildir): {If mbox format used nothing to add in main.cf}

mail_location = maildir:~/Maildir


Do these steps ONLY if you want Maildir. This setup will put the Maildir in each user's home directory.

If you are using Postfix as your MTA, then add the following line to your /etc/postfix/main.cf file:


    # vim /etc/postfix/main.cf
---------------------------
home_mailbox = Maildir/
---------------------------

Edit /etc/dovecot/dovecot.conf:

mail_location = maildir:/home/%u/Maildir


$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
   @@@ Great Job!!!! we have done..Lets check it with Outlook express.....@@@@
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$


While configuring Outlook express (Keep in mind):

    We have to go advanced mail setup on Advanced Tab.
        >> Server Port Numbers
            ~ Outgoing mail (SMTP) 465
            ~ Incomming mail(POP3) 995
            ~ Give tick mark [v] on This Server requires SSL (Option)

Monday, December 30, 2013

How to Install and Configure Open LDAP server and client in Debian 6 (Squeeze)

What is LDAP?
============

LDAP stands for Lightweight Directory Access Protocol. As the name suggests, it is a lightweight client-server protocol for accessing directory services specifically X.500-based directory services. LDAP runs over TCP/IP or other connection oriented transfer services.

A directory is similar to a database, but tends to contain more descriptive, attribute-based information. The information in a directory is generally read much more often than it is written. Directories are tuned to give quick-response to high-volume lookup or search operations. They may have the ability to replicate information widely in order to increase availability and reliability, while reducing response time. When directory information is replicated temporary inconsistencies between the replicas may be OK, as long as they get in sync eventually.


LDAP Installation in Debian:

    # apt-get install slapd ldap-utils

After the completion of successful download of the LDAP Packages it will start installing automatically...
    Follow the Steps during Installation....
   
    >> Setup process will ask for Admin Password. Please provide your desired password
    >> You have to re-enter the same passowrd to match the previous given password.


LDAP Configuration in Debian:


If you want to configure LDAP you need to edit /etc/ldap/slapd.conf file....
   
    # vim /etc/ldap/ldap.conf

=============================================================
# LDAP Defaults

# See ldap.conf(5) for details
# This file should be world readable but not world writable.

BASE    dc=mehedi,dc=com
URI     ldap://192.168.0.15/

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never
TLS_CACERT      /etc/ssl/certs/ca-certificates.crt
=============================================================


Run the Configuration assistant....(Reconfigure)

        # dpkg-reconfigure slapd


The following options will appear and chose the appropriate options as follows:
====================================================================
    >> Ommit OpenLDAP Server configuration [SELECT NO]
    >> Enter DNS Domain Name [mehedi.com] "without bracket"
    >> Enter Organization Name [MEHEDI COMPANY] "without bracket"
    >> Enter the LDAP Administrator password *********
    >> Re-enter the password *********
    >> Select the backend database [ SELECT HDB]
    >> Do you want the database to be removed when slapd is purged [SELECT YES]
    >> Move Old database [SELECT YES]
    >> Allow LDAPv2 Protocol? [SELECT NO]

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        ya..Great work man....you have done....
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Now check you ldap server....
======================

    # ldapsearch -x

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# extended LDIF
# LDAPv3
# base <dc=mehedi,dc=com> (default) with scope subtree
# filter: (objectclass=*)
# requesting: ALL

# mehedi.com
dn: dc=mehedi,dc=com
objectClass: top
objectClass: dcObject
objectClass: organization
o: Mehedi
dc: mehedi

# admin, mehedi.com
dn: cn=admin,dc=mehedi,dc=com
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: admin
description: LDAP administrator

# Group, mehedi.com
dn: ou=Group,dc=mehedi,dc=com
ou: Group
objectClass: organizationalUnit
objectClass: top

# Admin Group, Group,mehedi.com
dn: cn=Admin Group,ou=Group,dc=mehedi,dc=com
cn: Admin Group
gidNumber: 1001
objectClass: posixGroup
objectClass: top

# Mehedi Hasan, Admin Group, Group, mehedi.com
dn: cn=Mehedi Hasan,cn=Admin Group,ou=Group,dc=mehedi,dc=com
givenName: Mehedi
sn: Hasan
cn: Mehedi Hasan
uid: mehedi
uidNumber: 1001
gidNumber: 1001
homeDirectory: /home/users/mehedi
loginShell: /bin/sh
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: top

# search result
search: 2
result: 0 Success

# numResponses: 6
# numEntries: 5
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



Install phpldapadmin for LDAP Server Administration:

    # apt-get install phpldapadmin


Create a symbolic link for phpldapadmin directory.
    # ln -s /usr/share/phpldapadmin/ /var/www/phpldapadmin

Now we have to edit the config file:


    # vim /etc/phpldapadmin/config.php

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$servers = new Datastore();
$servers->newServer('ldap_pla');
$servers->setValue('server','name','Unixmen LDAP Server');
$servers->setValue('server','host','192.168.0.15');
$servers->setValue('server','base',array('dc=mehedi,dc=com'));
$servers->setValue('login','bind_id','cn=admin,dc=mehedi,dc=com');
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Common Errors and Solution :

=========================================================
Cannot create a posixAccount / posixGroup in a clear LDAP directory
=========================================================
   
Just we have to commented out the <readonly> tag in posixAccount.xml and posixGroup.xml



    # vim /etc/phpldapadmin/templates/creation/posixAccount.xml

-----------------------------------------------------------
<attribute id="uidNumber">
        <display>UID Number</display>
        <icon>terminal.png</icon>
        <order>6</order>
        <page>1</page>
<!--    <readonly>1</readonly> -->
        <value>=php.GetNextNumber(/;uidNumber)</value>
</attribute>
-----------------------------------------------------------


    # vim /etc/phpldapadmin/templates/creation/posixGroup.xml

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

<attribute id="gidNumber">
        <display>GID Number</display>
        <order>2</order>
        <page>1</page>
<!--    <readonly>1</readonly> -->
        <spacer>1</spacer>
        <value>=php.GetNextNumber(/;gidNumber)</value>
        <!-- <value><![CDATA[=php.GetNextNumber(/;gidNumber;false;(&(objectClass=posixGroup));*2,+1000)]]></value> -->
</attribute>
--------------------------------------------------------------


Finally restart the Apache2 service:

    # /etc/init.d/apache2 restart

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Now open a browser and give the URL http://192.168.0.15/phpldapadmin
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    Remember the following important steps:
     >> Firstly add an Organizational Unit (OU)
    >> Under the created OU we will create a new Generic:Posix Group
    >> Under the posix group add or create some Generic: User Account

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

===========================================
===========================================
LDAP Cleint Configuration (Debian Squeeze):
===========================================
===========================================


LDAP client-package Installation in Debian:

    # apt-get install libnss-ldap libpam-ldap nscd

During installation it will ask you for several credentials:
   
    >> ldap://192.168.0.15 [ Use ldap not ldapi ]
    >> dc=mehedi,dc=com    [ as yours ]
    >> LDAP version to use : 3
    >> LDAP account for root: [clear every thing. The field should be Blank]
    >> LDAP root account Password: [Leave it Blank]
    >> Allow LDAP admin account to behave like local root? : NO
    >> Does the LDAP database require login? : NO


Now we should modify the nsswitch file for Ldap to work....
    # vim /etc/nsswitch.conf

add ldap beside compat in first three lines...[as follows]

-------------------------------------
passwd:         compat ldap
group:            compat ldap
shadow:         compat ldap

hosts:             files dns
networks:       files

protocols:      db files
services:        db files
ethers:           db files
rpc:               db files

netgroup:       nis
--------------------------------------



At this stage we have to reconfigure LDAP cleint package by the following command:
    # dpkg-reconfigure libpam-ldap

    Now it will ask you for several credentials again:
   
    >> ldap://192.168.0.15 [ Use ldap not ldapi ]
    >> dc=mehedi,dc=com    [ as yours ]
    >> LDAP version to use : 3
    >> Allow LDAP admin account to behave like local root? : NO
    >> Does the LDAP database require login? : NO
    >> Local encryption algorithm to use for passwords: crypt
    >> PAM profiles to enable: [select both Unix & LDAP Authenticaion]


=======================================================================
Yahhhooooo.....great job...reboot  LDAP client pc and login with LDAP user and passwd
=======================================================================
After successfully login with LDAP user name and password it will you a message [No directory, Logging in with HOME=/]


ha ha ha now check the Ldap server passwd file by the following command:
    # getent passwd

now you can see the ldap users that you have create in LDAP admin panel.....

Monday, December 16, 2013

How to Setup and Configure WebHTB in Debian Squeeze

First of All we will ready our server as an Web Server with Database & SSL Support:

    # apt-get install mysql-server mysql-client apache2
    # apt-get install openssl ssl-cert
    # mkdir /etc/apache2/ssl
    # make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/apache2/ssl/apache.pem
    # a2enmod ssl
    # /etc/init.d/apache2 force-reload
    # cp /etc/apache2/sites-available/default /etc/apache2/sites-available/ssl


Change the SSL port 80 to 443:


# vim /etc/apache2/sites-available/ssl

=>> change <VirtualHost *:80> to

       <VirtualHost *:443>


=>> Add the following two lines between <virtualHost> container


</VirtualHost>
SSLEngine On
SSLCertificateFile /etc/apache2/ssl/apache.pem

</VirtualHost>


ReEnable SSL and forcefully restart the services:

# /etc/init.d/apache2 force-reload
# a2ensite ssl
# /etc/init.d/apache2 restart


Download and Install the required Packages:

# apt-get install libphp-adodb php5-cli php5-gd php-pear php5-snmp php5-adodb phpmyadmin curl libnet-netmask-perl

Downlad and configure WebHTB package and upzip package:

# apt-get install bzip2
# cd /var
# wget http://www.webhtb.ro/downloads/WebHTB_V2.9.bz2
# tar -jxvf WebHTB_V2.9.bz2
# chown -R www-data.www-data /var/webhtb



Now add the following lines in ssl file:

# vim /etc/apache2/sites-available/ssl


Alias /webhtb /var/webhtb
<Directory "/var/webhtb">
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
SSLEngine On


The ssl file should look like this Finally (In my case)
=======================================
<VirtualHost *:443>
        ServerAdmin webmaster@localhost
        Alias /webhtb /var/webhtb
        <Directory "/var/webhtb">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
        </Directory>
        SSLEngine On

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn
SSLEngine On
SSLCertificateFile /etc/apache2/ssl/apache.pem

        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
================================================

Restart the apache2 service:

# a2ensite ssl
# /etc/init.d/apache2 restart


Go to your favorite web browser and navigate the following Link:
https://Server-Ip-Address/webhtb/setup/


Now the Graphical Mode config will start......

    >> Give the mysql root password in the asking password text boxes...
    >> Chose the appropriate interface.. {Remember it should be your LAN facing interface not WAN }
    >> After pressing Apply it will redirect you https://Server_Ip_Address/webhtb/index.php#


=======================================================================
$$$$$ Here you Don't Need to add any new Interface bcoz you have already assigned a NIC in Setup Phase.
=======================================================================

Add Class from the (Classes+) Menu:

    >> Go to Classes+  >> Add Classes >> Add a New Class page will arrive..{add here as you need}

Now you have to Add Client:

    >> Go to Add client Menu
                >> CLINT can be any name but PCName (Client PC)can be a good one.
                >> BANDWIDTH IS IN kbps (kilo bit not byte)
                >> LIMIT (Limit at a certain bandwidth as you want...)
                >> MAC (You can apply policy through specific MAC)
                >> BURST & PRIORITY should be default (If you are not an Advanced User)
                >> UPLOAD (You can specify upload throttle speed)

            Optional:
                >> SRC IPS should be your gate way ip   
                >> DST IPS should be your Client PC IP

How to Compress and Decompress Files and Folders In Linux (tar & untar)

========================
Create and Extract .bz2 Files
========================

Introduction:

bzip2 and bunzip2 are file compression and decompression utilities. The bzip2 and bunzip2 utilities are newer than gzip and gunzip and are not as common yet, but they are rapidly gaining popularity.
The bzip2 utility is capable of greater compression ratios than gzip. Therefore, a bzip2 file can be 10-20% smaller than a gzip version of the same file. Usually,files that have been compressed by bzip2 will have a .bz2 extension.


Installing bzip2 in debian:

# apt-get install bzip2


To uncompress a tar.bz2 file:


# bunzip2 iRedMail-0.7.4.tar.bz2

Now iRedMail-0.7.4.tar.bz2 file is converted to iRedMail-0.7.4.tar. [bz2 will go away..only tar extention will remain]


To untar the tar file:

# tar -xvf iRedMail-0.7.4.tar

To uncompress only bz2 file not (tar.bz2) :

# tar -jxvf WebHTB_V2.9.bz2


===========================
Compressing a File Using bzip2:
===========================

To compress a file using bzip2:

# bzip2 imehedi.txt

To compress a folder using bzip2:

# tar -jcvf archive_name.tar.bz2 directory_to_compress {SYNTAX}

    Example:
            # tar -jcvf iRedMail-0.7.4.tar.bz2 iRedMail-0.7.4


========================
Create and Extract Zip Files
========================
Zip is probably the most commonly used archiving format out there today. Its biggest advantage is the fact that it is available on all operating system platforms such as Linux, Windows, and Mac OS, and generally supported out of the box. The downside of the zip format is that it does not offer the best level of compression. Tar.gz and tar.bz2 are far superior in that respect. Let’s move on to usage now.


To compress a directory with zip do the following:

    # zip -r archive_name.zip directory_to_compress {Syntax}

    Example:
           # zip -r imehedi.zip mehediDocs

To decompress or unzip a directory with zip do the following:

    # unzip archive_name.zip {Syntax}
   
    Example:
           # unzip imehedi.zip

=======================
Create and Extract tar Files
=======================

Tar is a very commonly used archiving format on Linux systems. The advantage with tar is that it consumes very
little time and CPU to compress files, but the compression isn’t very much either. Tar is probably the Linux/UNIX
version of zip – quick and dirty.

To compress a directory with tar do the following:

            # tar -cvf archive_name.tar directory_to_compress {SYNTAX}
   
    Example:
            # tar -cvf imehedi.tar imehediDocs


To decompress or untar a directory with zip do the following:

   
         # tar -xvf archive_name.tar {Syntax}
   
    Example:
           # tar -xvf imehedi.tar


============================
Create and Extract TAR.GZ Files
============================

This format is my weapon of choice for most compression. It gives very good compression while not utilizing too much of the CPU while it is compressing the data


To compress a directory with tar.gz do the following:

           # tar -zcvf archive_name.tar.gz directory_to_compress {Syntax}

    Example:
           # tar -zcvf imehedi.tar.gz imehediDocs


To compress a directory with tar.gz do the following:

         # tar -zxvf archive_name.tar.gz {Syntax}

    Example:
         # tar -zxvf imehedi.tar.gz

Saturday, December 14, 2013

How to Completely Backup and Restore Linux Mail Server

========
Concept:
========

Following files/dirs are required for traditional Linux user management:
* /etc/passwd - contains various pieces of information for each user account

* /etc/shadow - contains the encrypted password information for user's accounts and optional the password aging information.

* /etc/group - defines the groups to which users belong

* /etc/gshadow - group shadow file (contains the encrypted password for group)

* /var/spool/mail - Generally user emails are stored here.

* /home - All Users data is stored here.

You need to backup all of the above files and directories from old server to new Linux server.

================
Backup Procedure
================

Step 1:

First create a tar ball of old uses (old Linux system). Create a directory:
# mkdir /root/move/

Step 2:

Setup UID filter limit:
# export UGIDLIMIT=500


Users that are added to the Linux system always start with UID and GID values of as specified by Linux distribution or set by admin.
Limits according to different Linux distro:

    RHEL/CentOS/Fedora Core : Default is 500 and upper limit is 65534 (/etc/libuser.conf).
    Debian and Ubuntu Linux : Default is 1000 and upper limit is 29999 (/etc/adduser.conf).

Step 3:

Now copy /etc/passwd accounts to /root/move/passwd.mig using awk to filter out system account (i.e. only copy user accounts)
# awk -v LIMIT=$UGIDLIMIT -F: '($3>=LIMIT) && ($3!=65534)' /etc/passwd > /root/move/passwd.mig


Step 4:

Copy /etc/group file:
# awk -v LIMIT=$UGIDLIMIT -F: '($3>=LIMIT) && ($3!=65534)' /etc/group > /root/move/group.mig  [for RHEL/CentOS/Fedora ]
# awk -v LIMIT=$UGIDLIMIT -F: '($3>=LIMIT) && ($3!=29999)' /etc/group > /root/move/group.mig  [for Debian/Ubuntu ]

Step 5:

Copy /etc/shadow file:
# awk -v LIMIT=$UGIDLIMIT -F: '($3>=LIMIT) && ($3!=65534) {print $1}' /etc/passwd | tee - |egrep -f - /etc/shadow > /root/move/shadow.mig   [for RHEL/CentOS/Fedora ]
# awk -v LIMIT=$UGIDLIMIT -F: '($3>=LIMIT) && ($3!=29999) {print $1}' /etc/passwd | tee - |egrep -f - /etc/shadow > /root/move/shadow.mig   [for Debian/Ubuntu ]


Step 6:

Copy /etc/gshadow (rarely used):
# cp /etc/gshadow /root/move/gshadow.mig

step 7:

Make a backup of /home and /var/spool/mail dirs:
# tar -zcvpf /root/move/home.tar.gz /home
# tar -zcvpf /root/move/mail.tar.gz /var/mail
# tar -zcvpf /root/move/mail1.tar.gz /var/spool/mail

Step 8:
Use scp or usb pen or tape to copy or paste /root/move to a new Linux system.

Where,

    Users that are added to the Linux system always start with UID and GID values of as specified by Linux distribution or set by admin. Limits according to different Linux distro:
        RHEL/CentOS/Fedora Core : Default is 500 and upper limit is 65534 (/etc/libuser.conf).
        Debian and Ubuntu Linux : Default is 1000 and upper limit is 29999 (/etc/adduser.conf).

    You should never ever create any new system user accounts on the newly installed Cent OS Linux. So above awk command filter out UID according to Linux distro.
    export UGIDLIMIT=500 - setup UID start limit for normal user account. Set this value as per your Linux distro.

    awk -v LIMIT=$UGIDLIMIT -F: '($3>=LIMIT) && ($3!=65534)' /etc/passwd > /root/move/passwd.mig - You need to pass UGIDLIMIT variable to awk using -v option (it assigns value of shell variable UGIDLIMIT to awk program variable LIMIT). Option -F: sets the field separator to : . Finally awk read each line from /etc/passwd, filter out system accounts and generates new file /root/move/passwd.mig. Same logic is applies to rest of awk command.
   
    tar -zcvpf /root/move/home.tar.gz /home - Make a backup of users /home dir
   
    tar -zcvpf /root/move/mail.tar.gz /var/spool/mail - Make a backup of users mail dir

================
Restore Procedure
================

Step 1:
First, make a backup of current users and passwords:
# mkdir /root/newsusers.bak
# cp /etc/passwd /etc/shadow /etc/group /etc/gshadow /root/newsusers.bak

Step 2:
Create a directory in new Linux Server in which to be restored:
# mkdir /root/move/
paste all copied item to this directory from usb pen or tape like (group.mig, gshadow.mig, home.tar.gz, mail.tar.gz, passwd.mig, shadow.mig)


Step 3:
Now restore passwd and other files in /etc/
# cd /root/move/
# cat passwd.mig >> /etc/passwd
# cat group.mig >> /etc/group
# cat shadow.mig >> /etc/shadow
# /bin/cp gshadow.mig /etc/gshadow

Please note that you must use >> (append) and not > (create) shell redirection.


Step 4:
Now copy and extract home.tar.gz to new server /home
# cd /
# tar -zxvf /root/move/home.tar.gz


Step 5:
Now copy and extract mail.tar.gz (Mails) to new server /var/mail
# cd /
# tar -zxvf /root/move/mail.tar.gz

Step 5:
Now copy and extract mail1.tar.gz (Mails) to new server /var/spool/mail
# cd /
# tar -zxvf /root/move/mail1.tar.gz

Step 6:
# reboot

How to install and configure Caching-only DNS server in Debian



####################################################################
       @@@@ Implementing a caching-only DNS on Debian @@@@@
####################################################################

Step 1: 
                # apt-get install bind9 dnsutils
Step 2:
The config for bind in Debian is a subdirectory structure in /etc/bind.
                # cd /etc/bind
Step 3:
For a simple caching-only server, we have to leave /etc/bind/named.conf untouched . We just modify /etc/bind/named.conf.options  file to give the  forwarders IP address:
                # vim named.conf.options
-----------------------------------------------------------------------------------------------------

options {
        directory "/var/cache/bind";
        // If there is a firewall between you and nameservers you want
        // to talk to, you may need to fix the firewall to allow multiple
        // ports to talk.  See http://www.kb.cert.org/vuls/id/800113
        // If your ISP provided one or more IP addresses for stable
        // nameservers, you probably want to use them as forwarders.
        // Uncomment the following block, and insert the addresses replacing
        // the all-0's placeholder.


        forwarders {
             // OpenDNS servers
             208.67.222.222;  {Your ISP's DNS Address}
             208.67.220.220;  {Your ISP's DNS Address}
             // ADSL router
             192.168.1.1;  {If gateway router is available}
        };
        // Security options
        listen-on port 53 { 127.0.0.1; 192.168.1.100; };
        allow-query { 127.0.0.1; 192.168.1.0/24; };
        allow-recursion { 127.0.0.1; 192.168.1.0/24; };
        allow-transfer { none; };
        auth-nxdomain no;    # conform to RFC1035
        // listen-on-v6 { any; };
};
------------------------------------------------------------------------------------------------------
Step 4:
Restart bind to load the new configuration:
                # /etc/init.d/bind9 restart
                or
                # service bind9 restart
Step 5:
Update /etc/resolv.conf, so DNS queries will be performed locally:
nameserver 127.0.0.1

Step 6: Test our caching only dns server
                # dig www.yahoo.com

main portion of the output.................
;; Query time: 433 msec   [First time dig]
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon May 24 05:18:21 2010
;; MSG SIZE  rcvd: 265
//////////////////////////////////////////
;; Query time: 2 msec   [Second time dig]
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon May 24 05:18:21 2010
;; MSG SIZE  rcvd: 265
Important: we have to be more careful about the  server ip address that means from which dns the query is responded. (SERVER: 127.0.0.1#53(127.0.0.1))

Check for possible syntax errors:
root@server:~# named-checkconf

How Do I See Current Cache?
Type the following command to dump cache(s) to the dump file called /var/cache/bind/named_dump.db:
# rndc dumpdb
# less /var/cache/bind/named_dump.db
# grep 'yahoo.com' /var/cache/named/named_dump.db

How Do I Debug BIND 9 Caching Server Problems?
The first place is to look error or warnings in /var/log/syslog file using the grep, cat, more, less or awk commands:
# tail -f /var/log/syslog
Is Port 53 Open?
Next make sure BIND 9 caching server is running on default port 53, run:
# netstat -tulpn | grep :53