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

Log warning if used with ESM #526

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
71 changes: 71 additions & 0 deletions end2end/tests/hono-sqlite3-esm.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const t = require("tap");
const { spawn } = require("child_process");
const { resolve, join } = require("path");
const timeout = require("../timeout");

const appDir = resolve(__dirname, "../../sample-apps/hono-sqlite3-esm");
const pathToApp = join(appDir, "app.js");

t.test("it logs esm warnings", (t) => {
const server = spawn(`node`, [pathToApp, "4004"], {
env: { ...process.env, AIKIDO_DEBUG: "true", AIKIDO_BLOCKING: "true" },
cwd: appDir,
});

server.on("close", () => {
t.end();
});

server.on("error", (err) => {
t.fail(err.message);
});

let stdout = "";
server.stdout.on("data", (data) => {
stdout += data.toString();
});

let stderr = "";
server.stderr.on("data", (data) => {
stderr += data.toString();
});

// Wait for the server to start
timeout(2000)
.then(() => {
return Promise.all([
fetch("http://127.0.0.1:4004/add", {
method: "POST",
body: JSON.stringify({ name: "Test'), ('Test2');--" }),
headers: {
"Content-Type": "application/json",
},
signal: AbortSignal.timeout(5000),
}),
fetch("http://127.0.0.1:4004/add", {
method: "POST",
body: JSON.stringify({ name: "Miau" }),
headers: {
"Content-Type": "application/json",
},
signal: AbortSignal.timeout(5000),
}),
]);
})
.then(([sqlInjection, normalAdd]) => {
t.equal(sqlInjection.status, 200); // Not blocked
t.equal(normalAdd.status, 200);
t.match(
stderr,
/Your application seems to be running in ESM mode\. Zen does not support ESM at runtime yet\./
);
t.match(stdout, /Starting agent/);
t.notMatch(stderr, /Zen has blocked an SQL injection/); // Not supported
})
.catch((error) => {
t.fail(error.message);
})
.finally(() => {
server.kill();
});
});
8 changes: 8 additions & 0 deletions end2end/tests/hono-sqlite3.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ t.test("it blocks in blocking mode", (t) => {
t.equal(normalAdd.status, 200);
t.match(stdout, /Starting agent/);
t.match(stderr, /Zen has blocked an SQL injection/);
t.notMatch(
stderr,
/Your application seems to be running in ESM mode\. Zen does not support ESM at runtime yet\./
);
})
.catch((error) => {
t.fail(error.message);
Expand Down Expand Up @@ -114,6 +118,10 @@ t.test("it does not block in dry mode", (t) => {
t.equal(normalAdd.status, 200);
t.match(stdout, /Starting agent/);
t.notMatch(stderr, /Zen has blocked an SQL injection/);
t.notMatch(
stderr,
/Your application seems to be running in ESM mode\. Zen does not support ESM at runtime yet\./
);
})
.catch((error) => {
t.fail(error.message);
Expand Down
17 changes: 17 additions & 0 deletions library/helpers/isESM.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Checks at runtime if the Node.js application is using ESM.
* As it depends on the stack trace, it should be used directly after the file got imported / at top level of the library.
*/
export function isESM() {
// Save current stack trace limit and increase it a bit, to make sure we don't get too few frames
const currentStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 15;

// Capture the current stack trace
const stack = new Error().stack || "";

// Reset stack trace limit
Error.stackTraceLimit = currentStackTraceLimit;

return stack.includes("node:internal/modules/esm/loader:");
}
9 changes: 8 additions & 1 deletion library/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* eslint-disable import/no-unused-modules */
/* eslint-disable import/no-unused-modules, no-console */
import isFirewallSupported from "./helpers/isFirewallSupported";
import shouldEnableFirewall from "./helpers/shouldEnableFirewall";
import { setUser } from "./agent/context/user";
Expand All @@ -8,11 +8,18 @@ import { addHonoMiddleware } from "./middleware/hono";
import { addHapiMiddleware } from "./middleware/hapi";
import { addFastifyHook } from "./middleware/fastify";
import { addKoaMiddleware } from "./middleware/koa";
import { isESM } from "./helpers/isESM";

const supported = isFirewallSupported();
const shouldEnable = shouldEnableFirewall();

if (supported && shouldEnable) {
if (isESM()) {
console.warn(
"AIKIDO: Your application seems to be running in ESM mode. Zen does not support ESM at runtime yet."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why don't we return then?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It just feels safer in case there are false positive detections of the execution mode. One possibility I can think of but that's really rare is a ESM module loaded in a CJS project using something like TypeScript Execute (tsx) that also wraps require before we do.

);
}

require("./agent/protect").protect();
}

Expand Down
31 changes: 31 additions & 0 deletions sample-apps/hono-sqlite3-esm/Cats.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { promisify } from "util";

export class Cats {
/**
*
* @param {import("sqlite3").Database} db
*/
constructor(db) {
this.db = db;
this.all = promisify(this.db.all).bind(this.db);
}

async add(name) {
const result = await this.all(
`INSERT INTO cats(petname) VALUES ('${name}');`
);
return result;
}

async byName(name) {
const cats = await this.all(
`SELECT petname FROM cats WHERE petname = '${name}';`
);
return cats.map((row) => row.petname);
}

async getAll() {
const cats = await this.all("SELECT petname FROM cats;");
return cats.map((row) => row.petname);
}
}
110 changes: 110 additions & 0 deletions sample-apps/hono-sqlite3-esm/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { getDB } from "./db.js";
import * as Aikido from "@aikidosec/firewall";
import { Cats } from "./Cats.js";

const app = new Hono();

app.use(async (c, next) => {
Aikido.setUser({
id: "id",
name: "Name",
});

await next();
});

const db = await getDB();
const cats = new Cats(db);

app.get("/", async (c) => {
const catNames = await cats.getAll();
return c.html(
`
<html lang="en">
<body>
<h1>Vulnerable app using SQLite3</h1>
<ul id="list">
${catNames.map((name) => `<li>${name}</li>`).join("")}
</ul>
<form id="add-cat">
<label for="search">Add a new cat</label>
<input type="text" name="petname">
<input type="submit" value="Add" />
</form>
<p>SQL Injection: Test'), ('Test2');--</p>
<a href="/clear">Clear all cats</a>
<script>
document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("add-cat");
form.addEventListener("submit", async (event) => {
event.preventDefault();
fetch("/add", {
method: "POST",
body: JSON.stringify({ name: form.petname.value }),
headers: {
"Content-Type": "application/json"
}
}).then(response => response.json())
.then(data => {
if(!data.success) {
throw new Error("Response was not successful");
}
window.location.reload();
})
.catch(error => document.getElementById("list").innerHTML = "<li>" + error.message + "</li>");
});
});
</script>
</body>
</html>
`
);
});

app.post("/add", async (c) => {
const body = await c.req.json();

if (typeof body.name !== "string") {
return c.json({ error: "Invalid request" }, 400);
}

await cats.add(body.name);
return c.json({ success: true });
});

app.get("/clear", async (c) => {
try {
await new Promise((resolve, reject) => {
db.run("DELETE FROM cats;", (result, err) => {
if (err) {
return reject(err);
}
resolve(result);
});
});
return c.redirect("/", 302);
} catch (err) {
return c.json({ error: "Failed to clear cats" }, 500);
}
});

function getPort() {
const port = parseInt(process.argv[2], 10) || 4000;

if (isNaN(port)) {
console.error("Invalid port");
process.exit(1);
}

return port;
}

const port = getPort();
serve({
fetch: app.fetch,
port: port,
}).on("listening", () => {
console.log(`Server is running on port ${port}`);
});
28 changes: 28 additions & 0 deletions sample-apps/hono-sqlite3-esm/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import sqlite3 from "sqlite3";

/** @type {sqlite3.Database} */
let db;

export async function getDB() {
if (db) {
return db;
}

db = new sqlite3.Database(":memory:");

await new Promise((resolve, reject) => {
db.run(
`CREATE TABLE cats (
petname TEXT
);`,
(err) => {
if (err) {
return reject(err);
}
resolve();
}
);
});

return db;
}
Loading
Loading