PHP Security

PHP Security

Spread the love

PHP is as secure a language as any other programming language. It’s an open source server side scripting language that has various attributes and frameworks which requires programmers to write and engineer secure applications. 

In PHP there are several areas where security issues appear more frequently. Malicious users can exploit these vulnerabilities to gain sensitive information about your system or your users.

These vulnerabilities can include: 

  • Injection
  • Broken Authentication
  • Sensitive Data Exposure
  • Broken Access control
  • Cross Site Scripting (XSS)
  • Insecure Deserialization

PHP also relies on several third-party libraries which can have security vulnerabilities. If the application is using the vulnerable library version, then the application also may be vulnerable too.

Injection
A code injection happens when an attacker sends invalid data to the web application with the intention to make it do something that the application was not designed/programmed to do.
Perhaps the most common example around this security vulnerability is the SQL query consuming untrusted data. You can see one example below:

String query = “SELECT * FROM accounts WHERE custID = ‘” + request.getParameter(“id”) + “‘”;

This query can be made use of by calling up the web page executing it with the following URL: http://example.com/app/accountView?id=’ or ‘1’=’1 causing the return of all the rows stored on the database table.
The core of a code injection is the lack of validation of the data used by the web applications which means that this weakness can be present on almost any type of technology.

Following are the recommendations to prevent SQL injections

  • Use positive or “whitelist” server-side input validation.
  • For any residual dynamic queries, escape special characters using the specific escape syntax for that interpreter.
  • Use LIMIT and other SQL controls within queries to prevent mass disclosure of records in case of SQL injection.

Broken Authentication
A broken authentication can allow an attacker to use manual and/or automatic methods to try to gain control over any account they want in a system – or even worse – to gain complete control over the system. These threats can come in many forms. A web application contains a broken authentication threats if it:

  • Permits brute force or other automated threats.
  • Permits default, weak, or well-known common passwords.
  • Uses common text, encrypted, or weakly hashed passwords.
  • Has missing or ineffective multi-factor authentication.
  • Shown session IDs in the URL (e.g., URL rewriting).

Following are the recommended preventive measures.

  • Where the other possible way is the implementation of multi-factor authentication to prevent automated, credential stuffing, brute force, and stolen credential reuse threats.
  • Do not ship or make use of any default credentials, particularly for admin users.
  • Implement weak-password checks
  • Use a server-side, secure, built-in session manager that generates a new random session ID with high entropy after login. Session IDs should not be in the URL. Ids should also be securely stored and invalidated after logout, idle, and absolute timeouts.

Sensitive Data Exposure

Over the last few years, sensitive data exposure has been one of the most common threat around the world. Some sensitive data that needs protection is Credentials, Credit card numbers, Social Security Numbers, Medical information, Personally, identifiable information (PII), Other personal information. This threat is usually very hard to make use of; however, the consequences of a successful attack are dreadful. 

There are two types of data:

  1. Stored data – data at rest
  2. Transmitted data – data that is transmitted internally between servers, or to web browsers

Both types of data should be protected. When thinking about data in transit, one way to protect it on a website is by having an SSL certificate. Not encrypting sensitive data is the main reason why these attacks are still so widespread. 

Some of the ways to prevent data exposure are:

  • Do not store sensitive data unnecessarily.
  • Discard it as soon as possible or use PCI DSS compliant tokenization or even shorten. Data that is not retained cannot be stolen.
  • Make sure to encrypt all possible sensitive data at rest.
  • Ensure up-to-date and strong standardized algorithms, protocols, and keys are in place; use proper key management.
  • Disable caching for responses that contain sensitive data.
  • Store passwords using strong adaptive and salted hashing functions with a work factor (delay factor), such as bcrypt

Broken Access Control

Access controls are mainly designed to prevent users from acting outside their intended permissions, when threats exist in these controls, or there are no controls users can act outside of their intended permissions. This may help attackers to steal information from other users, modify data and perform actions as other users. Broken access controls can make applications at a high-risk for compromise, typically resulting in the impact of confidentiality and integrity of data. An adversary can steal information accessed by users of the application, exploit data by performing actions that various user roles can perform within the application, and in certain circumstances compromise the web server. 

Common access control vulnerabilities include:

  • Bypassing access control ensure by modifying the URL, internal application state, or the HTML page, or simply using a custom API attack tool
  • providing the primary key to be changed to another’s users record, permitting viewing or editing someone else’s account.
  • upgrading of privilege. 
  • Metadata exploitation, such as replaying or tampering with a JSON Web Token (JWT) access control token or a cookie or hidden field exploited to elevate privileges, or abusing JWT invalidation
  • CORS misconfiguration allows unauthorized API access.
  • Force browsing to authenticated pages as an unauthenticated user or to advanced pages as a standard user.  Entering API with missing access controls for POST, PUT and DELETE.

The technical recommendations to prevent broken access control are:

  • Except for public resources, deny by default.
  • Executing access control mechanisms once and reuse them throughout the application, including minimizing CORS usage.
  • Model access controls should enforce record ownership instead of accepting that the user can create, read, update, or delete any record.
  • Defuse web server directory listing and ensure file metadata (e.g. git) and backup files even if they are not present within web roots.
  • Maintain log access control failures, alert admins when appropriate (e.g. repeated failures).
  • Developers and QA staff should include functional access control units and integration tests.

Cross-Site Scripting (XSS)

Cross-Site Scripting (XSS) is the most used common singular security threat existing in web applications at large. XSS occurs when an attacker can inject a script, often JavaScript, into the output of a web application in such a way that it is executed in the client browser. This ordinarily happens by locating a means of breaking out of a data context in HTML into a scripting context – usually by injecting new HTML, JavaScript strings or CSS markup. HTML has no shortage of locations in which executable JavaScript can be injected and browsers have even managed to add more. The injection is sent to the web application via any means of input such as HTTP parameters.

Injected JavaScript can be used to accomplish quite a lot: stealing cookie and session information, performing HTTP requests with the user’s session, redirecting users to hostile websites, accessing and manipulating client-side persistent storage, performing complex calculations and returning results to an attacker’s server, attacking the browser or installing malware, leveraging control of the user interface via the DOM to perform a UI Redress (aka Clickjacking) attack, rewriting or manipulating in-browser applications, attacking browser extensions, and the list goes on…possibly forever.

Some preventive measures to reduce the chances of XSS attacks:

  • Using the frameworks that automatically escape XSS by design.
  • Escaping untrusted HTTP request data based on the context in the HTML output will resolve Reflected and Stored XSS vulnerabilities.
  • Put in context-sensitive encoding when modifying the browser document on the client side acts against DOM XSS. 
  • Allowing a content security policy (CSP) is a defense-in-depth mitigating control against XSS. 

Insecure Deserialization

There should be a way to transform the in-memory object into a stream of bytes which can be easily stored and shared. That is what the process of serialization is all about. When the game performs the serialization of an object, we say that the object is serialized.

The following function in php to perform the mutation of object to bytes is as follows:

$my_object = serialize($variable);

Deserialization is the opposite of serialization. In fact, it consists of converting the serialized data into an in-memory representation which the software can then manipulate. If we want to retrieve the state of the serialized character object, it needs to deserialize it first.

The following function in php to perform the mutation from bytes to object is as follows:

$my_bytes = unserialize($variable);

When a software deserializes user-maintained data without verification, we call it insecure deserialization. If the developer does not perform a verification before deserialization, the insecure deserialization will trigger the attacker’s code.

The best way to protect your web application from this type of risk is not to accept serialized objects from untrusted sources.

Following are some recommendations that you can try to implement:

  • Performing integrity checks such as digital signatures on any serialized objects to prevent hostile object creation or data tampering.
  • Impose strict type constraints during deserialization before object creation as the code typically expects a definable set of classes. 
  • Separating and running code that deserializes in low privilege environments when possible.
  • Logging  exceptions and failures, such as where the incoming type is not the expected type, or the deserialization throws exceptions.
  • Limiting or monitoring incoming and outgoing network connectivity from containers or servers that deserialize.
  • Monitoring deserialization, alerting if a user deserializes constantly.

Conclusion

Security vulnerabilities are a fact of life. While a security breach can be damaging to your business, there are plenty of ways you can protect your PHP sites and mitigate your risk that don’t require you to be a security genius with the right training, awareness, tools, and practices, you can safely run PHP applications today and in future .

Abison Varghese

10+ years experienced engineer with the ability to work collaboratively with clients and in-house agency teams to provide rapid, robust and client-acclaimed front-end and back-end user experience on the solutions.

54321
(1 vote. Average 5 of 5)
Leave a reply

Your email address will not be published. Required fields are marked *