DEV Community

Cover image for Cyber security - common vulnerabilities and their prevention methods which every aspiring developer should know about
Md Mazidul Haque Farabi
Md Mazidul Haque Farabi

Posted on

Cyber security - common vulnerabilities and their prevention methods which every aspiring developer should know about

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, phishing, SQL injection, XSS, CSRF, DDoS, 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 have already been cracked and therefore developers should aim for an updated algorithm such as 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 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 or Trojans.

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, even being serverless, has its own set of vulnerabilities. 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 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) 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 for Node.js, Django for Python, Rails for Ruby, Laravel for PHP, ASP for C#, and Spring for Java.

  • to filter out suspicious texts from forms and field entries

//AntiSamy is a Java component that can sanitize HTML/CSS to eliminate potentially malicious JavaScript.
antisamy.safe(request.getParameter("name"));
Enter fullscreen mode Exit fullscreen mode
  • to use prepared statements while writing SQL queries
//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();
Enter fullscreen mode Exit fullscreen mode

Again, backend or full-stack developers should also

  • always encrypt or hash sensitive information
//call an AES encryption class to encrypt text
encryptedText = aes.encrypt(text, key, salt);
Enter fullscreen mode Exit fullscreen mode
  • assign and validate a CSRF token with each form
//add csrf-token in HTML
<INPUT TYPE="HIDDEN" NAME="csrf" VALUE="<%=generateCSRF.csrftoken()%>">
Enter fullscreen mode Exit fullscreen mode
//verify using backend
String token = request.getParameter("csrf");
        if (csrfverifier.verifycsrftoken(token)) {
//csrf-token verified
Enter fullscreen mode Exit fullscreen mode
  • check all the input data or uploaded files with server-side functionality
//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) {
    }
Enter fullscreen mode Exit fullscreen mode
//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);
Enter fullscreen mode Exit fullscreen mode
  • not rely on JavaScript for validation
//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");
  }
Enter fullscreen mode Exit fullscreen mode

It’s a good idea to include a confirm authorization process to prevent brute force attacks in case of too many wrong login attempts.

//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;
Enter fullscreen mode Exit fullscreen mode

Cookies should also have a secure, HttpOnly and same-site-strict attribute added to them to avoid cookie-hijacking.

//a way to set cookies with attributes in Java
response.setHeader("Set-Cookie", "key=value; HttpOnly; SameSite=strict")
Enter fullscreen mode Exit fullscreen mode

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 or 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).

Top comments (1)

Collapse
 
vabro profile image
vala broumand

that was cool and i learnt a lot , i will appreciate that if you write about IDOR vulns <3