Pages

Monday, March 25, 2013

If you’re a sysadmin of Cpanel server, you might be aware of the JailShell. Its nothing but a User Shell with limited privileges. Users requesting for shell access to the webhosting server are provided with such shell instead of bash (Which provides root level privileges to users) .

Jailshell limits the users access to their home directory and keeps rest of the file system safe. Still there are chances of such users breaking into your system, so be sure of providing shell access to your servers. Jailshell mounts the filesystems of the users, who login via SSH under a directory called /home/virtfs. This contains users home directory and a false file system which links back to system directories like /bin, /usr etc.

NOTE: Be careful! Don’t remove any folder which is inside /home/virtfs,NEVER. As I said earlier, this folder links back to your systems root file system. You might end up screwing up your server if you attempt it.

So, we got to know that the Jailshell provides a restricted shell access to users and mounts the home directory temporarily at /home/virtfs.

Now, what if you still see the directories of different users mounted under /home/virtfs?

Right, this normally happens when users forget to logout properly from their SSH sessions. As a system admin, you’re responsible to unmount these directories safely.

How do I do that?

You can find all the virtfs mounts in /proc/mounts. Run cat /proc/mounts.

Now, its time to unmount them one by one. For that you have to take the second column of the output. Or write a simple for loop as follows.

Similarly, to check URL encoding, you can use SecFilterCheckURLEncoding; to control request body buffering, use SecRequestBodyAccess; to control what happens once the response body limit is reached, use SecResponseBodyLimitAction; and to specify the response body buffering limit, use SecResponseBodyLimit.

The full list of configuration directives, their usage and syntax is at available on modsecurity.org.

Rules — the basics

The mod_security rule engine is where gathered data is checked for any malicious or particular content. Rules are directives in the configuration file that decide what to do with the data parsed by the configuration directives. The rule language is a vast topic; we’ll only discuss basic rule-writing syntax, and rule directives to secure Web applications from all the attacks we’ve discussed so far.

The main directive used to create rules is SecRule, whose syntax is as follows:

SecRule VARIABLES OPERATOR [ ACTIONS]

VARIABLES: Specify which places to check in an HTTP transaction. mod_securitypreprocesses raw transaction data, making it easy for rules to focus on the logic of detection. Currently, variables are divided into request, server, and response variables, parsing flags and time variables. You can use multiple variables in a single rule with the | operator.

OPERATORS: Specify a regular expression, pattern or keyword to be checked in the variable(s). There are four types of operators: string-matching, numerical, validation and miscellaneousoperators. Operators always begin with a @ character, and are always followed by a space.

ACTIONS: Specify what to do if the rule evaluates to “true” — step on to another rule, display an error message, or any other task. Actions are divided into seven categories: disruptive,flow, metadata, variable, logging, special and miscellaneous actions.

Here is a simple example of a rule:

SecRule ARGS|REQUEST_HEADERS "@rx <script" id:101,msg: 'XSS

Attack', severity:ERROR,deny,status:404

Here, ARGS and REQUEST_HEADERS are variables (request parameters and request headers, respectively); @rx is the operator used to match a pattern in the variables (here, this pattern is<script); id, msg, severity, deny and status are all actions to be performed if the pattern is matched. This rule is used to avoid XSS attacks by checking for a <script pattern in the request parameters and header, and generates an 'XSS Attack' message. The id:101 is given to the rule; it will deny any matching request with a 404 status response.

Let’s look at another example, for more clarity:

SecRule ARGS:username "@streq admin" chain,deny

SecRule REMOTE_ADDR "!@streq 192.168.1.1"

This is an example of chaining two rules, and the transfer of control to another rule if the first rule holds true. The first rule checks for the string admin in the request’s username parameter. If found, the second rule will be activated, which denies all such requests that are not from the192.168.1.1 IP address. Thus, chaining rules help to create complex rules.

Now, writing filtering rules for each attack will be very cumbersome, and also prone to human error. Here, mod_security provides users with another directive, SecFilter. This looks for a keyword in the request. It will be applied to the first line of the request (the one that looks like GET /index.php?parameter=value HTTP/1.0). In case of POST requests, the body of the request will be searched too (provided request body buffering is enabled). All pattern matches are case-insensitive, by default. The syntax for SecFilter is SecFilter KEYWORD.

Rules against major attacks

Let’s look at some rules to prevent major attacks on Web applications.

SQL injection

Suppose you have an application that is vulnerable to SQL-injection attacks. An attacker could try to delete all records from a MySQL table, like this:

http://www.example.com/login.php?user=arpit';DELETE%20FROM%20users--

This can be prevented with the following directive:

SecFilter "delete[[:space:]]+from"

Whenever such a request is caught by the filter, something similar to the following code is logged to audit_log:

In response to the attack, SecFilterDefaultAction is applied (the request is denied, logged, and the attacker gets a 500 error). If you want a different action to take place (like, redirect the request to a HTML page that can provide customised warning content), you can specify this in the rule, as follows:

To prevent more SQL injection attacks, we can add a few other directives like:

SecFilter "insert[[:space:]]+into"

SecFilter "select.+from"

SecFilter "drop[[:space:]]table"

SecFilter create[[::space:]]+table

SecFilter update.+set.+=

SecFilter union.+select

SecFilter or.+1[[:space:]]*= [[:space:]]1

SecFilter '.+--

SecFilter xp_enumdsn

SecFilter xp_cmdshell

SecFilter xp_regread

SecFilter xp_regwrite

SecFilter xp_regdeletekey

The last five are particularly used for MS SQL server-specific injection attacks.

The only problem with SecFilter is that it scans the whole request instead of particular fields. Here, SecFilterSelective is useful; it allows you to choose exactly what to search. The syntax is:

SecFilterSelective LOCATION KEYWORD [ACTIONS]

Here, LOCATION decides which area of the request to be filtered. Hence, for SQL injection, you can also use:

SecFilterSelective SCRIPT_FILENAME "login.php" chain

SecFilterSelective ARG_user "!^[a-zA-Z0-9\.@!]{1,10}$"

The above code will validate the user parameter, and allow only the white-list of characters we have given. If for some reason you cannot take this approach, and must use a deny-what-is-badmethod, then at least remove single quotes ('), semicolons (;), dashes, hyphens (-), and parenthesis (()).

XSS attacks

For XSS attacks, we can use the following directives:

SecFilter "<(.|\n)+>"

SecFilter "<[[:space:]]*script"

SecFilter "<script"

SecFilter "<.+>"

And also, some additional filters like:

SecFilterSelective THE_REQUEST "<[^>]*meta*\"?[^>]*>"

SecFilterSelective THE_REQUEST "<[^>]*style*\"?[^>]*>"

SecFilterSelective THE_REQUEST "<[^>]*script*\"?[^>]*>"

SecFilterSelective THE_REQUEST "<[^>]*iframe*\"?[^>]*>"

SecFilterSelective THE_REQUEST "<[^>]*object*\"?[^>]*>"

SecFilterSelective THE_REQUEST "<[^>]*img*\"?[^>]*>"

SecFilterSelective THE_REQUEST "<[^>]*applet*\"?[^>]*>"

SecFilterSelective THE_REQUEST "<[^>]*form*\"?[^>]*>"

Though these filters will detect a large number of XSS attacks, they are not foolproof. Due to the multitude of different scripting languages, it is possible for an attacker to create many different methods for implementing an XSS attack that would bypass these filters. Hence, here it is advised that you also keep on adding your own filters.

To protect against an XSS attack done via PHP session cookies, you can use the following:

SecFilterSelective ARG_PHPSESSID "!^[0-9a-z]*$"

SecFilterSelective COOKIE_PHPSESSID "!^[0-9a-z]*$"

Command execution attacks

For command execution attacks, you can use the following directives:

SecFilter /etc/password

SecFilter /bin/ls

Here, the attacker may try to use a string like /bin/./sh to bypass the filter — butmod_security automatically reduces /./ to / and // to /, and also decodes URL-encoded characters. You can also use the white-list approach:

SecFilterSelective SCRIPT_FILENAME "directory.php" chain

SecFilterSelective ARG_dir "!^[a-zA-Z/_-\.0-9]+$"

This chained rule-set will only allow letters, numbers, underscore, dash, forward slash, and period in the dir parameter. Filtering out command directory names is also a good option, and can be done as follows:

Directory traversal attacks

For path/directory traversal attacks, the following directives are mostly used:

SecFilter "\.\./"

SecFilterSelective SCRIPT_FILENAME "/scripts/foo.cgi" chain

SecFilterSelective ARG_home "!^[a-zA-Z].{15,}\.txt"

The last two filters are chained, and will reject all parameters to the home argument that is a filename of more than 15 alpha characters, and that doesn’t have a .txt extension.

Similarly, you can prevent predictable resource location attacks also, and protect against sensitive file misuse, with two recommended solutions. First, remove files that are not intended for public viewing from all Web server-accessible directories. After this, you can create security filters to identify if someone probes for these files:

These two filters will deny access to both — unused, but commonly scanned for directories, and files with common backup extensions.

Web pages that are dynamically created by the directory-indexing function will have a title that starts with “Index of /”. We can use this as a signature, and add the following directives to catch and deny access to this data:

SecFilterScanOutput On

SecFilterSelective OUTPUT "\<title\>Index of /"

Information leakage

Here, we are introduced to the OUTPUT filtering capabilities of mod_security, which you should enable by adding SecFilterScanOutput On in the configuration file. We can easily set up a filter to watch for common database error messages being sent to the client, and then generate a generic 500 status code instead of the verbose message:

SecFilterScanOutput On

SecFilterSelective OUTPUT "An Error Has Occurred" status:500

SecFilterSelective OUTPUT "Fatal error:"

Output filtering can also be used to detect successful intrusions. These rules will monitor output, and detect typical keywords resulting from a command execution on the server.

SecFilterSelective OUTPUT "Volume Serial Number"

SecFilterSelective OUTPUT "Command completed"

SecFilterSelective OUTPUT "Bad command or filename"

SecFilterSelective OUTPUT "file(s) copied"

SecFilterSelective OUTPUT "Index of /cgi-bin/"

SecFilterSelective OUTPUT ".*uid\=\("

Secure file uploads

mod_security is capable of intercepting files uploaded through POST requests and multi-part/form-data encoding through PUT requests. It will always upload files to a temporary directory. You can choose the directory using the SecUploadDir directive:

SecUploadDir /tmp

It is better to choose a private directory for file storage, somewhere that only the Web server user account is allowed access. Otherwise, other server users may be able to access files uploaded through the Web server. You can choose to execute an external script to verify a file before it is allowed to go through to the application. The SecUploadApproveScript directive enables this, like the following example:

SecUploadApproveScript /usr/local/apache/bin/upload_verify.pl

RFI attacks

RFI attacks are generally easy to detect, with something like the following directive:

Often during the reconnaissance phase, attackers look for the Web server identity and version. Web servers typically send their identity with every HTTP response, in the Server header. Apache is particularly helpful here; it not only sends its name and full version, by default, but also allows server modules to append their versions. Here, you can confuse the attackers by using something like:

SecServerSignature "Microsoft-IIS/5.0"

PHP code cannot be injected directly, but it may be possible to have code recorded on disk to be executed later, using an LFI attack. The following rule will detect such an injection attempt, but will ignore XML documents, which use similar syntax:

SecRule ARGS "@rx <\?(?!xml)"

Logging

There are three places where, depending on the configuration, you may find mod_securitylogging information:

mod_security debug log: If enabled via the SecFilterDebugLevel andSecFilterDebugLog directives, it contains a large number of entries for every request processed. Each log entry is associated with a log level, which is a number from 0 (no messages at all) to 4 (maximum logging). You normally keep the debug log level at 0, and increase it only when you are debugging your rule set.

Apache error log: Some of the messages from the debug log will make it into the Apache error log (even if you set mod_security debug log level to 0). These are the messages that require an administrator’s attention, such as information about requests being rejected.

mod_security audit log: When audit logging is enabled (using the SecAuditEngine andSecAuditLog directives), mod_security can record each request (and its body, provided request body buffering is enabled) and the corresponding response headers.

Here is an example of an error message resulting from invalid content discovered in a cookie:

The message indicates that the request was rejected (“Access denied”) with an HTTP 500response because the content of the cookie sessionid contained content that matched the pattern !(^$|^[a-zA-Z0-9]+$). (The pattern allows a cookie to be empty, but if it is not, it must consist only of one or more letters and digits.)

Note: I once again stress that neither LFY nor myself are responsible for the misuse of the information given here. Any attack techniques described here are meant to give you the knowledge that you need to protect your own infrastructure. Please use the tools and techniques sensibly.

This article has just scratched the surface of mod_security. For more details on rule writing and other important directives, please refer to ModSecurity Handbook by Ivan Ristic — a must-read book for anyone interested in this topic.

We will deal with other ways to secure Apache in the next article. Always remember: Know hacking, but no hacking.

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.mysql> update user set password=PASSWORD("testpass") where User='root';ERROR 1046 (3D000): No database selectedmysql> show databases;

+--------------------+| Database |+--------------------+| information_schema || mysql || test |+--------------------+3 rows in set (0.13 sec)mysql> use mysql; Reading table information for completion of table and column namesYou can turn off this feature to get a quicker startup with -A

If you are getting “(13)Permission denied: /home/username/public_html/shop/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable, referer: http://www.yourdomain.com/shop/index.html” error in apache error logs file /usr/local/apache/logs/error_log as well as the site is showing 403 Forbidden Error.

Then first please check the permissions of your folder and .htaccess file because folder permission are most likely 755 and .htaccess permission 644. Permissions can be changed via FTP or SSH.

In case you still are getting the same problem, then it might be the Frontpage Extensions causing the problem. To fix:

* Login into your CPanel account* Click on “Frontpage Extensions” icon* Click on “Reinstall extensions” button beside your problem domain.*If you do not use any frontpage extensions, it’s good to uninstall this extension* Done. The “.htaccess pcfg_openfile: unable to check htaccess file” problem has been fixed.

** If you are not on CPanel hosting, please contact your system administrator to fix the problem. ***

Thursday, March 21, 2013

Usually there are many scripts available and they have different configuration file name using which we can use to update the configuration of website and it does include database username and password details.

If you have root or shell access you can locate the file under using below cmd, but make sure are are in the correct document root of the domain.find . -type f -name “config_file”i.efind . -type f -name “wp-config.php”

Check Repair & Optimize mysql Databases:

You can use either Mysqlcheck or Myisamchk to Check and/or Repair database tables. Mysqlcheck and Myisamchk are similar in purpose, there are some essential differences. Mysqlcheck as well as Myisamchk can Check, Repair and Analyze MyISAM tables. Mysqlcheck can also check InnoDB tables, so if database engine used for the databases is other than MyISAM, i.e InnoDB then try to use Mysqlcheck cmd.———————————————————————————————————++Check, Repair and Optimize Using mysqlcheck cmd:———————————————————————————————————

+Check, Repair and Optimize All tables in All Databases when you’re running a MySQL server on Linux.# mysqlcheck –auto-repair –check –optimize –all-databases

Change cPanel password from Cmd:

1) You can change the Cpanel password using below cmd as well as you need to Synchronize the password with your default FTP user, if you are unable to use the new password to connect to ftp account.# /scripts/chpass Username Password

Username : cPanel account usernamePassword : New password that to be set

Wednesday, March 20, 2013

Installing phpShield LoadersThe first thing we need to do is check a couple of PHP settings. The easiest way to do this is with a phpinfo file. If you don't know how to create a phpinfo file, you canNow that you have a php info file, upload it to your website's public_html directory and view it in your browser by typing http://www.yoursite.com/phpinfo.php in your address bar. You want to find/verify the following in your phpinfo.php file:Your PHP versionThread Safety is disabledenable_dl is set to onThe path to your extension_dirPath to your php.ini fileNow connect to your webserver using your favorite SSH client and login as root.Create a new working directory then change directories:

mkdir ~/phpshield cd ~/phpshield

Download the phpSHIELD loaders:

wget http://phpshield.com/loaders/phpshield.loaders.linux.zip

or if you have a 64 bit OS (most people will have a 32 bit OS so you will most likely use the code above)

wget http://phpshield.com/loaders/phpshield.loaders.linux-64.zip

Extract the loaders:

unzip phpshield.loaders.linux.zip

If you do a directory list: ls

you will see a bunch of files named phpshield.4.3.lin to phpshield.5.2.lin

. What we want to do here is find the phpshield file with the number that matches your PHP version. You can find your PHP version at the very top of your phpinfo file from earlier. Now we need to copy the appropriate phpshield loader file to your PHP extensions directory.

Sunday, March 10, 2013

How to enable/Disable cPanel webmail interface for a user account or in server.

Customer wants to enable only the HORDE webmail interface for his domain and disable the rest. Usually there are three (3) webmail clients (horde, squirrel mail, roundcube). However, I was advised to make sure that a specific customer does not see more than one specified. I enabled “AUTOLOAD” option in the webmail interface but he is not satisfied. He came back asking to allow only HORDE interface for his webmail. How should i do that?

Solution: Consider my domain name is “hemanth.com” and my account name is “hemanth“. Now follow the steps below.

Note: The option 0 is enable and 1 is disable. in above line only HORDE is enabled in the webmail and Roundcube and squirrel is disabled.

5) Then restart the cpanel service/etc/init.d/cpanel restart

Now login to your webmail and check for the option.

This will change the server wide for all the domains in the server:1) Login to your WHM2) Go to “Server Configuration”3) Click on “Tweak Settings”4) Select mail option.5) Turn off “Round Cube and Squirrel”6) Save it.====================Redirections

Saturday, March 9, 2013

Htop is an interactive and real time process monitoring application for Linux. It shows complete list of processes running and easy to use for normal tasks. We can interact with mouse those who love to play with mouse. You can scroll vertically to view the full process list, and scroll horizontally to view the full command line of the process.

The USE db_name statement tells MySQL to use the db_name database as the default (current) database for subsequent statements. The database remains the default until the end of the session or until another USE statement is issued:

Making a particular database current by means of the USE statement does not preclude you from accessing tables in other databases. The following example accesses the author table from the db1 database and the editor table from the db2 database:

Which SHOULD copy all the tables (*.frm, *.MYI, *.MYD) into the new directory - the script does require the DBI perl module though. To restore these backup files simply copy them back into your MySQL data directory.

This is my preferred method of backing up. This outputs the table structure and data in series of SQL commands stored in a text file. The simplified syntax is

mysqldump -u <username> -p <database> > file.sql

eg:

mysqldump -u user1 -p accounts > dump.sql

Restoring a DataBase from Dump:---------------------------------------

Sunday, March 3, 2013

The command rm -rf / deletes everything it possible can, including files on your hard drive and files on connected removable media devics. This command is more understandable if it’s broken down:

rm – Remove the following files.

-rf – Run rm recursively (delete all files and folders inside the specified folder) and force-remove all files without prompting you.

/ – Tells rm to start at the root directory, which contains all the files on your computer and all mounted media devices, including remote file shares and removable drives.

Linux will happily obey this command and delete everything without prompting you, so be careful when using it! The rm command can also be used in other dangerous ways – rm –rf ~ would delete all files in your home folder, while rm -rf .* would delete all your configuration files.

This short line defines a shell function that creates new copies of itself. The process continually replicates itself, and its copies continually replicate themselves, quickly taking up all your CPU time and memory. This can cause your computer to freeze. It’s basically a denial-of-service attack.

The command > /dev/sda line works similarly – it runs a command and sends the output of that command directly to your first hard drive, writing the data directly to the hard disk drive and damaging your file system.

command – Run a command (can be any command.)

> – Send the output of the command to the following location.

/dev/sda – Write the output of the command directly to the hard disk device.

/dev/null is another special location – moving something to /dev/null is the same thing as destroying it. Think of /dev/null as a black hole. Essentially, mv ~ /dev/null sends all your personal files into a black hole.

mv – Move the following file or directory to another location.

~ – Represents your entire home folder.

/dev/null – Move your home folder to /dev/null, destroying all your files and deleting the original copies.