Security of internet applications
The issue of the security of internet applications, and hence e-commerce, SaaS services, web platforms and even simple websites based on CMS systems, is becoming more and more popular lately.
In recent years, we have seen many leakages of users personal data from various popular websites. These leaks are very dangerous in themselves, and the consequences are compounded by their scale – in the case of some Web Applications, we can talk about millions of user accounts. The data obtained by cybercriminals allows, among others, to take over the identity of users using them in criminal activities – the list of potential threats is very long, and placing the e-mail addresses of users of the hacked system on the SPAM mailing list is one of the less painful consequences).
The issue is so important and wide that the recently introduced GDPR directive allows for imposing huge fines on entrepreneurs who insufficiently secured their users’ data, and in the case of letting a leakage to happen, did not take appropriate steps to minimize the damage.
The reason for data leaks are usually vulnerabilities in the structure of applications, which are used by hackers to perform an attack. You can read about the most popular attacks, the vulnerabilities used to perform them, and how to protect your application to prevent them later in the article.
What is OWASP?
The Open Web Application Security Project is a non-profit open community dedicated to providing practical, cost-effective information about application security. The OWASP collects data about the most critical vulnerabilities that are commonly found in web applications and periodically publishes the Top 10 Web Application Security Risks (the last updated in 2017).
Let’s focus on secure develop site, this means how a developer should avoid the danger scenarios.
Injection flaws occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.
The type of arrangement Injection:
- SQL – injection queries into a SQL statement.
- NoSQL – influencing fo NoSQL Database
- OS – execution of shell tools with unsanitized Input
- LDAP – the execution of commands such a granting permissions to unauthorized queries.
We should have in mind that the Injection is at the top of the list because it is relatively easy to carry.
Let’s see how to prevent in Production.
We use prepare statement and parameter bindings and avoid RAW QUERY as much as possible.
The varies constraints help to prevent mass influence. The easier way is adding the LIMIT boundaries.
The application should validate incoming data before using it. Laravel has the huge validation abilities out of the box.
I recommend to use them. One of the useful PHP function is filter_var, which can be used for filter correctness of email address. By the way the Laravel
From the other side, we need to think about escaping all outgoing data before passing it to its final destination. Laravel is equipped for Blade template engine which uses a well-known PHP function to escaping data
Here, it’s worth to list the most useful PHP helpers:
Conclude the whole discussion we need to remember two rights:
- Sanitize all incoming data before using it.
- Escape all outgoing data before passing it to its final destination.
2. Broken Authentication and Session Management
Any application dealing with data faces the challenge of ensuring only the right parties ever have access to the data. Let’s imagine that we build Gateway platform where we collect customer banking details, shopping cart details and Taxes information or we build the health protection application keeping the healthy sensitive information of our users. Today every application have implemented Session management and authentication user. We are responsible for developing the security mechanism which will guard against unauthenticated access to users resources.
Laravel’s tools will help within. The framework offers basic tools called Laravel Auth. Auth covers session guard either on WEB or API level by choosing accoding driver to routing. The application authenticates users with username (email) and password where ale password are hash via bcrypt algorithm which is one way that means there is no way to restoring plain text for hashing password. Resetting password is available by e-mail resetting process.
Following by trends, many applications offer the authenticating via a third-party application, social media (Facebook, GitHub…) where Laravel delivery Socialize Package, easy and comfortable package supports all popular portals.
Building a well-protected API we are going to share users resources only for a trusted destination. We implement authenticated server by ourselves with Oauth2 access restriction implemented by Laravel Passport. This powerful package provides full range grants, an ability for defining scopes and authentication by short-lived Access Token.
We see that Laravel helps us in keeping our application secure but sometimes we would go further than we can implement additionally two-factor authentication via SMS or 2FA Google application. A good way for protection against
brute force attacks is limiting or increasingly delay failed login attempts. Eventually implementing weak-password checking will be a good approach but instead of use a required pattern for password implement the poor frequency password (check 10000 popular passwords). Thinking about a password, php7.2 supports Argon2 algorithm hashing password and from version 5.6 Laravel provides a driver for Argon2.
We shouldn’t forget about HTTPS which nowadays became standard. No one feels safety when sees the browser security alert on the login page.
The last one but not least is avoiding Client-Side Sessions (cookie driver). We can’t trust data which are out of our control because we never know that malicious user didn’t manipulate with them.
3. Sensitive Data Exposure (including General Data Protection Regulation)
Sensitive data deserves extra protection such as encryption at rest or in transit, as well as special precautions when exchanged with the browser.
There are to way leaking data outside.
The inside causes take part where the corporation hasn’t enough caution around credentials and staff management. Beyond staff management, there should be periodically Credential Audits to ensuring that any sensitive data didn’t leak. Manager or team leader is responsible to teach developers how to prevent for leaking data outside and how to safety sharing credentials (avoid email, slack, social media). The good approach is using VPN (Virtual Private Network) with LDAP with one enter place for workers. LDAP allows for efficient management for accesses and privileges the person incorporation. When we work in the first-security mindset cooperate each together. Engaging many workers with clear divide roles who is a developer, a code-reviewer, and a deployed person ensures find the security bugs in the first line before they go to production.
Thinking about protecting sensitive data we should focus on external breach also. We need to be very cautioned about poor and misconfiguration the database server. Weak protection server housing backup database could the reason leaking many sensitive data. To keeping protection under control we should encrypt data both in-transit and at rest. The server where the database is placed needs to be well encrypted. If we decide to move data Cloud, the security will be on cloud provider site. Choosing Amazon services we have sure that Amazon RDS encrypted instances use the industry standard AES-256. We can also encrypt in our site using Laravel encryption and remember never build your own cryptography.
4. XML External Entities (XXE)
This type of attack against an application which parses XML input. Similar to injection, the attack occurs when the application accepts XML directly and XML input contains a reference to an external entity which is processed by a weakly configured XML parser.
We still meet with XML functionality in many techniques like SOAP, RSS, SAML.
There is a couple of good practice helping protecting our application against XXE attacks. The most common for each work with incoming data is using server-side input validation, filtering, and sanitization ale input. Usually, we pretty sure how the XML should look like. For example, if we know that XML doesn’t need to load the external entity, to increase protection we disable this functionality on library level libxml_disable_entity_loader (libxml2).
Other good practice could use JSON instead XML if is possible. With working with SOAP provides update SOAP 1.2 or higher.
5. Broken Access Control
Behind the Access Control, we understand the restriction on what authenticated users are allowed to do. Some action can process only by superadmin because they have flow-on whole application. Attackers would access unauthorized functionality and data such as access other user’s accounts, view sensitive data, modify access roles.
In Broken Authentication and Session Management aspect, we dive into authentication issues. Laravel helps us with two authorization solutions, gates, and policies.
Gates determinate if a user is authorized to perform a given action. When application consists of functionalities either for regular user or administrator, the gates suit there well. The code will be readable and application parts clearly separated as you can see on code snippet below.
On the other hand, the one user’s resources cannot be visible for another user. The viewing of resources has to be limited to the owner. Here we can engage in Laravel Policies. The policy allows showing resources only owner and rejects a request if it detects unauthorized accessing attempt.
Policy duplicates to controller’s action.
Controller authorizes resources before sharing them.
6. Security Misconfiguration
Good security requires having a secure configuration defined and deployed the application. Is there always be? I think no really. Especially when our advisor is haste. Simple scenario: we ship a rough prototype to production with improperly configured permissions on cloud services, Next, we forget to disable rendering errors and in a result, the application exposes the error renders for users. Common problem, unnecessary features are enabled and installed, how? Some packages which we tried on scratch and later stop using but not uninstalled.
We can go step by step to build a good production environment. First, find helpful tools which can make deploy automatically. It could be Jenkins or Travis. A repeatable process that makes it fast and easy to deploy another environment that is properly locked down. We focus on keeping every application instance (Development, Staging, and Production) configurations as close as possible excluding credentials. The credentials should be defined in environment files (e.g. .env) and obvious never commit to the repository. The review of using packages will be helpful to keep stack tools up today. With ninth risk description, we focus closer on external tools.
7. Cross-Site Scripting (XSS)
XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation or escaping. The result of attack could be hijacked user sessions, deface web sites, redirect malicious sites.
XSS Attacks have two forms.
- Store XSS – Store XSS – the attacker inserts malicious payload to the database, and if the data will not properly excaped then the script executes immediately after the page loaded.
- Reflect XSS – the attack happens when unvalidated and unescaped user inputs are loaded along render page. For example, it happens when executing malicious HMTL in the victim’s browser by replacing the link in the email.
Preventing XSS attacks goes well if we follow below rules.
- Always validate input data
- Escaping data before presenting the user
- Sanitize user input before writing it to disk
A good practice is to use POST and PUT Method to persist data. Laravel delivers mechanism protecting the Cross-Site Request Forgery out of the box.
8. Insecure Deserialization
We often use the serialization objects process in our application because the native format usually offers more features than JSON or XML but we expose application for attacks against malicious users.
The deserialization process takes place with service like:
- Remote- and inter-process communication (RPC/IPC)
- Web services, Micro services,
- Message brokers (Pusher)
- Bazy danych, cache servery, file systems
- HTTP cookies, HTML form parameters
This attacks open opportunity to make denial-of-service, access control, and remote code execution attacks. The attacker changes the data content which processing causes modifying application logic and changing behavior application achieving by remote code execution.
There are few good approaches to limit this risk. We are maintainers codebase, thanks to that we allow accepting only trusted data for deserialization, explicitly defining whitelist the deserialization of classes. The privileges of deserialized code should be a constraint to part for application where it operates.
Logging incoming requests for JSON deserialization and monitoring exceptions helps up to proactively detect and block potential attacks.
9. Using Components With Known Vulnerabilities
We mentioned above about using external packages in our application. Nowadays, in composer era, every application cooperates with external code. There is a risk that one of the packages has vulnerabilities. This package could break down our application.
How to prevent against it?
Only obtain components from official sources over secure links. During the maintain application continuously we make inventory the versions of both client-side and server-side components. Then we will find unused dependencies which we will remove. Additionally, we will discover outdated packages which we will update.
We can automate the process of finding components with vulnerabilities by using a dedicated tool, sensiolabs/security-checker
The checker gives the report including components list with known vulnerabilities. Then we decide how to fix the issues.
10. Insufficient Logging & Monitoring
We can imagine that correct logging and monitoring system finds attackers before they’ve had the chance to actually infiltrate the system. Some attacks make deface the whole application but others can go simultaneously with regular requests. It is a place where CSP (content security policy) protects us against being victims. The content security policy could be created along the application goes up. Every new functionality requires some resources and has some potential weaknesses, which we patch if possible or monitoring by logging.
Laravel natively use Monolog Tool. This powerful tool is easy (helper, fasade), creates easy consumed format logs including many levels (DEBUG … NOTICE … EMERGENCY). Since version 5.6 Laravel was equipped in advance configurable log module.
The configuration file allows you to either configure your application’s log channels (slack, single) or aggregate multiple log channels into a single channel.
Our applications are exposed to many attacks. The above list doesn’t show all available potential risks. Those are the most occurrence in production applications. We need in mind these list as a ground of good security approach for creating an application.
It’s worth to follow the OWASP community announce to be up today with nowadays trends.
author: Kamil Piętka