0% found this document useful (0 votes)
58 views

Defensive Programming Developing A Web A

This document discusses developing secure web applications using defensive programming techniques. It begins by describing the anatomy of web development, including client-side and server-side scripting. Defensive programming is then introduced as a method to reduce vulnerabilities by validating inputs and handling exceptions. Common web application security risks are also overviewed based on the Open Web Application Security Project, including SQL injection, file inclusion, and cross-site scripting. The document argues that defensive coding practices can help eliminate security incidents and close system loopholes to prevent cybercriminal exploitation of web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Defensive Programming Developing A Web A

This document discusses developing secure web applications using defensive programming techniques. It begins by describing the anatomy of web development, including client-side and server-side scripting. Defensive programming is then introduced as a method to reduce vulnerabilities by validating inputs and handling exceptions. Common web application security risks are also overviewed based on the Open Web Application Security Project, including SQL injection, file inclusion, and cross-site scripting. The document argues that defensive coding practices can help eliminate security incidents and close system loopholes to prevent cybercriminal exploitation of web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Defensive programming: Developing a web

application with a secure coding practices


Cite as: AIP Conference Proceedings 2617, 050006 (2022); https://doi.org/10.1063/5.0119726
Published Online: 22 November 2022

Syarifah Bahiyah Rahayu, Arniyati Ahmad and Siti Hajar Zainal Rashid

AIP Conference Proceedings 2617, 050006 (2022); https://doi.org/10.1063/5.0119726 2617, 050006

© 2022 AIP Publishing LLC.


Defensive Programming: Developing a Web Application
with a Secure Coding Practices
Syarifah Bahiyah Rahayu1,2, a), Arniyati Ahmad2, b) and Siti Hajar Zainal Rashid2, c)
1
CyberSecurity & Digital Industrial Revolution Centre, National Defence University of Malaysia, 57000 Kuala
Lumpur, Malaysia
2
Faculty of Defence Science & Technology, National Defence University of Malaysia, 57000 Kuala Lumpur,
Malaysia
a)
Corresponding author: [email protected]
b)
[email protected]
c)
[email protected]

Abstract. Web Application Development has shown progressive and rapid growth using various techniques. Nonetheless,
web application security is a major component in web development that is often overlooked or not properly focused on.
Due to ad hoc existence and poor code written, most available web applications are vulnerable and desirable target for the
attackers. To alleviate this issue, the use of defensive programming basic technique allows the developers to develop secure
applications. Defensive programming includes validate output and correctly manages error messages. This avoids the
misuse of snippets and builds the program in a consistent way despite unpredictable inputs. The purpose of this paper is
twofold. Firstly, this paper discussed the development of a web application program using PHP as server-side scripting
exploiting defensive programming techniques to overwhelm web application vulnerabilities. Secondly, this paper examined
common vulnerabilities of web application risks refer to Open Web Application Security Project to validate the
effectiveness of defensive programming technique. The work presented in this paper shall be a fundamental guideline for
the development of secure web-based applications.

ANATOMY OF WEB DEVELOPMENT


Web application are relied upon by many services, as it constantly requires communicating with databases and
back-end services so that information could be presented to end user via a browser. Furthermore, most of the web
application have multiple of services running in a background so it can cope with user’s requirements and requests.
There are three components needed to build up a web application which are web browser, application server and
database server. For a dynamic web application, data need to be store in database. For database server, there are
multiple type of relational database management system (RDMS) available for managing data of the web application.
It includes MySQL, Oracle Database or Microsoft SQL Server. Different type of RDMS used need a different type of
configuration and programming skills. Moreover, in today technology, developers are allowing to choose lots of
available scripting language for a development of web application. However, developers usually need to focus only
two type of scripting language during development of web application.

Client-Side Scripting
This type of coding will be executed or interpreted in the browser for the end user interacting to it. Most popular
Client-Side scripting are:
• HTML (HyperText Markup Language)
• CSS (Cascading Style Script)
• JavaScript

The 3rd International Conference of Information & Communication Technology 2021 (ICICTM 2021)
AIP Conf. Proc. 2617, 050006-1–050006-9; https://doi.org/10.1063/5.0119726
Published by AIP Publishing. 978-0-7354-4255-9/$30.00

050006-1
Dynamic Server-Side Scripting
This scripting will be use as interstitial between client-side script and databases. It is not visible to the site’s visitor.
Below are examples of popular Server-Side Scripting:
 PHP – free redistribution and usually combine with MySQL database.
 ASP – Microsoft web server (IIS) Scripting language
 ASP.NET – Successor of ASP
 Phyton – general level of high-level programming language with free redistribution
A process of developing of web application is demanding in line with requirement of web applications in an
organization nowadays. In conjunction to that, developer need to deal with new type of scripting technology as well as
cyber threat that become more sophisticated each day. There are lot of processes need to be considered by the
development team during a development of web application. Figure 1 below shows an example of a web application’s
framework [1] . It clearly showed that there are lot of component involve creating a web application.

FIGURE 1. CheckMyCode web application architecture

A developer needs to write thousands line of codes in different services of application and to complete the client’s
project within a given time therefore they are tending to copy few coding functions from the internet. However, some
of those coding functions were not updated and could comprises vulnerabilities. Therefore, this action will create a
loophole to the developed web application, and then give opportunities for hackers to perform cyber-attack. Poor
written code can impact the safe arrival of the web application.
This paper is organized as follows. The first section will briefly introduce the concept of Defensive Programming.
Next section will present some of the top web application security risk. This is followed by the methodology section
applied on this paper. Moreover, this paper also explains the most top 10 web application vulnerabilities and methods
to secure it as well as discussing and demonstrating the implementation of security risk aware during the development
of web application specifically for web application that are developed using PHP server-side scripting language.
Conclusion and future works follow in the last section, respectively.

DEFENSIVE PROGRAMMING
Best coding practices will ease coding maintenance, which reducing code defects. For instance, proper coding
conventions may detect immediately any anomalies [2] in coding. These practices reduce application vulnerabilities,

050006-2
such as unexpected bugs. Consequently, it caused web application disruption due to invalid or unexpected outputs and
unintended behaviors. Therefore, web developers should apply defensive programming.
Defensive programming is a mechanism to create a trust zone [3] where it reduces software vulnerabilities [4] and
protects its source code [5]. Common defensive programming techniques are assertions and exception handlers. The
assertion checks a condition based on specified constraints, and the exception handler catches unexpected events while
the application is running. Thus, defensive programming may eliminate incidents in cybersecurity [6]. For instance,
validation of input data, users, and files is essential to reduce system exploitation, security vulnerability, and data
violation. The incidents may open a window for cybercriminal, in which have disastrous effects on security.

WEB APPLICATION SECURITY TREND


Cybercriminals are eyeing potential web applications to become their next victims. Average daily web attacks from
Oct 2019 to Oct 2020 is at least 12 million attack per day. According to Technologies [7], in October 2019, the spike
was high due to SSH worms for cryptomining. Then, the highest peak web application attack was in December 2019
due to few factors such as COVID-19 epidemic and companies’ annual closure While other days the attacks are ups
and downs like market stocks. The lowest attack was in March 2020 when WHO (World Health Organization)
announced COVID-19 as pandemic, most countries are lockdown. After few months, in May 2020, remote work
became a new norm. People are using internet for their daily work and leisure; some may trade security with ease of
use and access. Consequently, the web attacks have increased. In August 2020, the DDoS attack has been spread where
it demands ransom in bitcoin. Subsequently, in September 2020 there are more than 33 million web application attacks
such SQL Injection, Local File Inclusion, and Cross-Site Scripting.
Web applications vulnerabilities are categorized in term of i) technical; ii) configurational; and iii) security [8]. This
paper is addressing the security vulnerabilities. The security vulnerabilities are determined on its severity impact: high,
medium, and low. Open Web Application Security Project [9] states the most common vulnerabilities of web
application risks.
Other application security vulnerabilities are including insecure deserialization and insufficient logging &
monitoring. Thus, for cybercriminals to exploit the web application, they must be able to connect to the computer
system. Therefore, any system loopholes must be closed. The next session discusses on the methods to protect web
applications.

SCOPE OF GUIDELINE.
There are various types of controls that could be implemented to protect the web application, therefore reduce the
risk of specific security vulnerability. The type of controls that should be taken includes:
a) Physical Controls. Examples include computer lock, alarm system.
b) Technical Controls. Examples include antivirus software, firewalls, implementation of Intrusion Prevention
System (IPS)
c) Operational Controls. Dealing with human behavior, such as computer security engineer having an
awareness to update antivirus software installed in each of the employee’s computer.
Serious security breaches would be happened if these controls is not properly addressed [10]. All these types of
controls highly dependable to a collaboration of variety of hardware, software, and human behavior. This include
development team which are assigned and responsible to develop a secure web-based application furthermore mitigate
the risk associated to the web application security.
This research paper will discuss on the development of web application program that using PHP as a server-side
scripting. PHP has become a dominant server-side scripting language used for dynamic web content. Compared to
other server-side scripting language such as ASP.NET, Ruby, Java, ColdFusion, etc., PHP is the most commonly used
language for server-side web development, representing almost 79.0% of all web application program [11–14]. The
increasing utilization of PHP framework for web application has made PHP more attractive to both development team
and hackers. Furthermore, current PHP web application have been continuously reported of having security
vulnerabilities despite its popularity.
Some of most publicized data breach were resulting from a successful attacks against web application, and the
reason behind it mostly due to human error or negligence [15]. Writing a secure PHP script helps to mitigate the attack
attempt as the it should behave as predictable despite unexpected inputs or user action. This paper will focus on
mitigation of injection such as XSS injection attack and SQL injection attack, right error handling, bot attacks and

050006-3
misconfiguration while writing PHP code. According to OWASP Top Ten documentation [9], this security risks is
among top ten web application security risk.

WEB APPLICATION COMPONENTS’ VULNERABILITIES


In every three to five years, the OWASP Top 10 web vulnerabilities will be revised and published. The latest of
2020 version of Top 10 OWASP vulnerabilities as listed in Table 1. While in Figure 2 shows components of the
backend architecture of web, consists of web server, web application server and database server. There are ten ways
to secure a web application which includes:
a) Input Validation
b) Authentication
c) Authorization
d) Configuration Management
e) Sensitive Data
f) Session Management
g) Cryptography/Hashing
h) Parameter Manipulation
i) Exception Management
j) Auditing and logging

TABLE 1. Top 10 of Wasp Vulnerabilities [9]


10 OWASP Vulnerabilities 2020 Threats Description
Injection A code injection happens when an attacker purposely sends an invalid data to the
web application
Broken Authentication A broken authentication vulnerability allows an attacker to use a manual or an
automatic method and try to gain control over any account in the system
Sensitive Data Exposure Sensitive data such as credentials, credit card or social security numbers, and
medical information which need special data protection
XML External Entity An XML External Entity attack is a type of attack against an application that
parses XML input
Broken Access control Website security access controls will limit a visitor access only to the page or
sections needed by the type of user
Security misconfigurations Security misconfigurations can be at anywhere in the environment, including
network-attached devices, databases, web and application servers, and containers.
Cross Site Scripting (XSS) XXS occurs when malicious client-side JavaScript or HTML scripts are injected
into a web page and then use the web application as an attack vector to hijack user
sessions, deface websites, or redirect the victim to sites under the attacker’s
control
Insecure Deserialization Insecure deserialization offers hackers an attack vector that used for remote code
execution to conduct injection attacks, replay attacks, and attacks utilizing
privilege escalation.
Using Components with known Incorporate open-source components such as libraries and frameworks. Any
vulnerabilities component with a known vulnerability

050006-4
FIGURE 2. Components of the backbend architecture

SECURE CODING METHODS FOR PHP WEB DEVELOPMENT


Defensive programming is act at the top of layer security to protect valuable data and information especially for
sensitive data such as card credit number, identity number and password where it very valuable for those who use it
for their needs in the wrong path. Writing a code is never a straightforward process, although with a well achieved
requirement and design. Error handling, secure code construction, input validation implementation is the common
task which could fail even with good team of developers and good pre-development design. However, with the
advancement of technology, some programmers tend to copy few coding functions from internet. Some of those
coding functions possibly not secure where it may have a loophole. This part of this paper will present easy to follow
guideline of coding a secure PHP web application.

Input Validation
The point to make input validation is to prevent user insert false data and wrong format of information. Malformed
of input could trigger injection attacks, memory leakage and therefore a compromised system.
Figures below shows an alert message in a web application if user fill a textbox with wrong input format. There
are multiple ways of coding to validate an input.

FIGURE 3. Alert message if wrong format of email submitted

FIGURE 4. Alert message if wrong specification of password submitted

050006-5
PHP provide a simple function for input validation. Figures below show a simple code of PHP for a developer to
implement input validation.

FIGURE 5. Input validation for a textbook type “text”

FIGURE 6. Input validation for a textbook type “email”

FIGURE 7. Input validation for a textbook type “password”

The most common input validation attack includes XSS attacks, SQL Injection and Buffer Overflow [16]. If not
validated correctly, malicious input that includes code, scripts or commands could be used to exploit vulnerabilities.
By implementing input validation, the injection attack could be mitigated and sometimes make an attack process more
difficult against the web application [17].

Strategic Popup Alert for Login (Error Handling)


Improper error handling can introduce variety of information to the potential attacker. Web application frequently
display error message during the normal operation. Common error message includes out of memory, null pointer
exception, system call failure, unavailable database, network timeout others common condition that cause the error to
be display to users. Unhandled error message could provide meaningful information to users. Although its does not
provide a lot of detail, error message could still reveal important clues how the web application works.

FIGURE 8. Error message in login page

050006-6
One of an attack to gain access to an account is brute forcing the login page. Lists of username and passwords are
tried to gain access into user’s account. Specific message such as “Invalid password” to a valid “username” tried make
this attack process faster by eliminating large number of “usernames”. At this point, effort of brute-forcing was
reduced as the “invalid password” notification shows that the username tried is exist. Therefore, choosing to generate
error message in login process while writing a code as shown in the figures above will safeguarding the web
application from common web attacks.

Misconfiguration (PHP Session)


Session was added to PHP Version 4.0 introduce an easy method that allow a variable to stick around and be used
across multiple pages of the web application. Undestroyed session value after logout page could lead to the broken
authentication vulnerabilities [18]–[20]. Reducing the minimum lifetimes of session reduce the likelihood of a
successful session hijacking. A good managing of session ID includes renewing session ID after successful login,
destroying session ID after certain timeout and afterwards user logout and do not show session ID in the URL.

FIGURE 9. Use of session destroy()

Figure 9 shows a PHP code on a way to destroying session ID therefore defending the web application against
session hijacking. Discovered session ID provides a way to attacker to impersonate the valid user, therefore giving
them a way to perform any action which the user could perform.

Mitigating Denial of Service (DoS) Attack using CAPTCHA


A CAPTCHA is a type of challenge–response test used in computing to determine whether the user is a human.
The use of CAPTCHA in a web application preserves the bandwidth of the application server of web application
therefore allow only legitimate users to access the application. Usually, the CAPTCHA will implement at register and
contact page where it called “naked form” such in ‘Contact Form’ as shown in Figure 10.

FIGURE 10. Random number CAPTCHA in contact page

Generating a CAPTCH may require some processing, however CAPTCHA is one of the method proposed to
prevent DoS attack (Mehra et al, 2011). It is beneficial to use CAPTCHA to maintain the uptime of the application
and protect the web application from spam robot.

050006-7
Hashing
Hashing is an algorithm that calculates a fixed-size bit string value from a file. It is impossible to reconstruct input
data from a hashing value, although the hash function is known. Hashing is one of the ways to store confidential
information securely. Hashing confidential information such as password, credit-card information, user’s medical
information helps mitigating data breach attack. Hashing transforms information into a far shorter fixed-length value
or key which represents the input data.
PHP introduce a password_hash() function that create a secure hash of a password. This function introduces a
strong hashing algorithm and adds a random salt to prevent rainbow tables and dictionary attacks. Salted hashes
include random string so that every hash will have a different value although the input value is the same.
To verify the password hashes by password_hash() (as shown in Figure 11), PHP provided password_verify()
function (as shown in Figure 12). As of June 2020, the default algorithm used for hashing is Bcrypt and PHP can
change the algorithm if there any secure algorithm implemented.

$passwordHash=password_hash($password, PASSWORD_DEFAULT);

FIGURE 11. Using PHP function of password_hash() to hashing a password

password_verify ( string $password , string $hash ):


bool

FIGURE 12. Using PHP password_verify() function to verify hashing password

FIGURE 13. Hash password in stored in the database

By using password_hash() function, the developers no longer necessary to manually to added a salt before hashing
as it already defined in the algorithm provided. All updates and security mechanism of this function all delegated to
PHP.

CONCLUSION AND FUTURE WORK


Web application development is growing rapidly and continues to explore their services to meet the need for the
technology and users. Due to ad hoc existence and poor code written, most available web applications are vulnerable
and desirable target for the attackers. To address this issue, this paper explained on development of web application
program using PHP as a server-side scripting exploiting the use of defensive programming techniques. In addition,
mitigation on web applications vulnerabilities (OWASP, 2020) have been deliberated. For example, XSS injection
attack, SQL injection attack, right error handling, bot attacks and misconfiguration while writing PHP code. This paper
proposed an effective way to write a secure PHP code using defensive programming approach accordingly. In future,
further work is necessary to scale down web application security vulnerability risk by implementing various types of
controls such as physical control, technical control, and operational control. For instance, to defend from spoofing
attack is by using IP filtration, traffic encryption with the help of HTTPS and SSH protocols, VPN. Further research
will be implementing other server-side web development languages such as Python and ASP.net.

050006-8
REFERENCES
1. M. Azahari, A. Ahmad, and S. B. Rahayu, TEST Eng. Manag. 81, 4774–4778 (2019).
2. L. Thaduri. Detecting Application Anomalies: Machine Learning Detecting Application Anomalies: Machine
Learning Approach Approach. https://repository.stcloudstate.edu/msia_etds (20 May 2020).
3. Guarnieri, Marco et al. “Hardware-Software Contracts for Secure Speculation,” in 2021 IEEE Symposium on
Security and Privacy (SP) (2021), pp. 1868-1883.
4. T. M. Hughes, “Autonomously and Responsibly Responding to Missing or Invalid SAS®Data Sets Through
Exception Handling Routines,” in PharmaSUG Proceedings (2020).
5. D. Sahu and D. Tomar, Int. J. Adv. Comput. Networks Its Secur. 4, 71–75 (2014).
6. M. T. Rossi, R. Greca, L. Iovino, G. Giacinto, and A. Bertoli, “Defensive Programming for Smart Home
Cybersecurity,” in Proceedings - 5th IEEE European Symposium on Security and Privacy Workshops (2020),
pp. 600–605.
7. Technologies. State of the Internet / Security | Retail Attacks and API Traffic.
https://www.akamai.com/newsroom/press-release/state-of-the-internet-security-retail-attacks-and-api-traffic
(Accessed 2019).
8. Dalai and S. Jena, “Evaluation of web application security risks and secure design patterns,” in Proceedings of
the 2011 International Conference on Communication, Computing & Security, ICCCS 2011 (2011), pp. 565-
568.
9. OWASP. OWASP Top Ten Web Application Security Risks. https://owasp.org/www-project-top-ten/ (2020).
10. V. S. Mdunyelwa, J. F. Van Niekerk, and L. A. Futcher, “Secure Coding Practices in the Software Development
Capstone Project,” in Proc. Elev. Int. Symp. Hum. Asp. Inf. Secur. Assur. (HAISA 2017) Secur., no. HAISA
(2017), pp. 282–291.
11. T. Crawford and T. Hussain, “A Comparison of Server Side Scripting Technologies,” in Proc. 2017 Int. Conf.
Softw. Eng. Res. Pract., (2017), p. 75.
12. Kumari and Nandal, Int. J. Adv. Res. Comput. Sci. 8, 1231–1235, (2017).
13. D. Gope, D. J. Schlais, and M. H. Lipasti, ACM SIGARCH Comput. Archit. News 45, 507–520 (2017).
14. W3Techs. Usage Statistics and Market Share of Server-side Programming Languages for Websites.,
https://w3techs.com/technologies/overview/programming_language (Accessed 20 January 2021).
15. D. Kaplan. 5 Most Common Web Application Attacks (And 3 Security Recommendations).
https://www.msspalert.com/cybersecurity-breaches-and-attacks/5-most-common-web-application-attacks/
(Accessed 29 January 2021).
16. W. Marashdih, Z. F. Zaaba, and K. Suwais, “Cross Site Scripting: Investigations in PHP Web Application,” in
Proc. - 2018 Int. Conf. Promis. Electron. Technol. ICPET 2018 (2018), pp. 25–30.
17. OWASP, C5. Validate All Inputs. https://owasp.org/www-project-proactive-controls/v3/en/c5-validate-inputs
(Accessed 27 January 2021).
18. ESDS. What Do You Know About Broken Authentication and Session Breach?
https://www.esds.co.in/blog/what-do-you-know-about-broken-authentication-and-session-
breach/#sthash.stwC3o70.dpbs (Accessed 29 January 2021).
19. OWASP. WSTG - Latest | OWASP 2020. https://owasp.org/www-project-web-security-testing-guide/latest/4-
Web_Application_Security_Testing/06-Session_Management_Testing/06-Testing_for_Logout_Functionality
(Accessed 29 January 2021).
20. Mozilla. WebAppSec/Secure Coding Guidelines – MozillaWiki.
https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines#Session_Management (Accessed 29 January
2021).
21. M. Mehra, M. Agarwal, R. Pawar, and D. Shah, “Mitigating denial of service attack using CAPTCHA
mechanism,” in Int. Conf. Work. Emerg. Trends Technol. 2011, ICWET 2011 - Conf. Proc. (2011), pp. 284–287.

050006-9

You might also like