GCP Security Lab: Intro to Web App Penetration Testing with DVWA

José ToledoJosé Toledo
19 min read

Disclaimers & Personal Context

  • My Views: This project and the views expressed in this blog post are my own and do not necessarily reflect the official stance or opinions of Google Cloud or any other entity.

  • Learning Journey: This lab is another opportunity for me to expand my self-learning journey across various cloud providers. I want to recognize that Google Cloud Platform has phenomenal, expertly built courses. If you're looking for structured, official training, check out Cloud Skills Boost – it's a fantastic resource!

  • Lab Environment: This lab is for educational purposes only. All activities are simulated within my dedicated lab project.

  • Cost & Cleanup: I'm using a fresh GCP account, similar to what a new user might experience. New GCP sign-ups typically come with a generous $300 in free credits, which should be more than enough to complete this lab without incurring significant costs. I'll provide a comprehensive cleanup section at the very end of this guide to help you remove all created resources and avoid any unexpected billing.

  • Crucial Tip: Always perform cloud labs in a dedicated, isolated project to avoid impacting production environments or existing resources. Ask me how I know – I may or may not have broken things by testing in production before... and learned the hard way!

Introduction

In my last post, I showed you how to defend a web application using Cloud Armor. But to be a security professional, it helps to understand what you're defending against! You have to think like an attacker.

This blog post is a new installment in my GCP Cybersecurity Series. This time, I'm taking a hands-on approach to introduce you to the world of web application penetration testing. We'll be using DVWA (Damn Vulnerable Web Application), a classic tool specifically designed to be insecure, so that you can safely practice and learn about common vulnerabilities.

Important Context: This is an Introduction, Not a Comprehensive Guide. It's important to understand that this lab is not a comprehensive course in web penetration testing. It's meant to be a high-level introduction to what these types of attacks look like in practice. The goal is to provide a thought exercise: as you perform these attacks, think about how you would detect them and, more importantly, how a defense-in-depth strategy (like the one you built with Cloud Armor in my previous post) would have prevented them.

The Plan:

  • Part 1: The Basics: I'll give you a quick overview of common web app vulnerabilities and some real-world impact.

  • Part 2: The Lab: We'll set up a secure-by-default VM on GCP to host our DVWA instance.

  • Part 3: The Attack: We'll then use our lab to demonstrate and exploit these vulnerabilities.

  • Part 4: The Defense: I'll show you where to find evidence of these attacks in Cloud Logging, connecting this lab back to the skills you've learned previously.

By the end, you'll have a much deeper appreciation for why tools like Cloud Armor are so critical for protecting web applications.

Be Prepared: This is a Comprehensive Lab! This guide covers a lot of ground and involves many steps. Depending on your experience and how many breaks you take, this lab could easily take 2-4 hours (or more) to complete from start to finish. Feel free to complete it in multiple sittings!

I recommend using Google Cloud Shell for this lab. To access Cloud Shell, simply click the rectangle icon with >_(typically located at the top-right of the GCP Console window).

Ethical Considerations & Responsible Security Testing

Critical Reminder: With Great Knowledge Comes Great Responsibility

Before we dive into the technical aspects of this lab, it's essential to establish the ethical foundation for everything we'll be doing. The techniques you're about to learn can be powerful tools that can be used for both protecting and attacking systems.

The Golden Rules of Ethical Security Testing:

  • Only test systems you own or have explicit written permission to test. This includes your own lab environments, systems where you have formal authorization, or official penetration testing platforms like DVWA, HackTheBox, or TryHackMe.

  • Never use these techniques against production systems, websites, or applications that don't belong to you - even if they appear vulnerable. Unauthorized testing is illegal and can result in serious legal consequences, including criminal charges.

  • Responsible Disclosure: If you discover vulnerabilities in real systems during authorized testing, follow responsible disclosure practices. This means privately notifying the organization first, giving them reasonable time to fix the issue before any public disclosure.

  • Professional Development Only: The goal of learning these techniques is to better understand how attacks work so you can more effectively defend against them. Think of yourself as a digital immune system - you're learning about threats to build better defenses.

Why This Matters: The cybersecurity industry relies on professionals who understand both sides of the security equation. By learning how attacks work in controlled environments, you become a more effective defender. However, this knowledge must always be applied ethically and legally.

Remember: We're building security professionals, not creating new threats. Use these skills to make the digital world safer for everyone.

Let’s get started!

Part 1: Web App Vulnerabilities 101

Before we dive into the hands-on lab, let's establish a common understanding of the web application vulnerabilities we'll be exploiting. My tool of choice for this is DVWA (Damn Vulnerable Web Application), an open-source PHP/MySQL web application intentionally built to be insecure. It serves as a legal and safe environment for security enthusiasts like us to practice penetration testing techniques. Many of the vulnerabilities present in DVWA are part of the OWASP Top 10, a widely recognized list of the most critical security risks to web applications published by the Open Worldwide Application Security Project.

Here's a quick look at some of the attacks we'll be simulating and why they pose a serious threat:

  • SQL Injection (SQLi): Imagine a website's login form. When you type your username and password, the application constructs a SQL query behind the scenes to check your credentials against a database. SQL Injection is an attack where I manipulate what I type into that form, not just with my username, but with snippets of malicious SQL code. If the application isn't careful about validating my input, it might execute my code, allowing me to bypass authentication, retrieve sensitive data from the database (like all user credentials or financial records), or even modify or delete information. This is a primary cause of massive data breaches we often hear about.

  • Cross-Site Scripting (XSS): This attack involves injecting malicious client-side script, typically JavaScript, into web pages that are then viewed by other users. Think of a comment section on a blog or a forum post. If the website doesn't properly sanitize user-submitted content, I could embed a script. When another user loads that page, their browser executes my script. With XSS, I could steal their session cookies (allowing me to hijack their login session), deface the website, redirect them to malicious phishing sites, or execute arbitrary code in their browser under the website's legitimate context.

  • Command Injection: Many web applications need to interact with the server's operating system, for example, to list files, ping an IP address, or run diagnostic tools. Command Injection exploits flaws in how these applications handle user input that gets passed to system commands. If input isn't sanitized, I can inject additional commands. A successful command injection can grant me arbitrary code execution on the server itself, potentially leading to full control over the compromised machine, allowing for malware installation, data exfiltration, or further network penetration.

  • File Inclusion (LFI/RFI): Web applications sometimes include files based on parameters in the URL (e.g., example.com/page.php?file=about.html). File Inclusion vulnerabilities arise when an attacker manipulates this parameter to include a file that was not intended. With Local File Inclusion (LFI), I can trick the application into displaying the contents of sensitive files already on the server (like password files or configuration files with credentials). With Remote File Inclusion (RFI), I might even be able to include and execute a file hosted on a remote server I control, which can lead to remote code execution and compromise the entire server.

  • File Upload: Many web applications allow users to upload files, such as profile pictures or documents. If the application doesn't properly validate the type and content of the uploaded files, I can upload a malicious file (often a "web shell" – a small script that gives me a remote command interface). Once the malicious file is uploaded, if I can access it via a web browser, I can execute arbitrary commands on the server, potentially gaining full control over the web server and its data.

Part 2: The Lab - Setting Up Your Test Environment on GCP

Goal: In this phase, I will deploy a Compute Engine VM and configure it to serve the DVWA web application.

  • Why GCP? You don't have to deploy DVWA on GCP. This is often something someone would do on their own machine in a local VM (using tools like VirtualBox or VMware Workstation), and you absolutely can do that if you prefer! However, I figured this was another great opportunity to test some of my GCP skills, specifically around deploying and securing a web server in the cloud. Plus, once you're done with this lab, you can come back and apply Cloud Armor (from my previous lab in this series) to this DVWA instance and try the attacks again, seeing how a WAF defends against them!

1. Set Essential Variables & Enable APIs

  • Why: This ensures my gcloud commands are consistent and my project has the necessary services enabled.

  • How to set: Copy and paste this block into your Cloud Shell:

      export GCP_PROJECT_ID="gcp-cloudarmor-lab-jt" # My example project ID
      export REGION="us-central1"
      export ZONE="${REGION}-a"
      export DVWA_VM_NAME="dvwa-lab-vm"
      export YOUR_EXTERNAL_IP="YOUR_EXTERNAL_IP_ADDRESS" # Replace with your actual external IP
    
      echo "Using project: $GCP_PROJECT_ID"
      gcloud config set project $GCP_PROJECT_ID
      gcloud services enable compute.googleapis.com --project=$GCP_PROJECT_ID
    

2. Create a Static External IP Address

  • Why: This static external IP address is a billable resource that will be permanently assigned to my dvwa-lab-vm. I'm creating it first to ensure the resource exists before I try to attach it to the VM.

  • How to create (gcloud CLI - Recommended):

      echo "Creating a new static external IP address 'dvwa-ip'..."
      gcloud compute addresses create dvwa-ip \
          --region=$REGION \
          --project=$GCP_PROJECT_ID
    
  • How to create (Cloud Console - Alternative):

    1. Navigate to VPC network > IP addresses in the GCP Console.

    2. Click + RESERVE EXTERNAL STATIC ADDRESS.

    3. Name: dvwa-ip

    4. Region: us-central1.

    5. Click RESERVE.

3. Deploy the VM (dvwa-lab-vm) and Attach the Static IP

  • Why: This VM will host my vulnerable web application. I will deploy it with the public IP I just created for easy access, but I will immediately lock it down with firewall rules.

  • How to deploy (gcloud CLI - Recommended):

      echo "Deploying new DVWA VM and attaching the static external IP..."
      gcloud compute instances create $DVWA_VM_NAME \
          --project=$GCP_PROJECT_ID \
          --zone=$ZONE \
          --machine-type=e2-medium \
          --network-interface=network=default,subnet=default,address=dvwa-ip \
          --tags=dvwa-server,ssh \
          --create-disk=auto-delete=yes,boot=yes,device-name=$DVWA_VM_NAME,image=projects/ubuntu-os-cloud/global/images/family/ubuntu-2204-lts,mode=rw,size=20,type=pd-balanced \
          --labels=app=dvwa,lab=pen-testing
    

4. Set Firewall Rules (CRITICAL STEP!)

  • Why: This step is absolutely critical for security. DVWA is deliberately vulnerable. You MUST ensure that only your IP address can access the VM via HTTP, and that SSH access is secure.

  • How to configure (gcloud CLI - Recommended):

      # IMPORTANT: You must replace 'YOUR_EXTERNAL_IP_ADDRESS' with your actual public IP!
      # Go to Google and search "what is my ip" to get this address.
      export YOUR_EXTERNAL_IP="YOUR_EXTERNAL_IP_ADDRESS"
    
      # Create a firewall rule to allow HTTP access only from YOUR IP (CRITICAL!)
      gcloud compute firewall-rules create allow-http-from-my-ip \
          --project=$GCP_PROJECT_ID \
          --network=default \
          --action=ALLOW \
          --direction=INGRESS \
          --rules=tcp:80 \
          --source-ranges=$YOUR_EXTERNAL_IP/32 \
          --target-tags=dvwa-server \
          --description="Allow HTTP access to DVWA only from my IP"
    
      # Create a firewall rule to allow SSH access via IAP (Simpler and Secure)
      gcloud compute firewall-rules create allow-ssh-iap-dvwa \
          --project=$GCP_PROJECT_ID \
          --network=default \
          --action=ALLOW \
          --direction=INGRESS \
          --rules=tcp:22 \
          --source-ranges=35.235.240.0/20 \
          --target-tags=ssh \
          --description="Allow SSH access to DVWA via IAP"
    

    Note: The /32 at the end of your IP address in --source-ranges specifies a single IP address.

5. Install DVWA and Its Dependencies

  • Goal: SSH into the VM and install the web server, database, and PHP components required for DVWA.

  • How to install (Inside VM SSH session - Recommended):

    • First, SSH into the VM:

        gcloud compute ssh $DVWA_VM_NAME --zone=$ZONE --project=$GCP_PROJECT_ID
      
    • Once inside the VM, run the following command to automatically install all dependencies and DVWA:

        sudo bash -c "$(curl --fail --show-error --silent --location https://raw.githubusercontent.com/IamCarron/DVWA-Script/main/Install-DVWA.sh)"
      
    • After it runs, the script will provide you with the DVWA login details. Be sure to note them down.

6. Verify Access & Finalize Setup

  • Goal: Confirm that the DVWA login page is accessible from your browser, and finalize the database setup. Also, confirm it's not accessible from an unauthorized source.

  • How to verify:

    • Get the external IP of your dvwa-lab-vm from gcloud compute instances list.

    • a. Verify Access from Your Allowed IP:

      • Open your web browser on your computer (whose IP is $YOUR_EXTERNAL_IP) and navigate to http://YOUR_DVWA_VM_EXTERNAL_IP/dvwa.

      • Expected: You should see the DVWA database setup screen.

    • b. Finalize Setup:

      • At the bottom of the DVWA page, click the "Create / Reset Database" button.

      • The page will reload and you will be taken to the DVWA login page. You can now log in with the default credentials (admin/password) provided by the script.

    • c. Demonstrate Inaccessibility from an Unauthorized IP (e.g., your cell phone):

      • Turn off Wi-Fi on your cell phone to ensure it's using cellular data (which will give it a different external IP address than your home/office network).

      • Expected: You should NOT be able to access the page. You should see a timeout or "site not reachable" error. This proves your firewall rule is working as intended to block unauthorized access.

        • (Remember to turn your cell phone's Wi-Fi back on when done!)
    • After verifying, type exit to close the SSH session and return to Cloud Shell:

        exit
      

Part 3: The Lab - Performing Web Attacks

Goal: Now that DVWA is installed and running, it's time to see its vulnerabilities in action. In this phase, I will use the DVWA lab environment to perform and understand some basic web application attacks.

  • Important: For each of these attacks, make sure you are logged into DVWA with the default credentials (admin/password). You should also navigate to DVWA Security in the left menu and set the Security Level to "low" to ensure the attacks are successful.

A Quick Guide to the DVWA Interface

DVWA's interface is straightforward, but it's helpful to know what to look for before we start.

  • Left-Hand Navigation: On the left side of the page, you'll see a navigation bar with a list of different vulnerabilities. We will be going through several of these, from SQL Injection to File Upload.

  • Security Level: The DVWA Security tab at the bottom of the navigation bar lets you change the security level of the application. The vulnerabilities have different levels of difficulty (low, medium, high, and impossible). For this lab, we'll set it to "low" to ensure our attacks are successful and easy to understand.

  • "View Source" and "View Help" Buttons: At the bottom of each challenge page, you'll find two helpful buttons:

    • View Help: This button provides a high-level explanation of the vulnerability and gives you hints on how to exploit it. It’s a great resource for learning.

    • View Source: This button shows you the underlying PHP code for the challenge page. You can review the code to see exactly why the page is vulnerable. This is the ultimate tool for understanding the flaw.

Knowing these features will make the lab much more effective! Now, let's get into the attack demonstrations.

1. SQL Injection (SQLi) Demonstration

  • Why: This demonstration shows how an attacker can bypass a normal application query and manipulate the underlying database to retrieve unauthorized information.

  • How to perform:

    1. Open your web browser and navigate to the DVWA login page at http://YOUR_DVWA_VM_EXTERNAL_IP/dvwa. Log in with the credentials provided by the install script.

    2. In the DVWA menu on the left, select SQL Injection.

    3. In the input field for "User ID," try a normal ID first (e.g., 1) and click "Submit." The result should show a single user's information.

    4. Now, enter the following SQLi payload to bypass the normal query and retrieve all users from the database:

       1' or '1'='1
      
      • Analyze: This payload closes the initial SQL query with 1', adds a new condition or '1'='1' (which is always true), and then comments out the rest of the original query.

      • Expected Result: The page should now display a table of all users in the database, demonstrating that the SQLi attack was successful.

2. Cross-Site Scripting (XSS) Demonstration

  • Why: This attack demonstrates how a malicious script can be injected into a web page and executed by a user's browser.

  • How to perform:

    1. In the DVWA menu on the left, select XSS (Reflected).

    2. In the "Enter your name" input field, enter the following XSS payload:

       <script>alert('XSS!');</script>
      
      • Expected Result: A JavaScript pop-up window should appear in your browser with the message "XSS!". This confirms the malicious script was successfully injected and executed by your browser.

3. Command Injection Demonstration

  • Why: This demonstration shows how an attacker can execute commands on the server's operating system.

  • How to perform:

    1. In the DVWA menu on the left, select Command Injection.

    2. In the input field, enter a simple command like 127.0.0.1 and click "Submit." The result will show the output of a ping command from the server.

    3. Now, enter the following Command Injection payload to execute a second, unauthorized command (in this case, ls -l):

       127.0.0.1 && ls -l
      
      • Expected Result: The page will display the output of the ping command, followed by the output of the ls -l command, demonstrating that you successfully injected and executed a second command on the server.

4. File Inclusion Demonstration (LFI)

  • Why: This attack demonstrates how a vulnerability can expose the underlying file system, allowing an attacker to read sensitive files that should never be public.

  • How to perform:

    1. In the DVWA menu on the left, select File Inclusion.

    2. In the URL of your browser, you'll see a parameter like page=.... Change the URL path to read a sensitive local file on the server. For example, to read the /etc/passwd file, change the URL to:

       http://YOUR_DVWA_VM_EXTERNAL_IP/dvwa/vulnerabilities/fi/?page=../../../../../../etc/passwd
      
      • Expected Result: The contents of the /etc/passwd file (a common file containing user account information) will be displayed in your browser, demonstrating a successful Local File Inclusion (LFI) attack.

5. File Upload Demonstration

  • Why: This attack shows how an insecure file upload can allow an attacker to upload and execute malicious code, potentially leading to full server compromise.

  • How to perform:

    1. Open your favorite text editor on your local machine and paste in the following PHP code, saving the file as malicious.php:

       <?php echo shell_exec($_GET["cmd"]); ?>
      

      This is a very basic "web shell" that will execute whatever command (cmd) is passed to it via the URL.

    2. In the DVWA menu on the left, select File Upload.

    3. Click the "Choose File" button and select the malicious.php file you just created on your local machine.

    4. Click Upload.

    5. The file will be uploaded to a specific directory on the server (usually ../../hackable/uploads/). Now, navigate to the URL for that file to execute it and run a command (e.g., id):

       http://YOUR_DVWA_VM_EXTERNAL_IP/DVWA/hackable/uploads/malicious.php?cmd=id
      
      • Expected Result: The page should display the output of the id command (e.g., uid=33(www-data) gid=33(www-data) groups=33(www-data)), demonstrating that you were able to upload a malicious file and execute a command on the server.

Part 4: The Defense - The Challenge

Goal: Now that you've seen these web attacks in action, it's time to put all the skills from this series together. Instead of me walking you through the logging and WAF setup, I'm giving you a challenge to do it yourself!

Your Challenge: Connect the Defense to the Offense

  1. Set up Logging for DVWA: Go back to my post on GCP Cybersecurity Lab: Unmasking Malicious Activity with Cloud Logging & Monitoring and follow the instructions to set up the Ops Agent. Your goal is to configure the Ops Agent on your dvwa-lab-vm to collect Apache access logs. Once that's done, re-run your attacks and see if you can find the evidence of your attacks in Cloud Logging.

  2. Enable Cloud Armor: Go back to my post on GCP Security Lab: Shielding Your Web Apps with Cloud Armor WAF and follow the instructions to create and attach a Cloud Armor security policy. Create rules to specifically block the SQLi, XSS, and File Upload payloads.

  3. Test Your Defense: Once Cloud Armor is enabled, try performing the same attacks again. Your goal is to see a 403 Forbidden message and for the attacks to fail.

  4. Verify the Blocks: Check Cloud Logging again to see how the logs change. Instead of 200 OK responses in Apache's logs, you should see evidence in the Load Balancer's logs that Cloud Armor blocked the requests.

This challenge will reinforce everything you've learned so far and give you a complete, end-to-end understanding of the security lifecycle in GCP. I find one of the downsides of tutorials is that they often don’t push you to try something different, this is my way of helping push you to that. I specifically built all of these labs in a sequence so they could build on each other and lead you to this.

Part 5: Cleaning Up Your Lab Environment

  • Why clean up? This is a critical final step in any cloud lab! To avoid incurring unnecessary costs for resources you're no longer using and to keep your GCP project tidy, it's essential to delete all the resources I created during this lab.

I'll provide gcloud CLI commands for quick cleanup, and I'll outline the Console steps as well.

Important Note on Deletion Order: Resources sometimes have dependencies (e.g., you can't delete a network address while it's in use). I'll provide the commands in a logical order to minimize dependency errors.

1. Delete the DVWA VM

  • Why: The VM is the primary source of cost for this lab. Deleting it first ensures you stop accruing compute charges.

  • How to delete (gcloud CLI - Recommended):

      echo "Deleting the DVWA VM: $DVWA_VM_NAME..."
      gcloud compute instances delete $DVWA_VM_NAME --zone=$ZONE --project=$GCP_PROJECT_ID --quiet
    
  • How to delete (Cloud Console - Alternative):

    1. Navigate to Compute Engine > VM instances in the GCP Console.

    2. Select the checkbox next to dvwa-lab-vm.

    3. Click the DELETE button at the top and confirm the deletion.

2. Delete Static External IP Address

  • Why: Static IP addresses are a billable resource. Releasing it ensures you're no longer charged for it.

  • How to delete (gcloud CLI - Recommended):

      echo "Deleting the static external IP address 'dvwa-ip'..."
      gcloud compute addresses delete dvwa-ip --region=$REGION --project=$GCP_PROJECT_ID --quiet
    
  • How to delete (Cloud Console - Alternative):

    1. Navigate to VPC network > IP addresses in the GCP Console.

    2. Find the dvwa-ip address.

    3. Click the checkbox next to it.

    4. Click the DELETE STATIC ADDRESS button at the top and confirm the deletion.

3. Delete Firewall Rules

  • Why: While generally free, keeping unnecessary firewall rules is a bad security practice.

  • How to delete (gcloud CLI - Recommended):

      echo "Deleting firewall rules for DVWA..."
      gcloud compute firewall-rules delete allow-http-from-my-ip allow-ssh-iap-dvwa --project=$GCP_PROJECT_ID --quiet
    
  • How to delete (Cloud Console - Alternative):

    1. Navigate to VPC Network > Firewall rules in the GCP Console.

    2. Select the checkboxes next to allow-http-from-my-ip and allow-ssh-iap-dvwa.

    3. Click the DELETE button at the top and confirm the deletion.

4. Delete the Entire GCP Project (Most Comprehensive Cleanup)

  • Why: This is the most thorough way to ensure all resources and associated configurations are removed, guaranteeing no further costs.

  • How to delete (Cloud Console - Recommended):

    1. Go to IAM & Admin > Settings in the GCP Console.

    2. Click SHUT DOWN.

    3. Enter your Project ID (gcp-cloudarmor-lab-jt) to confirm. Note: Project deletion can take several days to complete fully.

Conclusion & Next Steps

Phew! If you've made it this far (especially if you did the challenges), congratulations! You've successfully navigated a comprehensive GCP cybersecurity lab. You've gone from building a secure environment to tearing down its defenses in a safe way, and now you have a much deeper appreciation for why tools like Cloud Armor are so critical.

This lab serves as an excellent foundation and a great way to familiarize yourself with deploying web applications and applying security controls within GCP. It also gives you a hands-on taste of how attackers exploit common vulnerabilities.

What's Next? This lab touched upon just a few facets of GCP security. In future posts, I'll continue to explore more topics.

Just like always, the journey of learning cybersecurity never truly ends.

Thanks for making it to the end. Keep learning! See ya soon :).

0
Subscribe to my newsletter

Read articles from José Toledo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

José Toledo
José Toledo