• New PHP-CGI exploit: CVE-2012-1823, Badly affecting php scripts

    Recently some folks reported an interesting and nasty bug with php which will allow an intruder to view the source code and access the file systems.

    As per the update from php ( http://php.net ) , this bug has gone unnoticed for at least past 8 years .

    # Who all are affected ?

    If you are using Apache mod_cgi to run PHP you may be vulnerable to this bug.

    # Are you safe ?

    Just pass the argument “ ?-s “ to any of  your php pages and see.  Are you shocked ???
    If you pass the following arguments in your site , say example.com :

    1 ) http://example.com/index.php?-s
    Will dump your source code of the file index.php ( in simple words it will display the content of the file index.php )

    2) http://example.com/index.php?-dauto_prepend_file%3d/etc/passwd+-n
    Will display your /etc/passwd file !!!!!!!

    # Which all php versions are affected ?

    The PHP Group – PHP 5.3.11,PHP 5.3.10, 5.4.0 and  5.4.1

    # How to fix ?

    To fix this, upgrade your php to PHP 5.3.12 or PHP 5.4.2.

    # Any Patch ?

    Yes , php has provided  a temporary work around . I have tested and confirmed ( in php 5.3.10 )that  this will close the loop hole .
    Apply the following rewrite rule in your sites DocumentRoot .htaccess file .

     
             RewriteCond %{QUERY_STRING} ^(%2d|-)[^=]+$ [NC]
             RewriteRule ^(.*) $1? [L]

     

    # More Reference ?
    http://eindbazen.net/2012/05/php-cgi-advisory-cve-2012-1823/
    http://www.php.net/archive/2012.php#id2012-05-03-1

  • Hash Table Vulnerability or Hash Collision


    Description :-

    A hash table or hash map is a data structure that uses a hash function to map identifying values, known as keys , to their associated values . Thus, a hash table implements an associative array.  The various application servers store POST form data in hash tables, so that later they could be used during application development. If more than one key is hashed to a single hash using hash function, then it can lead to a problem called hash collision. Any application platform  that use a hash function  is easily affected by this vulnerability.

    A recent n.runs’ AG’s report explains that “If the language does not provide a randomized hash function or the application server does not recognize attacks using multi-collisions, an attacker can degenerate the hash table by sending lots of colliding keys. The algorithmic complexity of inserting n elements into the table then goes to O(n**2), making it possible to exhaust hours of CPU time using a single HTTP request” .

    This in turn results on DoS(Denial of Service) attacks. In general terms, DoS attacks are implemented by either forcing the targeted computer(s) to reset, or consuming its resources so that it can no longer provide its intended service or obstructing the communication media between the intended users and the victim so that they can no longer communicate adequately.

    How the attack works :-

    Here, three different keys namely wolf, tiger and elephant are hashed to the same hash 05 through hash function. This increases the complexity of processing a request which involves these key values and finally results in hash collisions.

    Let us now take a quick glance at how these hash table vulnerabilities affect PHP, JAVA and Tomcat..

    1) Apache Tomcat

    As the Apache Tomcat uses hash tables for storing various http request parameters, it is affected by the above mentioned issues.

    As a remedial measure, Tomcat’s Mark Thomas said: “Tomcat has implemented a work-around for this issue by providing a new option (maxParameterCount) to limit the number of parameters processed for a single request, This default limit is 10000: high enough to be unlikely to affect any application; low enough to mitigate the effects of the DoS.”

    The workaround is available in variants 7.0.23 and onwards, and 6.0.35 and later. However it is suggested to implement these measures and to upgrade to safer versions which are less prone to such attacks.

    2) Java

    Java uses the HashMap and Hashtable classes, which use the String.hashcode() hash function. Hence it could be affected by hash collision.

    3) PHP

    The case of PHP is not different too. It uses another hash function, which paves a reason for these attacks to happen in PHP as well. PHP is telling to tweak max_input_time and max_execution_time.  Also they released one bug fix ,but not for production servers.

    Refer : http://www.php.net/archive/2011.php#id2011-12-25-1

    For those working platforms, where fixes are not yet released, the suggested work arounds are:-

    1. Limit CPU time
      Limiting the processing time for a single request can help minimize the impact of malicious requests.

    2. Limit maximum POST size
      Limiting the maximum POST request size can reduce the number of possible predictable collisions, thus reducing the impact of an attack.

    3. Limit maximum request parameters
      Some servers offer the option to limit the number of parameters per request, which can also minimize impact.

    In short, the basic idea is to regulate the traffic of CPU utilization. thereby,at least you can keep a control on such attacks affecting your server before the respective fixes are released.

    Reference :-
    http://www.nruns.com/_downloads/advisory28122011.pdf

    http://www.kb.cert.org/vuls/id/903934

  • Resin SSL configuration in five steps !!

    Resin is a powerful web server which will run smoothly with java and html ( it will  support php also ).  Its very tough to get details about resin except from the www.caucho.com   site.  Hope that this doc will be helpful for the System admins who are working with  resin .  Its a simple  5 steps doc to setup ssl certificate for resin.

     

    1)  Create Key

    openssl  genrsa  -des3  -out  www.adminlgos.info.key  2048

    2)  Create CSR

    openssl req -new -key www.adminlogs.info.key -out www.adminlogs.info.csr

    3) Purchase the SSL using the above csr

    4) SSL configuration for resin web server
    ( We should save the ssl key , chainfile ( CA bundle ) and certificate in ”  /usr/local/resin/keys  ” )

    # vi /usr/local/resin/resin.conf

    <server id=”adminlogs” address=”192.168.1.2″>
    <http id=”adminlogs” address=”192.168.1.2″ port=”8080″/>
    <http id=”adminlogs” address=”192.168.1.2″ port=”8443″>
    <openssl>
    <certificate-file>keys/adminlogs.crt</certificate-file>
    <certificate-key-file>keys/adminlogs.key</certificate-key-file>
    <certificate-chain-file>keys/admin-inter.txt</certificate-chain-file>
    <password>password</password>
    </openssl>
    </http>
    </server>

    Terms : –
    certificate-file  : SSL certificate location
    certificate-key-file : SSL key file location
    certificate-chain-file : chain file location
    chain file  contains both ca bundle and ssl certificate
    For example you should create the file as follows , certificate first and then ca bundle.
    cat adminlogs.crt >> admin-inter.txt
    cat intermediate.txt >> admin-inter.txt

    password : Password given at the time of SSL Key creation in first step

    5) Restart resin

    /usr/local/resin/bin/resin-servers.sh restart

  • 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 !!!

     

  • Computer Threats

    I think most of the people are confused with these terms like computer virus,worms,Trojans,malware etc . I was also like that before reading a nice doc by kaspersky labs .  I would like to keep the same document  here in my blog , because i felt its very useful.

    What is the difference between a virus and a worm?

    A virus is a program that replicates, i.e. it spreads from file to file on your system and from PC to PC. In addition, it may be programmed to erase or damage data.

    Worms are generally considered to be a subset of viruses, but with certain key differences. A worm is a computer program that replicates, but does not infect other files. Instead, it installs itself once on a computer and then looks for a way to spread to other computers.

    In the case of a virus, the longer it goes undetected, the more infected files there will be on the computer. Worms, however, create a single instance of their code. Moreover, unlike a virus, a worm code is stand-alone. In other words, a worm is a separate file while a virus is a set of code which adds itself to existing files.

    What is a DoS attack? What is a DDoS attack?

    A Denial-of-Service (DoS) attack is designed to hinder or stop the normal functioning of a web site, server or other network resource. There are various ways for hackers to achieve this. One common method is to flood a server by sending it more requests than it is able to handle. This will make the server run slower than usual (and web pages will take much longer to open), and may crash the server completely (causing all websites on the server to go down).

    A distributed-Denial-of-Service (DDoS) attack differs only in the fact that the attack is conducted using multiple machines. The hacker typically uses one compromised machine as the ‘master’ and co-ordinates the attack across other, so-called ‘zombie’, machines. Both master and zombie machines are typically compromised by exploiting a vulnerability in an application on the computer, to install a Trojan or other piece of malicious code.

    What is PHISHING?

    Phishing is a very specific type of cybercrime designed to trick you into disclosing personal financial details. Cybercriminals create a fake website that looks just like a bank’s website (or any other web site where online financial transactions are conducted e.g. eBay). They then try to trick you into visiting this site and typing in your confidential data, such as your login, password or PIN. Typically, cybercriminals send out a large numbers of e-mails containing a hyperlink to the fake site.

    What is a ROOTKIT?

    This term describes a collection of programs used by a hacker to evade detection while trying to gain unauthorized access to a computer. The term originated in the Unix world, although it has since been applied to the techniques used by authors of Trojans that run under Microsoft® Windows® to conceal their actions. Rootkits have been used increasingly as a form of stealth to hide Trojan activity. When installed on the system, rootkits are not only invisible to users, but they are designed to escape detection of security software as well. The fact that many people log into their computers with administrator rights, rather than creating a separate account with restricted access, makes it easier for cybercriminals to install a rootkit.

    What is MALWARE?

    Malware – short for malicious software – is an umbrella term that refers to any software program deliberately created to perform an unauthorized and often harmful action. Viruses, backdoors, keyloggers, password stealers and other Trojan horse programs, Word and Excel macro viruses, boot sector viruses, script viruses (batch, windows shell, java, etc.) and Trojans, crimeware, spyware and adware are but a few examples of what is considered malware.

    It was once sufficient to call something a ‘virus’ or ‘Trojan horse’, but infection methods and vectors evolved and the terms virus and Trojan no longer provided a satisfactory definition for all the types of rogue programs that exist.

    What is a TROJAN and where did the name come from?

    The term Trojan refers to the wooden horse used by the Greeks to sneak inside the city of Troy and capture it. The classic definition of a Trojan is a program that poses as legitimate software but when launched will do something harmful. Trojans can’t spread by themselves, which is what distinguishes them from viruses and worms.

    Today, Trojans are typically installed secretly and deliver their malicious payload without your knowledge. Much of today’s crimeware is comprised of different types of Trojans, all of which are purpose-built to carry out a specific malicious function. The most common are Backdoor Trojans (often they include a keylogger), Trojan Spies, password stealing Trojans and Trojan Proxies that convert your computer into a spam distribution machine.

    What is a “DRIVE-BY DOWNLOAD”?

    In a drive-by download, your computer becomes infected just by visiting a website which contains malicious code. Cybercriminals search the Internet looking for vulnerable web servers that can be hacked. On such servers, cybercriminals can inject their malicious code (often in the form of malicious script) onto the web pages. If your operating system or one of your applications is un-patched, a malicious program is downloaded to your computer automatically when you access the infected web page.

    What is a KEYLOGGER?

    These are programs which record key presses (i.e. what a user types on the keyboard) and can be used by a hacker to obtain confidential data (login details, passwords, credit card numbers, PINs, etc.). Backdoor Trojans typically come with an integrated keylogger.

    What is ADWARE?

    Adware is the general term applied to programs that either launch advertisements (often pop-up banners) or re-direct search results to promotional web sites. Adware is often built into freeware or shareware programs: if you download a freeware program, the adware is installed on your system without your knowledge or consent. Sometimes a Trojan will secretly download an adware program from a web site and install it on your computer.

    Web browsers that aren’t up-to-date often contain vulnerabilities. Such browsers are vulnerable to hackers tools (often referred to as Browser Hijackers) that can download adware to your computer. Browser Hijackers may change browser settings, redirect incorrectly typed or incomplete URLs to a specific site, or change the default homepage. They may also redirect searches to pay-to-view (often pornographic) web sites.

    Typically, adware programs do not show themselves in the system in any way: there will be no listing under Start | Programs, no icons in the system tray and nothing in the task list. They seldom come with a de-installation procedure and attempts to remove them manually may cause the original carrier program to malfunction.

    What is a BOTNET?

    The term used for a network of computers controlled by cybercriminals using a Trojan or other malicious program.

    What is SPYWARE?

    As the name suggests, this is software that is designed to harvest your data and forward it to a third party without your consent or knowledge. Such programs may monitor key presses (‘keyloggers’), collect confidential information (passwords, credit card numbers, PIN numbers, etc.), harvest e-mail addresses or track browsing habits. In addition to all of this, spyware inevitably affects your computer’s performance.

    Reference :- http://www.kaspersky.com

  • 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

     

  • 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

  • Script to remove iframe injection

    iframe injections are common in unsecured webservers.

    Usually it will affect the whole domains which are hosted in the server.

    Using the following script you can remove the injected iframe from your webserver.

    =================
    find /home \( -name “*.php” -o -name “*.html” -o -iname “*.htm” \) -exec grep -l “a5i.ru” {} \; -exec sed -i “/”a5i.ru”/d” {} \;
    =================

    The above command will remove the line which contains the word ” a5i.ru ” . The command will search all the files under /home

    Its better to take the necessary backup before running the above scripts. ( Its worked fine in the test environment )

    The basic steps that is to be done to prevent this type of attack in future are

    1) Scan your server periodically and check for rootkits and vulnerablilities.

    2) Update all the 3rd party softwares to the latest version

    3) Make sure your ftp paswords are updated

    4) Make sure appropriate file permissions are used for every file and directory on the web server.

    5) Also make sure your local machine is free from viruses and trojans.