Skip to content

Commit

Permalink
Merge pull request #463 from cmu-sei/v8
Browse files Browse the repository at this point in the history
readme and endpoint cleanup for html, css and js
  • Loading branch information
sei-dupdyke authored Nov 6, 2024
2 parents 5151e0f + 614a373 commit 49e7159
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 106 deletions.
18 changes: 0 additions & 18 deletions src/ghosts.pandora/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,24 +71,6 @@
app.include_router(iso_routes.router)


@app.get("/", tags=["Information"])
async def hello_world() -> Response:
"""
Returns a simple 'Hello World' message.
Returns:
Response: A response containing 'Hello World'.
"""
logger.info("Received request for Hello World endpoint.")
try:
response = Response(content="Hello World", status_code=200)
logger.info("Successfully generated Hello World response.")
return response
except Exception as e:
logger.error(f"Error in Hello World endpoint: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")


@app.get("/about", tags=["Information"])
async def about() -> dict:
"""
Expand Down
44 changes: 40 additions & 4 deletions src/ghosts.pandora/app/routes/html_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import zipfile
from io import BytesIO
from utils.helper import generate_random_name
import random

router = APIRouter()
fake = Faker()
Expand Down Expand Up @@ -83,7 +84,7 @@ def return_chm(file_name: str = None) -> StreamingResponse:

return response


@router.get("/", tags=["Information"])
@router.get("/html", tags=["Web"])
@router.post("/html", tags=["Web"])
@router.get("/html/{file_name}", tags=["Web"])
Expand All @@ -99,17 +100,28 @@ def return_html(file_name: str = None) -> HTMLResponse:
logger.info(f"Generating HTML file: {file_name}")

# Create random HTML content
title = fake.text()

body = ""
for _ in range(random.randint(1, 20)):
if random.randint(2, 100) > 55:
body = body + f"<h3>{fake.sentence().replace('.','')}</h3>"
body = body + f"<p>{fake.paragraph(nb_sentences=random.randint(1, 100))}</p>"
if random.randint(1, 100) > 85:
body = body + f"<img src='images/{fake.word()}.png?h={random.randint(80, 200)}&w={random.randint(200, 400)}'/>"

header = f'<script type="text/javascript" src="/scripts/{fake.uuid4()}.js"></script><link rel="stylesheet" href="/css/{fake.uuid4()}/{fake.word()}.css" type="text/css" />'
html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random HTML File</title>
{header}
<title>{title}</title>
</head>
<body>
<h1>Random HTML Content</h1>
<p>{fake.paragraph()}</p>
{body}
</body>
</html>
"""
Expand All @@ -120,3 +132,27 @@ def return_html(file_name: str = None) -> HTMLResponse:
logger.info("HTML file generated successfully.")

return response

@router.get("/{file_path:path}.css", tags=["Web"])
def return_css(file_name: str = None) -> HTMLResponse:

fonts=["sans-serif","serif","geneva","georgia","Arial","Verdana","Helvetica","Tahoma","Trebuchet MS","Times New Roman","Garamond","Courier New"]

content = "* {font-family:" + random.choice(fonts) + "} h1 {font-family:" + random.choice(fonts) + "} body {width:" + str(random.randint(65, 100)) + "%;}"

response = HTMLResponse(content=content, media_type="text/css")

logger.info("css file generated successfully.")

return response

@router.get("/{file_path:path}.js", tags=["Web"])
def return_css(file_name: str = None) -> HTMLResponse:

content = f"console.log('{fake.word()}, /{fake.date()}');"

response = HTMLResponse(content=content, media_type="text/javascript")

logger.info("js file generated successfully.")

return response
143 changes: 59 additions & 84 deletions src/ghosts.pandora/readme.md
Original file line number Diff line number Diff line change
@@ -1,74 +1,49 @@
You're right; with FastAPI, the application should typically be run using an ASGI server like Uvicorn. The command `python app.py` would not work unless you've set up an entry point for running the application within `app.py`.
# GHOSTS PANDORA SERVER

To run the FastAPI application, you would use the `uvicorn` command as mentioned earlier. Here’s the corrected section of the documentation:
GHOSTS PANDORA is a web server that responds to a myriad of request types with randomized content generated in real-time. Used in conjunction with [GHOSTS](https://github.com/cmu-sei/GHOSTS) NPCs, the two can provide for agents that are periodically downloading content other than simple HTML and associated image, CSS, and JS files.

### Running the FastAPI Application
## Running this server

To run the FastAPI application using Uvicorn, execute the following command:
Pandora is a FastAPI application — run it using Uvicorn by executing the following command in app directory:

```bash
uvicorn app:app --host 0.0.0.0 --port 80 --reload
```

### Updated Documentation

Here's the revised documentation reflecting this correction:

```markdown
__ _ __ ___ __ _ _ _ _
/__ |_| / \ (_ | (_ |_) /\ |\ | | \ / \ |_) /\
\_| | | \_/ __) | __) | /--\ | \| |_/ \_/ | \ /--\

uvicorn main:app --host 0.0.0.0 --port 80 --reload
```

# GHOSTS PANDORA SERVER

GHOSTS PANDORA is a web server that responds to a myriad of request types with randomized content generated in real-time. Used in conjunction with [GHOSTS](https://github.com/cmu-sei/GHOSTS) NPCs, the two can provide for agents that are periodically downloading content other than simple HTML and associated image, CSS, and JS files.

## Running this server

### Creating a Virtual Environment

1. **Navigate to your project directory.**
2. **Create a virtual environment:**
```bash
python3 -m venv venv
```
```bash
python3 -m venv venv
```
3. **Activate the virtual environment:**
- On Linux/Mac:
```bash
source venv/bin/activate
```
- On Windows:
```bash
venv\Scripts\activate
```
- On Linux/Mac:
```bash
source venv/bin/activate
```
- On Windows:
```bash
venv\Scripts\activate
```

### Bare Metal

This assumes the host server is a common Linux distribution. For images to render correctly, the PIL or the more recent Pillow library is necessary. See here for more information on [Pillow installation and configuration](https://pillow.readthedocs.io/en/latest/installation.html).

1. Using a Python 3 distribution >= 3.9.0
2. In the terminal, run:
```bash
pip install -r requirements.txt
```

### Running the FastAPI Application

To run the FastAPI application using Uvicorn, execute the following command:

```bash
uvicorn app:app --host 0.0.0.0 --port 80 --reload
```
```bash
pip install -r requirements.txt
```

### As a Docker Container

1. See the included `docker-compose.yml` file.
2. Run:
```bash
docker-compose up -d
```
```bash
docker-compose up -d
```

## Capabilities

Expand All @@ -77,14 +52,15 @@ uvicorn app:app --host 0.0.0.0 --port 80 --reload
To enable streaming video:

1. In the container's `/usr/src/app/app.config` file:
```bash
$ docker exec -it pandora /bin/bash
$ vi /usr/src/app/app.config
[video]
video_enabled=False
nginx_enabled=False
```
```bash
$ docker exec -it pandora /bin/bash
$ vi /usr/src/app/app.config
[video]
video_enabled=False
nginx_enabled=False
```
2. Set these to `True`, save the file, and exit.
3. Exit the container and restart it. It should start.
Expand All @@ -93,45 +69,45 @@ To enable streaming video:
### By Directory
- **/api** - All requests beginning with `/api` automatically respond with JSON. This includes:
- `/api/users`
- `/api/user/a320f971-b3d9-4b79-bb8d-b41d02572942`
- `/api/reports/personnel`
- **/csv** - All requests beginning with `/csv` automatically respond with CSV. Like the above, this includes URLs such as:
- `/csv/users`
- `/csv/user/winx.jalton`
- `/csv/reports/HR/payroll`
- **/i, /img, /images** - All requests beginning with these directories automatically respond with a random image of type [gif, jpg, png]. Examples:
- `/i/v1/a9f6e2b7-636c-4821-acf4-90220f091351/f8f8b1f0-9aa5-4fc7-8880-379e3192748e/small`
- `/images/products/184f3515-f49b-4e07-8c8b-7f978666df0e/view`
- `/img/432.png`
- **/pdf** - All requests respond with a random PDF document. Examples:
- `/pdf/operations/SOP_Vault/a7f48bd5-84cb-43a1-8d3d-cd2c732ddff6`
- `/pdf/products`
- **/docs** - All requests respond with a random Word document.
- **/slides** - All requests respond with a random PowerPoint document.
- **/sheets** - All requests respond with a random Excel document.
- **/api** - All requests beginning with `/api` automatically respond with JSON. This includes:
- `/api/users`
- `/api/user/a320f971-b3d9-4b79-bb8d-b41d02572942`
- `/api/reports/personnel`
- **/csv** - All requests beginning with `/csv` automatically respond with CSV. Like the above, this includes URLs such as:
- `/csv/users`
- `/csv/user/winx.jalton`
- `/csv/reports/HR/payroll`
- **/i, /img, /images** - All requests beginning with these directories automatically respond with a random image of type [gif, jpg, png]. Examples:
- `/i/v1/a9f6e2b7-636c-4821-acf4-90220f091351/f8f8b1f0-9aa5-4fc7-8880-379e3192748e/small`
- `/images/products/184f3515-f49b-4e07-8c8b-7f978666df0e/view`
- `/img/432.png`
- **/pdf** - All requests respond with a random PDF document. Examples:
- `/pdf/operations/SOP_Vault/a7f48bd5-84cb-43a1-8d3d-cd2c732ddff6`
- `/pdf/products`
- **/docs** - All requests respond with a random Word document.
- **/slides** - All requests respond with a random PowerPoint document.
- **/sheets** - All requests respond with a random Excel document.
### By Request Type
For requests indicating a specific file type, there are a number of specific handlers built to respond with that particular kind of file, such as:
- .csv
- Image requests [.gif, .ico, .jpg, .jpeg, .png]
- .json
- Office document requests
- .doc, .docx
- .ppt, .pptx
- .xls, .xlsx
- .pdf
- .csv
- Image requests [.gif, .ico, .jpg, .jpeg, .png]
- .json
- Office document requests
- .doc, .docx
- .ppt, .pptx
- .xls, .xlsx
- .pdf
So that a URL such as `/users/58361185-c9f2-460f-ac45-cb845ba88574/profile.pdf` would return a PDF document typically rendered right in the browser.
All unhandled request types, URLs without a specific file indicator, or requests made outside specifically handled directories (from the preceding section) are returned as HTML, including:
- `/docs/by_department/operations/users`
- `/blog/d/2022/12/4/blog_title-text`
- `/hello/index.html`
- `/docs/by_department/operations/users`
- `/blog/d/2022/12/4/blog_title-text`
- `/hello/index.html`
## API Documentation
Expand All @@ -140,4 +116,3 @@ API documentation can be found at `/docs`.
[DISTRIBUTION STATEMENT A] This material has been approved for public release and unlimited distribution.
Copyright 2017 Carnegie Mellon University. All Rights Reserved. See LICENSE.md file for terms.
```

0 comments on commit 49e7159

Please sign in to comment.