Tuesday, September 21, 2021

A guide to OWASP’s secure coding

This blog was written by an independent guest blogger.

Modern organizations rely heavily on software and systems. Secure coding standards are significant, as they give some assurance that software installed on the organization’s system is protected from security flaws. These security standards, when used correctly, can avoid, identify, and remove loopholes that might jeopardize software integrity. Furthermore, whether developing software for portable gadgets, desktop systems, or servers, secure coding is critical for modern software development.

According to the Software Engineering Institute, software architecture or coding flaws are responsible for up to 90% of security problems. Hence, that's why safe coding techniques and guidelines are critical.

There are several approaches to create applications safely, like CERT Coding Standards, Common Weakness Enumeration, etc. But the OWASP (Open Web Application Security Project) offers meticulous secure coding criteria.

The technological measures related to minimizing the incidence of software bugs are the subject of the OWASP Checklist. Although web applications and their accompanying architecture are the primary emphases, most recommendations apply to any software deployment environment.

Input validation

Input validation ensures that only correctly formatted input enters a database and averts erroneous data from staying in the database and causing subsequent elements to fail.

Input validation must place as soon in the data stream as workable, ideally as quickly as the system gets input from the user.

The input is rigorously checked for any variables which lead the software to act strangely, which might cause threats like injection and cross-site scripting.

As per the OWASP Checklist, a few techniques to stay safe from input validations are;

  • Conduct all data validation on a trusted system
  • There should be a centralized input validation routine for the application
  • Verify that header values in both requests and responses contain only ASCII characters
  • Validate all input against a “white” list of allowed characters whenever possible
  • If any potentially hazardous characters must be allowed as input, be sure that you implement additional controls like output encoding, secure task specific APIs, and accounting to use that data throughout the application. Examples of common hazardous characters include: < > ” ' % ( ) & + ' “

Let's have a look at an example.

code snippet

Figure 1 Source: w3schools. JavaScript Validation Code Snippet

There is a mandatory field here: Name. Use w3schools to run this demo. You'll see an alert saying “Name must be filled out” if you ignore the field and hit submit. It is input validation utilizing JavaScript.

Output encoding

When the user inputs data, software must encode it before output. The process of output encoding entails converting special characters into a distinct but identical format which is no more hazardous to the destination translator. Several coding environments, such as .Net Core, include output encoding built-in.

As per the OWASP Checklist, a few techniques to use output encoding are;

  • Utilize a standard, tested routine for each type of outbound encoding
  • Contextually output encodes all data returned to the client that originated outside the application's trust boundary. HTML entity encoding is one example but does not work in all cases
  • Contextually sanitize all output of un-trusted data to queries for SQL, XML, and LDAP.

I am using the XSS alert script for output encoding/escaping as an example. Use freeformatter to run this demo.

XSS alert

Authentication and password management

Passwords are one of the least safe user authentication methods, yet they are also frequently used for web applications for safeguarding online data.

Authentication is the procedure of confirming that a person, organization, or site is who they say they are. Password management is a collection of guidelines and procedures that individuals must adopt while saving passwords to maintain the confidentiality and availability of assets.

OWASP recommends the following methods:

  • Implement monitoring to identify attacks against multiple user accounts, utilizing the same password.
  • Implement password hashing on a trusted system
  • Authentication failure responses should not indicate which part of the authentication data was incorrect. For example, instead of “Invalid username” or “Invalid password”, just use “Invalid username and/or password” for both. Error responses must be truly identical in both display and source code.
  • Enforce password length requirements established by policy or regulation.
  • Require authentication for all pages and resources, except those specifically intended to be public.
  • All administrative and account management functions must be at least as secure as the primary authentication mechanism.
  • Use Multi-Factor Authentication for highly sensitive or high-value transactional accounts.

As per the 2020 State of Password and Authentication Security Behaviors Report,

  • 50% of IT responders and 39% of users use the same password across organizational accounts.
  • 56% of people who use personal gadgets to access job information do not utilize two-factor authentication.

Session management

Session management is the procedure of safely processing many requests from a particular user or organization to a web-based application. HTTP uses it to interact between webpages and browsers, and a session is a collection of HTTP requests and actions started by a single person.

The PHP code in the following scenario creates a new session.

PHP code

Figure 2 Source: tutorialrepublic.com

According to the OWASP, the below are among the best practices.

  • Set the domain and path for cookies containing authenticated session identifiers to an appropriately restricted value for the site.
  • Logout functionality should be available from all pages protected by authorization.
  • Generate a new session identifier on any re-authentication.
  • Set the “secure” attribute for cookies transmitted over a TLS connection.
  • Session management controls should use well vetted algorithms that ensure sufficiently random session identifiers.
  • Establish a session inactivity timeout as short as possible, based on balancing risk and business functional requirements.

Access control

The practice of authorizing or refusing particular requests from a person, application, or procedure is known as access control. The process of giving and removing credentials is also part of access control. It is the essential security service for a good deal of software, and it is supported by the majority of many other security services as well.

A few access control approaches are listed below, from a diverse variety:

  • Restrict access to protected functions to only authorized users.
  • Deny all access if the application cannot access its security configuration information.
  • Use only trusted system objects, e.g., server-side session objects, for making access authorization decisions.
  • Create an Access Control Policy to document an application's business rules, data types, and access authorization criteria and processes so that access can be properly provisioned and controlled.
  • Restrict access to application data to only authorized users.

Identification and access management rely primarily on authentication and authorization. Imagine the following scenario.

Assume you need to get into one of your corporation's intranets networks to get some documents.

  • You could identify yourself by entering your login credentials in the login form.
  • You confirm your identity by entering in your matching password to gain accessibility to the page through authentication.
  • The access rights that your sysadmin assigns for you are known as authorization. When you've verified your identity and signed into the service, such access controls define what actions you could perform with the documents.

Cryptographic practices

Cryptographic practices are employed to maintain information confidentiality and integrity. Different cryptographic approaches, such as symmetric-key cryptography or public-key cryptography, can be deployed throughout the transfer of information and storage depending on the security demands and risks present.

For instance, cryptography in daily life refers to several scenarios in which cryptography provides a safe service, such as withdrawing money from a bank, safe web surfing, emails and data storage, and the usage of a cellular smartphone.

The following are a few of the cryptographic practices:

  • Cryptographic modules should fail securely.
  • Establish and utilize a policy and process for how cryptographic keys are managed.
  • Protect master secrets from unauthorized access.
  • All cryptographic functions used to protect secrets must be implemented on a trusted system.

Error handling and logging

Error handling refers to the processes used to deal with unexpected outcomes when a program or software is given unusual input. Error handling problems may expose many details about the victim, and it can find entry locations in the victim's characteristics.

Researchers from the University of Toronto discovered that even minor mistakes in error handling or failing to address problems in any way result in severe failures in distributed systems.

In the below instance, you can see a SQL query error, coupled with the website installation location to find a weak entry spot.

SQL error

Logging maintains a record of modifications to any application. For instance, a hacker searches for individuals who use the same credentials. Hackers can use these credentials to get access to all accounts. Since there may be no logging or tracking of such event occurrences, hackers can perform the same attack after several weeks with new credentials.

A few errors handling and logging approaches are listed below, from a diverse variety:

  • Use error handlers that do not display debugging or stack trace information.
  • Properly free allocated memory when error conditions occur.
  • Logging controls should support both the success and failure of specified security events.
  • Log all input validation failures.
  • Log all authentication attempts, especially failures.
  • Use a cryptographic hash function to validate log entry integrity.
  • Implement generic error messages and use custom error pages.

Data protection

Hackers can steal data in a variety of methods from online and web applications. Data thefts are proven occurrences that might cause the illicit entry to or exposure of critical, private, or other guarded information. So, data protection is the procedure of preventing essential information from being tampered with, compromised, or lost.

According to the OWASP, the below are among the best practices.

  • Remove unnecessary application system documentation as this can reveal useful information to attackers.
  • Disable auto-complete features on forms expected to contain sensitive information, including authentication.
  • Implement least privilege – restrict users to only the functionality, data, and system information required to perform their tasks.
  • Implement appropriate access controls for sensitive data stored on the server. That includes cached data, temporary files, and data accessible only by specific system users.

Communication security

Communication security is the practice of keeping illegal interceptors from obtaining understandable telecommunications while still sending information to the receivers.

Encryption secures all confidential data. TLS (Transport Layer Security) security protocol uses in combination with various encryption methods to secure communications.

Email hacking is a prevalent communication security breach. For example, in 2019 attackers hacked 773 million Outlook emails.

As per OWASP Checklist, a few techniques for communication security are:

  • Utilize a single standard TLS implementation that is configured appropriately.
  • Implement encryption for the transmission of all sensitive information.
  • Specify character encoding for all connections.
  • Filter parameters containing sensitive information from the HTTP referrer when linking to external sites.

System configuration

System configuration refers to the computer hardware, procedures, and distinct elements that make up the complete system and its limits. To gain illegal administration rights or information about the system, hackers frequently try to attack unfixed weaknesses or get exposure to standard accounts, unsecured file systems, and so on.

For system configurations, use the below criteria:

  • Restrict the web server, process, and service accounts to the least privileges possible.
  • Define which HTTP methods, Get or Post, the application will support and whether it will be handled differently in different pages in the application.
  • Implement an asset management system and register system components and software in it.
  • Remove test code or any functionality not intended for production before deployment.

Database security

The term database security relates to a set of technologies, policies, and procedures for ensuring and maintaining database Confidentiality, Integrity, and Availability (CIA) triads.

In 2020, per Microsoft, an internal customer support database containing anonymized user records was unintentionally published online. Around 250 million Microsoft customers' data was leaked publicly without password security.

Jeremiah Fowler, a security researcher, discovered a database belongs to Estee Lauder in February. The unprotected database, according to Fowler, compromised private data held in over 440 million client identities.

SQL injection is the common attack that exploit database security. For instance, as OR “”=”” is always TRUE, the SQL will retrieve all entries from the “Users” table.

SQL injection

Figure 3 source: w3schools

The following are some database security strategies:

  • Use secure credentials for database access.
  • Use stored procedures to abstract data access and allow for the removal of permissions to the base tables in the database.
  • Turn off all unnecessary database functionality.
  • Disable any default accounts that are not required to support business requirements.
  • Utilize input validation and output encoding and be sure to address meta characters. If these fail, do not run the database command.

File management

File management is all about protecting sensitive data from prying hackers by enforcing strict rights management policies and maintaining authorization.

System administrators can establish file limitations, privileges, and responsibilities using a file management system. That improves effectiveness as it involves giving roles to individuals and allowing varying kinds of accessibility to files.

Per ITRC and the US Department of Health and Human Services, the biggest data theft affected over 98.2 million people during the first quarter of 2021.

Below are some OWASP-provided strategies:

  • Limit the type of files that can be uploaded to only those needed types for business purposes.
  • Prevent or restrict the uploading of any file that may be interpreted by the webserver.
  • Never send the absolute file path to the client.
  • Scan user-uploaded files for viruses and malware.

Memory management

Memory management is techniques used to maintain software and information in memory and monitor their utilization and recover system memory whenever feasible.

Per Chief Security Architect, Schneider Electric;

“Memory-based attacks are happening all around us, and no one seems to want to talk about it because there hasn’t been a lot of defense against them. Virsec has an extraordinary and effective solution for defending against memory-based attacks. These guys are monsters in that.”

To effectively manage memory, you might perform the following measures:

  • Double-check that the buffer is as large as specified.
  • Properly free allocated memory upon the completion of functions and at all exit points.
  • Specifically, close resources; don’t rely on garbage collection. (e.g., connection objects, file handles, etc.)
  • Check buffer boundaries if calling the function in a loop and ensure there is no danger of writing past the allocated space.

Conclusion

Integrating the approaches mentioned above into your program and online applications deploying them into production will help protect you against several assaults that may ultimately breach the Confidentiality, Integrity, and Availability Triad.

The post A guide to OWASP’s secure coding appeared first on Cybersecurity Insiders.


September 22, 2021 at 09:09AM

0 comments:

Post a Comment