• How to PCI Compliance your c-panel server

    The major credit card issuers created PCI (Payment Card Industry) compliance standards to protect personal information and ensure security when transactions are processed using a payment card. All members of the payment card industry (financial institutions, credit card companies and merchants) must comply with these standards if they want to accept credit cards. Failure to meet compliance standards can result in fines from credit card companies and banks and even the loss of the ability to process credit cards. ( Reference : http://www.practicalecommerce.com )

    There are six categories of PCI standards that must be met in order for a retailer to be deemed compliant

      cPanel PCI Tips & Tricks

    •         Webserver Uses Plain-text form based Authentication
    •         Entropy Chat (Port 2084)
    •         Disable SSLv2 for cPanel
    •         Mailman Unencrypted Login Information Disclosure
    •         cPanel Frontpage
    •         SSL Certificate Subject Does Not Match Target
    •         cPanel OpenSSL

    ASV stands for approved scanning vendor

    ====>  Webserver Uses Plain-text form based Authentication

    Generally when you see this ‘risk’, it is referring to ports 2082, 2086, or 2095. Those ports are the NON-SSL cPanel ports. All of those ports are cPanel related. 2082 is for cPanel, 2086 is used for WHM, 2095 is used for webmail. To resolve this issue, since cPanel does not really allow for an easy way to disable the services running on the plain-text authentication ports, you will need to just block those ports in the servers firewall and use the secure port versions of the services instead. Secure versions to use instead:

    2083 – cPanel
    2087 – WHM
    2096 – Webmail

    Blocking non-SSL/STUNNEL Ports

    If you use the APF firewall, to block the plain authentication ports you can just remove the port numbers 2082, 2086, 2095 from the configuration file, located at:

    You can block the ports ( 2082, 2086, or 2095 ) in CSF conf and restart CSF

    ====> TCP 2084 EntropyChatServer

    The Entropy Chat Server is found to be running on your server. This poses a potential security risk.

    Solution Fix:

    Disable Entropy Chat. You can do this by either disabling the port 2084 in your firewall, or by turning off Entropy Chat via your WebHost Manager (WHM). You can do this via WHM by logging into WHM and going to:

    “Main >> Service Configuration >> Service Manager”

    There should be a checkbox next to Entropy Chat. Uncheck it and save changes.

    ====> SSLv2 cPanel ports

    Non-SSL cPanel, WHM, webmail ports as a failing issue.

    PLEASE NOTE, THIS IS GENERALLY NOT AN ISSUE ANYMORE WITH THE LATEST CPANEL VERSION AND IS LISTED FOR REFERENCE NOW ONLY.

    Disable sslv2 in cpanel by using stunnel:

    perl -i -p -e ‘s/nativessl=1/nativessl=0/g’ /var/cpanel/cpanel.config

    edit the Files:

    /usr/local/cpanel/etc/stunnel/mycabundle/stunnel.conf
    /usr/local/cpanel/etc/stunnel/default/stunnel.conf

    and Add:

    options = NO_SSLv2
    ciphers = AES256-SHA:DES-CBC3-SHA:AES128-SHA:RC4-SHA:RC4-MD5

    (beneath the “Authentication stuff” section) Both files need to be chattr’d to prevent reset during a upcp:

    chattr +i /usr/local/cpanel/etc/stunnel/mycabundle/stunnel.conf
    chattr +i /usr/local/cpanel/etc/stunnel/default/stunnel.conf

    You can also refer Disable support for sslv2 low-encryption ciphers

    ====> cPanel Frontpage / mod_frontpage

    The wording may vary but will generally be something along the lines of complaining about Apache mod_frontpage module being vulnerable to a buffer overflow error, that could initate privilege escalation such as root access. That is a false positive as it is based solely on a default apache installation, not the custom cPanel installation. You may see something along the following listed in your PDF:

       TCP 443 https 7
        The remote host is using the Apache mod_frontpage module.
        mod_frontpage older than 1.6.1 is vulnerable to a buffer overflow
        which may allow an attacker to gain root access.
        Since we are not able to remotely determine the version of
        mod_frontpage you are running, you are advised to manually
        check which version you are running as this may be a false positive.
        If you want the remote server to be remotely secure,
        we advise you do not use this module at all.
        Solution: Disable this module
        Risk Factor: High
        CVE : CVE-2002-0427

    This is the easiest fix, since, there is no fix. Submit to your ASV scanning company that this issue is a false positive and offer the following URL from cPanel’s own documentation themselves as proof:

    http://docs.cpanel.net/twiki/bin/view/AllDocumentation/PCIComplianceInfo/ScanningSoftware#mod_frontpage

    Quoted from cPanel:

    “When using a cPanel configured Apache, fpexe is configured differently than on a default installation as such: Apache 2

    With Apache 2.x or 2.2.x compiled through EasyApache, fpexe is replaced by /scripts/fp-auth which is never setuid root. Apache 1

    With Apache 1.3.x compiled through EasyApache, fpexe is custom built from the shar files in /scripts/fetchfpexec, /scripts/fpexec3 and /scripts/fp3. fpexec will only be setuid if Apache’s suexec functionality is disabled. Even with suexec disabled, fpexec is not directly executing the frontpage binaries. fpexe hands the work off to /scripts/fp-auth which does additional access checks.

    As noted above, using either Apache 1 or 2 compiled through cPanel’s EasyApache system does not leave a system vulnerable to the exploit noted in the CVE report as /scripts/fp-auth prevents the privilege escalation scenario from occurring.

    Note: We do recommend discontinuing the use of mod_frontpage based on compatibility and support. The module is no longer supported by any upstream development team and has reached end-of-life. While we will continue to support mod_frontpage as long as it is practical to do so, there are better publishing methods available. We recommend enabling WebDAV (cpdavd) for publishing as it provides enhanced security and stability and is an actively supported protocol.”

    ====> Mailman Unencrypted Login Information Disclosure

    This basically means that the login administration page for mailman is available as an unencrypted URL, ie “http” and not “httpS”

    The easy fix, auto-redirecting urls to encrypted https urls.

    Create the file:

    /usr/local/cpanel/3rdparty/mailman/cgi-bin/.htaccess

    Add the following contents to it:

    RewriteEngine on
    RewriteCond %{SERVER_PORT} 80
    RewriteCond %{REQUEST_URI} mailman
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/mailman/$1   [R=301,L]

    If that does not work it is possible the domain you’re testing doesn’t have an SSL cert. Try putting the server’s hostname in the RewriteRule, ie:

    RewriteEngine on
    RewriteCond %{SERVER_PORT} 80
    RewriteCond %{REQUEST_URI} mailman
    RewriteRule ^(.*)$ https://HOST.DOMAINNAME.COM/mailman/$1   [R=301,L]

    Edit /usr/local/cpanel/3rdparty/mailman/Mailman/mm_cfg.py adding these 2 lines at the bottom:

    DEFAULT_URL_PATTERN = ‘https://%s/mailman/’
    PUBLIC_ARCHIVE_URL = ‘https://%(hostname)s/pipermail/%(listname)s’

    Run the following command:

    /usr/local/cpanel/3rdparty/mailman/bin/withlist -l -a -r fix_url

    Test it. Go to any site that is hosted on the server and append the mailman URLs from the PCI vulnerability, ie:

    http://DOMAIN.COM/mailman/admin/mailman

    ====>  cPanel – SSL Certificate Subject Does Not Match Target – Port 2096

    If your PCI report lists “SSL Certificate Subject Does Not Match Target”, and specifies that it is for port 2096 (cPanel Webmail), this is a false positive. However, instead of submitting it as a false positive, there is an easy fix.

    The report may look similiar to:

    When a server’s SSL certificate is invalid, clients cannot properly verify that the server is authentic, resulting in a lack of trust.

    The certificate is invalid, due to at least one of the following three reasons:

    Expired – The current date is past the expiration date of the certificate. Subject does not match target – The name on the certificate is not the same as the name of the site, so a client cannot verify that the certificate belongs to the server. Untrusted issuer (or self-signed) – The certificate was not issued by a trusted certificate authority. In the case of self-signed certificates, the server issued its own certificate, possibly by default.

    Service: TCP 2096 Certificate Issued To: *.WEBSITENAMEHERE.com

    Login to WHM and go to “Tweak Settings”:

    “Main >> Server Configuration >> Tweak Settings

    From there find the section called “Redirection”.

    If you wish, select the option “Always redirect users to the ssl/tls ports when visiting /cpanel /webmail, etc.”

    That should be set in my opinion, however the actual fix for this issue is to select the “Origin Domain Name” box, and also the “Original Domain Name” box under the item “When visiting /cpanel or /whm or /webmail with SSL, you can choose to redirect to”

    Reference : – http://www.getfreepci.com

  • Are you worried about ssl certificate expiry ?

    Are you worried about ssl certificate expiry  ?  I found a good solution for that 🙂 . This script will monitor the ssl certificate expiry and  will  provide e-mail notifications when a certificate is getting close to expire !!!

    1) Download and setup the script for execution

    wget http://prefetch.net/code/ssl-cert-check
    chmod 744 ssl-cert-check

    2) To find the ssl expiry details of a local certificate

    ./ssl-cert-check -c  /usr/local/sss/adminlogs.crt

    3) To find  the ssl expiry details of a remote domain

    ./ssl-cert-check -s www.adminlogs.info -p 443

    4) To find the ssl expiry details of a list of domains

    If you are managing a number of domains , you can place the domains in a file with port number as follows

    # vi  /home/domainlist
    www.adminlogs.info 443
    www.google.com  443
    www.yahoo.com  443

    Then save the file and execute the script with the option ” -f ”

    ./ssl-cert-check -f  /home/domainlist  ./ssl-cert-check -i -f domainlist

    here ”  i ” will give the details of ssl provider/issuer
    5)  Setup e-mail alerts if ssl expiry date is less than or equal to 20 days

    ssl-cert-check can provide e-mail notifications when a certificate is getting close to expiring. The expiration interval can be controlled with ssl-cert-check’s “-x” (expiration interval) option, and the e-mail address to send notifications can be passed as an argument to the “-e” (e-mail address to send alerts) option.

    ./ssl-cert-check -a  -f   /home/domainlist  -q -x 20 -e  [email protected]

    You can add the above command in cron and monitor your ssl certificate validity .

    You can find more ssl related stuffs here : most-common-openssl-commands

    Thank you prefetch.net for this excellent script !!!

     

  • Automate your ftp operations

    In our day to day operations , sometimes we will need to automate ftp operations. Today one of my client asked me to setup a cronjob to download files from remote machine using ftp

    We can do this in two ways

    1) FTP automation

    vi /usr/local/scripts/ftp-auto.sh

    #!/bin/bash
    HOST='adminlogs.info'
    USER='ftpadmin'
    PASSWD='password'
    ftp -n -v $HOST << EOT
    ascii
    user $USER $PASSWD
    prompt n Interactive mode Off
    mkdir linux
    cd linux
    bye
    EOT
    sleep 3

    I have included an example , you can add your ftp operation’s after “prompt “

     

    2) SFTP automation

    vi /usr/local/scripts/sftp-auto.sh

    #!/bin/bash
    HOST="adminlogs.info"
    USER="ftpadmin"
    PASS="password"
    FIRE=$(expect -c "
    spawn /usr/bin/sftp -o \"BatchMode no\" -b /tmp/commandfile  [email protected]$HOST
    expect \"password:\"
    send \"$PASS\r\"
    interact
    ")
    echo "$FIRE"

    Note : –

    You should install ” expect ” , using  yum install expect

    You can add your own ftp commands in ” /tmp/commandfile ” .

     

     

  • Useful linux commands to monitor/find server banndwidth usage.

    If you are getting any alerts from nagios ( Bandwidth Monitoring using Nagios ) or from the check_bandwidth script ( Bandwidth Monitoring script ) , regarding high bandwith usage of your server then  you should find the cause . To my experience the following two commands can help  you lots to dig on this issue. ( personally i will prefer iftop 😉 )

    1)  vnstat

    Description:-
    vnStat is a console-based network traffic monitor. It keeps a log of hourly, daily and monthly network traffic for the selected interface(s). However, it isnât a  packet  sniffer.
    The traffic information is analyzed from the proc and sys filesystems depending on availability. That way vnStat can be used even without root permissions on most systems.

    Installation

    # yum install vnstat

    vnstat options

    -tr time
    Calculate how much traffic goes through the selected interface during the given time seconds. The time will be 5 seconds


    -d, –days
    Show traffic for days.


    -h, –hours
    Show traffic for the last 24 hours


    -m, –months
    Show traffic for months.

    You can change the default interface using the option ” vnstat -u -i eth2 ” ,  Also to keep the database updated you can use the following script on crontab

    */5 * * * *  if [ -x /usr/bin/vnstat ] && [ `ls /var/lib/vnstat/ | wc -l` -ge 1 ]; then /usr/bin/vnstat -u; fi

    ( If you’re not satisfied with the appearance of vnStat’s command-line interface, you can install Bjorge Dijkstra’s PHP-based Web front end for vnStat ( http://www.sqweek.com/sqweek/files/vnstat_php_frontend-1.5.1.tar.gz ), which takes the data collected by the command-line vnStat and displays it in tables and graphically in your browser. The front end requires a Web server configured with PHP (and php-gd installed) )

    2 ) iftop

    Description :-
    iftop  listens  to network traffic on a named interface, or on the first interface it can find which looks like an external interface if none is specified, and displays a table of
    current bandwidth usage by pairs of hosts.  iftop must be run with sufficient permissions to monitor all network traffic on the interface; see pcap(3) for more information, but on
    most systems this means that it must be run as root.

    By  default,  iftop  will look up the hostnames associated with addresses it finds in packets. This can cause substantial traffic of itself, and may result in a confusing display.
    You may wish to suppress display of DNS traffic by using filter code such as not port domain, or switch it off entirely, by using the -n option or by pressing R when  the  program
    is running.

    By  default,  iftop  counts  all  IP packets that pass through the filter, and the direction of the packet is determined according to the direction the packet is moving across the
    interface.  Using the -F option it is possible to get iftop to show packets entering and leaving a given network.  For example, iftop -F 10.0.0.0/255.0.0.0  will  analyze  packets
    flowing in and out of the 10.* network

    Installation
    # yum install iftop

    Options

    # iftop -i eth0

    While iftop is running, you can press any one of the following keys to display more output.

    S – display source port
    D – display destination port
    n – show IP instead of host name
    1/2/3 – sort by the specified column
    < – sort by source name
    > – sort by dest name
    P – pause display ( else it will be often updated to show the current status )
    j/k – scroll display
    ? – for help

    To configure sms alert configuration for nagios refer here : Nagios sms alert configuration
    You can refer more about iftop here : http://www.ex-parrot.com/~pdw/iftop/

  • Linux user account management.

    Scenario :-

    To setup the following user policies to meet one of  our clients corporate  IT security policy.
    1) Minimum Password length should be 8 .
    2) Password should be expired after 90 days .
    3) Restricting  the use of previous passwords.
    4) Lock the account after 5 login failures.
    5) “sudo or su ” access is only for the mentioned accounts.

     

    Enabling Password Aging

    The following files and parameters in the table are used when a new account is created with the useradd command. These settings are recorded for each user account in the /etc/shadow file. Therefore, make sure to configure the following parameters before you create any user accounts using the useradd command:

    /etc/login.defs     PASS_MAX_DAYS   90     Maximum number of days a password is valid.
    /etc/login.defs     PASS_MIN_DAYS    7     Minimum number of days before a user can change the password since the last change.
    /etc/login.defs     PASS_MIN_LEN    n/a    This parameter does not work. It is superseded by the PAM module "pam_cracklib". See Enforcing Stronger Passwords for more information.
    /etc/login.defs     PASS_WARN_AGE    7     Number of days when the password change reminder starts.
    /etc/default/useradd     INACTIVE   14     Number of days after password expiration that account is disabled.
    /etc/default/useradd     EXPIRE            Account expiration date in the format YYYY-MM-DD.

    To see the current password aging setting of a use

    #  chage -l username
    Last password change                                            : Jun 22, 2011
    Password expires                                                   : never
    Password inactive                                                  : never
    Account expires                                                     : never
    Minimum number of days between password change          : 0
    Maximum number of days between password change         : 99999
    Number of days of warning before password expires           : 7

     

    Enforcing Stronger Passwords

    The pam_cracklib module checks the password against dictionary words and other constraints.

    The following example shows how to enforce the following password rules:
    – Minimum length of password must be 8
    – Minimum number of lower case letters must be 1
    – Minimum number of upper case letters must be 1
    – Minimum number of digits must be 1
    – Minimum number of other characters must be 1

    pam_cracklib.so
    minlen=8
    Minimum length of password is 8
    pam_cracklib.so
    lcredit=-1
    Minimum number of lower case letters is 1
    pam_cracklib.so
    ucredit=-1
    Minimum number of upper case letters is 1
    pam_cracklib.so
    dcredit=-1
    Minimum number of digits is 1
    pam_cracklib.so
    ocredit=-1
    Minimum number of other characters is 1

    To setup these password restrictions, edit the /etc/pam.d/system-auth file and add/change the following pam_cracklib arguments highlighted in blue:

    auth        required      /lib/security/$ISA/pam_env.so
    auth        sufficient    /lib/security/$ISA/pam_unix.so likeauth nullok
    auth        required      /lib/security/$ISA/pam_deny.so
    account     required      /lib/security/$ISA/pam_unix.so
    account     sufficient    /lib/security/$ISA/pam_succeed_if.so uid < 100 quiet
    account     required      /lib/security/$ISA/pam_permit.so
    password    requisite     /lib/security/$ISA/pam_cracklib.so retry=3 minlen=8 lcredit=-1 ucredit=-1 dcredit=-1 ocredit=-1
    password    sufficient    /lib/security/$ISA/pam_unix.so nullok use_authtok md5 shadow
    password    required      /lib/security/$ISA/pam_deny.so
    session     required      /lib/security/$ISA/pam_limits.so
    session     required      /lib/security/$ISA/pam_unix.so

    Now verify that the new password restrictions work for new passwords. Simply login to a non-root account and change the password using the passwd command. Note that the above requirements are not enforced if you run the passwd command under root.

     

    Restricting Use of Previous Passwords

    The pam_unix module parameter remember can be used to configure the number of previous passwords that cannot be reused. And the pam_cracklib module parameter difok can be used to specify the number of characters hat must be different between the old and the new password.

    we set PASS_MIN_DAYS to 7, which specifies the minimum number of days allowed between password changes. Hence, if we tell pam_unix to remember 26 passwords, then the previously used passwords cannot be reused for at least 6 months (26*7 days).

    Here is an example. Edit the /etc/pam.d/system-auth file and add/change the following pam_cracklib and pam_unix arguments:

    auth        required      /lib/security/$ISA/pam_env.so
    auth        sufficient    /lib/security/$ISA/pam_unix.so likeauth nullok
    auth        required      /lib/security/$ISA/pam_deny.so
    account     required      /lib/security/$ISA/pam_unix.so
    account     sufficient    /lib/security/$ISA/pam_succeed_if.so uid < 100 quiet
    account     required      /lib/security/$ISA/pam_permit.so
    password    requisite     /lib/security/$ISA/pam_cracklib.so retry=3 minlen=8 lcredit=-1 ucredit=-1 dcredit=-1 ocredit=-1 difok=3
    password    sufficient    /lib/security/$ISA/pam_unix.so nullok use_authtok md5 shadow remember=26
    password    required      /lib/security/$ISA/pam_deny.so
    session     required      /lib/security/$ISA/pam_limits.so
    session     required      /lib/security/$ISA/pam_unix.so

    NOTE:
    If the /etc/security/opasswd doesn’t exist, create the file.

    # ls -l /etc/security/opasswd
    -rw——-  1 root root 0 Dec  8 06:54 /etc/security/opasswd

     

    Locking User Accounts After Too Many Login Failures

    In the following example I will show how to lock only individual user accounts after too many failed su or login attempts.

    Add the following two lines highlighted in blue to the /etc/pam.d/system-auth file as shown below:

    auth        required      /lib/security/$ISA/pam_env.so
    auth        required      /lib/security/$ISA/pam_tally.so onerr=fail no_magic_root
    auth        sufficient    /lib/security/$ISA/pam_unix.so likeauth nullok
    auth        required      /lib/security/$ISA/pam_deny.so
    account     required      /lib/security/$ISA/pam_unix.so
    account     required      /lib/security/$ISA/pam_tally.so per_user deny=5 no_magic_root reset
    account     sufficient    /lib/security/$ISA/pam_succeed_if.so uid < 100 quiet
    account     required      /lib/security/$ISA/pam_permit.so
    password    requisite     /lib/security/$ISA/pam_cracklib.so retry=3
    password    sufficient    /lib/security/$ISA/pam_unix.so nullok use_authtok md5 shadow
    password    required      /lib/security/$ISA/pam_deny.so
    session     required      /lib/security/$ISA/pam_limits.so
    session     required      /lib/security/$ISA/pam_unix.so

    The first added line counts failed login and failed su attempts for each user. The default location for attempted accesses is recorded in /var/log/faillog.

    The second added line specifies to lock accounts automatically after 5 failed login or su attempts (deny=5). The counter will be reset to 0 (reset) on successful entry if deny=n was not exceeded. But you don’t want system or shared accounts to be locked after too many login failures (denial of service attack). To exempt system and shared accounts from the deny=n parameter, I added the per_user parameter to the module. The per_user parameter instructs the module NOT to use the deny=n limit for accounts where the maximum number of login failures is set explicitly. For example:

    # faillog -u apache  -m -1
    The faillog command with the option “-m -1” has the effect of not placing a limit on the number of failed logins. To instruct the module to activate the deny=n limit for this account again, run:

    # faillog -u apache -m 0

    By default, the maximum number of login failures for each account is set to 0 which instructs pam_tally to use the deny=n parameter.

     

    Disable unwanted su access

    Enabling su access for selected accounts will give an additional layer of security on your servers. I have used the following steps to enable this.

    1) Create a user  as member of Wheel group (root is a member of wheel group )

    useradd -G wheel suadmin

    password suadmin

    2) Enable su access only for wheel group menbers

    # Uncomment the following line in the file /etc/pam.d/su

    auth            required        pam_wheel.so use_uid

    Its better to take a back of this file before making any changes

  • Linux Server Security

    An apple a day keeps the doctor  away 🙂

    Whenever  i login to my servers i will execute  the following simple commands before starting any other works.

    a) “ w “ to check server load , server uptime and the users who are logged in

    b) “df -h “ to confirm none of the drives diskspace are critical

    1. top -c “ ( shift +m will sort the process memory wise and shift+ p will sort the process cpu usage wise ) and confirm no strange process are running.
    1. check /tmp using “ ls -la “ and confirm no suspicious files are present

    As we you might see , the above task will take less than 5 minutes and the result will be worth the effort.

    Prevention is always better than cure

    Linux is secure , but its a tedious job for an admin to keep his/her server safe and secure always. Every day we are facing new new threats and vulnerabilities.  If we are concerned about your server security then it should be mandatory to do atleast the following tweaks in your server .

    Phase 1 : Installations

    1) Install and configure Firewall + LFD (CSF)

    http://www.configserver.com/cp/csf.html

    Feataures :-

    • Easy Installation and Configuration
    • Brute Force Attack Prevention
    • Server Security Checks
    • Port scan prevention and blocking
    • Intrusion detection system
    • IP Blocking and more..

    Installation and configuration :-

    # cd /etc

    # wget http://www.configserver.com/free/csf.tgz

    # tar zxf csf.tar.gz

    # sh csf/install.sh

    ( Specify which ports you want to allow )

    # vi /etc/csf/csf.conf

    # Allow incoming TCP ports

    TCP_IN = “20,21,22,25,53,80,110,143,443,465,953,993,995,3306,3434”

    # Allow outgoing TCP ports

    TCP_OUT = “20,21,22,25,37,43,53,80,110,113,443,587,873,953,3306,3434”

    # Allow incoming UDP ports

    UDP_IN = “20,21,53,953”

    # Allow outgoing UDP ports

    # To allow outgoing traceroute add 33434:33523 to this list

    UDP_OUT = “20,21,53,113,123,873,953”

    #If you are happy with the setting then we can change the testing mode as follows

    #Disable the Testing Mode and Start the Firewall

    TESTING = “0”

    Save the file and restart the firewall!

    # csf -r


    2 ) Install and configure rootkit detection software – Rkhunter

    rkhunter (Rootkit Hunter) is a unix based tool that scans for rootkits ,backdoors and possible local exploits. It does this by comparing SHA hashes of important files with known good ones in online database, searching for default directories (of rootkits), wrong permissions, hidden files, suspicious strings in kernel modules, and special tests for Linux and Freebsd.

    Login to your server via SSH as root then Type

    # cd /usr/local/src

    Download the latest Version of RKHunter

    http://sourceforge.net/projects/rkhunter/

    # tar -xzf rkhunter-tar.gz

    # cd rkhunter-1.3.6

    # ./installer.sh –layout /usr/local –install

    # rkhunter -c will scan the server for known rootkits.

    Lets setup RKHunter to e-mail you daily scan reports.

    # vi /etc/cron.daily/rkhunter.sh

    Add The Following:

    #!/bin/bash

    /usr/local/bin/rkhunter -c –cronjob 2>&1 | mail -s “RKhunter Scan Details”  alerts[at]adminlogs.info


    3) Scan and harden /tmp /var/tmp directories

    Its always better to create a separate partition for /tmp, Also we need to confirm /tmp is clean. To know more about linux /tmp hack , click here : /tmp hack

    # dd if=/dev/zero of=/dev/tmpFS bs=1M count=1500
    The above will create a file with 1.5Gb size ,we can change the size of the file as per our need.

    # /sbin/mkfs.ext3 /dev/tmpFS

    will create a ext3 partition

    # take the back up of current /tmp
    cp -Rpf /tmp /tmpbackup

    # mount the newly created file system as no exec and nosuid
    mount -o loop,noexec,nosuid,rw /dev/tmpFS /tmp

    # apply stikybit permission to /tmp
    chmod 1777 /tmp

    # Restore the old /tmp
    cp -Rpf /tmpbackup/* /tmp/

    For securing /dev/shm mount it as follows in /etc/fstab
    # vi /etc/fstab

    tmpfs /dev/shm tmpfs defaults,nosuid,noexec,rw 0 0

    /var/tmpMnt /tmp ext2 loop,noexec,nosuid,nodev,rw 0 0

    # mount -o remount /dev/shm

    We should do the same for /var/tmp also , because some applications will use /var/tmp as temporary folder and its also a public place.

    # mv /var/tmp /var/tmp.bkp

    # ln -s /tmp /var/tmp

    NB :- we should restart the services like mysql and clamd which are using /tmp or /var/tmp for socket file creation

     

    4) Install Mod_security apache module with latest custom rules

    ModSecurity is a free opensource web application firewall which can help you to guard against LFI (local file inclusion attacks) and SQL injection vulnerabilities.

    # cp -pr /etc/httpd/conf /etc/htpd/conf.bkp

    # yum install libxml2 libxml2-devel httpd-devel

    # Download latest verstion of mod_secuirty module

    wget http://www.modsecurity.org/download/modsecurity-apache_2.*.tar.gx

    # tar zxf modsecurity-apache_2.*.tar.gz
    # cd modsecurity-apache_2.*
    # cd apache2

    # ./configure

    # make & make install

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

    LoadModule unique_id_module modules/mod_unique_id.so
    LoadFile /usr/lib/libxml2.so
    LoadModule security2_module modules/mod_security2.so
    Include conf/modsecurity/*.conf

    # /etc/init.d/httpd restart

    NB :- I will prefer to compile apche as DSO and this will help us to install additional modules using the tool apxs ( Apache extented services )
    For example
    download the mod_security module and untar
    # cd mod_security
    # <apache-home>/bin/apxs -cia mod_security.c
    the above will do all the above with out effecting the currently running apache.


    5) Install Antivirus toolkit ClamAV

    Clam AntiVirus is an open source (GPL) anti-virus toolkit for UNIX, designed especially for e-mail scanning on mail gateways. It provides a number of utilities including a flexible and scalable multi-threaded daemon, a command line scanner and advanced tool for automatic database updates. The core of the package is an anti-virus engine available in a form of shared library.

    Here is a list of the main features:

    • command-line scanner
    • fast, multi-threaded daemon with support for on-access scanning
    • milter interface for sendmail
    • advanced database updater with support for scripted updates and digital signatures
    • virus scanner C library
    • on-access scanning (Linux® and FreeBSD®)
    • virus database updated multiple times per day (see home page for total number of signatures)
    • built-in support for various archive formats, including Zip, RAR, Tar, Gzip, Bzip2, OLE2, Cabinet, CHM, BinHex, SIS and others
    • built-in support for almost all mail file formats
    • built-in support for ELF executables and Portable Executable files compressed with UPX, FSG, Petite, NsPack, wwpack32, MEW, Upack and obfuscated with SUE, Y0da Cryptor and others

    # create a user for clamav to use:
    useradd clamav
    Some OS’s require you to add the group as well:
    groupadd clamav
    Don’t worry if the user and/or group already exist.

    # Download the latest stable ClamAV distribution from http://www.clamav.net
    Note: If you are running Fedora Core 4 or earlier, you cannot install any version of ClamAV later than 0.91.2 because of a broken gcc.

    # Expand the distribution and cd into the resultant directory and build ClamAV using:
    tar -xzf clamav-*
    cd clamav*
    ./configure –disable-zlib-vcheck
    make
    make install

    # vi  /usr/local/etc/freshclam.conf
    Comment out the line (put a # as the first character on the line) near the top that says simply:
    Example

    # vi  /usr/local/etc/clamd.conf
    Comment out the line (put a # as the first character on the line) near the top that says simply:
    Example

    # vi  /usr/local/etc/clamd.conf
    Change the following line:
    #LocalSocket /tmp/clamd.socket
    to this:
    LocalSocket /tmp/clamd

    # Run ldconfig to create the necessary links and cache to most recent shared libraries
    ldconfig

    # Run freshclam to download the latest definitions:
    freshclam

    # To scan the folder

    clamscan -r /home

    Note: The following will no longer work as ClamAV has decided not to include the init examples in their latest version. You will have to create your own init script to start clamd or download an old version of ClamAV (pre-v0.95) and get the init script from there.

    /bin/cp -fv contrib/init/RedHat/clamd /etc/init.d/clamd
    chown root:root /etc/init.d/clamd
    chmod +x /etc/init.d/clamd
    chkconfig clamd on
    service clamd restart


    6) Install and configure mod_evasive

    mod_evasive is an evasive maneuvers module for Apache to provide evasive action in the event of an HTTP DoS or DDoS attack or brute force attack. It is also designed to be a detection tool, and can be easily configured to talk to ipchains, firewalls, routers, and etc. mod_evasive can stand up to even large attacks. Its features will prevent you from wasting bandwidth or having a few thousand CGI scripts running as a result of an attack.

    Login too your server and execute

    # cd /usr/local/src
    # wget http://www.sfr-fresh.com/unix/privat/mod_evasive_1.10.1.tar.gz
    # tar -xzvf mod_evasive_1.10.1.tar.gz
    # cd mod_evasive
    # cd apache 2.0.x
    # /usr/sbin/apxs -cia mod_evasive20.c

    Then add add this too httpd.conf
    <IfModule mod_evasive20.c>
    DOSHashTableSize 3097
    DOSPageCount 6
    DOSSiteCount 100
    DOSPageInterval 2
    DOSSiteInterval 2
    DOSBlockingPeriod 600
    </IfModule>

    # Restart apache


    Phase 2 : Make Changes

     

    1) Secure root login : Disable root login and only allow wheel group members to use switch user option ( su – )

    # vi /etc/ssh/sshd_config

    ( Enable protocol 2 and disable PermitRoot login as follows )

    Protocol 2

    PermitRootLogin No
    # save the file and restart sshd service

    Create a new user as a member of wheel group ( root user is a member of wheel group )
    # useradd -G  wheel  serveradmin
    # passwd serveradmin (Give a strong password )

    Restrict the user to su
    # vi /etc/pam.d/su
    # Uncomment the following line to require a user to be in the “wheel” group.
    auth            required        pam_wheel.so use_uid

    Now only the users in wheel group can use ” su – ”

    # Add the following line in ”  /root/.bash_profile ” , which will send an alert if anyone logged as root.

       
    echo 'CRITICAL ALERT - Logged as Root on:' `date` `who` | mail -s "Alert: Logged as Root on Server `hostname` from `who | awk '{print $6}'`" your_full_email_address

     

    2) Extended Binary Hardening Chmod dangerous files . It could be a good idea to restrict some commands to be executed by users that do not have root privileges and thus having your system more secure.

    3) Inetd hardening Disable Telnet

    #  mv /etc/xinetd.d/telnet /etc/xinetd.d/telnet.bkp
    # /etc/rc.d/init.d/xinetd restart

    4) Host.conf & Sysctl Hardening – Sysctl.conf is used to harden your kernel. The purpose of hardening this is to avoid DOS and Spoofing attacks to your system.

    # cp -p /etc/host.conf  /etc/host.conf.bkp
    # vi /etc/host.conf
    multi on
    nospoof on

    Syctl Hardening : –

    # cp -p /etc/sysctl.conf /etc/sysctl.conf.bkp
    # >  /etc/sysctl.conf
    # Vi  /etc/sysctl.conf
    ### paste the following and save the file
    # Disables packet forwarding
    net.ipv4.ip_forward=0
    # Disables IP source routing
    net.ipv4.conf.all.accept_source_route = 0
    net.ipv4.conf.lo.accept_source_route = 0
    net.ipv4.conf.eth0.accept_source_route = 0
    net.ipv4.conf.default.accept_source_route = 0
    # Enable IP spoofing protection, turn on source route verification
    net.ipv4.conf.all.rp_filter = 1
    net.ipv4.conf.lo.rp_filter = 1
    net.ipv4.conf.eth0.rp_filter = 1
    net.ipv4.conf.default.rp_filter = 1
    # Disable ICMP Redirect Acceptance
    net.ipv4.conf.all.accept_redirects = 0
    net.ipv4.conf.lo.accept_redirects = 0
    net.ipv4.conf.eth0.accept_redirects = 0
    net.ipv4.conf.default.accept_redirects = 0
    # Enable Log Spoofed Packets, Source Routed Packets, Redirect Packets
    net.ipv4.conf.all.log_martians = 0
    net.ipv4.conf.lo.log_martians = 0
    net.ipv4.conf.eth0.log_martians = 0
    # Disables IP source routing
    net.ipv4.conf.all.accept_source_route = 0
    net.ipv4.conf.lo.accept_source_route = 0
    net.ipv4.conf.eth0.accept_source_route = 0
    net.ipv4.conf.default.accept_source_route = 0
    # Enable IP spoofing protection, turn on source route verification
    net.ipv4.conf.all.rp_filter = 1
    net.ipv4.conf.lo.rp_filter = 1
    net.ipv4.conf.eth0.rp_filter = 1
    net.ipv4.conf.default.rp_filter = 1
    # Disable ICMP Redirect Acceptance
    net.ipv4.conf.all.accept_redirects = 0
    net.ipv4.conf.lo.accept_redirects = 0
    net.ipv4.conf.eth0.accept_redirects = 0
    net.ipv4.conf.default.accept_redirects = 0
    # Disables the magic-sysrq key
    kernel.sysrq = 0
    # Decrease the time default value for tcp_fin_timeout connection
    net.ipv4.tcp_fin_timeout = 15
    # Decrease the time default value for tcp_keepalive_time connection
    net.ipv4.tcp_keepalive_time = 1800
    # Turn off the tcp_window_scaling
    net.ipv4.tcp_window_scaling = 0
    # Turn off the tcp_sack
    net.ipv4.tcp_sack = 0
    # Turn off the tcp_timestamps
    net.ipv4.tcp_timestamps = 0
    # Enable TCP SYN Cookie Protection
    net.ipv4.tcp_syncookies = 1
    # Enable ignoring broadcasts request
    net.ipv4.icmp_echo_ignore_broadcasts = 1
    # Enable bad error message Protection
    net.ipv4.icmp_ignore_bogus_error_responses = 1
    # Log Spoofed Packets, Source Routed Packets, Redirect Packets
    net.ipv4.conf.all.log_martians = 1
    # Increases the size of the socket queue (effectively, q0).
    net.ipv4.tcp_max_syn_backlog = 1024
    # Increase the tcp-time-wait buckets pool size
    net.ipv4.tcp_max_tw_buckets = 1440000
    # Allowed local port range
    net.ipv4.ip_local_port_range = 16384 65536

    Run the following commands to enable the above changes without  rebooting the server.
    # /sbin/sysctl -p
    # sysctl -w net.ipv4.route.flush=1

    5) Hide Apache Information – You should hide apache banner information from being displayed so the attackers are not aware of what version of Apache version you are running and thus making it more difficult for them to exploit any system holes and thus making vulnerability scanners work harder and in some cases impossible without knowing banner information.
    How To:
    Modify /etc/httpd/conf/httpd.conf
    Change the ServerSignature line to: ServerSignature Off
    Change the ServerTokens line to: ServerTokens Prod

    Restart Apache: /sbin/service httpd restart

    6) Hide PHP Information – You should hide php banner information from being displayed so the attackers are not aware of what version of PHP version you are running and thus making it more difficult for them to exploit any system holes and thus making vulnerability scanners work harder and in some cases impossible without knowing banner information.
    How To:
    Modify php.ini
    Change the expose_php line to: expose_php=Off
    Notice: You may need to restart Apache.

    7) Disable PHP dangerous function
    How To:
    Locate your php.ini and then edit:
    1) whereis php.ini
    2) vi /usr/local/lib/php.ini
    Edit the line:
    disable_functions = “” to
    disable_functions =
    “symlink,shell_exec,exec,proc_close,proc_open,popen,system,dl,passthru,escapeshellarg,
    escapeshellcmd”

    3) restart httpd

    8 ) Remove Unwanted Services/daemons

    #chkconfig gpm off
    #chkconfig haldaemon off
    #chkconfig lm_sensors off
    #chkconfig mcstrans off
    #chkconfig multipathd off
    #chkconfig named off ( if you are not using named )
    #chkconfig netfs off
    #chkconfig netplugd off
    #chkconfig nscd off
    #chkconfig portmap off
    #chkconfig rdisc off
    #chkconfig syslauthd off
    #chkconfig sendmail off ( if you are using sendmail as mail server  , then its needed )
    #chkconfig smb off
    #chkconfig snmpd off  ( if you are using cacti , then its needed )
    #chkconfig snmptrapd off
    #chkconfig winbind off

    OPTIONAL

    Securing History It would be a good idea to secure .bash_history to avoid deletion or redirection to /dev/null from the user so he cant clean or delete his last typed commands into the system.
    How To:
    chattr +a .bash_history (append)
    chattr +i .bash_history

    I know its not completing here , but its just a start !!!!!

    I spent hours to make this doc , I am happy to include your suggestions and modification

     

  • 101 tricks to increase your Apache Web Server Performance

    There are no tricks or short cuts to tune Apache for maximum performance. As per my experience, it will take a minimum 10 to 15 days to tweak and force the webserver to provide maximum performance. There are also other bottle necks like bad coding, cross over scripting, improper indexed tables  and hardware issues. So if your webserver is slow then do check the above errors before blaming apache

    I would like to share some Apache performance tuning methods to boost your server performance for a minimum of 20 to 40%.

    Healthy body hosts a healthy life & mind , First and most important thing is to select a good hardware for your webserver .

    A webserver should have a strong CPU support , fast network card and plenty of Ram. Just like other services RAM is the most important spec and never compel a webserver to swap.Selecting the above things also depends on the number of websites hosted and the network traffic. If you are hosting a normal website with average traffic. I will suggest at least 4 GB ram

    Old is not always gold , If you need fastest webserver then go for latest softwares

    Select latest and stable Os and software’s to setup a perfect web server.  Most of the vendors will introduce significant performance improvements in new versions.
    Also update all the 3rd party software’s on your server to latest one to avoid vulnerabilities.

    Load less and perform more , Compile time configuration options

    1) Load the necessary modules only : –

    Apache server is a modular program and which giving a great control to admins to select the necessary modules in the installation time or later.

    We can compile apache in two ways , as static binary or as Dynamic Shared Object ( DSO) . Advantage of DSO over static is , if we compile apache as DSO (–enable so)  then we can add or drop modules with out disturbing the running apache using the the tool ” apxs “. But for static installation ,  you need to recompile the whole apache to include an additional module.  For more deatils visit :  LAMP server setup

    2) Select Appropriate MPM :-

    Apache is comes with a list of Multi process modules ( MPM ). MPM is responsible for binding to network ports on the machine, accepting requests, and dispatching children to handle the requests . We can choose appropriate MPM as per the requirements. To know more about apache mpm modules refer here :

    3) Process handling :-

    For example ,

    • StartServers 10
    • MinSpareServers 10
    • MaxSpareServers 25
    • ServerLimit 300
    • MaxClients 300
    • MaxRequestsPerChild 10000

    With the above configuration, we start with 10-25 processes and set a top limit of  300. Anything above this number will cause serious swapping and thrashing under a load.

    The StartServers directive sets the number of child server processes created on startup. As the number of processes is dynamically controlled depending on the load, there is usually little reason to adjust this parameter

    The MinSpareServers directive sets the desired minimum number of idle child server processes. An idle process is one which is not handling a request. If there are fewer than MinSpareServers idle, then the parent process creates new children at a maximum rate of 1 per second

    The  MaxSpareServers directive sets the desired maximum number of idle child server processes. An idle process is one which is not handling a request. If there are more than MaxSpareServers  idle, then the parent process will kill off the excess processes.

    Tuning of this parameter should only be necessary on very busy sites. Setting this parameter to a large number is almost always a bad idea. If you are trying to set the value lower than MinSpareServers, Apache will automatically adjust it to MinSpareServers + 1

    The MaxRequestPerChild directive sets the limit on the number of requests that an individual child server process will handle. After MaxRequestPerChild  requests, the child process will die. If  MaxRequestPerChild is 0, then the process will never expire

    Note that when more connections are attempted than there are workers, the connections are placed into a queue. The default queue size value is 511 and can be adjusted with the ListenBackLog directive. (The maximum length of the queue of pending connections. Generally no tuning is needed or desired, however on some systems it is desirable to increase this when under a TCP SYN flood attack)

    Requests vs. Client Connections

    1) KeepAlive

    Enable HTTP persistent connections to improve latency times and reduce server load significantly [25% of original load is not uncommon].

    prefork MPM:

    KeepAlive On
    KeepAliveTimeout 2
    MaxKeepAliveRequests 80

    worker MPM:

    KeepAlive On
    KeepAliveTimeout 15
    MaxKeepAliveRequests 80

    With the prefork MPM, it is recommended to set ‘KeepAlive’ to ‘Off’. Otherwise, a client will tie up an entire process for that span of time. Though in my experience, it is more useful to simply set the ‘KeepAliveTimeout’ value to something very low [2 seconds seems to be the ideal value]. This is not a problem with the worker MPM [thread-based].

    With the worker, the default 15 second timeout is setup to keep the connection open for the next page request; to better handle a client going from link to link. Check logs to see how long a client remains on each page before moving on to another link. Set value appropriately [do not set higher than 60 seconds].

    2) Timeout

    Lower the amount of time the server will wait before failing a request.

    Other RunTime Configurations : –

    1) Hostname Lookups

    If you are enabling hostname lookups then Apache will try to log host names instead of IP . This will give lots of additional work to apache , because to every request dns lookup to be completed before finishing the request. Hostnamelookup directive is set to default off prior with apache1.3. Leave it Off and use post-processing program such as logresolve to resolve IP addresses in Apache’s access logfiles. Logresolve is comes with Apache.

    2) FollowSymLinks and SymLinkIfOwnerMatch

    Wherever in your URL-space you do not have an Options FollowSymLinks, or you do have an Options SymLinksIfOwnerMatch Apache will have to issue extra system calls to check up on symlinks. One extra call per filename component. For example, if you had:

    DocumentRoot /www/htdocs
    <Directory />
    Options SymLinksIfOwnerMatch
    </Directory>

    and a request is made for the URI /index.html. Then Apache will perform lstat(2) on /www, /www/htdocs, and /www/htdocs/index.html. The results of these lstats are never cached, so they will occur on every single request. If you really desire the symlinks security checking you can do something like this:

    DocumentRoot /www/htdocs
    <Directory />
    Options FollowSymLinks
    </Directory>

    <Directory /www/htdocs>
    Options -FollowSymLinks +SymLinksIfOwnerMatch
    </Directory>

    This at least avoids the extra checks for the DocumentRoot path. Note that you’ll need to add similar sections if you have any Alias or RewriteRule paths outside of your document root. For highest performance, and no symlink protection, set FollowSymLinks everywhere, and never set SymLinksIfOwnerMatch

    3) Allow override

    If you are keeping the allow override settings as enable , then apache will search for .htaccess file in each directory . For example

    DocumentRoot /usr/local/apache/htdocs
    <Directory />
    AllowOverride all
    </Directory>

    If a request is made for URI /index.html, then Apache will attempt to open /.htaccess, /usr/.htaccess, /usr/local/.htaccess, /usr/local/apache/.htacces and /usr/local/apache/htdocs/.htaccess. These additional file system lookups add to the latency. If .htaccess is required for a particular directory, then enable it for that directory alone. If you don’t want .htaccess then use “ AllowOverride None “

    4) Negotiation

    If at all possible, avoid content-negotiation if you’re really interested in every last ounce of performance.

    Instead of using

    DirectoryIndex index

    Use a complete list of options:

    DirectoryIndex  index.cgi index.pl index.shtml index.html

    Also use the most common one as first value.

    You can read more about negotiation here : http://httpd.apache.org/docs/2.0/content-negotiation.html

    5) Extended Status

    If mod_status is included, make sure that directive ‘ExtendedStatus’ is set to ‘Off’. Otherwise, Apache will issue several extra time-related system calls on every request made.

    Extended Status Off

    Performance Boosting Modules

    1) mod_expires

    Include mod_expires for the ability to set expiration dates for specific content; utilizing the ‘If-Modified-Since’ header cache control sent by the user’s browser/proxy. Will save bandwidth and drastically speed up your site for [repeat] visitors.
    Note that this can also be implemented with mod_headers.

    2) mod_deflate

    With mod_deflate, you can compress HTML, text or XML files to approx. 20 – 30% of their original sizes, thus saving you server traffic

    LoadModule deflate_module modules/mod_deflate.so
    <Location />
    AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml application/x-javascript
    </Location>

    Here I have discussed only basic performance tweaks , we need to work closely with a webserver to tune its to get maximum performance .  To achieving maximum performance,  will depends on lots of other things like  how tweaked your mysql/DB server , how secure your server etc.  I am expecting your suggestions and advices on this.

    Reference : –  http://httpd.apache.org/docs/2.0/misc/perf-tuning.html

  • Vulnerable files in /tmp : Secure /tmp

    Some times web servers will show abnormal load or  we will get some abuse alert from our DC regarding packet flood from our server. Most of the cases some naughty “.pl”  files may be causing this issue.

    I have added a new post  in security section, for more details about linux server security click here :Linux Server Security

    Usually the following will help you to fix these type of hacks permanently .

    Phase I  ( Find the cause )

    check the currently running  process  using top command

    $ nice top -c ( usually you can see some “a.pl / b. pl ” files are running and eating most of the server resources )

    Find the exact location of the vulnerable  process

    $ lsof -p <process id >  | more

    Null root the file location and move the files to backup for further investigation

    for example its running from /tmp/abc
    $ mv /tmp/abc /tmp/abc_bkp
    $chmod -R 000  /tmp/abc_bkp
    $ ps aux | grep .pl

    $kill -9 < pid’s >

    This will stop to execute the vulnerable file again

    Phase II (Prevention is better than cure )

    1) Secure /tmp

    /tmp is a public place with lots of privileges and permissions for  the intruders.

    If you are concerned about your webserver security then /tmp should be secured.

    $dd if=/dev/zero of=/dev/tmpFS bs=1M count=1024

    $/sbin/mkfs.ext3 /dev/tmpFS

    Create a backup copy of your current /tmp drive:
    $ cp -rpf /tmp /tmpbackup

    $mount -o loop,noexec,nosuid,rw /dev/tmpFS /tmp
    $chmod 1777 /tmp

    Copy the old data:
    $ cp -Rpf /tmpbackup/* /tmp/
    $ rm -rf /tmpbackup

    Permanent Mounting :-
    Edit /etc/fstab and add this:
    /dev/tmpFS  /tmp  ext3   loop,nosuid,noexec,rw 0 0
    $  mount -o remount /tmp

    Secure /var/tmp:

    $ mv /var/tmp /var/tmp1
    $  ln -s /tmp /var/tmp

    Copy the old data back:
    $ cp /var/tmp1/* /tmp/
    $ rm -rf /var/tmp1

    secure /dev/shm
    Change the following in /etc/fstab
    “none /dev/shm tmpfs defaults,rw 0 0” to
    “none /dev/shm tmpfs defaults,nosuid,noexec,rw 0 0”

    Remount /dev/shm:
    $ mount -o remount /dev/shm

    Note that you should restart the services which are using /tmp for their proper working ( eg:- mysql )

    2) Compile php as cgi

    3) Install apache mod_security

    4) Remove shell access for all the users like apache,mysql,nagios,nobody

    5)  Disable php functions from php.ini

    I have added a detailed post in security section : Linux Server Security

  • LAMP server setup

    LAMP stands for Linux Apache ,Mysql and PHP . As the name implies we should keep the same order while installing the softwares.

    This doc is explaining  the compilation of apache and  php from latest source.  Here apache is compiled as DSO and php  as apache module.

    Install latest softwares

    wget http://apache.oss.eznetsols.org//httpd/httpd-2.2.19.tar.gz
    wget http://dev.mysql.com/get/Downloads/MySQL-5.5/MySQL-5.5.13-1.linux2.6.i386.tar/from/http://mirror.csclub.uwaterloo.ca/mysql/
    wget http://sg.php.net/get/php-5.2.17.tar.gz/from/this/mirror

    Here i have used the above version’s , you can use the necessary versions from the below sites.

    http://httpd.apache.org/download.cgi    |    http://dev.mysql.com/downloads   |      http://php.net/downloads.php

    ####  Install and compile apache as DSO ####

    DSO stands for dynamic shared object.  If we compile apache as dso then we can add additional modules with out disturbing the working/production server . Here we are using the apache tool ” apxs – stands for apache extended service ” to achieve this . I will explain more about DSO later in this doc.

    # yum install gcc gcc-c++

    # tar -zxf httpd-2.2.19.tar.gz

    cd httpd-2.2.19

    make clean

    # ./configure --prefix=/usr/local/apache --enable-shared=max --enable-module=rewrite --enable-module=so

    ( configure will help to customize the installation and also it will check and confirm all the necessary packages and dependencies are installed )
    make

    (make will compile the necessary modules )

    make install

    ( make install will install the binary to the directory mentioned in prefix )

    Once everything is completed with out any error’s , that fine. You have completed apache installation .

    All the necessary configuration files and binaries  are will be in /usr/local/apache

    /usr/local/apache/bin/apachectl -k  start

    After starting apache  just confirm its running fine.
    ps aux | grep httpd

    If everything is fine then try to browse your web server ip  . You will get a apache default page ” its works ! ”

    If you want to tune your apache server for better performance then try this : Apache performance tuning

    ####  Install   Mysql #####

    Download necessary package (rpm) from the mysql website and install using rpm command.

    #   tar -xf  Mysql-*

    rm -f  *-test-*.rpm ( remove the test rpm )

    rpm -ivh *

    (Install rest of the rpm’s )

    Once you complete the installation as above , setup a root password for mysql using the command

    start mysql using

    /etc/init.d/mysql start

    After restarting the mysql service , set a root password for security purpose.

    /usr/bin/mysqladmin -u root password  ‘new root password’

    Test and confirm mysql installation is perfect

    # mysql -u root -p

    > create database admin;

    >exit

    Check and the database is created in /var/lib/mysql , which is the default data directory.

    #### Install and Compile php as apache module ####

    yum install gd   gd-devel   libxml2-devel   libpng-devel  libjpeg-devel

    tar -zxf php-5.2.17.tar.gz

    cd php-5.2.17

    ./configure --prefix=/usr/local/php5 --with-apxs2=/usr/local/apache/bin/apxs --disable-debug --enable-xml --with-gd  --with-gettext  --with-mysql=/usr

    make

    make install

    cp php.ini-dist   /usr/local/lib/php.ini

    ( copy the sample php configuration to /usr/local/lib)

    ln -s /usr/local/lib/php.ini   /etc/php.ini

    Once everything completed fine , then the php binaries will be installed in the prefix directory

    You can verify the installation using

    /usr/local/php5/bin/php -v
    PHP 5.2.17 (cli) (built: Jun  8 2011 04:45:05)
    Copyright (c) 1997-2010 The PHP Group
    Zend Engine v2.2.0, Copyright (c) 1998-2010 Zend Technologies

    ##### Test and confirm web server is able to load a php pages #####

    1)  Confirm php module is added to apache

    # grep php /usr/local/apache/conf/httpd.conf

    LoadModule php5_module        modules/libphp5.so

    2) Find the DocumentRoot of  your  apache and create a test php file

    grep DocumentRoot /usr/local/apache/conf/httpd.conf
    DocumentRoot “/usr/local/apache/htdocs”

    vi /usr/local/apache/htdocs/index.php
    <?
    phpinfo();
    ?>

    3) Now we need to add the following two directives to apache conf

    # vi /usr/local/apache/conf/httpd.conf

    ( search for ” AddType” and add the following in the next line , The AddType directive maps the given filename extensions onto the specified content type  )

    AddType application/x-httpd-php  .php

    (Search for DirectoryIndex and replace the line with following )

    DirectoryIndex index.html  index.php

    Restart apache and check the webserver is loading this index.php file ,

    http://192.168.1.2/index.php

    Its should display the phpinfo page as follows

    Hope this will helps you to setup a Lamp server  🙂  , If you are looking for a well tuned webserver then check this : Apache performance tuning

     

     

     

  • Difference between rpm and yum

    rpm ( redhat package manager)
    is  a powerful Package Manager, which can be used to build, install, query, verify, update, and erase individual software packages.
    RPM is the default package manager in default but rpm is not  having the advantage of tracking dependencies .

    Install a package using rpm
    #rpm -ivh packagename.rpm

    i – install
    v – verbose
    h – display status hash bar

    install a package with out considering dependancy
    #rpm -ivh –nodep packagename.rpm

    remove a package
    #rpm -e packagename.rpm

    Show installed packages
    # rpm -qa

    Find the corresponding package of a binary
    # which ls
    /bin/ls

    # rpm -qf /bin/ls
    coreutils-5.97-23.el5_4.1

    To find the files installed by a specific package
    # rpm -ql coreutils-5.97-23.el5_4.1
    /bin/ls
    /usr/bin/unexpand
    /usr/bin/uniq

    yum ( Yellow Dog Update Modifier)
    is  an interactive, rpm based, package manager. It can automatically perform system updates, including dependency analysis and obsolete processing based on “repository” meta-
    data. It can also perform installation of new packages, removal of old packages and perform queries on the installed and/or available packages among many  other  commands/services
    (see below). yum is similar to other high level package managers like apt-get and smart

    If you want to install a package , first check whether the package is already installed or not

    # yum list | grep httpd
    # yum install httpd
    # yum remove httpd
    Or even we can install multiple packages in a single command
    # yum install httpd vsftpd
    # yum upgrade httpd
    # yum search | grep httpd
    # yum info httpd
    # yum clean
    to remove/clean yum cache
    # yum downgrade
    Will  try  and  downgrade  a  package from the version currently installed to the previously highest version
    # yum -y httpd
    Assume yes; assume that the answer to any question which would be asked is yes

    yum list :  List all available and installed packages
    yum list available :  List all packages in the yum repositories available to be installed
    yum list updates : List all packages with updates available in the yum repositories
    yum list recent :   List packages recently added into the repositories.
    yum clean all :   Runs yum clean packages and yum clean headers, yum clean metadata and yum clean dbcache as above.

    Yum can view the yum installation tips here install yum on CentOs 5