Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improves season 1 level 3 solution #113

Merged
merged 6 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
"extensions": ["ms-python.python", "ms-python.vscode-pylance", "ms-vscode.cpptools-extension-pack", "redhat.vscode-yaml", "golang.go"]
}
},
"postCreateCommand": "npm install --prefix Season-2/Level-4/ Season-2/Level-4/ && npm install --global mocha"
"postCreateCommand": "npm install --prefix Season-2/Level-3/ Season-2/Level-3/ && npm install --global mocha"
}
2 changes: 1 addition & 1 deletion Season-1/Level-2/hack.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// As all other levels, your goal is to get this file to pass.

// Run hack by opening a terminal and running the following:
// $ make Season-1/Level-2/hack && ./Season-1/Level-2/hack
// $ make -B Season-1/Level-2/hack && ./Season-1/Level-2/hack

// As a reminder, to pass this level, both this file alongside tests.c must pass.

Expand Down
2 changes: 1 addition & 1 deletion Season-1/Level-2/tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// This file contains passing tests.

// Run them by opening a terminal and running the following:
// $ make Season-1/Level-2/tests && ./Season-1/Level-2/tests
// $ make -B Season-1/Level-2/tests && ./Season-1/Level-2/tests

#include "code.h"

Expand Down
91 changes: 61 additions & 30 deletions Season-1/Level-3/solution.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,65 @@
import os
# Model solution follows

# Example of a secure function that doesn't suffer from path traversal
def safe_path(path):
base_dir = os.path.dirname(os.path.abspath(__file__))
filepath = os.path.normpath(os.path.join(base_dir, path))
if base_dir != os.path.commonpath([base_dir, filepath]):
return None
return filepath

# Following the above, this is the secure version of the respective function on code.py
def get_prof_picture(self, path=None):
# setting a profile picture is optional
if not path:
pass

# defends against path traversal attacks
if path.startswith('/') or path.startswith('..'):
return None

# builds path
base_dir = os.path.dirname(os.path.abspath(__file__))
prof_picture_path = os.path.normpath(os.path.join(base_dir, path))
if base_dir != os.path.commonpath([base_dir, prof_picture_path]):
return None

with open(prof_picture_path, 'rb') as pic:
picture = bytearray(pic.read())

# assume that image is returned on screen after this
return prof_picture_path
import os
from flask import Flask, request

### Unrelated to the exercise -- Starts here -- Please ignore
app = Flask(__name__)
@app.route("/")
def source():
TaxPayer('foo', 'bar').get_tax_form_attachment(request.args["input"])
TaxPayer('foo', 'bar').get_prof_picture(request.args["input"])
### Unrelated to the exercise -- Ends here -- Please ignore

class TaxPayer:

def __init__(self, username, password):
self.username = username
self.password = password
self.prof_picture = None
self.tax_form_attachment = None

# returns the path of an optional profile picture that users can set
def get_prof_picture(self, path=None):
# setting a profile picture is optional
if not path:
pass

# defends against path traversal attacks
if path.startswith('/') or path.startswith('..'):
return None

# builds path
base_dir = os.path.dirname(os.path.abspath(__file__))
prof_picture_path = os.path.normpath(os.path.join(base_dir, path))
if base_dir != os.path.commonpath([base_dir, prof_picture_path]):
return None

with open(prof_picture_path, 'rb') as pic:
Fixed Show fixed Hide fixed
picture = bytearray(pic.read())

# assume that image is returned on screen after this
return prof_picture_path

# returns the path of an attached tax form that every user should submit
def get_tax_form_attachment(self, path=None):
tax_data = None

# A tax form is required
if not path:
raise Exception("Error: Tax form is required for all users")

# Validate the path to prevent path traversal attacks
base_dir = os.path.dirname(os.path.abspath(__file__))
tax_form_path = os.path.normpath(os.path.join(base_dir, path))
if base_dir != os.path.commonpath([base_dir, tax_form_path]):
return None

with open(tax_form_path, 'rb') as form:
Fixed Show fixed Hide fixed
tax_data = bytearray(form.read())

# assume that tax data is returned on screen after this
return tax_form_path


# Solution explanation
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion Season-2/Level-4/code.js → Season-2/Level-3/code.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Welcome to Secure Code Game Season-2/Level-4!
// Welcome to Secure Code Game Season-2/Level-3!

// Follow the instructions below to get started:

Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions Season-2/Level-4/hack.js → Season-2/Level-3/hack.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// Run hack.js by following the instructions below:

// Run file by opening a terminal and running the following:
// $ mocha Season-2/Level-4/hack.js
// $ mocha Season-2/Level-3/hack.js

// If you're inside a Codespace, the above should be running smoothly.

// In case you're running this locally, please run the following command first,
// and then run the hack file:
// $ npm install Season-2/Level-4/ && npm install --global mocha
// $ npm install Season-2/Level-3/ && npm install --global mocha

const app = require("./code");
// const app = require("./solution"); // To test the solution, uncomment this line and comment the one above
Expand Down
9 changes: 8 additions & 1 deletion Season-2/Level-3/hint.txt
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
How does the site handle user input before and after displaying it?
Entities are primarily used to make XML documents more modular, maintainable, and efficient.
Hackers always look for unconventional ways of exploiting a feature.

Especially if that feature (replaceEntities) allows them to retrieve file contents from the server.
The server also appears to behave differently when retrieving files with a specific extension.

Can you trick the server into uploading files with that special extension and.. have an impact to what this code does?
But do we really need the upload endpoint? Why did the developer create it in the first place?
File renamed without changes.
File renamed without changes.
File renamed without changes.
4 changes: 2 additions & 2 deletions Season-2/Level-4/tests.js → Season-2/Level-3/tests.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// Run tests.js by following the instructions below:

// Run file by opening a terminal and running the following:
// $ mocha Season-2/Level-4/tests.js
// $ mocha Season-2/Level-3/tests.js

// If you're inside a Codespace, the above should be running smoothly.

// In case you're running this locally, please run the following command
// first, and then run the tests' file:
// $ npm install Season-2/Level-4/ && npm install --global mocha
// $ npm install Season-2/Level-3/ && npm install --global mocha

const app = require("./code");
// const app = require("./solution"); // To test the solution, uncomment this line and comment the one above
Expand Down
6 changes: 3 additions & 3 deletions Season-2/Level-3/code.py → Season-2/Level-4/code.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Welcome to Secure Code Game Season-2/Level-3!
# Welcome to Secure Code Game Season-2/Level-4!

# Follow the instructions below to get started:

Expand All @@ -12,15 +12,15 @@
# Run code.py (RECOMMENDED for this level) by following the instructions below:

# Run by opening a terminal and running the following:
# $ export FLASK_APP=Season-2/Level-3/code.py && export FLASK_ENV=development && export FLASK_DEBUG=0 && flask run
# $ export FLASK_APP=Season-2/Level-4/code.py && export FLASK_ENV=development && export FLASK_DEBUG=0 && flask run

import os
import re
from flask import Flask, request, render_template
app = Flask(__name__)

# Set the absolute path to the template directory
template_dir = os.path.abspath('Season-2/Level-3/templates')
template_dir = os.path.abspath('Season-2/Level-4/templates')
app.template_folder = template_dir

# Hard-coded planet data
Expand Down
File renamed without changes.
9 changes: 1 addition & 8 deletions Season-2/Level-4/hint.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1 @@
Entities are primarily used to make XML documents more modular, maintainable, and efficient.
Hackers always look for unconventional ways of exploiting a feature.

Especially if that feature (replaceEntities) allows them to retrieve file contents from the server.
The server also appears to behave differently when retrieving files with a specific extension.

Can you trick the server into uploading files with that special extension and.. have an impact to what this code does?
But do we really need the upload endpoint? Why did the developer create it in the first place?
How does the site handle user input before and after displaying it?
File renamed without changes.
2 changes: 1 addition & 1 deletion Season-2/Level-3/tests.py → Season-2/Level-4/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# This file contains passing tests.

# Run them by opening a terminal and running the following:
# $ python3 Season-2/Level-3/tests.py
# $ python3 Season-2/Level-4/tests.py

# Note: first you have to run code.py following the instructions
# on top of that file so that the environment variables align but
Expand Down
48 changes: 24 additions & 24 deletions Season-2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,87 +82,87 @@ Due to the nature of file conventions in the `go` programming language, some fil

If you need assistance, don't hesitate to ask for help in our [GitHub Discussions](https://github.com/skills/secure-code-game/discussions) or on our [Slack](https://gh.io/securitylabslack) in the [#secure-code-game](https://ghsecuritylab.slack.com/archives/C05DH0PSBEZ) channel.

## Season 2 - Level 3: Space-Crossing
## Season 2 - Level 3: Planet XMLon

_Nice work finishing Level 2: Lumberjack ! It's now time for Level 3: Space-Crossing_ :sparkles:
_Nicely done! Level 2: Lumberjack is complete. It's time for Level 3: Planet XMLon_ :partying_face:

Languages: `python3`
Languages: `javascript`

### 🚀 Credits

The author of this level is [Viral Vaghela](https://www.linkedin.com/in/viralv/).
The author of this level is Deniz Onur Duzgun [@dduzgun-security](https://github.com/dduzgun-security).

You can be next! We welcome contributions for new game levels! Learn more [here](https://github.com/skills/secure-code-game/blob/main/CONTRIBUTING.md).

### 📝 Storyline

Our solar system is 4.6 billion years old and it's constantly expanding. So does human interest around the world with local communities of enthusiasts constantly forming in an increasingly digitized world. Space enthusiasts use the internet as an information bank and to connect with their counterparts. This was exactly what drove a local community of space enthusiasts to create a public website, featuring their meetups, alongside contact information and a simple search bar where users can discover rare facts about planets. Having said that, did you know that ninety-five per cent (95%) of the Universe is invisible? What percentage of security issues is invisible though, and for how long? Do you have what it takes to secure the site and progress to Level 4?
Embark on your quest as a daring EXXplorer in the vibrant landscape of the newly discovered Planet XMLon. The alien inhabitants are baffled by mysterious disruptions in their data transmissions, which may have been caused by the main developer E.T. who added more features than intended. Help them decode the extraterrestrial XML signals and unveil the secrets hidden within the starry constellations of tags, attributes and `.admin` files. Can you secure them all?

### :keyboard: Setup instructions

- For Levels 2-4 in Season 2, we encourage you to enable code scanning with CodeQL. For more information about CodeQL, see "[About CodeQL](https://codeql.github.com/docs/codeql-overview/about-codeql/)." For instructions on setting up code scanning, see "[Setting up code scanning using starter workflows](https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/setting-up-code-scanning-for-a-repository#setting-up-code-scanning-using-starter-workflows)."
For Levels 2-4 in Season 2, we encourage you to enable code scanning with CodeQL. For more information about CodeQL, see "[About CodeQL](https://codeql.github.com/docs/codeql-overview/about-codeql/)." For instructions on setting up code scanning, see "[Setting up code scanning using starter workflows](https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/setting-up-code-scanning-for-a-repository#setting-up-code-scanning-using-starter-workflows)."

### :keyboard: What's in the repo?

- `code` includes the vulnerable code to be reviewed.
- `hack` exploits the vulnerabilities in `code`. Running `hack` will fail initially and your goal is to get this file to pass 🟢.
- `hack.admin` is a file used by administrators for debugging purposes.
- `hint` offers guidance if you get stuck. Remember that you can also view the CodeQL scanning alerts.
- `package.json` contains all the dependencies required for this level. You can install them by running `npm install`.
- `package-lock.json` ensures that the same dependencies are installed consistently across different environments.
- `solution` provides one working solution. There are several possible solutions.
- `templates/index.html` host a simple front-end to interact with the back-end.
- `tests` contains the unit tests that should still pass 🟢 after you implement your fix.
- `.env.production` is an internal server-side file containing a secret environment variable.

### 🚦 Time to start!

1. Review the code in `code.py`. Can you spot the bug(s)?
1. Start by installing the dependencies required for this level, by running `npm install`. These dependancies reside inside `package.json`.
1. Review the code in `code.js`. Can you spot the bug(s)?
1. Try to fix the bug. Open a pull request to `main` or push your fix to a branch.
1. You successfully completed this level when you (a) resolve all related code scanning alerts and (b) when both `hack.py` and `tests.py` pass 🟢.
1. You successfully completed this level when you (a) resolve all related code scanning alerts and (b) when both `hack.js` and `tests.js` pass 🟢.
1. If you get stuck, read the hint and try again.
1. If you need more guidance, read the CodeQL scanning alerts.
1. Compare your solution to `solution.py`.
1. Compare your solution to `solution.js`.

If you need assistance, don't hesitate to ask for help in our [GitHub Discussions](https://github.com/skills/secure-code-game/discussions) or on our [Slack](https://gh.io/securitylabslack) in the [#secure-code-game](https://ghsecuritylab.slack.com/archives/C05DH0PSBEZ) channel.

## Season 2 - Level 4: Planet XMLon
## Season 2 - Level 4: Space-Crossing

_Nicely done! Level 3: Space-Crossing is complete. It's time for Level 4: Planet XMLon_ :partying_face:
_Nice work finishing Level 3: Planet XMLon! It's now time for Level 4: Space-Crossing_ :sparkles:

Languages: `javascript`
Languages: `python3`

### 🚀 Credits

The author of this level is Deniz Onur Duzgun [@dduzgun-security](https://github.com/dduzgun-security).
The author of this level is [Viral Vaghela](https://www.linkedin.com/in/viralv/).

You can be next! We welcome contributions for new game levels! Learn more [here](https://github.com/skills/secure-code-game/blob/main/CONTRIBUTING.md).

### 📝 Storyline

Embark on your quest as a daring EXXplorer in the vibrant landscape of the newly discovered Planet XMLon. The alien inhabitants are baffled by mysterious disruptions in their data transmissions, which may have been caused by the main developer E.T. who added more features than intended. Help them decode the extraterrestrial XML signals and unveil the secrets hidden within the starry constellations of tags, attributes and `.admin` files. Can you secure them all?
Our solar system is 4.6 billion years old and it's constantly expanding. So does human interest around the world with local communities of enthusiasts constantly forming in an increasingly digitized world. Space enthusiasts use the internet as an information bank and to connect with their counterparts. This was exactly what drove a local community of space enthusiasts to create a public website, featuring their meetups, alongside contact information and a simple search bar where users can discover rare facts about planets. Having said that, did you know that ninety-five per cent (95%) of the Universe is invisible? What percentage of security issues is invisible though, and for how long? Do you have what it takes to secure the site and progress to Level 4?

### :keyboard: Setup instructions

For Levels 2-4 in Season 2, we encourage you to enable code scanning with CodeQL. For more information about CodeQL, see "[About CodeQL](https://codeql.github.com/docs/codeql-overview/about-codeql/)." For instructions on setting up code scanning, see "[Setting up code scanning using starter workflows](https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/setting-up-code-scanning-for-a-repository#setting-up-code-scanning-using-starter-workflows)."
- For Levels 2-4 in Season 2, we encourage you to enable code scanning with CodeQL. For more information about CodeQL, see "[About CodeQL](https://codeql.github.com/docs/codeql-overview/about-codeql/)." For instructions on setting up code scanning, see "[Setting up code scanning using starter workflows](https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/setting-up-code-scanning-for-a-repository#setting-up-code-scanning-using-starter-workflows)."

### :keyboard: What's in the repo?

- `code` includes the vulnerable code to be reviewed.
- `hack` exploits the vulnerabilities in `code`. Running `hack` will fail initially and your goal is to get this file to pass 🟢.
- `hack.admin` is a file used by administrators for debugging purposes.
- `hint` offers guidance if you get stuck. Remember that you can also view the CodeQL scanning alerts.
- `package.json` contains all the dependencies required for this level. You can install them by running `npm install`.
- `package-lock.json` ensures that the same dependencies are installed consistently across different environments.
- `solution` provides one working solution. There are several possible solutions.
- `templates/index.html` host a simple front-end to interact with the back-end.
- `tests` contains the unit tests that should still pass 🟢 after you implement your fix.
- `.env.production` is an internal server-side file containing a secret environment variable.

### 🚦 Time to start!

1. Start by installing the dependencies required for this level, by running `npm install`. These dependancies reside inside `package.json`.
1. Review the code in `code.js`. Can you spot the bug(s)?
1. Review the code in `code.py`. Can you spot the bug(s)?
1. Try to fix the bug. Open a pull request to `main` or push your fix to a branch.
1. You successfully completed this level when you (a) resolve all related code scanning alerts and (b) when both `hack.js` and `tests.js` pass 🟢.
1. You successfully completed this level when you (a) resolve all related code scanning alerts and (b) when both `hack.py` and `tests.py` pass 🟢.
1. If you get stuck, read the hint and try again.
1. If you need more guidance, read the CodeQL scanning alerts.
1. Compare your solution to `solution.js`.
1. Compare your solution to `solution.py`.

If you need assistance, don't hesitate to ask for help in our [GitHub Discussions](https://github.com/skills/secure-code-game/discussions) or on our [Slack](https://gh.io/securitylabslack) in the [#secure-code-game](https://ghsecuritylab.slack.com/archives/C05DH0PSBEZ) channel.

Expand Down
Loading