Cyber security - common vulnerabilities and their prevention methods which every aspiring developer should know about
Tags: cybersecurity, security
Published: 2022-10-23 15:28:20

There are many common vulnerabilities that are being exploited far too often by hackers on the internet - as they endeavor to abuse protected information by making it public: such as _passwords_ and associated _email addresses_, or _phone numbers_.
 
In order to execute these attacks, hackers repeatedly use methods such as **[brute force](https://en.wikipedia.org/wiki/Brute-force_attack)**, **[phishing](https://en.wikipedia.org/wiki/Phishing)**, **[SQL injection](https://en.wikipedia.org/wiki/SQL_injection)**, **[XSS](https://en.wikipedia.org/wiki/Cross-site_scripting)**, **[CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery)**, **[DDoS](https://en.wikipedia.org/wiki/Denial-of-service_attack)**, etc. _Broken access controls_, _unencrypted data transmission_, and _storing passwords in the database without hashing_ are also some major malpractices that invite evil hackers to be tempted to find a way into the system and annihilate it.

Old hashing algorithms such as [MD5](https://en.wikipedia.org/wiki/MD5) have already been cracked and therefore developers should aim for an updated algorithm such as [BCrypt](https://en.wikipedia.org/wiki/Bcrypt) or better.

_Phishing attacks_ are more commonly used to steal the login credentials of a user's email or another important service - as the user enters the password in an _exactly similar-looking_ page's password field, not knowing that this wasn't the actual website and his data was sent to the hacker's database. Sometimes hackers use **[ransomware](https://en.wikipedia.org/wiki/Ransomware)** to blackmail companies into paying a hefty amount out of fear of being sued or facing legal charges if sensible information about customers is leaked. Validating uploaded files is very necessary because they may contain **[malware](https://en.wikipedia.org/wiki/Malware)** or **[Trojans](https://en.wikipedia.org/wiki/Trojan_horse_(computing))**.

_Kali Linux_, although made for penetration testing purposes, is more commonly used by hackers as it offers lots of free tools to ameliorate their approach. [Web3](https://en.wikipedia.org/wiki/Web3), even being serverless, has its own set of [vulnerabilities](https://www.cloudflare.com/learning/insights-web3-security/). _Identity theft_ in mobile banking has also been a profitable scam for fraudulent con artists in the South Asian regions.
 
When _Canva_ got hacked in 2019, about _140 million users_ had their data breached. And on March of 2021, _CNA Financial_ had to pay more than _$40 million_ in ransom after being targeted for a cyberattack.

Recently, _Uber_ - the pioneer of ride-sharing companies was hacked by a teenager who used **[social engineering](https://en.wikipedia.org/wiki/Social_engineering_(security))** techniques to get access to a restricted workspace and manipulate it. Numerous such attacks are happening every day.
 
To avoid these sorts of online invasions, web developers must be aware of the methods hackers use and also know how to prevent them. The _Open Web Application Security Project [(OWASP)](https://owasp.org/)_ has documented the top security vulnerabilities that are frequent on the internet, along with measurements to take as a precaution for those frailties. I'm going to use Java to explain some security steps that must be in order.
 

## Some good practices for programmers can be
 

- to use code frameworks that initially come with security protocols
> [Express](https://en.wikipedia.org/wiki/Express.js) for _Node.js_, [Django](https://en.wikipedia.org/wiki/Django_(web_framework)) for _Python_, [Rails](https://en.wikipedia.org/wiki/Ruby_on_Rails) for _Ruby_, [Laravel](https://en.wikipedia.org/wiki/Laravel) for _PHP_, [ASP](https://en.wikipedia.org/wiki/Active_Server_Pages) for _C#_, and [Spring](https://en.wikipedia.org/wiki/Spring_Framework) for _Java_.

- to filter out suspicious texts from forms and field entries
```java
//AntiSamy is a Java component that can sanitize HTML/CSS to eliminate potentially malicious JavaScript.
antisamy.safe(request.getParameter("name"));
```

- to use prepared statements while writing SQL queries
```java
//a select query in SQL using prepared statements
PreparedStatement=Connection.prepareStatement("SELECT * FROM registerform WHERE name =? AND email =?", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
PreparedStatement.setString(1, username);
PreparedStatement.setString(2, email);
ResultSet=PreparedStatement.executeQuery();
```

## Again, backend or full-stack developers should also

- always encrypt or hash sensitive information
```java
//call an AES encryption class to encrypt text
encryptedText = aes.encrypt(text, key, salt);
```

- assign and validate a CSRF token with each form
```java
//add csrf-token in HTML
<INPUT TYPE="HIDDEN" NAME="csrf" VALUE="<%=generateCSRF.csrftoken()%>">
```
```java
//verify using backend
String token = request.getParameter("csrf");
		if (csrfverifier.verifycsrftoken(token)) {
//csrf-token verified
```

- check all the input data or uploaded files with server-side functionality
```java
//this code checks if a password follows the recommended variation and redirects back if otherwise
if(request.getParameter("password")==null || request.getParameter("password").length() < 8 || !Pattern.matches("^(?=.*[A-Za-z])(?=.*\\d)(?=.*[@$!%*#?&+=_,.-/(){}])[A-Za-z\\d@$!%*#?&+=_,.-/(){}]{8,}$", request.getParameter("password"))) {
		try
	{
			response.sendRedirect("signup.jsp");
			session.setAttribute("message", "Password must be at least 8 charecters long!<br>(with at least one letter, one number and one special charecter)");
			flag = 0;
			return;
		}catch(Exception ex) {
	}
```
```java
//this code checks if the uploaded file is an image and returns the image format
String format = "none";
ImageInputStream iis = ImageIO.createImageInputStream(new File(dir));
// get all currently registered readers that recognize the image format
Iterator<ImageReader> iterate = ImageIO.getImageReaders(iis);
		  if (!iterate.hasNext()) {
			  return format;
		  }
		  // get the first reader
		  ImageReader reader = iterate.next();
		  format = reader.getFormatName();
		  // close stream
		  iis.close();
return ".".concat(format);
```

- **not** rely on JavaScript for validation
```javascript
//this code only validates symbols in JavaScript, which can be bypassed easily
  var symbols = /[@$!%*#?&+=_,.-/(){}]/g;
  if(myInput.value.match(symbols)) {
	  symbol.classList.remove("invalid");
	  symbol.classList.add("valid");
  } else {
	  symbol.classList.remove("valid");
	  symbol.classList.add("invalid");
  }
```

It’s a good idea to include a _confirm authorization_ process to prevent brute force attacks in case of too many wrong login attempts. 
```java
//each time a user fails to enter the correct login details, increase the number of attempts for that user in the database by 1
attempts += 1;
//if a user fails five or more consecutive times to login, redirect the user to another page to verify identity
if (attempts > 4) {
response.sendRedirect("forgotyourpassword.jsp");
return;
}
//if a user correctly logs in, (before entering the wrong password for five or more consecutive times) set the number of incorrect attempts back to 0
attempts = 0;
```
Cookies should also have a _secure_, _HttpOnly_ and _same-site-strict_ attribute added to them to avoid **[cookie-hijacking](https://en.wikipedia.org/wiki/Session_hijacking)**.
```java
//a way to set cookies with attributes in Java
response.setHeader("Set-Cookie", "key=value; HttpOnly; SameSite=strict")
```

CMS-powered websites such as WordPress sites are also not out of the threat and require different security strategies which may be found in the form of security plugins. Not having an _HTTPS-secure_ padlock should be a clear red flag to visitors trying to access a website, as it indicates that the site doesn’t use a proper **_SSL/TLS_** protocol.
> Websites that use SSL/TLS will have a padlock icon next to their domain, and their URL will start with **_https://_**, while websites that don't use SSL will not have the padlock icon or may have a cancelled padlock icon and their URL will start with only **_http://_** and might also show a warning before you proceed to view the pages of that website.

It is advantageous to further use security enhancement functionalities provided by organizations like _OAuth_ and _Cloudflare_ to ensure a safer online infrastructure. Also, developers can use [reCaptcha](https://en.wikipedia.org/wiki/ReCAPTCHA) or [hCaptcha](https://handwiki.org/wiki/HCaptcha) to keep out unwanted programs.
> Websites that have captcha enabled, may show an _I'm not a robot_ pop-up or may be seen as a _protected by xyzCaptcha_ at the bottom-right corner of a page.

It must always be remembered that security should be the top priority while making critical web platforms that require online transactions or the storage of sensitive information. And that all other factors such as page speed, responsiveness, and UI should be down the list - after security. As security measures are placed, developers should try out their defense mechanisms by _penetration testing_ their website while using _sandbox_ credentials. Setting up _two-factor authentication_ and _Identity and Access Management_ should be taught to all the employees of a company.
> Two-factor authentication or **2FA** uses a changing-OTP prompt that only the user has access to by an app or device. Identity and Access Management can be used to deny some _Admin roles_ or _Root access_ to designers and developers, (working on the same Cloud Service or other workpspace) who shouldn't have those roles.

Moreover, most registration-based websites now urge their users to create a strong password that is hard to guess.
> A strong password consists of at least _8 charecters_ (with at least _one letter_, _one number_ and _one special charecter_).