You are on page 1of 30

UNIT I

FUNDAMENTALS OF WEB APPLICATION SECURITY


The history of Software Security-Recognizing Web Application Security Threats, Web Application
Security, Authentication and Authorization, Secure Socket layer, Transport layer Security, Session
Management-Input Validation.
**********************************************************************************
THE HISTORY OF SOFTWARE SECURITY
The Enigma Machine, Circa 1930
● An Enigma machine is a famous encryption machine used by the Germans during WWII to transmit
coded messages.
● The Enigma machine used electric-powered mechanical rotors to both encrypt and decrypt text-based
messages sent over radio waves
● Enigma machines use a form of substitution encryption.
● Substitution encryption is a straightforward way of encoding messages, but these codes are fairly easy
to break.
● A simple example of a substitution encryption scheme is a Caesar cipher. A Caesar cipher shifts each
letter of the alphabet some number of places. A Caesar cipher with a shift of 1 would encode an A as a
B, an M as an N, and a Z as an A, and so on.
● Below is an image of a Caesar cipher with a shift of 3.

● But Enigma machines are much more powerful than a simple Caesar cipher
How an Enigma Machine Works:
● An Enigma machine is made up of several parts including a keyboard, a lamp board, rotors, and
internal electronic circuitry. Some machines, such as the ones used by the military, have additional
features such as a plugboard.

1
● When a key on the keyboard is pressed, one or more rotors move to form a new rotor configuration
which will encode one letter as another.
● Current flows through the machine and lights up one display lamp on the lamp board, which shows the
output letter.
● So if the "K" key is pressed, and the Enigma machine encodes that letter as a "P," the "P" would light
up on the lamp board.
● Each month, Enigma operators received codebooks which specified which settings the machine would
use each day. Every morning the code would change.
● Plugboard settings: A/L – P/R – T/D – B/W – K/F – O/Y
● A plugboard is similar to an old-fashioned telephone switch board that has ten wires, each wire
having two ends that can be plugged into a slot.
● Each plug wire can connect two letters to be a pair (by plugging one end of the wire to one
letter’s slot and the other end to another letter).
● To implement this day-key first you would have to swap the letters A and L by connecting them
on the plugboard, swap P and R by connecting them on the plugboard, and then the same with
the other letter pairs listed above.
● Essentially, a one end of a cable would be plugged into the "A" slot and the other end would be
plugged into the L slot.
● Before any further scrambling happens by the rotors, this adds a first layer of scrambling where
the letters connected by the cable are encoded as each other.
● For example, if I were to encode the message APPLE after connecting only the "A" to the "L",
this would be encoded as LPPAE.
● Rotor (or scrambler) arrangement: 2 — 3 —1
● The Enigma machines came with several different rotors, each rotor providing a different
encoding scheme.

2
● In order to encode a message, the Enigma machines took three rotors at a time, one in each of
three slots.
● Each different combination of rotors would produce a different encoding scheme.
● To accomplish the configuration above, place rotor #2 in the 1st slot of the enigma, rotor #3 in
the 2nd slot, and rotor #1 in the 3rd slot.
● Rotor orientations: D – K –P
● On each rotor, there is an alphabet along the rim, so the operator can set in a particular
orientation.
● For this example, the operator would turn the rotor in slot 1 so that D is displayed, rotate the
second slot so that K is displayed, and rotate the third slot so that P is displayed.
Automated Enigma Code Cracking, Circa 1940
● A major flaw with the Enigma code was that a letter could never be encoded as itself.
● In other words, an “M” would never be encoded as an “M.”
● This was a huge flaw in the Enigma code because it gave codebreakers a piece of information they
could use to decrypt messages.
● If the codebreakers could guess a word or phrase that would probably appear in the message, they
could use this information to start breaking the code.
● The decoders could then begin cracking the code with a process of elimination approach.
Example:
Find possible contenders for the encoding of the word “RAIN” in the coded string below. (The
symbol % is used to denote unknown letters).

Coded Message E R W N I K O L K M M M M

Phrase R A I N % % % % % % % % %

● RAIN cannot be encoded as ERWN because the N in RAIN and the N in ERWN match up.
Since N cannot be encoded as itself, this isn’t the encoding.
● Let’s shift our message one slot to the right, and see if the result is a valid encoding.

Coded Message E R W N I K O L K M M M M

Phrase % R A I N % % % % % % % %

● RAIN cannot be encoded as RWNI because the R in RAIN matches with the R in RWNI.
Let’s shift again.

3
Coded Message E R W N I K O L K M M M M

Phrase % % R A I N % % % % % % %

● RAIN cannot be encoded as WNIK because the I in RAIN matches with the I in WNIK.

Coded Message E R W N I K O L K M M M M

Phrase % % % R A I N % % % % % %

● RAIN can be encoded as NIKO because the two phrases have no letters that match up. So
NIKO is a possible encoding of RAIN.
● If we repeat this process, we will find that NIKO, IKOL, KOLK, OLKM, LKMM, KMMM,
and MMMM are all possible encodings of RAIN since no letters match up between RAIN and
the encoding.
Introducing the “Bombe”
● Alan Turing and Gordon Welchman designed a machine called the Bombe machine which used
electric circuits to solve an Enigma encoded message in under 20 minutes.
● The Bombe machine would try to determine the settings of the rotors and the plugboard of the
Enigma machine used to send a given coded message.
● The standard British Bombe machine was essentially 36 Enigma machines wired together, this
way, the Bombe machine would simulate several Enigma machines at once.
● Most Enigma machines had three rotors and to represent this in the Bombe, each of the Enigma
simulators in the Bombe had three drums, one for each rotor.
● The Bombe's drums were color coded to correspond with which rotor they were simulating.
● 3-rotor Enigma machine only used three rotors at a time, the top one of the three simulated the
left-hand rotor of the Enigma scrambler, the middle one simulated the middle rotor, and the bottom
one simulated the right-hand rotor.
● Bombe machine would make a guess about a plugboard setting.
● The Bombe machine shifts the rotor positions, and chooses a new guess and repeats this process
until a satisfying arrangement of settings appears.
● Because electric circuits can perform computations very quickly, the Bombe machine can go
through all the rotor combinations in about 20 minutes.
3. Telephone “Phreaking,” Circa 1950
● Telephone "phreaking" refers to the practice of manipulating or exploiting the telephone network
to make free or unauthorized calls.

4
● This activity gained popularity in the 1950s and continued into the 1970s.
● Phreaking was essentially a form of hacking, where individuals, known as "phreakers," sought to
understand and exploit the vulnerabilities in the telephone system to make long-distance or
international calls without paying for them.
Here are some key points about telephone phreaking circa 1950:
Blue Boxes:
● One of the most famous tools used by early phreakers was the "blue box."
● A blue box was a device that generated the same tones used by the phone system to route and
switch calls.
● By playing the right tones, phreakers could trick the system into granting them free access to
long-distance lines.
Captain Crunch:
● John Draper, also known as "Captain Crunch," gained notoriety for using a blue box that
emitted a 2600 Hz tone.
● This specific frequency allowed him to access the internal phone company network.
● Draper earned his nickname because he discovered that the toy whistle given away in Cap'n
Crunch cereal produced the exact 2600 Hz tone needed for this purpose.
Tandem Switching Systems:
● Phreakers exploited the weaknesses in the tandem switching systems used by telephone
companies.
● These systems relied on in-band signaling, where control information was transmitted within
the same frequency range as the voice signals.
● Phreakers could manipulate these signaling tones to gain unauthorized access.
Exploration of the Phone Network:
● Phreakers were essentially hobbyists who enjoyed exploring the intricacies of the phone
network.
● They often shared their findings with others in underground communities, and this collaborative
spirit contributed to the evolution of phreaking techniques.
Legal Actions:
● As phreaking became more widespread, telephone companies and law enforcement took notice.
● The authorities began cracking down on phreakers, and legal actions were taken against those
caught engaging in unauthorized access to the phone network.
Impact on Telecommunications:

5
● The era of telephone phreaking played a role in the evolution of telecommunication security.
● It prompted telephone companies to enhance their systems to prevent unauthorized access and
led to the development of more secure signaling methods
4. Anti-Phreaking Technology, Circa 1960
● In response to the rise of telephone phreaking during the 1960s, telephone companies began
implementing various anti-phreaking technologies and security measures to protect their networks
from unauthorized access.
Out-of-Band Signaling:
One of the vulnerabilities exploited by phreakers was in-band signaling, where control signals
were transmitted within the same frequency range as the voice signals.
MF (Multi-Frequency) Signaling:
Multi-Frequency (MF) signaling replaced the earlier in-band signaling methods. MF signaling
used pairs of audio tones to represent different signals, and these tones were transmitted on separate
channels. This made it more challenging for phreakers to generate the correct tones to manipulate the
telephone system.
Increased Security Awareness:
Telephone companies educated their staff and customers about the risks of unauthorized access
and the importance of maintaining the security of the telephone network. This included training on
recognizing and reporting unusual activities.
Legal Measures:
In addition to technological solutions, legal measures were taken to deter phreakers. Acts of
unauthorized access to the telephone network were treated as criminal offenses, and individuals caught
engaging in phreaking activities could face legal consequences.
Encryption and Authentication:
Encryption and authentication mechanisms were introduced to secure communications
between switches and to prevent unauthorized access to sensitive network information.
5. The Rise of the World Wide Web, Circa 2000
● In the 1990s, the web was almost exclusively used as a way of sharing documents written in HTML.
Websites did not pay attention to user experience, and very few allowed the user to send any inputs
back to the server in order to modify the flow of the website.
● The early 2000s marked a new era for the internet because websites began to store user-submitted data
and modify the functionality of the site based on user input.
● This new ideology in building websites gave birth to social media as we know it today.
● Web 2.0 enabled blogs, wikis, media sharing sites, and more.

6
● This radical change in web ideology caused the web to change from a document- sharing platform to
an application distribution platform.
● Apple website in the 2000s, but in 2007 it was promoted to the top right of the UX instead of a link at
the bottom.
● In 2002, Microsoft’s ActiveX plug-in for browsers ended up with a vulnerability that allowed remote
file uploads and downloads to be invoked by a website with malicious intentions.
● By the mid-2000s, hackers were regularly utilizing “phishing” websites to steal credentials.
● No controls were in place at the time to protect users against these websites.
RECOGNIZING WEB APPLICATION SECURITY THREATS
Recognizing web application security threats requires a combination of awareness, vigilance, and
proactive measures. Here are some steps to help you recognize and identify potential web application
security threats:

1. Stay Informed:
● Keep yourself updated on the latest security threats, vulnerabilities, and attack techniques by
following security blogs, forums, and official security advisories.
2. Understand Common Threats:
● Familiarize yourself with common web application security threats such as SQL injection,
Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and others. Understand how
these attacks work and their potential impact.
3. Security Training:
● Provide security training to developers, administrators, and other stakeholders involved in the
development and maintenance of web applications. Ensure they understand security best practices
and potential risks.
4. Regular Security Audits:
● Conduct regular security audits and assessments, including penetration testing and code reviews.
Look for vulnerabilities in the code, configurations, and overall architecture of the web
application.
5. Use Security Tools:
● Employ automated security tools, such as web application scanners and vulnerability assessment
tools, to identify potential security issues. These tools can help detect common vulnerabilities and
misconfigurations.

7
6. Monitor Logs and Anomalies:
● Implement comprehensive logging and monitoring mechanisms. Regularly review logs for unusual
or suspicious activities, such as repeated failed login attempts, unusual patterns of data access, or
unexpected system behavior.
7. Security Headers and Protocols:
● Check if the web application is using proper security headers (e.g., Content Security Policy,
Strict-Transport-Security). Ensure that the application follows secure communication protocols
(HTTPS) to encrypt data in transit.
8. Input Validation:
● Verify that input validation mechanisms are in place to prevent common injection attacks. Ensure
that user inputs are properly validated and sanitized to prevent the execution of malicious code.
9. Session Management:
● Review how sessions are managed and ensure that session tokens are securely handled. Check for
the implementation of secure session timeouts, token regeneration, and protection against session
fixation attacks.
10. File Upload Security:
● Assess the security of file upload functionality. Implement proper file type verification, size
limitations, and ensure that uploaded files are stored securely.
11. API Security:
● If the web application uses APIs, make sure that API endpoints are secure, and access is properly
authenticated and authorized. Check for rate limiting to prevent abuse.
12. Third-Party Components:
● Be cautious with third-party components, libraries, and plugins. Keep them updated and monitor
security advisories related to these components.
13. Security Headers:
● Ensure that the web application includes necessary security headers (e.g., Content Security Policy,
X-Frame-Options) to enhance security and mitigate certain types of attacks.
14. User Awareness:
● Educate users about potential security threats, such as phishing attacks and the importance of using
strong, unique passwords.

8
WEB APPLICATION SECURITY

Web application security is the practice of defending websites, web applications, and web services
against malicious cyber-attacks such as SQL injection, cross-site scripting, or other forms of potential
threats.

Web application security checklist

In addition to WAFs, there are a number of methods for securing web applications. The following
processes should be part of any web application security checklist:

Information gathering – Manually review the application, identifying entry points and client-side
codes. Classify third-party hosted content.

Authorization – Test the application for path traversals; vertical and horizontal access control issues;
missing authorization and insecure, direct object references.

Cryptography – Secure all data transmissions. Has specific data been encrypted? Have weak
algorithms been used? Do randomness errors exist?

Denial of service – Improve an application’s resilience against denial of service threats by testing for
anti-automation, account lockout, HTTP protocol DoS and SQL wildcard DoS. This doesn’t cover
protection from high-volume DoS and DDoS attacks, which are best countered by a combination of
filtering solutions and scalable resources.

Refer to the OWASP Web Application Security Testing Cheat Sheet for additional information; it’s also
a valuable resource for other security-related matters.

Web Application Security Threats:

1. Injection Attacks
● A web app that is vulnerable to injection attacks accepts untrusted data from an input field
without any proper sanitation. By typing code into an input field, the attacker can trick the
server into interpreting it as a system command and thereby act as the attacker intended.
● Some common injection attacks include SQL injections, Cross-Site Scripting, Email Header
Injection, etc. These attacks could lead to unauthorized access to databases and exploitation of
admin privileges.

9
How to prevent:
● Keep untrusted inputs away from commands and queries.
● Use a safe Application Programming Interface (API) that avoids interpreters or uses
parameterized interfaces.
● Filter and sanitize all inputs as per a whitelist. This prevents the use of malicious character
combinations.

2. Broken Authentication
● Broken authentication is an umbrella term given to vulnerabilities wherein authentication and
session management tokens are inadequately implemented.
● This improper implementation allows hackers to make claims over a legitimate user’s identity,
access their sensitive data, and potentially exploit the designated ID privileges.
How to prevent:
● End sessions after a certain period of inactivity.
● Invalidate a session ID as soon as the session ends.
● Place limiters on the simplicity of passwords.
● Implement multi-factor authentication (2FA/MFA).

3. Cross Site Scripting (XSS)


● It is an injection-based client-side attack. At its core, this attack involves injecting malicious
code in a website application to execute them in the victims’ browsers eventually.
● Any application that doesn’t validate untrusted data adequately is vulnerable to such attacks.
● Successful implementation results in theft of user session IDs, website defacing, and redirection
to malicious sites (thereby allowing phishing attacks).
How to prevent:
● Encode all user-supplied data.
● Use auto-sanitization libraries such as OWASP’s AntiSamy.
● Whitelist inputs to disallow certain special character combinations.

4. Insecure Direct Object References (IDOR)


● Mostly through manipulation of the URL, an attacker gains access to database items belonging
to other users. For instance, the reference to a database object is exposed in the URL.
● The vulnerability exists when someone can edit the URL to access other similar critical
information (such as monthly salary slips) without additional authorization.

10
How to prevent:
● Implement proper user authorization checks at relevant stages of users’ web app journey.
● Customize error messages so that they don’t reveal critical information about the respective
user.
● Try not to disclose reference to objects in the URL; use POST based information transmission
over GET.

5. Security Misconfigurations
● According to OWASP top 10 2017, this is the most common web application security threats
found across web applications.
● This vulnerability exists because developers and administrators “forget” to change some default
settings such as default passwords, usernames, reference IDs, error messages, etc.

Types of Web Application Security Solutions

Web application firewall (WAF)


● Managed 24/7 by our team of security experts, Imperva cloud WAF uses crowdsourcing
technology and IP reputation to prevent attacks aiming to exploit application vulnerabilities.
● This solution also comes complete with a custom rules engine, enabling total on-the-fly control
over all security policies.
DDoS protection
● Our multi-faceted DDoS mitigation services offer blanket protection against all network layer
and application DDoS attacks.

11
● Imperva users can choose between DNS and BGP-enabled options to secure websites, web
applications and server infrastructure.
Bot filtering
● Malicious bots are used in mass-scale automated assaults, accounting for over 90% of all
application layer attacks.
● Imperva bot filtering is a free service that uses advanced client classification, a progressive
challenge system and reputational scoring to identify and filter out nefarious bot traffic.
Web App and API Protection (WAAP):
● WAAP provides much the same protection as a WAF solution but extends it to protect APIs as
well as web apps.
DDoS Mitigation:
● DDoS mitigation solutions are designed to identify and filter out malicious traffic attempting to
overwhelm a web app or API.
API Gateways:
● API gateways manage access to APIs, reducing the risk of API abuse and the use of
undocumented shadow APIs by attackers.

AUTHENTICATION AND AUTHORIZATION


AUTHENTICATION:
● Authentication refers to the process of verifying a user’s identity, usually by requiring them to
provide valid credentials (e.g., username and password).
● The primary goal of authentication is to confirm that a user is who they claim to be before
granting access to the application.
Authentication Methods in Web Applications
1. Cookie-Based Authentication
Cookies are generally used to handle user authentication in web applications.

12
Working of cookie-based authentication in web apps:
● The client browser sends the POST request for login credentials to the server. The server then
verifies the credentials sent to it with the HTTP 200 OK status code.
● It creates a session ID stored in the server and returns it to the client via
Set-Cookie: session=….
● On the subsequent requests, the session ID from the cookie is verified in the server, and the
corresponding request is processed.
● When you log out of the app, your session ID will be cleared from both the client and server.

2. Token-Based Authentication
● This method is on the rise as we see more and more Single Page Applications (SPAs) being
made.
● One of the most common ways to implement token-based authentication is to use JSON Web
Tokens (JWTs).
● JWTs are an open standard that defines a self-contained way to transmit information between
parties as JSON objects securely.

13
Working of token-based authentication:
● When the credentials are received from the client's browser, the server validates these
credentials and also generates a signed JWT containing all of the user information.
● The token is stateless, so it never gets stored on the server.
● Over the following requests, the token is passed to the server and then gets decoded in order to
verify it on the server.
3. Third-Party Access (OAuth, API-token)
The third-party access authentication can work in two ways:
Via API-token:
● It's usually the same as we discussed above on JWT, where the token is sent to the
authorization header and handled at some API gateway to authenticate the user.
Via Open Authentication (OAuth):
● As you might have guessed by its name, OAuth is an open protocol that allows secure
authentication methods from the web, mobile, and desktop applications.
● This protocol authenticates against the server as a user.
● The recommendation is to implement OAuth 1.0a or OAuth 2.0. OAuth 2.0 relies on
HTTPS for security and it currently implemented by Google, Facebook, Twitter etc.,
● OAuth 2 provides secured delegate access to a resource based on user.
● OAuth 2 does this by allowing a token to be issued by Identity provider to these third party
applications, with the approval of user.
● The client then uses the token to access the resource on behalf of that user.

14
4. OpenId
● OpenId is HTTP based protocol that uses identity provider to validate a user.
● The user password is secured with one identity provider, this allows other service providers
a way to achieve Single SignOn(SSO) without requiring password from user.
● There are many OpenId enabled account on the internet and organizations such as Google,
Facebook, Wordpress, Yahoo, PayPal etc., uses OpenId to authenticate users.
● The latest version of OpenId is OpenId Connect, which provides OpenId(authentication) on
top of OAuth 2.0(authorization) for complete security solution.
5. Security Assertion Markup Language (SAML)
● Security assertion markup language makes use of the same Identity provider which we saw
in OpenId, but it is XML based and more flexible.
● The recommended version for SAML is 2.0. SAML also provides a way to achieve Single
SignOn(SSO), user can make use of the Identity provider URL to login into the system
which redirects with XML data back to your application page which can then be decoded
to get the user information.
● We have SAML providers like G Suite, Office 365, OneLogin, Okta etc.,
Authentication Libraries:
PassportJS
● PassportJS is one of the most popular auth libraries for Express. Apart from Local
Authentication, Passport has support for OpenID, OAuth 1.0, SAML, and OAuth 2.0.
● There are around 500 providers/strategies which can be used with Passport. You can check our
recent tutorial which covers Passport.
Grant
● Grant is another auth library. It has support for Express, Hapi, and Koa. Like Passport, the grant
supports OpenID connect OAuth 1.0a & OAuth 2.0. There are currently 180 supported
providers.
Firebase Authentication
● Firebase Auth has limited OAuth providers (Facebook, Github, Twitter, Google, Apple,
Microsoft). However, it does provide Auth for email login, anonymous login, and phone
number login.
● A full authentication workflow is provided by the Firebase Auth API. Also, we can link
Multiple OAuth users to a single user.

15
AUTHORIZATION:
● Authorization is the process of determining the level of access a user has within an application,
based on their role or permissions.
● Once a user is authenticated, the authorization system controls which resources they can access
and what actions they can perform.
Authorization in systems and applications typically works through the following steps:
✔ Authentication:
● This is the first step where the user’s identity is confirmed.
● This is usually done through a username and password, biometric data, or other means of identity
verification.
● To gain a deeper understanding of the authentication process, read this article about the
explanation of authentication.
● It provides valuable insights into the various methods and techniques used to verify a user’s
identity during the authentication phase.
✔ Access Request:
● Once the user is authenticated, they can request access to specific resources or perform certain
actions within the system.
● This request includes the user’s identity and the resources or actions they want to access.
✔ Authorization Check:
● The system then checks against its access control policies (these policies are pre-defined sets of
rules about who can access what and when).
● This check determines if the authenticated user has the necessary permissions to access the
requested resources or perform the desired actions.
✔ Access Granted or Denied:
● Depending on the outcome of the authorization check, the system either grants or denies the user’s
access requests.
● If access is granted, the user can interact with the resources or perform the actions they requested.
● If the access is denied, the user receives an appropriate response indicating that they do not have
permission.
✔ Logging:
● The system typically logs the authorization process – who requested access, what they requested,
and whether the request was granted or denied.
● This is important for security, compliance, and auditing purposes.

16
Importance of Authorization:
❖ Data Protection:
● Authorization helps safeguard sensitive data by granting access only to authorized individuals.
● It controls who can see or modify data, significantly reducing the risk of data breaches and
protecting user privacy.
❖ Role Management:
● Authorization involves attribute-based access control, allowing different access levels to be
assigned based on user roles or attributes.
● This ensures that users only gain access rights to the resources necessary for their roles,
mitigating the risk of misuse or unauthorized access.
❖ Regulatory Compliance:
● Many industries have regulations requiring certain levels of data protection.
● Implementing proper authorization processes, including granting access rights judiciously, can
help a business stay compliant with these regulations.
❖ Audit Trail:
● Authorization systems often maintain logs, tracking who accessed what and when.
● This provides an audit trail for system use review, incident investigations, and demonstrating
regulatory compliance.
❖ Access Management:
● By managing and controlling what actions each user can perform, authorization plays a key role
in preventing system misuse.
● This access management ensures users cannot perform actions outside of their granted access
rights, either accidentally or maliciously.
Examples of Authorization
● Role-based Access Control (RBAC):
This form of authorization, often used in a computer system, assigns access permissions based
on users’ roles. For instance, in a hospital system, doctors have different access policies than nurses,
reflecting their different roles.
● Attribute-based Access Control (ABAC):
ABAC authorizes actions based on policies and attributes, such as user role, resource, or
environment. An example might be a cloud storage system that uses access control lists to manage
permissions, providing or restricting client privileges.

17
● Discretionary Access Control (DAC):
In DAC systems, resource owners have the authority to grant or revoke access. This can be seen
in network-shared folders, where the folder’s owner controls access permissions.
● Mandatory Access Control (MAC):
With MAC, authorization work is done based on classification rules. For example, a military
computer system might use MAC, allowing classified information access only to personnel with
matching security clearance.
● Token-based Authorization:
Common in web applications, where a token, granted after successful login, is used to authorize
client requests. For instance, social media platforms employ tokens to authorize user actions and
provide appropriate access.
● OAuth:
This is an open-standard authorization protocol that allows “secure designated access.” An
example can be linking Spotify to Facebook, where OAuth allows Spotify access to your Facebook
profile without sharing your Facebook password.
SECURE SOCKET LAYER (SSL)
Secure Socket Layer (SSL) provides security to the data that is transferred between web browser and
server. SSL encrypts the link between a web server and a browser which ensures that all data passed
between them remain private and free from attack.
Secure Socket Layer Protocols:
● SSL record protocol
● Handshake protocol
● Change-cipher spec protocol
● Alert protocol
SSL Protocol Stack:

18
SSL Record Protocol:
SSL Record provides two services to SSL connection.
● Confidentiality
● Message Integrity
● In the SSL Record Protocol application data is divided into fragments.
● The fragment is compressed and then encrypted MAC (Message Authentication Code) generated by
algorithms like SHA (Secure Hash Protocol) and MD5 (Message Digest) is appended.
● After that encryption of the data is done and in last SSL header is appended to the data.

Handshake Protocol:
Handshake Protocol is used to establish sessions. This protocol allows the client and server to
authenticate each other by sending a series of messages to each other. Handshake protocol uses four
phases to complete its cycle.
● Phase-1: In Phase-1 both Client and Server send hello-packets to each other. In this IP session,
cipher suite and protocol version are exchanged for security purposes.
● Phase-2: Server sends his certificate and Server-key-exchange. The server end phase-2 by sending
the Server-hello-end packet.
● Phase-3: In this phase, Client replies to the server by sending his certificate and
Client-exchange-key.
● Phase-4: In Phase-4 Change-cipher suite occurs and after this the Handshake Protocol ends.

19
Change-cipher Protocol:
● This protocol uses the SSL record protocol. Unless Handshake Protocol is completed, the SSL
record Output will be in a pending state.
● After the handshake protocol, the Pending state is converted into the current state.
● Change-cipher protocol consists of a single message which is 1 byte in length and can have only
one value.
● This protocol’s purpose is to cause the pending state to be copied into the current state.

Alert Protocol:
This protocol is used to convey SSL-related alerts to the peer entity. Each message in this protocol
contains 2 bytes.

The level is further classified into two parts:

20
● Warning (level = 1):
This Alert has no impact on the connection between sender and receiver. Some of them are:
Bad certificate : When the received certificate is corrupt.
No certificate: When an appropriate certificate is not available.
Certificate expired: When a certificate has expired.
Certificate unknown: When some other unspecified issue arose in processing the certificate,
rendering it unacceptable.
Close notify: It notifies that the sender will no longer send any messages in the connection.
Unsupported certificate: The type of certificate received is not supported.
Certificate revoked: The certificate received is in revocation list.
● Fatal Error (level = 2):
This Alert breaks the connection between sender and receiver. The connection will be stopped, cannot
be resumed but can be restarted. Some of them are :
Handshake failure: When the sender is unable to negotiate an acceptable set of security parameters
given the options available.
Decompression failure: When the decompression function receives improper input.
Illegal parameters: When a field is out of range or inconsistent with other fields.
Bad record MAC: When an incorrect MAC was received.
Unexpected message: When an inappropriate message is received.
The second byte in the Alert protocol describes the error.

Characteristics that make it a reliable solution for securing online transactions:


1. Encryption: The SSL certificate uses encryption algorithms to secure the communication between
the website or service and its users. This ensures that the sensitive information, such as login
credentials and credit card information, is protected from being intercepted and read by
unauthorized parties.
2. Authentication: The SSL certificate verifies the identity of the website or service, ensuring that
users are communicating with the intended party and not with an impostor. This provides assurance
to users that their information is being transmitted to a trusted entity.
3. Integrity: The SSL certificate uses message authentication codes (MACs) to detect any tampering
with the data during transmission. This ensures that the data being transmitted is not modified in
any way, preserving its integrity.

21
4. Non-repudiation: SSL certificates provide non-repudiation of data, meaning that the recipient of
the data cannot deny having received it. This is important in situations where the authenticity of the
information needs to be established, such as in e-commerce transactions.
5. Public-key cryptography: SSL certificates use public-key cryptography for secure key exchange
between the client and server. This allows the client and server to securely exchange encryption
keys, ensuring that the encrypted information can only be decrypted by the intended recipient.
6. Session management: SSL certificates allow for the management of secure sessions, allowing for
the resumption of secure sessions after interruption. This helps to reduce the overhead of
establishing a new secure connection each time a user accesses a website or service.
7. Certificates issued by trusted CAs: SSL certificates are issued by trusted CAs, who are
responsible for verifying the identity of the website or service before issuing the certificate. This
provides a high level of trust and assurance to users that the website or service they are
communicating with is authentic and trustworthy.

TRANSPORT LAYER SECURITY


● Transport Layer Security (TLS) is a cryptographic protocol that secures the connection between a web
server and a web application using data encryption.
● It applies to all data exchanged over the network, including emails, web browsing sessions, and file
transfers.
● Hackers cannot access users’ sensitive data like login credentials and credit card numbers.

How Does TLS Work:


❖ TLS uses encryption for the client and server to generate a secure connection between the applications.
❖ It begins when users access a secured website by specifying the TLS encryption method like the
advanced encryption standard (AES).
❖ It works with two security layers – the TLS record protocol and the TLS handshake protocol.
❖ These protocols use symmetric and asymmetric cryptography methods to secure data transfer and
communications between the clients and web servers.
❖ The TLS handshake protocol, for example, uses asymmetric cryptography to generate public and
private keys that encrypt and decrypt data.
The overall process is as follows:
1. The client sends a list of all TLS versions along with suggestions for a cipher suite and
generates a random number that will be used later.
2. The server confirms which options it will use to initiate the connection.

22
3. The server sends a TLS certificate to the client for the authentication process.
4. After validating the certificate, the client creates and sends a pre-master key encrypted by the
server’s public key and decrypted by the server’s private key.
5. The client and server generate session keys using the previously generated random numbers
and the pre-master key.
6. Both the client and server have a finished message that has been encrypted with a session key.
7. The TLS handshake process is finished, and both the client and server have created secure
symmetric encryption.
❖ The record protocol uses symmetric encryption to generate unique session keys for each connection
during the handshake process.
❖ It also adds all data exchanged with a hash-based message authentication code (HMAC) to verify
the data authenticity.
❖ TLS is becoming a standard practice for most modern browsers and other applications, where it
serves three purposes:
● Encryption. It hides the data transferred from third parties through encoded information.
● Authentication. TLS connection ensures both parties’ identities are who they claim to be by
providing a certificate.
● Integrity. Finally, it verifies that the data transmitted has not been forged or tampered with
during the delivery process.

TLS Protocol Benefits in Businesses and Web Applications:


Transport layer security protocol offers many benefits, such as:
● Preventing eavesdropping and tampering. TLS provides secure internet communications
between a client and a server with a trusted cipher suite. This way, hackers cannot read the data
transmitted on the internet, including online transactions.
● Providing data integrity. By supporting authentication code, TLS provides privacy and data
integrity. It ensures that all information will reach its destination without any loss or alteration
from third parties.
● Improving search engine optimization (SEO). Website security is a vital Google ranking
factor as they aim to build a safe browsing experience. Therefore, using TLS protocols will
give you a competitive edge, improving your site’s ranking on search engines.
● Enhancing customer trust. Using a TLS connection will provide users with a secure web
browsing experience, which will build customer trust in any business. This way, customers will

23
feel more comfortable providing their data for creating a new account or making online
purchases.
● Offering granular control. TLS has a robust and reactive alert system to help users identify a
problem. It gives control over what can be transmitted or received in a secure session so that
users will receive notification alerts if there’s any problem like the err SSL version or cipher
mismatch error.

Differences between TLS and SSL:


✔ Key differences between SSL and TLS that make TLS a more secure and efficient protocol are
message authentication, key material generation and the supported cipher suites, with TLS
supporting newer and more secure algorithms.
✔ TLS and SSL are not interoperable, though TLS currently provides some backward compatibility in
order to work with legacy systems.
✔ Additionally, TLS -- especially later versions -- completes the handshake process much faster
compared to SSL. Thus, lower communication latency from an end-user perspective is noticeable.

Attacks against TLS/SSL:


● The infamous Heartbleed bug was the result of a surprisingly small bug vulnerability discovered
in a piece of cryptographic logic that relates to OpenSSL's implementation of the
TLS heartbeat mechanism, which is designed to keep connections alive even when no data is being
transmitted.
● Although TLS isn't vulnerable to the POODLE attack because it specifies that all padding bytes
must have the same value and be verified, a variant of the attack has exploited certain
implementations of the TLS protocol that don't correctly validate encryption padding byte
requirements.
● The BEAST attack was discovered in 2011 and affected version 1.0 of TLS. The attack focused
on a vulnerability discovered in the protocol's cipher block chaining (CBC) mechanism. This
enabled an attacker to capture and decrypt data being sent and received across the "secure"
communications channel.
● An optional data compression feature found within TLS led to the vulnerability known as CRIME.
This vulnerability can decrypt communication session cookies using brute-force methods. Once
compromised, attackers can insert themselves into the encrypted conversation.
● The Browser Reconnaissance and Exfiltration via Adaptive Compression of Hypertext
(BREACH) vulnerability also uses compression as its exploit target, like CRIME. However, the

24
difference between BREACH and CRIME is the fact that BREACH compromises Hypertext
Transfer Protocol (HTTP) compression, as opposed to TLS compression. But, even if TLS
compression isn't enabled, BREACH can still compromise the session.

SESSION MANAGEMENT
● Session management is the process of maintaining and controlling user sessions in a web application
or system.
● It involves managing the interaction between a user and the system during a specific period.
● It involves assigning a unique session identifier to each user, which is stored on the server side and
used to retrieve relevant session data.
● It ensures that users remain authenticated throughout browsing and enables personalized experiences.
● This facilitates session state maintenance, timeout management, and secure logout handling, ensuring
seamless, secure experiences.
Key Components of Session Management

● Session Creation: When a user initiates a session by accessing a web application, a unique session
ID is generated for that user. This ID identifies and associates the user’s interactions with the
session.
● Session Tracking: The server keeps track of active sessions by associating each session ID with
relevant user data. This data can be stored in server-side storage, such as a database or memory
cache.

25
● Session Timeout: Sessions have a predefined timeout period to ensure that inactive sessions are
automatically terminated. When a session runs out, the user must log in again to establish a new
session.
● Session Termination: Users can manually terminate their sessions by logging out of the
application. When a session is terminated, all associated session data is cleared, and the session ID
becomes invalid.
● Session Security: Session management systems use security measures to protect against session
hijacking or fixation attacks and unauthorized access.

Types of Session Management


There are two main types of session management:

● Client-side Session Management:


In this type, the session data is stored and managed on the client side, typically within a
cookie or using browser storage mechanisms such as local or session storage. The session data may
be encrypted or encoded to maintain security. The server relies on the client to send the session data
with each request, and the server validates and processes it accordingly.
● Server-side Session Management:
In this type, the session data is stored and managed on the server. The server generates a
distinct session ID for each user and maintains the associated session data. The session ID is
typically stored as a cookie on the client side and sent with each request. The server retrieves the
session data based on the session ID and uses it to maintain user state and perform authentication
and authorization checks.

26
INPUT VALIDATION
● Input validation is a technique used to ensure that data entered into any system, website, or web app
is valid and meets specific criteria.
● It’s typically implemented for websites and web apps that receive and process user-inputs (such as
forms) to check for properly formed data.
● There are many different types and levels of validation,
o syntactic validation (which checks the input, types, and lengths)
o semantic validation (which ensures supplied values make sense in the application
context).
● If a website or app doesn’t perform proper input validation checks, malformed data may be entered to
the system or trigger malfunctions.
● For this reason, data from all untrusted sources (such as website visitors) should be validated as early
as possible to mitigate risk.

Why is input validation important?

Input validation is important for three main reasons:


1. Functionality
● By verifying that data inputs are in the correct format and within expected ranges, you can
ensure data is received and processed correctly by your website’s back-end.
● For example, if a user specifies incorrect credit card details on your purchase process, you
won’t be able to charge them.
2. Security
● Validating user inputs is extremely important for website security because it helps prevent bad
actors from entering potentially harmful data, mitigating the risk of cross-site scripting (XSS)
or SQL injection attacks.
3. User experience
● Input validation can drastically improve user experience by informing users if they have
entered invalid data.
● For example, if a user accidentally provides their name instead of email address in a certain
field, input validation can catch the error and inform them of the mistake.

27
Common Input Validation Techniques:

Client-Side Validation

● Client-side validation is like a friendly helper right at your fingertips when using computer
programs or websites.
● It’s the immediate check that happens on your own device as you type information.
● This quick validation helps catch simple mistakes or missing details before you even submit
anything.
● For example, If you forget to put your email address in the right format, client-side validation would
give you an error message right away.
● While it’s helpful for giving instant feedback and making sure you’re on the right track, it’s
important to remember that it’s not the only line of defense.
● Stronger security measures and defense in depth are needed to ensure that everything is safe and
secure on a bigger scale.
Server-Side Validation

● Server-side validation is like a watchful guardian that stands behind the scenes when you interact
with computer programs or websites.
● Unlike client-side validation, which happens on your device, server-side validation takes place on
the actual server where the program or website is hosted.
● It’s an extra layer of security that ensures the information you provide meets all the necessary rules
and standards, even if someone tries to bypass the client-side checks.
● This thorough validation helps prevent any incorrect or harmful data from entering the system,
making sure that the program works as intended and that your data remains safe.
● Server-side validation is like the last checkpoint before any data gets processed, acting as the final
safeguard against potential security risks and errors.
Regular Expressions

● Regular expressions, often called regex, are like magic patterns for searching and matching text
within computer programs or websites.
● They’re powerful search queries that can find specific words, numbers, or patterns in a sea of
information. Using a combination of characters and symbols, regular expressions allow you to
define complex criteria for identifying and manipulating strings of text.
● Whether it’s validating email addresses, checking for phone numbers, or searching for specific
keywords, regular expressions provide a versatile tool to handle a wide range of text-related tasks.

28
● While they might seem a bit cryptic at first, mastering regular expressions can unlock a whole new
level of control and precision in managing and processing data.
Whitelisting and Blacklisting

● Whitelisting and blacklisting, also now commonly referred to as “allow list” and “deny list”, are
two different approaches to managing access and permissions within computer programs or
websites.
● Whitelisting is the most effective form of input validation and is like having a VIP list, where only
the explicitly approved items or entities are allowed, and everything else is denied.
● It’s a strict and cautious method that ensures only trusted elements can interact with the system.
● On the other hand, blacklisting works like a list of things to avoid, where specific items are
identified as problematic and blocked, while everything else is permitted.
● While both approaches have their merits, whitelisting is often considered more secure as it only
permits known and verified entities, reducing the chances of unforeseen vulnerabilities.
● Blacklisting, while useful, can sometimes miss new or creative ways that attackers might try to
breach the system.
● The choice between these two methods depends on the level of control and security required for a
particular system or application.
Implementing Effective Input Validation

● Implementing effective input validation is crucial to building secure and reliable computer
programs or websites and considered the go-to standard for protecting against injection attacks.
● Best practices for input validation involves a combination of strategies aimed at ensuring that the
data entering the system is safe and accurate.
● Firstly, adopt a comprehensive approach by validating inputs both on the client-side and
server-side. Client-side validation provides quick feedback to users, while server-side validation
acts as the final line of defense.
● Secondly, use strong validation techniques like regular expressions to define precise patterns that
valid inputs must match.
● This prevents both common and complex input errors from sneaking through such as special
characters often used in attacks. Thirdly, employ whitelisting and blacklisting techniques, reducing
the risk of unexpected data causing issues.
● Regularly update validation rules to adapt to changing requirements and potential vulnerabilities.
● By consistently staying informed about the latest security trends and techniques, you can stay
ahead of potential threats.

29
● In essence, combining various methods and keeping validation practices up-to-date is the key to
fortifying your system against potential security vulnerabilities.
Empowering Digital Security Through Input Validation

● In the dynamic digital world, where innovation and convenience are powered by technology,
securing our digital assets stands as an essential concern.
● Throughout this blog post, we’ve introduced the significance of input validation and its robust
impact on preventing security vulnerabilities.
● By adopting best practices and diligently implementing thorough validation techniques,
organizations become empowered to withstand a broad spectrum of potential threats.
● As we navigate the line between innovation and security, input validation remains a powerful tool,
if not the most important for enabling us to shape a digital landscape that can withstand evolving
security challenges.

30

You might also like