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

Add sudo propagation check for azure #147

Merged
Show file tree
Hide file tree
Changes from 1 commit
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
32 changes: 28 additions & 4 deletions src/plugins/azure/ssh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ This file is part of @p0security/cli

You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
**/
import { isSudoCommand } from "../../commands/shared/ssh";
import { SshProvider } from "../../types/ssh";
import { azAccountSetCommand, azLogin, azLoginCommand } from "./auth";
import { ensureAzInstall } from "./install";
Expand All @@ -26,6 +27,19 @@ import {
} from "./types";
import path from "node:path";

const unprovisionedAccessPatterns = [
{
// The output of `sudo -v` when the user is not allowed to run sudo
pattern: /Sorry, user .+ may not run sudo on .+/,
},
] as const;

const validPreTestAccessPatterns = [
{
pattern: /sudo: a password is required/,
},
] as const;

// TODO: Determine what this value should be for Azure
const PROPAGATION_TIMEOUT_LIMIT_MS = 2 * 60 * 1000;

Expand Down Expand Up @@ -55,8 +69,18 @@ export const azureSshProvider: SshProvider<

propagationTimeoutMs: PROPAGATION_TIMEOUT_LIMIT_MS,

// TODO(ENG-3149): Implement sudo access checks here
preTestAccessPropagationArgs: () => undefined,
preTestAccessPropagationArgs: (cmdArgs) => {
if (isSudoCommand(cmdArgs)) {
return {
...cmdArgs,
// `sudo -v` prints `Sorry, user <user> may not run sudo on <hostname>.` to stderr when user is not a sudoer.
// we have to use `-n` flag to avoid the oauth prompt on azure cli.
command: "sudo",
arguments: ["-nv"],
};
}
return undefined;
},

// Azure doesn't support ProxyCommand, as nice as that would be. Yet.
proxyCommand: () => [],
Expand Down Expand Up @@ -161,8 +185,8 @@ export const azureSshProvider: SshProvider<
bastionId: request.permission.bastionHostId,
}),

// TODO: Implement
unprovisionedAccessPatterns: [],
unprovisionedAccessPatterns,
validPreTestAccessPatterns,

toCliRequest: async (request) => {
return {
Expand Down
42 changes: 28 additions & 14 deletions src/plugins/ssh/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,19 +57,28 @@ const accessPropagationGuard = (
) => {
let isEphemeralAccessDeniedException = false;
let isLoginException = false;
let isValidPreTestError = false;

child.stderr.on("data", (chunk) => {
const chunkString: string = chunk.toString("utf-8");
parseAndPrintSshOutputToStderr(chunkString, options);

const match = provider.unprovisionedAccessPatterns.find((message) =>
chunkString.match(message.pattern)
const matchUnprovisionedPattern = provider.unprovisionedAccessPatterns.find(
(message) => chunkString.match(message.pattern)
);

if (match) {
const matchPreTestPattern = provider.validPreTestAccessPatterns?.find(
(message) => chunkString.match(message.pattern)
);
GGonryun marked this conversation as resolved.
Show resolved Hide resolved

if (matchUnprovisionedPattern) {
isEphemeralAccessDeniedException = true;
}

if (matchPreTestPattern && !matchUnprovisionedPattern) {
isValidPreTestError = true;
}

if (provider.loginRequiredPattern) {
const loginMatch = chunkString.match(provider.loginRequiredPattern);
isLoginException = isLoginException || !!loginMatch; // once true, always true
Expand All @@ -83,6 +92,7 @@ const accessPropagationGuard = (
return {
isAccessPropagated: () => !isEphemeralAccessDeniedException,
isLoginException: () => isLoginException,
isValidPreTestError: () => isValidPreTestError,
};
};

Expand Down Expand Up @@ -170,11 +180,8 @@ async function spawnSshNode(
);

// TODO ENG-2284 support login with Google Cloud: currently return a boolean to indicate if the exception was a Google login error.
const { isAccessPropagated, isLoginException } = accessPropagationGuard(
provider,
child,
options
);
const { isAccessPropagated, isLoginException, isValidPreTestError } =
accessPropagationGuard(provider, child, options);

const exitListener = child.on("exit", (code) => {
exitListener.unref();
Expand Down Expand Up @@ -203,6 +210,15 @@ async function spawnSshNode(

options.abortController?.abort(code);
if (!options.isAccessPropagationPreTest) print2(`SSH session terminated`);
if (
options.isAccessPropagationPreTest &&
provider.validPreTestAccessPatterns &&
isValidPreTestError()
) {
// override the exit code to 0 if the expected error was found, this means access is ready.
resolve(0);
return;
}
resolve(code);
});
});
Expand Down Expand Up @@ -355,6 +371,7 @@ const preTestAccessPropagationIfNeeded = async <
credential: P extends SshProvider<infer _PR, infer _O, infer _SR, infer C>
? C
: undefined,
setupData: SshAdditionalSetup | undefined,
endTime: number
) => {
const testCmdArgs = sshProvider.preTestAccessPropagationArgs(cmdArgs);
Expand All @@ -365,7 +382,7 @@ const preTestAccessPropagationIfNeeded = async <
const { command, args } = createCommand(
request,
testCmdArgs,
undefined, // No need to re-apply SSH options from setupData
setupData,
proxyCommand
);
// Assumes that this is a non-interactive ssh command that exits automatically
Expand Down Expand Up @@ -427,22 +444,21 @@ export const sshOrScp = async (args: {

const endTime = Date.now() + sshProvider.propagationTimeoutMs;

let sshNodeExit;

try {
const exitCode = await preTestAccessPropagationIfNeeded(
sshProvider,
request,
cmdArgs,
proxyCommand,
credential,
setupData,
endTime
);
if (exitCode && exitCode !== 0) {
return exitCode; // Only exit if there was an error when pre-testing
}

sshNodeExit = await spawnSshNode({
return await spawnSshNode({
GGonryun marked this conversation as resolved.
Show resolved Hide resolved
credential,
abortController: new AbortController(),
command,
Expand All @@ -455,6 +471,4 @@ export const sshOrScp = async (args: {
} finally {
await setupData?.teardown();
}

return sshNodeExit;
};
23 changes: 16 additions & 7 deletions src/types/ssh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ export type CliPermissionSpec<
export const SupportedSshProviders = ["aws", "azure", "gcloud"] as const;
export type SupportedSshProvider = (typeof SupportedSshProviders)[number];

export type AccessPattern = {
/** If the error matches this string, indicates that access is not provisioned */
readonly pattern: RegExp;
/** Maximum amount of time to wait for provisioning after encountering this error */
readonly validationWindowMs?: number;
};

export type SshProvider<
PR extends PluginSshRequest = PluginSshRequest,
O extends object | undefined = undefined,
Expand Down Expand Up @@ -102,13 +109,15 @@ export type SshProvider<
/** Unwraps this provider's types */
requestToSsh: (request: CliPermissionSpec<PR, O>) => SR;

/** Regex matches for error strings indicating that the provider has not yet fully provisioned node acces */
unprovisionedAccessPatterns: readonly {
/** If the error matches this string, indicates that access is not provisioned */
readonly pattern: RegExp;
/** Maximum amount of time to wait for provisioning after encountering this error */
readonly validationWindowMs?: number;
}[];
/** Regex matches for error strings indicating that the provider has not yet fully provisioned node access */
unprovisionedAccessPatterns: readonly AccessPattern[];

/** Regex matches for error strings indicating that the provider is ready for node access.
* Used to override error codes during access propagation testing.
*/
validPreTestAccessPatterns?: readonly AccessPattern[];

/** Regex matches for error strings indicating that the provider has fully provisioned */

/** Converts a backend request to a CLI request */
toCliRequest: (
Expand Down
Loading