Jit- announcement icon

Jit now supports GitLab! Learn how to implement automated code security across your projects in minutes.

Learn more

10 Malicious Code Examples You Need to Recognize to Defend Your SDLC

Dotan Agmon writer profile image
By Dotan Agmon
Jit Logo
Edited by Jit Team

Updated June 12, 2024.

a purple background with a lock on it and the words 10 malcious code examples

Modern software development isn’t just about software development. The escalating surge in cyber attacks fundamentally reshapes developers’ roles as we know them. Dev teams now find themselves responsible not just for crafting and pushing out innovative software but for protecting its code, and the urgency to strengthen app security is rising.

There were 5.5 billion malware attacks in 2022, fueled by the staggering growth of specific attacks such as crypto-jacking, which increased by 43%, and IoT malware, which spiked by 87%. Even GitHub repositories have been targeted with fraudulent commits, making developers think twice before getting codes from their trusted places.

Considering developers’ lack of superpowers (at least at the time of writing), how are dev teams meant to prevent and remediate such diverse and dangerous threats? Understanding exactly what malicious code you could deal with is a solid first step.

What is malicious code?

Malicious code, or malware, is software designed to damage computer systems, applications, and networks without user consent. Contrary to security vulnerabilities and misconfigurations, which happen accidentally due to coding errors, improper input validation, and other mistakes in development stages, malicious code has a clear intent to harm. For instance, attackers could be looking to steal private information, spy on companies’ activity, extort money, or disrupt systems through Distributed Denial of Service (DDoS) attacks.

There are various types of malware, some more well-known than others, such as ransomware, viruses, and trojans. Malware can also breach the SSDLC through various means, such as infected dependencies, compromised development environments, social engineering, software supply chain attacks, or zero-day exploits.

Understanding these entry points and nuances is crucial for developers to reinforce security measures across the company, know which DAST, SAST, and SCA security tools to adopt, and shield against these evolving threats.

a couple of cartoon characters standing next to each other


10 Malicious Code Examples You Need to Recognize to Defend Your SDLC

1. Backdoors

A backdoor acts as a gateway into a computer system, allowing unauthorized users to infiltrate without raising an alarm. Backdoors are a real challenge because they're masters at hiding and enable attackers to control compromised systems for longer, leading to extensive data breaches, sensitive information theft, and prolonged exploitation.

Here are some examples of backdoor attacks:

def secret_function():    
	# Perform critical system operations
	pass

def normal_function():
	# Execute non-critical, everyday tasks
	pass

# Check for a hidden parameter
if "backdoor_access" in locals():
	if backdoor_access:
		secret_function()
	else:
		normal_function()

In this code, the secret_function carries out a malicious task. The conditional check for a hidden parameter, "backdoor_access," can trigger the secret_function. Those aware of this concealed access point could silently activate the secret function, potentially leading to unauthorized and harmful system actions.

2. Scripting Attacks / Cross-Site Scripting (XSS) Attacks

Cross-site scripting fools a website with some weaknesses, making it send harmful JavaScript to users. The attacker has complete control over the victim's ability to interact with the application once the malicious code has been allowed to run inside the victim's browser.

XSS attacks lead to data theft, session hijacking, and unauthorized access to sensitive information. These attacks can also harm user trust, tarnish the reputation of web applications, and lead to legal consequences under data privacy laws such as GDPR and CCPA.

Here is an example of an XSS attack:

<!DOCTYPE html>
<html>
<head>
  <title>XSS Example</title>
</head>
<body>
  <div>
    <!-- Imagine this data comes from user input or an untrusted source -->
    <p>User's comment: <script>alert('Malicious Script')</script></p>
  </div>
  <!-- This user input is not properly sanitized -->
  <div>
    <p>User's comment: <?php echo $_GET['comment']; ?></p>
</div>
</body>
</html>

Think of a website that enables users to add their input/publish comments. In this example, an attacker published a comment containing a script that reads “Malicious Script.” Because this comment was displayed without being adequately sanitized or escaped, it will be executed in the context of other users’ browsers. Users accessing the comment will be alerted with a “Malicious Script” message, demonstrating that attackers can run code within the user’s browser. This exemplifies a real problem with this type of attack: attackers can replace the "alert" command with a more complicated command (or set of commands) that runs within the user's browser, and this code would steal the user's data.

3. Insecure authentication and session management

Insecure authentication and session management stem from a weak Identity and Access Management (IAM) strategy. As part of your IAM plan, you must provide users with just enough permissions to access their needed resources. But this is only one side of the coin.

You must also regularly verify your users’ identities through mechanisms such as MFA, monitor their behavior to ensure no suspicious activity goes undetected and manage your secrets properly. Failure to do so results in attacks where bad actors discover some user’s passwords and suddenly have a free pass to access your resources.

a man sitting on a swing chair with the words hackers when you use m


4. Remote Code Execution (RCE)

Remote Code Execution (RCE) enables intruders to run unauthorized code on a remote system, usually over a network. Such attacks often involve taking advantage of weaknesses or misconfigurations in software or hardware or deceiving a user into executing harmful code. If attackers successfully exploit an RCE vulnerability, they can run code and compromise your systems.

a diagram of a web site with a mailbox and a web site


5. SQL Injection

Structured Query Language or SQL injection is a common cyber threat that allows attackers to manipulate a web application's database by injecting malicious SQL code into an app’s input fields. These input fields could be any data entry point on the website, such as a web form or URL. If successful, SQL Injection attacks enable attackers to access and work with databases, potentially exposing sensitive data.

Here’s an example of a SQL injection:

user_input = input("Enter your username: ")
sql_query = "SELECT * FROM users WHERE username = '" + user_input + "'"
cursor.execute(sql_query)

In this example, user input is directly passed into the SQL query string. If an attacker enters malicious input, they can manipulate the SQL query and potentially gain unauthorized access to the database.

6. XML External Entity (XXE) Vulnerability

XXE is a sneaky trick that targets programs dealing with special XML files. It happens when a program's XML reader isn't set up well and reads a reference to a resource on the server or an external URL. When the XML file is parsed, the app may process the referenced entity, potentially revealing secret information, stopping a service, making the server do things it shouldn't, and even peeking at other parts of the computer.

For example, consider a code snippet that parses XML data without proper protection:

import xml.etree.ElementTree as ET
xml_data = """
<!DOCTYPE data [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<data>&xxe;</data>
"""
root = ET.fromstring(xml_data)

When this Python script is executed, and the XML document is processed using the ElementTree library, it tries to access the /etc/passwd file.

7. Man-in-the-Middle (MitM) Attack

MitM attacks target communication channels, allowing attackers to intercept data exchanges between two parties without their knowledge. MitM attacks create the potential for eavesdropping, data manipulation, and unauthorized access to sensitive information.

For instance, consider a scenario where a user connects to a public Wi-Fi network. An attacker positions themselves between the user and the network gateway, intercepting data transmissions without either party being aware and capturing sensitive information, such as login credentials or confidential messages.

8. Trojan Horses

a cartoon picture of a horse made out of cardboard


Trojan horses, named after the mythological deceit, are malicious software that appear harmless but carry hidden threats. Trojan horses are a big threat because they sneakily bring in bad software, mess with your systems, and might even steal data. Their hidden nature makes them a strong risk to the safety of your computer systems.

Here’s an example of a Trojan horse attack:

# This is a legitimate-looking Python script
def display_cute_kittens():
    print("Here are some cute kittens:")
    # Display images of cute kittens here
# The code below appears unrelated to the above function
def steal_sensitive_data():
    with open("sensitive_data.txt", "r") as file:
        data = file.read()
    # Send the stolen data to a remote server controlled by the attacker
# The following code is intentionally hidden
display_cute_kittens()
# Unbeknownst to the user, the Trojan horse performs malicious activities
steal_sensitive_data()

In this simple example, the code initially appears harmless as it displays cute kittens. However, hidden within the script is malicious functionality that secretly accesses and exfiltrates sensitive data from a file, potentially sending it to an attacker-controlled server.

9. Credential Stuffing

Credential stuffing is a persistent threat to online security, exploiting the reuse of usernames and passwords across different services. Attackers leverage previously compromised login credentials and employ large-scale automated login attempts to gain unauthorized access to user accounts on various websites or applications.

a diagram showing the components of a system


10. Unvalidated Redirects and Forwards

In URL Redirection attacks, the attacker manipulates a URL and sends it to the victim. When the victim opens the URL, the website redirects them to a destination specified by the attacker, which may be a malicious or unintended site. These tricky links can allow attackers to manipulate an application's processes.

Here’s an example of a URL Redirection attack:

@WebServlet("/UnvalidatedForwardServlet")
public class UnvalidatedForwardServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        String destination = request.getParameter("destination");
        if (destination != null && !destination.isEmpty()) {
            try {
                // forward the request to the specified destination
                request.getRequestDispatcher(destination).forward(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // Inform users if the destination is invalid
            response.getWriter().println("Invalid destination");
        }
    }
}

This servlet accepts a destination parameter, but it lacks proper validation to ensure the forwarding destination is safe and authorized. As a result, an attacker could manipulate the destination parameter to redirect users to potentially malicious locations.

Preventing and mitigating malicious code

Malicious code attacks are dangerously widespread, but there are effective ways to prevent them:

1. Validate and sanitize user inputs before processing

Check that any data or information users provide meets specific criteria such as length, format, or range and sanitize it to remove potentially harmful components. This will help you protect your app against security threats (particularly injection attacks such as SQL injection and cross-site scripting) and ensure safe data handling.

2. Regularly update and audit your codebase

Ensure you update your software components as needed, apply security patches promptly, and regularly audit and scan your codebase for unexpected vulnerabilities. These may be standard security practices - but getting the basics right is fundamental.

3. Expand and automate your security toolchain

If you want to take security one step further (which, at this point, is really the only way forward), consider expanding your security toolchain with SAST, DAST, and SCA. Leveraging these tools is key in shifting security left and protecting every SDLC stage.

DevSecOps orchestration tools like Jit let you integrate powerful open-source security testing tools such as OWASP ZAP, Semgrep, and OSV-Scanner into your CI/CD pipeline, automate them to run for every PR and manage them all in one place. Each vulnerability alert comes with detailed reporting and remediation suggestions so you can take action right away.

4. Get your IAM game on

Lastly, base your IAM strategy on the Principle of Least Privilege, ensuring that users have the minimum number of privileges they need to perform their tasks - and nothing else. Implement strong authentication mechanisms such as Time-based One-Time Passwords (TOTP) or Certificate-based Authentication (CA) and closely monitor user identity and activity to identify gaps and restrict access controls where possible.

A 360-degree approach to defending your SDLC

Attackers are not cutting corners when it comes to discovering new ways to get into your systems - in fact, they are adding new ones. Thankfully, you don’t have to reinvent the wheel to protect your SDLC: continuous and automated security will do the job for you. Specialized DevSecOps tools like Jit integrate all the testing capabilities you need into your CI/CD while making it easier to manage different tools and react to their findings promptly. Explore more here.