Application Security

Failure to restrict URL access

Photo by visuals on Unsplash

As with many other web application vulnerabilities, this one also aligns with access control rights. Applications use URL restrictions to prevent non-privileged users from accessing privileged data and resources. Every clickable button in a web application directs to a URL. A failure to restrict access vulnerability means that while clicking the button in the application would prevent access, directly using the URL into the browser allows access. When an application fails to restrict URL access, malicious actors can use “forced browsing” for an attack.

For example, a web application might have a URL structure that looks like this:

www.insecurewebapp.com/failure… the attackers know that the last item in that URL is the data type, they can try to take guesses at the URL structure for a specific type of sensitive information.

www.insecurewebapp.com/failure… the application has a failure to restrict URL access vulnerability, plugging that URL directly into the browser gives the attacker access.

Preventing Cross-Site Scripting Attacks

Photo by Pawel Czerwinski on Unsplash

Implementing HTTP security headers are an essential way to keep your site and your visitors safe from attacks and hackers. In a previous post, we dove into how the X-Frame-Options header and frame-ancestors directive can help combat click jacking. In today’s post, we want to go more in-depth with the X-XSS-Protection header, as well as the newer CSP Reflected-XSS directive, and how they can help prevent cross-site scripting (XSS) attacks.

What is X-XSS Protection?

The x-xss-protection the header is designed to enable the cross-site scripting (XSS) filter built into modern web browsers. This is usually enabled by default, but using it will enforce it. It is supported by Internet Explorer 8+, Chrome, and Safari. The recommended configuration is to set this header to the following value, which will enable the XSS protection and instruct the browser to block the response in the event that a malicious script has been inserted from user input, instead of sanitizing.

x-xss-protection: 1; mode=block

Cross-site Scripting (XSS)

Cross-site scripting, also known as XSS, is basically a way to inject code that will perform actions in the user’s browser on behalf of a website. Sometimes this is seen by the user and sometimes it can go totally unnoticed in the background. There are many different types of XSS vulnerabilities, below are two of the most common.

Reflective XSS: These are usually the most common types. Typically these are within HTTP query parameters and are used by server-side scripts to parse and display a page of results for the user.

Persistent XSS: These are when the data from the attacker is actually saved on the server and then displayed to the user, mimicking a normal page.

Other XSS vulnerabilities include DOM-based, stored server, reflected server, stored client, reflected client, and the subset of a client. Below is an example of how an XSS attack works.

X-XSS-Protection Directives

0 value disables the XSS Filter, as seen below.

x-xss-protection:0;

1 value enables the XSS Filter. If a cross-site scripting attack is detected, in order to stop the attack, the browser will sanitize the page.

x-xss-protection:1; mode=block

Enabling X-XSS Protection Header

The x-xss-protection the header is easy to implement and only requires a slight web server configuration change. You might also want to check to make sure you don’t already have the header enabled. Here is a couple of easy ways to quickly check.

  1. Open up the network tab in Chrome DevTools and if your site is using a security header it will show up on the Headers tab. You can see below that even we are using this security header on the KeyCDN blog.
  2. Another quick way to check your security headers is to quickly scan your site with a free tool, securityheaders.io, created by Scott Helme. This gives you a grade based on all of your security headers and you can see what you might be missing.

Enable in Nginx

add_header x-xss-protection "1; mode=block" always;

Enable in Apache

header always set x-xss-protection "1; mode=block"

Enable on IIS

To enable on IIS simply add it to your site’s Web.config file.

<httpProtocol>
    <customHeaders>
        <add name="X-XSS-Protection" value="1; mode=block" />
    </customHeaders>
</httpProtocol>
    .......
</system.webServer>

Reflected-XSS Directive

An important thing to keep in mind is that the X-XSS-Protection header is pretty much being replaced with the new Content Security Policy (CSP) Reflected-XSS directive. The reflected-xss directive instructs a user agent to activate or deactivate any heuristics used to filter or block reflected cross-site scripting attacks. Valid values are allowblock, and filter. This directive is not supported in the <meta> element.

However, it is not supported in all browsers yet, and so it is still recommended to use the x-xss-protection header. However, you could use both the x-xss-protection and reflected-xss together.

Summary

Hopefully, now you understand a little more about what the x-xss-protection HTTP response header does and how it can help prevent cross-site scripting (XSS) attacks. As seen above, this is very easy to implement. We use security headers on our websites and we encourage you to do the same. Together we can make the web a more secure place and help boost the security header usage numbers.

How to Secure Your PostgreSQL Database – 5 Tips

Photo by Caspar Camille Rubin on Unsplash

PostgreSQL may be the world’s most advanced open source database, but its 82 documented security vulnerabilities per the CVE database also make it highly exploitable. The popular object-relational database is considered superior to others regarding out-of-the-box security. However, proper measures are still required to protect web applications and underlying data. The following are 5 common ways to secure your PostgreSQL implementation from cyber attacks.

1. Do Not Use Trust Security.

When using Trust security, PostgreSQL assumes that anyone connected to the server is authorized to access the database with the database username specified (i.e., the DB trusts that they are who they say they are). To lock this down, edit your pg_hba.conf to use a non-trust authentication method like MD5. Additionally, template1 and PostgreSQL default databases should be revoked remote login access.

2. Use Hash-Based Column encryption for values that don’t need to be decrypted

Encryption methods such as AES are two-way—they can be decrypted—while hash-based encryption methods such as MD5 are one-way. For values that only need to be checked for a match, such as passwords, use one-way encryption for an added layer of security if table data is compromised.

3. Use Physical Separation to Isolate Datasets that Need to be Kept Apart

Using pg_hba and RBAC to control access to physically disparate databases ensures that data in two tables cannot be accessed/viewed simultaneously. Of course, this will break SQL joins, so only use in appropriate scenarios that require physical access separation during the life of a login session.

4. Consider Disabling Remote Access to PostgreSQL

This action alone eliminates a host of substantial attack vectors. Again, this can be set in the pg_hba.conf. If remote access to the database is required, SSH to the server housing the database and use a local connection afterward. Alternatively, you can set up tunnel access to PostgreSQL through SSH, effectively giving client machines access to remote databases as if they were local.9. Assign a Distinct Role for Each Application.

5. Use pg_hba.conf to Specify Which Hosts Can Use SSL-Encrypted and Unencrypted Connections

This can be accomplished by adding and removing the appropriate entries in the pg_hba.conf file. Generally speaking, all clients should be forced to connect with SSL by adding the necessary hostel entries. Using this model, all host entries should be removed (aside from localhost).

What are Web Shell Attacks? How to Protect Web Servers

Photo by Glenn Carstens-Peters on Unsplash

What is Web Shell?

A web shell is a malicious script written in popular web application languages – PHP, JSP, or ASP. They are installed on a web server operating system to facilitate remote administration. When weaponized, a web shell could allow threat actors to modify files and even access the root directory of the targeted web server. Both internet-facing and non-internet-facing servers (such as resource hosting servers) could fall victim to web shell attacks. Web shell attacks are a convenient cyber attack tactic because their execution doesn’t require additional programs. A communication channel can be simply achieved through the HTTP protocol in web browsers – this is why it’s so important to prefer HTTPS protocols.

How Do Web Shell Attacks Work?

Cyber attackers first locate servers with exposures vulnerable to web shell attacks through scanning software, such as Shodan.io. Shodan surfaces all internet-connected devices, including web servers and endpoints, that could be attack vectors for hidden web servers. Once a vulnerability is discovered, cyberattackers launch a web shell attack before installing a patch for the exposure. Exploiting vulnerability CVE-2020-5902 is an example of how fast cybercriminals use exposures that facilitate web shell injections. On June 30, 2020, F5 Networks released a patch for its Traffic Management User Interface (TMUI). The vulnerability facilitated Remote Code Execution (RCE) – a type of cyber attack involving the remote injection of malicious codes into a targeted system. After publishing the vulnerability on June 30, on July 4 (just four days later), an exploit code used to abuse the exposure was discovered.

CVE-2020-5902 exploit code – Source: Microsoft.com

The first stage of a server infection is to penetrate the outer layer of its ecosystem. This is usually achieved by pushing corrupted web shells through file upload web pages. After this, a Local File Include (LFI) vulnerability connects the web shell to a selected web application page. There are many other web shell injection strategies, including the detection and compromise of Exposed Admin Interfaces, Cross-Site Scripting (XSS), and SQL injections. After the web shell has been installed, a backdoor is naturally established, giving cybercriminals direct remote access to the compromised web server at any time. The efficiency of back door creation with web shells is why web shell attacks are primarily used as persistence mechanisms – establishing a long-term malicious internal network presence. Because of this, data breaches and ransomware injections rarely immediately follow a web shell attack. Hackers usually establish an access channel for a future attack or reconnaissance mission.

How to Block Web Shell Injections

It’s much easier to address the vulnerabilities that facilitate web shell injection than to intercept attacks. The following suggested controls and security tools should be used to locate and remediate all possible web shell injection points in your IT ecosystem.

1. Stay Updated with the Latest Security Patches

Security vulnerabilities are the most common pathways for web shell attacks. To block these entry points, keep all web applications, Content Management Systems, web server software, and third-party software updated with the latest security patches.

2. Disable Unnecessarily Web Server Functions

If a web shell is injected, its execution could be blocked if the functions that communicate with web server scripts are disabled in php.ini.Such web server functions include:

  • exec ()eval()shell _exec()assert()

3. Modify the Names of Sensitive Directories

To prevent the upload of corrupted image files, the directories that facilitate such uploads should ideally be completely disabled.If such an upload mechanism is necessary, the default names of these sensitive directories should be modified to make them harder to discover. Only privileged users should have permission to access these modifications to mitigate insider threat attacks.In addition to this, specify a filter for the permitted file types that can be uploaded to your web server.

4. Disable All Unnecessary WordPress Plugins

WordPress plugins are common attack vectors because anyone can develop them – even cybercriminals. To secure these vectors, only install plugins from trusted developers and uninstall all unnecessary plugins.

5. Implement a Firewall

A Web Application Firewall (WAF) is designed to prevent web shells and malicious payloads from being injected into an ecosystem by filtering all network traffic. Like antivirus software, keeping your firewall updated with the latest cybersecurity patches is important.

6. Implement File Integrity Monitoring

A file integrity monitoring solution will compare directory updates against the timestamps of clean directory scripts. If a discrepancy is detected, the requested installation on the code directory of the targeted web server will either be blocked or activate a security alert.

7. Monitor Your Attack Surface

An attack surface monitoring solution completes vulnerability scans of the entire attack surface – both internally and throughout the vendor network. This allows security teams to remediate exposure before cyber attackers discover and exploit them.

Authentication vs. Authorization: When To Use Which One

Photo by Markus Spiske on Unsplash

What’s the difference between authentication and authorization? Does it matter which you use — or do you need both? Are they the secure app’s chicken and egg problem? Let’s dive in.

What is authentication vs. authorization?

Generally, programmers have subconscious reasoning for applying security and access controls to their applications. If questioned, they’ll describe a simple set of AUTH codes that protect the app. Are you using authentication, authorization, or both? What’s the difference? Do these get mixed up because they both begin with “AUTH” and are sometimes referred to in the same way as short-hand? Maybe some of this mix comes from each seeming to allow you to address the other’s concerns if you stretch it a bit.

But authentication and authorization are two separate things. Even if they go hand-in-hand for many applications, it’s essential to know the difference. Once you fully grasp this, it’s clearer how to implement each securely and effectively.

Authentication vs. authorization example

I will use the application and actor of the terms to discuss authentication and authorization. My background is in web applications, so I think of people using my web application as visitors. But actor refers to any human or computer accessing your application in any manner. The term application means any piece of software. So we could be referring to a website visitor, a desktop application user, or a consumer querying your API.

Authentication refers to identifying the actor using your application. That’s it. All authentication is responsible for is saying, “I can identify this actor” or “this actor is unidentified.” The meaning and description of authentication are simple — that doesn’t mean the implementation is. For example, you might have a username and password, tokens, cookies, JWTs, or other ways to authenticate a user. But, after the process is complete, we either can identify the actor or we can’t.

Authorization refers to the permission to accomplish a task in your application. Tasks can be simple, like listing resources or seeing the details of an object. Advanced ones may create, update, or move data through a complex business workflow. Now, this is important: authorization does not require an authenticated actor. It just so happens that most authorization decisions are based on the specific permissions of an identified actor, but that isn’t a requirement. We’ll touch on this more later. But authorization is the mechanism that answers the question: “does this actor have permission to do this action.” Both authentication and authorization are necessary.

Let me share a real-world example.

A client had requested that their web application list the resources for any visitor. Multiple pages had this listing shown and an API. They then asked that if visitors click through to the detail page or request details over the API, the visitor must be authenticated.

Now, check for authenticated users at the top of the code that retrieves details. The other code needs no checks because it doesn’t matter if they’re logged in. (That is to say, whether the user is authenticated or not, either situation allows access.) This application has only two states: the user is authenticated or not.

Only two states are rarely the case. Furthermore, there’s hardly ever a time that an application matures without expanding its access controls beyond these two states. So, with this knowledge in place, I decided to implement authorization on all endpoints.

They implemented an authorization layer that simply returned valid on the endpoints that displayed lists of resources (including the API). A simple class reused on each endpoint always authorized access to the list of resources. Then, on the endpoint with the details, I created another class that returned true only when I had the visitor’s identity.

Then it happened: business requirements changed! About a week after the web page was launched, the business decided they wanted the lists of resources to be locked behind authentication. Guess what? Because I had used authentication correctly, to begin with, it was super simple. Next, I modified the authorization class to list resources to check for an identified visitor. Done! I imagine a scenario where lists require an authenticated user, but details need a user who has a subscription. If that happens, I’m ready! I’m prepared for future changes in the business, too.

What is the point?

Authentication determines an identity of an actor. Authorization decides if an actor has permission to take action. Your application, no matter how simple, should use both hand-in-hand. Authenticate actors when you must. Authorize actors, regardless of their identity, for every action.

What is OpenID Connect?

OpenID Connect extends the OAuth protocol to provide a dedicated identity and authentication layer that sits on top of the basic OAuth implementation. It adds some simple functionality that enables better support for the authentication use case of OAuth.

OAuth was not initially designed with authentication in mind; it was intended to be a means of delegating authorizations for specific resources between applications. However, many websites began customizing OAuth for use as an authentication mechanism. To achieve this, they typically requested read access to some basic user data and, if they were granted this access, assumed that the user authenticated themselves on the side of the OAuth provider.

These plain OAuth authentication mechanisms were far from ideal. For a start, the client application had no way of knowing when, where, or how the user was authenticated. As each of these implementations was a custom workaround of sorts, there was also no standard way of requesting user data for this purpose. To support OAuth properly, client applications would have to configure separate OAuth mechanisms for each provider, each with different endpoints, unique sets of scopes, and so on.

OpenID Connect solves a lot of these problems by adding standardized, identity-related features to make authentication via OAuth work in a more reliable and uniform way.

HTTP Verb Tampering

Photo by Christopher Gower on Unsplash

HTTP is the protocol that lets applications respond to requests and retrieve data. An HTTP verb is one of several actions the application can use when querying the server. Standard HTTP verbs include:

  • GET: retrieves data from specified source
  • HEAD: requests preview of specified resource
  • POST: submits entity to specified resource, such as editing data
  • PUT: transmits new data to the specified resource replacing the old information
  • DELETE: deletes the specified resource entirely

Most web applications use HTTP verbs to authenticate users and manage access privileges. However, malicious actors can bypass authentication and access controls to protect privileged information.

Hardening Your HTTP Security Headers Part 2

Photo by Maik Jonietz on Unsplash

4. X-Frame-Options

The x-frame-options header provides click jacking protection by not allowing iframes to load on your website. It is supported by IE 8+, Chrome 4.1+, Firefox 3.6.9+, Opera 10.5+, Safari 4+. Here is an example of what the header looks like:

x-frame-options: SAMEORIGIN

Enable in Nginx

add_header x-frame-options "SAMEORIGIN" always;

Enable in Apache

header always set x-frame-options "SAMEORIGIN"

5. Expect-CT

The expect-ct header prevents miss used certificates from being used by allowing websites to report and optionally enforce Certificate Transparency requirements. When this header is enabled the website is requesting the browser to verify whether or not the certificate appears in the public CT logs. Here is an example of what the header looks like:

expect-ct: max-age=604800, enforce, report-uri=”https://www.example.com/report”

Enable in Nginx

add_header expect-ct "max-age=604800, enforce, report-uri='https://www.example.com/report' always;

Enable in Apache

header always set expect-ct "max-age=604800, enforce, report-uri="https://www.example.com/report"

6. X-Content-Type-Options

The x-content-type-options header prevents Internet Explorer and Google Chrome from sniffing a response away from the declared content-type. This helps reduce the danger of drive-by downloads and helps treat the content the right way. Here is an example of what the header looks like:

x-content-type-options: nosniff

Enable in Nginx

add_header x-content-type-options "nosniff" always;

Enable in Apache

header always set x-content-type-options "nosniff"

7. Feature-Policy

The feature-policy header grants the ability to allow or deny browser features, whether in its own frame or content within an inline frame element (<iframe>). Here is an example of what the header looks like:

feature-policy: autoplay 'none'; camera 'none'

Enable in Nginx

add_header feature-policy "autoplay 'none'; camera 'none'" always;

Enable in Apache

header always set feature-policy "autoplay 'none'; camera 'none'"

Hardening Your HTTP Security Headers Part 1

Photo by Markus Spiske on Unsplash

There are a lot of things to consider when securing your website or web application, but a good place to start is to explore your HTTP security headers and ensure you are keeping up with best practices. In many cases, they are very easy to implement and only require a slight web server configuration change. HTTP security headers provide yet another layer of security by helping to mitigate attacks and security vulnerabilities. In this post, we will explore some of them to help you better understand their purpose and how to implement them.

What Are HTTP Security Headers?

Whenever a browser requests a page from a web server, the server responds with the content along with HTTP response headers. Some of these headers contain content metadata such as the content-encoding, cache-control, status error codes, etc.

Along with these are also HTTP security headers that tell your browser how to behave when handling your website’s content. For example, by using the strict-transport-security you can force the browser to communicate solely over HTTPS. There are six different HTTP security headers that we will explore below (in no particular order) that you should be aware of and we recommend implementing if possible.

1. Content Security Policy

The content-security-policy the header provides an additional layer of security. This policy helps prevent attacks such as Cross-Site Scripting (XSS) and other code injection attacks by defining content sources that are approved and thus allowing the browser to load them.

All major browsers currently offer full or partial support for content security policy. And it won’t break the delivery of the content if it does happen to be delivered to an older browser, it will simply not be executed.

There are many directives which you can use with content security policy. This example below allows scripts from both the current domain (defined by ‘self’) as well as google-analytics.com.

content-security-policy: script-src ‘self’ https://www.google-analytics.com

To explore all of the directives, and to see implementation on Nginx and Apache, make sure to check out our in-depth post on Content Security Policy.

2. X-XSS-Protection

The x-xss-protection the header is designed to enable the cross-site scripting (XSS) filter built into modern web browsers. This is usually enabled by default, but using it will enforce it. It is supported by Internet Explorer 8+, Chrome, and Safari. Here is an example of what the header looks like:

x-xss-protection: 1; mode=block

Enable in Nginx

add_header x-xss-protection “1; mode=block” always;

Enable in Apache

header always set x-xss-protection “1; mode=block”

3. HTTP Strict Transport Security (HSTS)

The strict-transport-security header is a security enhancement that restricts web browsers to access web servers solely over HTTPS. This ensures the connection cannot be established through an insecure HTTP connection which could be susceptible to attacks.

All major modern browsers currently support HTTP strict transport security except for Opera Mini and versions previous of Internet Explorer.

Here is an example of what the header looks like: You can include the max-age, subdomains, and preload.

strict-transport-security: max-age=31536000; includeSubDomains; preload

To read more about this header and see implementation on Nginx and Apache, make sure to check out our in-depth post on HTTP Strict Transport Security.

How to Detect Security Incidents Targeting Web Applications

Photo by Shamin Haky on Unsplash

The two most popular incident response frameworks come from NIST and SANS. While they differ in how they group and name the phases of incident response, both follow the same basic process. Based on this, here are six steps for incident handling in web application security: Prepare, Detect, Contain, Address, Recover, and Learn.

Step 1: Prepare

Preparation is by far the most essential stage of incident response. To secure your web assets, you first need to know what assets you have – and surprisingly, many organizations don’t even know that. Similarly, to ensure data security, you need to know your data, where it resides, who should have access to it, and how critical it is to your business.

Next, you need some kind of risk assessment process so you know what security events and impacts you are preparing for. Depending on your policies and requirements, this could involve formal threat modeling or a more informal approach to threat intelligence and identifying the most likely attack vectors.

In the preparation stage, you will likely identify weaknesses or blind spots you must address. For example, if you use a tool like Netsparker to run asset discovery followed by a vulnerability scan, you may find forgotten or unmaintained websites vulnerable to attack. These issues must be addressed to reduce your attack surface and close all the gaps, so you might call this Step 0: Prevent.

Whatever you put in your incident response plan, you need someone to implement it when things go wrong. Your incident response (IR) team will often simply be your IT security team, though large organizations may have a dedicated computer security incident response team (CSIRT). In either case, you must have specific team members on call and ready to follow established procedures.

Step 2: Detect

Web application attacks and data breaches are often only detected after many days or even months – or not detected at all, especially if they have no direct impact on operations. Careful logging and monitoring at the application level can help detect suspicious activity, such as repeated access attempts or unexpected user accounts being created. You can use a security information and event management (SIEM) solution to coordinate these monitoring efforts. Regular security testing using an accurate and up-to-date web vulnerability scanner is also vital to prevent attacks and find new vulnerabilities that attackers could already have exploited.

Step 3: Contain

After a web security incident is detected, your IR team needs to triage it and decide on the best action to minimize short-term impact and prevent minor issues from escalating into full-blown incidents. For example, suppose you detect a critical vulnerability in one of your business applications being actively exploited. In that case, the containment phase might involve setting up your web application firewall (WAF) to block this attack and prevent further damage. Advanced vulnerability scanners like Netsparker can even integrate with popular WAF platforms automatically.

Step 4: Address

Once the immediate threat is under control, you must fix or permanently address the issue. Continuing the example of your critical vulnerability, your security team would take the vulnerability report and create a fixed ticket for developers after deploying a WAF rule to block attacks in the containment phase. In the case of Netsparker, this process can also be automated to streamline communication and minimize the response time.

Recent global cyberattacks have served as a reminder that plugging security holes is often the easiest part. Advanced threat actors don’t do hit-and-run attacks but rather infiltrate target systems to maintain a stealthy and persistent presence. Eliminating the entry point starts a long and arduous process where your IT security and administrators check all potentially affected systems for malicious code, such as web shells, and then clean or rebuild them.

If you’ve had a data breach, you may also have legal obligations to take care of, such as GDPR-mandated notifications. Depending on the type of data and your jurisdiction and industry, you might need to report the incident to law enforcement or the relevant regulatory bodies and update this notification as more information becomes available.

Step 5: Recover

While most web application security incidents won’t require a full disaster recovery process, you need to have incident recovery procedures in place for every eventuality and every level of the application stack. In IT security, everything is connected, so a web application breach could be just one part of a broader attack that affects other systems or threatens business continuity. Regardless of the incident, the overriding goal of your recovery process should be to restore regular service while minimizing damage and disruption to business operations.

Step 6: Learn

Once the fire is out, you can move to post-incident activities such as a post-mortem or root cause analysis. This phase is probably the most important for improving long-term security since many web attacks are performed by reusing and adapting existing techniques. For example, fixing only a specific injection vulnerability without making the relevant part of the application code more secure may allow attackers to modify the attack payload slightly and breach the application again. By analyzing each incident and drawing the right lessons, you can return to step 1 – and be better prepared for the next attack.