Hide Apache and PHP Version and Signatures in Ubuntu Linux

secure-apache
Apache Security

By default, your Apache web server (and PHP if it is installed) will indicate to clients the exact version of the Apache software which is running. This version information can be seen in the HTTP response header.

At times, such behaviour is undesirable as some administrators think that this will make their server more vulnerable to attacks since an attacker will immediately know what software versions are running and may then easily gather any available exploits. The simple fact is, even if your server software is masked, and attacker can try to determine the versions using other means, or they can just try to attack it using all the exploits they have.

Regardless of whatever your intention is, turning off these signatures will add an additional level of complexity (albeit minimal) to a potential attacker.

The tutorial below explains.

How to disable Apache signature

Open the relevant apache2.conf config file:

nano /etc/apache2/apache2.conf

At the end of the file, or at some other sensible location, add the following lines:

ServerTokens Prod
ServerSignature off

Restart your server for the new changes to take effect:

/etc/init.d/apache2 restart

How to disable PHP signature

Open the relevant php.ini config file:

nano /etc/php5/apache2/php.ini

Find the line that says:

expose_php = On

And change it to:

expose_php = Off

Finally restart your server again for the new changes to take effect:

/etc/init.d/apache2 restart

Now your server is a little bit more secure from attackers since it will only indicate that it is an Apache server with no clues as to the version number of the modules which are installed.

Note: Disabling the “Server: Apache” line in the HTTP response header altogether cannot be readily done using configurations (if at all), and will usually have to be done by recompiling the web server binaries. If you are running such a critical application that warrants such extreme measures, this task is left up to you. The bottom line is that if your software is kept up to date, it shouldn’t matter if an attacker knows what type of web server you are running.

Advertisements

Preventing XSS Attacks

xss-attacks
XSS Attacks

In my last post I explained you what an XSS attack mean in this post I will explain how can we prevent such attacks.

Preventing a webpage from an XSS attack should always be there in your mind.You can better create a function that prevents these attacks and call it everytime.Fortunately its very simple to prevent these attacks.You should never trust a user that he or she will always input proper data.There are millions of attackers sitting online just to find a prey.

Every bit of data must be validated on input and escaped on output. This is the golden rule of preventing XSS.

To prevent attacks we should follow data validation,data sanitization and output escaping.

Data Validation

It is a process where you validate data according to its requirement.Every piece of data must be validated.

Eg : When you want to validate a phone number you should only allow the user to enter numbers and discard strings or characters.And if you want to allow some special characters like “plus”,”brackets” or “dashes” as such characters are also an acceptable phone format you may use a regular expression for same.

<?php
// validates an Indian mobile number
if (preg_match('^((\\+91-?)|0)?[0-9]{10}$', $phone)) {
    echo $phone . " is valid format.";
}

Data Sanitization

Its a process where you clean up the data by removing any unwanted bits.

Eg : You may want to remove all HTML markups from the data.

<?php
// sanitize HTML from the comment
$comment = strip_tags($_POST["comment"]);

Output Escaping

When presenting the data as output via a browser the output should be escaped to protect its meaning.

<?php
// escape output sent to the browser
echo "You searched for: " . htmlspecialchars($_GET["query"]);

Summary

Never trust the data coming from users and take all required actions to prevent such attacks.You can prevent them with Data Validation and Sanitization and also by escaping Output to protect users.

 

 

 

Cross Site Scripting Attacks (XSS)

 

xss-attacks
XSS Attacks

An XSS attack is one of the top most tried out attacks on a PHP enabled system and your PHP script may not be immune.

This attack is made by injection of code via a web form. The code injected can be any malicious client-side code, such as JavaScript, VBScript, HTML, CSS, Flash, and others. The code is used to save harmful data on the server or perform a malicious action within the user’s browser.

Sadly , many developers fails to deliver a secure code thus open to attacks.Every programmer should consider such attacks and vulnerabilities and try to make the program or script free from getting attacked.

Example

Let me give you an example which will explain you how does such attacks happen.

Below is an index.php page with the following code.

<form method="post" action="save.php">
   <input type = "text" name = "name">
   <input type="submit" name="submit" value="Save">
</form>

In the above html code there is a simple form with a textbox and submit button.On click of the button the form is submitted to save.php for further processing.

A genuine user will fillup his/her name but an attacker can inject code instead of name.

Suppose on save.php just prints out the name.

   echo $_POST['name'];

Suppose instead of writing a plane name the attacker inputs <script>alert(‘HaHa You are attacked!!’);</script>.

If the scripts are not filtered the user will see the popup with message “HaHa You are attacked!! “.

Such JavaScript alert messages though are not harmful still are malicious.But think about what could happen in the JavaScript code was written to steal a user’s cookie and extract sensitive information from it? There are far worse XSS attacks than a simple alert() call.

Types of XSS Attacks

  1. Non-Persistent : The kind of attack shown in the above example falls under this category.It means attacks in which the code is not actually stored on the server but is rather presented to the user.
  2. Persistent : This attack is more dangerous one in which the code is actually injected into server.

Summary

Hopefully this article gave you a good explanation of what cross-site scripting attacks are.Never trust data coming from the user or from any other third party sources.In my next post I’ll explain how these attacks can be prevented.

Send SMS with PHP.

php-smsRecently I had a customer’s requirement to send an sms from his web portal.

The SMS gateway that he was using didn’t had that meaningful documentation.After planning on how do I connect to the SMS Gateway , I decided to use PHP cURL.

PHP cURL is a very efficient and powerful library that allows you to connect and communicate to different servers.For more information on cURL visit http://www.php.net//manual/en/book.curl.php .

The below code connects to the SMS gateway and then sends the message.

$url = "http://smsurl/sms1"; // URL of the SMS Gateway
$curl_connection = curl_init($url); //Initialize curl handle
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string); //Set the post variables like username , password , sms text etc.
$result = curl_exec($curl_connection); //run the whole process and return the response
curl_close($curl_connection);  //close the curl handle

In the above code first the connection to the SMS Gateway is made.
Then the variables like username,password etc is passed.
These parameters and url are given by the SMS Gateway Provider.
The URL is then executed and finally the connection with the Gateway is closed.

 

 

allows you to connect and communicate to many different types of servers.. – See more at: http://goyal1989.blogspot.in/2011/06/how-to-send-sms-to-mobile-using-php.html#sthash.RDvKIBms.dpuf
very impressive library that allows you to connect and communicate to many different types of servers – See more at: http://goyal1989.blogspot.in/2011/06/how-to-send-sms-to-mobile-using-php.html#sthash.RDvKIBms.dpuf
very impressive library that allows you to connect and communicate to many different types of servers – See more at: http://goyal1989.blogspot.in/2011/06/how-to-send-sms-to-mobile-using-php.html#sthash.RDvKIBms.dpuf

 

 

 

Run Scheduler without accessing Cron.

Cronless
Cronless Job

 

To run a Scheduler you need to add an entry in cron.Many times hosting provider limits cron usage and without an entry in cron the Scheduler wont run.

However there is an easier way out as show in the below steps.

If you are using SugarCRM you will have to follow step 3 else the first two steps will suffice.

 

  1. Setup a cronjob at a free cron provider like http://www.cronless.com or www.setcronjob.com .
  2. Point them to the cron.php to your SugarCRM directory. For example http://yourdomain/SugarCRM/cron.php
  3. Comment the code as shown below in cron.php and save it. You dont need to this if you are not using SugarCRM.
                   
                       //$sapi_type = php_sapi_name();
                     //if (substr($sapi_type, 0, 3) != 'cli') {
                        //    sugar_die("cron.php is CLI only.");
                    //}

                

Now when the cron.php is visited on scheduled time it will trigger the Scheduler.

Isn’t it an awesome way to execute the Scheduler.Thanks to the cron providers.

 

 

 

 

Text to Speech with PHP & Google API

text to speech

In this tutorial we will see how to convert text to speech using Google API.It’s damn easy and you may use it to integrate it with your video or use it for your website.

Google API that we will be using is :
http://translate.google.com/translate_tts?tl=en&q=

Here the q variable is empty we need to pass our text separated by a ‘+’ sign.

Eg : http://translate.google.com/translate_tts?tl=en&q=My+name+is+Mukta+Chourishi
Try this on latest browsers.

I have written the complete code below.Try it out.

<?php
if($_POST){
//get the text
$text = substr($_POST['txttext'], 0, 100);

//we are passing as a query string so encode it, space will become +
$text = urlencode($text);

//give a file name and path to store the file
$file  = 'filename';
$file = $file . ".mp3";

//now get the content from the Google API using file_get_contents
$mp3 = file_get_contents("http://translate.google.com/translate_tts?tl=en&q=$text");

//save the mp3 file to the path
file_put_contents($file, $mp3);
}
?>
<html>
<body>
<h2>Text to Speech PHP Script</h2>

<form action="" method="post">
Enter your text:
<textarea name="txttext" rows="5" cols="30"></textarea>
<br>
<input type="submit" name="submit" value="Convert">
</form>

<?php  if($_POST){?>

<!-- play the audio file using a player. Here I'm used a HTML5 player. You can use any player insted-->
<audio controls="controls" autoplay="autoplay">
<source src="<?php echo $file; ?>" type="audio/mp3" />
</audio>

<?php }?>

</body>
</html>

HTML to PDF

html to pdf

In this post , I will cover as how you convert an HTML page into PDF  file on a fly.

You basically need an fpdf  library to do the task.You may download it from http://www.fpdf.org/en/download.php

We will be using HTML2FPDF class of fpdf library.

Now let us see, how to convert a sample HTML page into a PDF file using HTML2FPDF Library.

Below is the code for the conversion.

<?php
 require('html2fpdf.php');
 $pdf=new HTML2FPDF();
 $pdf->AddPage();
 $fp = fopen("sample.html","r");
 $strContent = fread($fp, filesize("sample.html"));
 fclose($fp);
 $pdf->WriteHTML($strContent);
 $pdf->Output("sample.pdf");
 echo "PDF file is generated successfully!";
 ?>

Just that simple.You just need to include html2fpdf.php.Here I have passed sample.html page,the pdf generated will have same content of sample.html page,however in the pdf format.

PHP Best Practices

php

  1. Do friendship with the PHP manual.

    • If you are new to php its time to get thorough with the php manual.
    • The manual is incredible very well documented.It has very helpful comments following each article.
    • Before Googling up the problem just head straight into the manual.
  2. Turn on Error Reporting.

    • When you are developing an application it is recommended you turn on error reporting.
    • With error reporting enabled you will see errors that might not be visible otherwise.
    • However during production turn it off back as you might not wish to make your visitors look on those stupid errors.
  3. Try an IDE

    • IDE are very helpful tools for developing an app.
    • They saves a lot of time and make your development easier.
    • Some of the features provided by an IDE are
      • Code Completion. (IDE has intelligence.Understands what you want to write)
      • Syntax Highlightning.(Displays warnings & errors in your code)
      • Code Formatting.(Makes indentation of code possible).
  4. Follow DRY approach

    • DRY stands for “Don’t Repeat Yourself”.
    • Very clear by the name it means don’t have redundant code.
  5. Improve Readability by indenting your code and using white spaces.

    • If you don’t follow this principle your code might end up looking like a garbage.
    • Use it properly so that your code becomes more readable and easy to search.
  6. Don’t use PHP short tags (<?=?>)

    • Often programmers use short tags when accessing variables.
    • However it saves some space but is deprecated.
    • Better use full tags (<?php ?>).
  7. Use proper naming conventions for variables & functions.

    • Use proper , meaningful names while declaring variables,functions and classes.This will help you and a fellow co-worker to understand your code.
  8. Keep Commenting the code.

    • Aside from using white space and indentations to separate the code, you’ll also want to use inline comments to annotate your code. You’ll thank yourself later when you’re needing to go back and find something in the code, or if you just can’t remember what a certain function did. It’s also useful for anyone else who needs to look over your code.
  9. Try a PHP framework.

    • A framework will definitely teach you valuable programming concepts(separating logic from design etc).
    • PHP framework like CodeIgniter or CakePHP allows you to quickly create an application.
    • You can learn a lot about PHP using PHP frameworks. Continue reading