@p0security/cli 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/__tests__/ssh.test.js +11 -10
- package/dist/commands/scp.js +7 -2
- package/dist/commands/shared.d.ts +16 -7
- package/dist/commands/shared.js +38 -16
- package/dist/commands/ssh.js +8 -2
- package/dist/common/subprocess.d.ts +10 -0
- package/dist/common/subprocess.js +72 -0
- package/dist/plugins/aws/ssh.d.ts +13 -0
- package/dist/plugins/aws/ssh.js +14 -0
- package/dist/plugins/aws/types.d.ts +16 -14
- package/dist/plugins/google/ssh-key.d.ts +14 -0
- package/dist/plugins/google/ssh-key.js +80 -0
- package/dist/plugins/google/ssh.d.ts +13 -0
- package/dist/plugins/google/ssh.js +13 -0
- package/dist/plugins/google/types.d.ts +49 -0
- package/dist/plugins/google/types.js +2 -0
- package/dist/plugins/{aws/ssm → ssh}/index.d.ts +2 -2
- package/dist/plugins/ssh/index.js +302 -0
- package/dist/plugins/ssh/types.d.ts +4 -0
- package/dist/plugins/ssh-agent/index.js +5 -39
- package/dist/types/request.d.ts +14 -11
- package/dist/types/request.js +0 -10
- package/package.json +1 -1
- package/dist/plugins/aws/ssm/index.js +0 -213
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.sshOrScp = void 0;
|
|
13
|
+
const keys_1 = require("../../common/keys");
|
|
14
|
+
const stdio_1 = require("../../drivers/stdio");
|
|
15
|
+
const util_1 = require("../../util");
|
|
16
|
+
const install_1 = require("../aws/ssm/install");
|
|
17
|
+
const aws_1 = require("../okta/aws");
|
|
18
|
+
const ssh_agent_1 = require("../ssh-agent");
|
|
19
|
+
const node_child_process_1 = require("node:child_process");
|
|
20
|
+
/** Matches the error message that AWS SSM print1 when access is not propagated */
|
|
21
|
+
// Note that the resource will randomly be either the SSM document or the EC2 instance
|
|
22
|
+
const UNAUTHORIZED_START_SESSION_MESSAGE = /An error occurred \(AccessDeniedException\) when calling the StartSession operation: User: arn:aws:sts::.*:assumed-role\/P0GrantsRole.* is not authorized to perform: ssm:StartSession on resource: arn:aws:.*:.*:.* because no identity-based policy allows the ssm:StartSession action/;
|
|
23
|
+
/**
|
|
24
|
+
* Matches the following error messages that AWS SSM print1 when ssh authorized
|
|
25
|
+
* key access hasn't propagated to the instance yet.
|
|
26
|
+
* - Connection closed by UNKNOWN port 65535
|
|
27
|
+
* - scp: Connection closed
|
|
28
|
+
* - kex_exchange_identification: Connection closed by remote host
|
|
29
|
+
*/
|
|
30
|
+
const CONNECTION_CLOSED_MESSAGE = /\bConnection closed\b.*\b(?:by UNKNOWN port \d+|by remote host)?/;
|
|
31
|
+
const PUBLIC_KEY_DENIED_MESSAGE = /Permission denied \(publickey\)/;
|
|
32
|
+
const UNAUTHORIZED_TUNNEL_USER_MESSAGE = /Error while connecting \[4033: 'not authorized'\]/;
|
|
33
|
+
const UNAUTHORIZED_INSTANCES_GET_MESSAGE = /Required 'compute\.instances\.get' permission/;
|
|
34
|
+
const DESTINATION_READ_ERROR = /Error while connecting \[4010: 'destination read failed'\]/;
|
|
35
|
+
const GOOGLE_LOGIN_MESSAGE = /You do not currently have an active account selected/;
|
|
36
|
+
/** Maximum amount of time after SSH subprocess starts to check for {@link UNPROVISIONED_ACCESS_MESSAGES}
|
|
37
|
+
* in the process's stderr
|
|
38
|
+
*/
|
|
39
|
+
const DEFAULT_VALIDATION_WINDOW_MS = 5e3;
|
|
40
|
+
/** Maximum number of attempts to start an SSH session
|
|
41
|
+
*
|
|
42
|
+
* Note that each attempt consumes ~ 1 s.
|
|
43
|
+
*/
|
|
44
|
+
const DEFAULT_MAX_SSH_RETRIES = 30;
|
|
45
|
+
const GCP_MAX_SSH_RETRIES = 120; // GCP requires more time to propagate access
|
|
46
|
+
/** The name of the SessionManager port forwarding document. This document is managed by AWS. */
|
|
47
|
+
const START_SSH_SESSION_DOCUMENT_NAME = "AWS-StartSSHSession";
|
|
48
|
+
/**
|
|
49
|
+
* AWS
|
|
50
|
+
* There are 2 cases of unprovisioned access in AWS
|
|
51
|
+
* 1. SSM:StartSession action is missing either on the SSM document (AWS-StartSSHSession) or the EC2 instance
|
|
52
|
+
* 2. Temporary error when issuing an SCP command
|
|
53
|
+
*
|
|
54
|
+
* 1: results in UNAUTHORIZED_START_SESSION_MESSAGE
|
|
55
|
+
* 2: results in CONNECTION_CLOSED_MESSAGE
|
|
56
|
+
*
|
|
57
|
+
* Google Cloud
|
|
58
|
+
* There are 5 cases of unprovisioned access in Google Cloud.
|
|
59
|
+
* These are all potentially subject to propagation delays.
|
|
60
|
+
* 1. The linux user name is not present in the user's Google Workspace profile `posixAccounts` attribute
|
|
61
|
+
* 2. The public key is not present in the user's Google Workspace profile `sshPublicKeys` attribute
|
|
62
|
+
* 3. The user cannot act as the service account of the compute instance
|
|
63
|
+
* 4. The user cannot tunnel through the IAP tunnel to the instance
|
|
64
|
+
* 5. The user doesn't have osLogin or osAdminLogin role to the instance
|
|
65
|
+
* 5.a. compute.instances.get permission is missing
|
|
66
|
+
* 5.b. compute.instances.osLogin permission is missing
|
|
67
|
+
* 6: Rare occurrence, the exact conditions so far undetermined (together with CONNECTION_CLOSED_MESSAGE)
|
|
68
|
+
*
|
|
69
|
+
* 1, 2, 3 (yes!), 5b: result in PUBLIC_KEY_DENIED_MESSAGE
|
|
70
|
+
* 4: results in UNAUTHORIZED_TUNNEL_USER_MESSAGE and also CONNECTION_CLOSED_MESSAGE
|
|
71
|
+
* 5a: results in UNAUTHORIZED_INSTANCES_GET_MESSAGE
|
|
72
|
+
* 6: results in DESTINATION_READ_ERROR and also CONNECTION_CLOSED_MESSAGE
|
|
73
|
+
*/
|
|
74
|
+
const UNPROVISIONED_ACCESS_MESSAGES = [
|
|
75
|
+
{ pattern: UNAUTHORIZED_START_SESSION_MESSAGE },
|
|
76
|
+
{ pattern: CONNECTION_CLOSED_MESSAGE },
|
|
77
|
+
{ pattern: PUBLIC_KEY_DENIED_MESSAGE },
|
|
78
|
+
{ pattern: UNAUTHORIZED_TUNNEL_USER_MESSAGE },
|
|
79
|
+
{ pattern: UNAUTHORIZED_INSTANCES_GET_MESSAGE, validationWindowMs: 30e3 },
|
|
80
|
+
{ pattern: DESTINATION_READ_ERROR },
|
|
81
|
+
];
|
|
82
|
+
/** Checks if access has propagated through AWS to the SSM agent
|
|
83
|
+
*
|
|
84
|
+
* AWS takes about 8 minutes, GCP takes under 1 minute
|
|
85
|
+
* to fully resolve access after it is granted.
|
|
86
|
+
* During this time, calls to `aws ssm start-session` / `gcloud compute start-iap-tunnel`
|
|
87
|
+
* will fail randomly with an various error messages.
|
|
88
|
+
*
|
|
89
|
+
* This function checks the subprocess output to see if any of the error messages
|
|
90
|
+
* are printed to the error output within the first 5 seconds of startup.
|
|
91
|
+
* If they are, the returned `isAccessPropagated()` function will return false.
|
|
92
|
+
* When this occurs, the consumer of this function should retry the `aws` / `gcloud` command.
|
|
93
|
+
*
|
|
94
|
+
* Note that this function requires interception of the subprocess stderr stream.
|
|
95
|
+
* This works because AWS SSM wraps the session in a single-stream pty, so we
|
|
96
|
+
* do not capture stderr emitted from the wrapped shell session.
|
|
97
|
+
*/
|
|
98
|
+
const accessPropagationGuard = (child, debug) => {
|
|
99
|
+
let isEphemeralAccessDeniedException = false;
|
|
100
|
+
let isGoogleLoginException = false;
|
|
101
|
+
const beforeStart = Date.now();
|
|
102
|
+
child.stderr.on("data", (chunk) => {
|
|
103
|
+
const chunkString = chunk.toString("utf-8");
|
|
104
|
+
if (debug)
|
|
105
|
+
(0, stdio_1.print2)(chunkString);
|
|
106
|
+
const match = UNPROVISIONED_ACCESS_MESSAGES.find((message) => chunkString.match(message.pattern));
|
|
107
|
+
if (match &&
|
|
108
|
+
Date.now() <=
|
|
109
|
+
beforeStart + (match.validationWindowMs || DEFAULT_VALIDATION_WINDOW_MS)) {
|
|
110
|
+
isEphemeralAccessDeniedException = true;
|
|
111
|
+
}
|
|
112
|
+
const googleLoginMatch = chunkString.match(GOOGLE_LOGIN_MESSAGE);
|
|
113
|
+
isGoogleLoginException = isGoogleLoginException || !!googleLoginMatch; // once true, always true
|
|
114
|
+
if (isGoogleLoginException) {
|
|
115
|
+
isEphemeralAccessDeniedException = false; // always overwrite to false so we don't retry the access
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
return {
|
|
119
|
+
isAccessPropagated: () => !isEphemeralAccessDeniedException,
|
|
120
|
+
isGoogleLoginException: () => isGoogleLoginException,
|
|
121
|
+
};
|
|
122
|
+
};
|
|
123
|
+
const spawnChildProcess = (credential, command, args, stdio) => (0, node_child_process_1.spawn)(command, args, {
|
|
124
|
+
env: Object.assign(Object.assign({}, process.env), credential),
|
|
125
|
+
stdio,
|
|
126
|
+
shell: false,
|
|
127
|
+
});
|
|
128
|
+
const friendlyProvider = (provider) => provider === "aws"
|
|
129
|
+
? "AWS"
|
|
130
|
+
: provider === "gcloud"
|
|
131
|
+
? "Google Cloud"
|
|
132
|
+
: (0, util_1.throwAssertNever)(provider);
|
|
133
|
+
/** Starts an SSM session in the terminal by spawning `aws ssm` as a subprocess
|
|
134
|
+
*
|
|
135
|
+
* Requires `aws ssm` to be installed on the client machine.
|
|
136
|
+
*/
|
|
137
|
+
function spawnSshNode(options) {
|
|
138
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
139
|
+
return new Promise((resolve, reject) => {
|
|
140
|
+
const child = spawnChildProcess(options.credential, options.command, options.args, options.stdio);
|
|
141
|
+
// TODO ENG-2284 support login with Google Cloud: currently return a boolean to indicate if the exception was a Google login error.
|
|
142
|
+
const { isAccessPropagated, isGoogleLoginException } = accessPropagationGuard(child, options.debug);
|
|
143
|
+
const exitListener = child.on("exit", (code) => {
|
|
144
|
+
var _a;
|
|
145
|
+
exitListener.unref();
|
|
146
|
+
// In the case of ephemeral AccessDenied exceptions due to unpropagated
|
|
147
|
+
// permissions, continually retry access until success
|
|
148
|
+
if (!isAccessPropagated()) {
|
|
149
|
+
const attemptsRemaining = options.attemptsRemaining;
|
|
150
|
+
if (options.debug) {
|
|
151
|
+
(0, stdio_1.print2)(`Waiting for access to propagate. Retrying SSH session... (remaining attempts: ${attemptsRemaining})`);
|
|
152
|
+
}
|
|
153
|
+
if (attemptsRemaining <= 0) {
|
|
154
|
+
reject(`Access did not propagate through ${friendlyProvider(options.provider)} before max retry attempts were exceeded. Please contact support@p0.dev for assistance.`);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
spawnSshNode(Object.assign(Object.assign({}, options), { attemptsRemaining: attemptsRemaining - 1 }))
|
|
158
|
+
.then((code) => resolve(code))
|
|
159
|
+
.catch(reject);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
else if (isGoogleLoginException()) {
|
|
163
|
+
reject(`Please login to Google Cloud CLI with 'gcloud auth login'`);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
(_a = options.abortController) === null || _a === void 0 ? void 0 : _a.abort(code);
|
|
167
|
+
(0, stdio_1.print2)(`SSH session terminated`);
|
|
168
|
+
resolve(code);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
const createProxyCommands = (data, args, debug) => {
|
|
174
|
+
let proxyCommand;
|
|
175
|
+
if (data.type === "aws") {
|
|
176
|
+
proxyCommand = [
|
|
177
|
+
"aws",
|
|
178
|
+
"ssm",
|
|
179
|
+
"start-session",
|
|
180
|
+
"--region",
|
|
181
|
+
data.region,
|
|
182
|
+
"--target",
|
|
183
|
+
"%h",
|
|
184
|
+
"--document-name",
|
|
185
|
+
START_SSH_SESSION_DOCUMENT_NAME,
|
|
186
|
+
"--parameters",
|
|
187
|
+
'"portNumber=%p"',
|
|
188
|
+
];
|
|
189
|
+
}
|
|
190
|
+
else if (data.type === "gcloud") {
|
|
191
|
+
proxyCommand = [
|
|
192
|
+
"gcloud",
|
|
193
|
+
"compute",
|
|
194
|
+
"start-iap-tunnel",
|
|
195
|
+
data.id,
|
|
196
|
+
"%p",
|
|
197
|
+
// --listen-on-stdin flag is required for interactive SSH session.
|
|
198
|
+
// It is undocumented on page https://cloud.google.com/sdk/gcloud/reference/compute/start-iap-tunnel
|
|
199
|
+
// but mention on page https://cloud.google.com/iap/docs/tcp-by-host
|
|
200
|
+
// and also found in `gcloud ssh --dry-run` output
|
|
201
|
+
"--listen-on-stdin",
|
|
202
|
+
`--zone=${data.zone}`,
|
|
203
|
+
`--project=${data.projectId}`,
|
|
204
|
+
];
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
throw (0, util_1.assertNever)(data);
|
|
208
|
+
}
|
|
209
|
+
const commonArgs = [
|
|
210
|
+
...(debug ? ["-v"] : []),
|
|
211
|
+
"-o",
|
|
212
|
+
`ProxyCommand=${proxyCommand.join(" ")}`,
|
|
213
|
+
];
|
|
214
|
+
if ("source" in args) {
|
|
215
|
+
return {
|
|
216
|
+
command: "scp",
|
|
217
|
+
args: [
|
|
218
|
+
...commonArgs,
|
|
219
|
+
// if a response is not received after three 5 minute attempts,
|
|
220
|
+
// the connection will be closed.
|
|
221
|
+
"-o",
|
|
222
|
+
"ServerAliveCountMax=3",
|
|
223
|
+
`-o`,
|
|
224
|
+
"ServerAliveInterval=300",
|
|
225
|
+
...(args.recursive ? ["-r"] : []),
|
|
226
|
+
args.source,
|
|
227
|
+
args.destination,
|
|
228
|
+
],
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
command: "ssh",
|
|
233
|
+
args: [
|
|
234
|
+
...commonArgs,
|
|
235
|
+
...(args.A ? ["-A"] : []),
|
|
236
|
+
...(args.L ? ["-L", args.L] : []),
|
|
237
|
+
...(args.N ? ["-N"] : []),
|
|
238
|
+
`${data.linuxUserName}@${data.id}`,
|
|
239
|
+
...(args.command ? [args.command] : []),
|
|
240
|
+
...args.arguments.map((argument) =>
|
|
241
|
+
// escape all double quotes (") in commands such as `p0 ssh <instance>> echo 'hello; "world"'` because we
|
|
242
|
+
// need to encapsulate command arguments in double quotes as we pass them along to the remote shell
|
|
243
|
+
`"${String(argument).replace(/"/g, '\\"')}"`),
|
|
244
|
+
],
|
|
245
|
+
};
|
|
246
|
+
};
|
|
247
|
+
/** Converts arguments for manual execution - arguments may have to be quoted or certain characters escaped when executing the commands from a shell */
|
|
248
|
+
const transformForShell = (args) => {
|
|
249
|
+
return args.map((arg) => {
|
|
250
|
+
// The ProxyCommand option must be surrounded by single quotes
|
|
251
|
+
if (arg.startsWith("ProxyCommand=")) {
|
|
252
|
+
const [name, ...value] = arg.split("="); // contains the '=' character in the parameters option: ProxyCommand=aws ssm start-session ... --parameters "portNumber=%p"
|
|
253
|
+
return `${name}='${value.join("=")}'`;
|
|
254
|
+
}
|
|
255
|
+
return arg;
|
|
256
|
+
});
|
|
257
|
+
};
|
|
258
|
+
const awsLogin = (authn, data) => __awaiter(void 0, void 0, void 0, function* () {
|
|
259
|
+
if (!(yield (0, install_1.ensureSsmInstall)())) {
|
|
260
|
+
throw "Please try again after installing the required AWS utilities";
|
|
261
|
+
}
|
|
262
|
+
return yield (0, aws_1.assumeRoleWithOktaSaml)(authn, {
|
|
263
|
+
account: data.accountId,
|
|
264
|
+
role: data.role,
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
const sshOrScp = (authn, data, cmdArgs, privateKey) => __awaiter(void 0, void 0, void 0, function* () {
|
|
268
|
+
if (!privateKey) {
|
|
269
|
+
throw "Failed to load a private key for this request. Please contact support@p0.dev for assistance.";
|
|
270
|
+
}
|
|
271
|
+
// TODO ENG-2284 support login with Google Cloud
|
|
272
|
+
const credential = data.type === "aws" ? yield awsLogin(authn, data) : undefined;
|
|
273
|
+
return (0, ssh_agent_1.withSshAgent)(cmdArgs, () => __awaiter(void 0, void 0, void 0, function* () {
|
|
274
|
+
const { command, args } = createProxyCommands(data, cmdArgs, cmdArgs.debug);
|
|
275
|
+
if (cmdArgs.debug) {
|
|
276
|
+
const reproCommands = [
|
|
277
|
+
`eval $(ssh-agent)`,
|
|
278
|
+
`ssh-add "${keys_1.PRIVATE_KEY_PATH}"`,
|
|
279
|
+
// TODO ENG-2284 support login with Google Cloud
|
|
280
|
+
...(data.type === "aws"
|
|
281
|
+
? [
|
|
282
|
+
`eval $(p0 aws role assume ${data.role} --account ${data.accountId})`,
|
|
283
|
+
]
|
|
284
|
+
: []),
|
|
285
|
+
`${command} ${transformForShell(args).join(" ")}`,
|
|
286
|
+
];
|
|
287
|
+
(0, stdio_1.print2)(`Execute the following commands to create a similar SSH/SCP session:\n*** COMMANDS BEGIN ***\n${reproCommands.join("\n")}\n*** COMMANDS END ***"\n`);
|
|
288
|
+
}
|
|
289
|
+
const maxRetries = data.type === "gcloud" ? GCP_MAX_SSH_RETRIES : DEFAULT_MAX_SSH_RETRIES;
|
|
290
|
+
return spawnSshNode({
|
|
291
|
+
credential,
|
|
292
|
+
abortController: new AbortController(),
|
|
293
|
+
command,
|
|
294
|
+
args,
|
|
295
|
+
stdio: ["inherit", "inherit", "pipe"],
|
|
296
|
+
debug: cmdArgs.debug,
|
|
297
|
+
provider: data.type,
|
|
298
|
+
attemptsRemaining: maxRetries,
|
|
299
|
+
});
|
|
300
|
+
}));
|
|
301
|
+
});
|
|
302
|
+
exports.sshOrScp = sshOrScp;
|
|
@@ -21,49 +21,15 @@ This file is part of @p0security/cli
|
|
|
21
21
|
You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
|
|
22
22
|
**/
|
|
23
23
|
const keys_1 = require("../../common/keys");
|
|
24
|
+
const subprocess_1 = require("../../common/subprocess");
|
|
24
25
|
const stdio_1 = require("../../drivers/stdio");
|
|
25
|
-
const node_child_process_1 = require("node:child_process");
|
|
26
|
-
/** Spawns a subprocess with given command, args, and options.
|
|
27
|
-
* May write content to its standard input.
|
|
28
|
-
* Stdout and stderr of the subprocess is printed to stderr in debug mode.
|
|
29
|
-
* The returned promise resolves or rejects with the exit code. */
|
|
30
|
-
const asyncSpawn = ({ debug }, command, args, options, writeStdin) => __awaiter(void 0, void 0, void 0, function* () {
|
|
31
|
-
return new Promise((resolve, reject) => {
|
|
32
|
-
var _a;
|
|
33
|
-
const child = (0, node_child_process_1.spawn)(command, args, options);
|
|
34
|
-
if (writeStdin) {
|
|
35
|
-
if (!child.stdin)
|
|
36
|
-
return reject("Child process has no stdin");
|
|
37
|
-
child.stdin.write(writeStdin);
|
|
38
|
-
}
|
|
39
|
-
child.stdout.on("data", (data) => {
|
|
40
|
-
if (debug) {
|
|
41
|
-
(0, stdio_1.print2)(data.toString("utf-8"));
|
|
42
|
-
}
|
|
43
|
-
});
|
|
44
|
-
child.stderr.on("data", (data) => {
|
|
45
|
-
if (debug) {
|
|
46
|
-
(0, stdio_1.print2)(data.toString("utf-8"));
|
|
47
|
-
}
|
|
48
|
-
});
|
|
49
|
-
child.on("exit", (code) => {
|
|
50
|
-
if (code !== 0) {
|
|
51
|
-
return reject(code);
|
|
52
|
-
}
|
|
53
|
-
resolve(code);
|
|
54
|
-
});
|
|
55
|
-
if (writeStdin) {
|
|
56
|
-
(_a = child.stdin) === null || _a === void 0 ? void 0 : _a.end();
|
|
57
|
-
}
|
|
58
|
-
});
|
|
59
|
-
});
|
|
60
26
|
const isSshAgentRunning = (args) => __awaiter(void 0, void 0, void 0, function* () {
|
|
61
27
|
try {
|
|
62
28
|
if (args.debug)
|
|
63
29
|
(0, stdio_1.print2)("Searching for active ssh-agents");
|
|
64
30
|
// TODO: There's a possible edge-case but unlikely that ssh-agent has an invalid process or PID.
|
|
65
31
|
// We can check to see if the active PID matches the current socket to mitigate this.
|
|
66
|
-
yield asyncSpawn(args, `pgrep`, ["-x", "ssh-agent"]);
|
|
32
|
+
yield (0, subprocess_1.asyncSpawn)(args, `pgrep`, ["-x", "ssh-agent"]);
|
|
67
33
|
if (args.debug)
|
|
68
34
|
(0, stdio_1.print2)("At least one SSH agent is running");
|
|
69
35
|
return true;
|
|
@@ -76,7 +42,7 @@ const isSshAgentRunning = (args) => __awaiter(void 0, void 0, void 0, function*
|
|
|
76
42
|
});
|
|
77
43
|
const isSshAgentAuthSocketSet = (args) => __awaiter(void 0, void 0, void 0, function* () {
|
|
78
44
|
try {
|
|
79
|
-
yield asyncSpawn(args, `sh`, ["-c", '[ -n "$SSH_AUTH_SOCK" ]']);
|
|
45
|
+
yield (0, subprocess_1.asyncSpawn)(args, `sh`, ["-c", '[ -n "$SSH_AUTH_SOCK" ]']);
|
|
80
46
|
if (args.debug)
|
|
81
47
|
(0, stdio_1.print2)(`SSH_AUTH_SOCK=${process.env.SSH_AUTH_SOCK}`);
|
|
82
48
|
return true;
|
|
@@ -89,7 +55,7 @@ const isSshAgentAuthSocketSet = (args) => __awaiter(void 0, void 0, void 0, func
|
|
|
89
55
|
});
|
|
90
56
|
const privateKeyExists = (args) => __awaiter(void 0, void 0, void 0, function* () {
|
|
91
57
|
try {
|
|
92
|
-
yield asyncSpawn(args, `sh`, [
|
|
58
|
+
yield (0, subprocess_1.asyncSpawn)(args, `sh`, [
|
|
93
59
|
"-c",
|
|
94
60
|
`KEY_PATH="${keys_1.PRIVATE_KEY_PATH}" && KEY_FINGERPRINT=$(ssh-keygen -lf "$KEY_PATH" | awk '{print $2}') && ssh-add -l | grep -q "$KEY_FINGERPRINT" && exit 0 || exit 1`,
|
|
95
61
|
]);
|
|
@@ -106,7 +72,7 @@ const privateKeyExists = (args) => __awaiter(void 0, void 0, void 0, function* (
|
|
|
106
72
|
exports.privateKeyExists = privateKeyExists;
|
|
107
73
|
const addPrivateKey = (args) => __awaiter(void 0, void 0, void 0, function* () {
|
|
108
74
|
try {
|
|
109
|
-
yield asyncSpawn(args, `ssh-add`, [
|
|
75
|
+
yield (0, subprocess_1.asyncSpawn)(args, `ssh-add`, [
|
|
110
76
|
keys_1.PRIVATE_KEY_PATH,
|
|
111
77
|
...(args.debug ? ["-v", "-v", "-v"] : ["-q"]),
|
|
112
78
|
]);
|
package/dist/types/request.d.ts
CHANGED
|
@@ -8,22 +8,25 @@ This file is part of @p0security/cli
|
|
|
8
8
|
|
|
9
9
|
You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
|
|
10
10
|
**/
|
|
11
|
+
import { AwsPermissionSpec, AwsSsh } from "../plugins/aws/types";
|
|
12
|
+
import { GcpPermissionSpec, GcpSsh } from "../plugins/google/types";
|
|
11
13
|
export declare const DONE_STATUSES: readonly ["DONE", "DONE_NOTIFIED"];
|
|
12
14
|
export declare const DENIED_STATUSES: readonly ["DENIED", "DENIED_NOTIFIED"];
|
|
13
15
|
export declare const ERROR_STATUSES: readonly ["ERRORED", "ERRORED", "ERRORED_NOTIFIED"];
|
|
14
|
-
export declare type
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
export declare type CliRequest = AwsSsh | GcpSsh;
|
|
17
|
+
export declare type PluginRequest = AwsPermissionSpec | GcpPermissionSpec;
|
|
18
|
+
export declare type CliPermissionSpec<P extends PluginRequest, C extends object | undefined = undefined> = P & {
|
|
19
|
+
cliLocalData: C;
|
|
17
20
|
};
|
|
18
|
-
export declare type
|
|
19
|
-
|
|
20
|
-
}> = {
|
|
21
|
+
export declare type PermissionSpec<K extends string, P extends {
|
|
22
|
+
type: string;
|
|
23
|
+
}, G extends object | undefined = undefined> = {
|
|
24
|
+
type: K;
|
|
25
|
+
permission: P;
|
|
26
|
+
generated: G;
|
|
27
|
+
};
|
|
28
|
+
export declare type Request<P extends PluginRequest> = P & {
|
|
21
29
|
status: string;
|
|
22
|
-
generatedRoles: {
|
|
23
|
-
role: string;
|
|
24
|
-
}[];
|
|
25
|
-
generated: P["generated"];
|
|
26
|
-
permission: P["permission"];
|
|
27
30
|
principal: string;
|
|
28
31
|
};
|
|
29
32
|
export declare type RequestResponse<T> = {
|
package/dist/types/request.js
CHANGED
|
@@ -1,16 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ERROR_STATUSES = exports.DENIED_STATUSES = exports.DONE_STATUSES = void 0;
|
|
4
|
-
/** Copyright © 2024-present P0 Security
|
|
5
|
-
|
|
6
|
-
This file is part of @p0security/cli
|
|
7
|
-
|
|
8
|
-
@p0security/cli is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License.
|
|
9
|
-
|
|
10
|
-
@p0security/cli is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
|
11
|
-
|
|
12
|
-
You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
|
|
13
|
-
**/
|
|
14
4
|
exports.DONE_STATUSES = ["DONE", "DONE_NOTIFIED"];
|
|
15
5
|
exports.DENIED_STATUSES = ["DENIED", "DENIED_NOTIFIED"];
|
|
16
6
|
exports.ERROR_STATUSES = [
|
package/package.json
CHANGED
|
@@ -1,213 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.sshOrScp = void 0;
|
|
13
|
-
const keys_1 = require("../../../common/keys");
|
|
14
|
-
const stdio_1 = require("../../../drivers/stdio");
|
|
15
|
-
const aws_1 = require("../../okta/aws");
|
|
16
|
-
const ssh_agent_1 = require("../../ssh-agent");
|
|
17
|
-
const install_1 = require("./install");
|
|
18
|
-
const node_child_process_1 = require("node:child_process");
|
|
19
|
-
/** Matches the error message that AWS SSM print1 when access is not propagated */
|
|
20
|
-
// Note that the resource will randomly be either the SSM document or the EC2 instance
|
|
21
|
-
const UNPROVISIONED_ACCESS_MESSAGE = /An error occurred \(AccessDeniedException\) when calling the StartSession operation: User: arn:aws:sts::.*:assumed-role\/P0GrantsRole.* is not authorized to perform: ssm:StartSession on resource: arn:aws:.*:.*:.* because no identity-based policy allows the ssm:StartSession action/;
|
|
22
|
-
/**
|
|
23
|
-
* Matches the following error messages that AWS SSM print1 when ssh authorized
|
|
24
|
-
* key access hasn't propagated to the instance yet.
|
|
25
|
-
* - Connection closed by UNKNOWN port 65535
|
|
26
|
-
* - scp: Connection closed
|
|
27
|
-
* - kex_exchange_identification: Connection closed by remote host
|
|
28
|
-
*/
|
|
29
|
-
const UNPROVISIONED_SCP_ACCESS_MESSAGE = /\bConnection closed\b.*\b(?:by UNKNOWN port \d+|by remote host)?/;
|
|
30
|
-
/** Maximum amount of time after AWS SSM process starts to check for {@link UNPROVISIONED_ACCESS_MESSAGE}
|
|
31
|
-
* in the process's stderr
|
|
32
|
-
*/
|
|
33
|
-
const UNPROVISIONED_ACCESS_VALIDATION_WINDOW_MS = 5e3;
|
|
34
|
-
/** Maximum number of attempts to start an SSM session
|
|
35
|
-
*
|
|
36
|
-
* Note that each attempt consumes ~ 1 s.
|
|
37
|
-
*/
|
|
38
|
-
const MAX_SSM_RETRIES = 30;
|
|
39
|
-
/** The name of the SessionManager port forwarding document. This document is managed by AWS. */
|
|
40
|
-
const START_SSH_SESSION_DOCUMENT_NAME = "AWS-StartSSHSession";
|
|
41
|
-
/** Checks if access has propagated through AWS to the SSM agent
|
|
42
|
-
*
|
|
43
|
-
* AWS takes about 8 minutes to fully resolve access after it is granted. During
|
|
44
|
-
* this time, calls to `aws ssm start-session` will fail randomly with an
|
|
45
|
-
* access denied exception.
|
|
46
|
-
*
|
|
47
|
-
* This function checks AWS to see if this exception is print1d to the SSM
|
|
48
|
-
* error output within the first 5 seconds of startup. If it is, the returned
|
|
49
|
-
* `isAccessPropagated()` function will return false. When this occurs, the
|
|
50
|
-
* consumer of this function should retry the AWS SSM session.
|
|
51
|
-
*
|
|
52
|
-
* Note that this function requires interception of the AWS SSM stderr stream.
|
|
53
|
-
* This works because AWS SSM wraps the session in a single-stream pty, so we
|
|
54
|
-
* do not capture stderr emitted from the wrapped shell session.
|
|
55
|
-
*/
|
|
56
|
-
const accessPropagationGuard = (child) => {
|
|
57
|
-
let isEphemeralAccessDeniedException = false;
|
|
58
|
-
const beforeStart = Date.now();
|
|
59
|
-
child.stderr.on("data", (chunk) => {
|
|
60
|
-
const chunkString = chunk.toString("utf-8");
|
|
61
|
-
const match = chunkString.match(UNPROVISIONED_ACCESS_MESSAGE) ||
|
|
62
|
-
chunkString.match(UNPROVISIONED_SCP_ACCESS_MESSAGE);
|
|
63
|
-
if (match &&
|
|
64
|
-
Date.now() <= beforeStart + UNPROVISIONED_ACCESS_VALIDATION_WINDOW_MS) {
|
|
65
|
-
isEphemeralAccessDeniedException = true;
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
(0, stdio_1.print2)(chunkString);
|
|
69
|
-
});
|
|
70
|
-
return {
|
|
71
|
-
isAccessPropagated: () => !isEphemeralAccessDeniedException,
|
|
72
|
-
};
|
|
73
|
-
};
|
|
74
|
-
const createBaseSsmCommand = (args) => {
|
|
75
|
-
return [
|
|
76
|
-
"aws",
|
|
77
|
-
"ssm",
|
|
78
|
-
"start-session",
|
|
79
|
-
"--region",
|
|
80
|
-
args.region,
|
|
81
|
-
"--target",
|
|
82
|
-
args.instance,
|
|
83
|
-
];
|
|
84
|
-
};
|
|
85
|
-
const spawnChildProcess = (credential, command, args, stdio) => (0, node_child_process_1.spawn)(command, args, {
|
|
86
|
-
env: Object.assign(Object.assign({}, process.env), credential),
|
|
87
|
-
stdio,
|
|
88
|
-
shell: false,
|
|
89
|
-
});
|
|
90
|
-
/** Starts an SSM session in the terminal by spawning `aws ssm` as a subprocess
|
|
91
|
-
*
|
|
92
|
-
* Requires `aws ssm` to be installed on the client machine.
|
|
93
|
-
*/
|
|
94
|
-
function spawnSsmNode(options) {
|
|
95
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
96
|
-
return new Promise((resolve, reject) => {
|
|
97
|
-
const child = spawnChildProcess(options.credential, options.command, options.args, options.stdio);
|
|
98
|
-
const { isAccessPropagated } = accessPropagationGuard(child);
|
|
99
|
-
const exitListener = child.on("exit", (code) => {
|
|
100
|
-
var _a, _b;
|
|
101
|
-
exitListener.unref();
|
|
102
|
-
// In the case of ephemeral AccessDenied exceptions due to unpropagated
|
|
103
|
-
// permissions, continually retry access until success
|
|
104
|
-
if (!isAccessPropagated()) {
|
|
105
|
-
const attemptsRemaining = (_a = options === null || options === void 0 ? void 0 : options.attemptsRemaining) !== null && _a !== void 0 ? _a : MAX_SSM_RETRIES;
|
|
106
|
-
if (attemptsRemaining <= 0) {
|
|
107
|
-
reject("Access did not propagate through AWS before max retry attempts were exceeded. Please contact support@p0.dev for assistance.");
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
spawnSsmNode(Object.assign(Object.assign({}, options), { attemptsRemaining: attemptsRemaining - 1 }))
|
|
111
|
-
.then((code) => resolve(code))
|
|
112
|
-
.catch(reject);
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
(_b = options.abortController) === null || _b === void 0 ? void 0 : _b.abort(code);
|
|
116
|
-
(0, stdio_1.print2)(`SSH session terminated`);
|
|
117
|
-
resolve(code);
|
|
118
|
-
});
|
|
119
|
-
});
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
const createProxyCommands = (data, args, debug) => {
|
|
123
|
-
const ssmCommand = [
|
|
124
|
-
...createBaseSsmCommand({
|
|
125
|
-
region: data.region,
|
|
126
|
-
instance: "%h",
|
|
127
|
-
}),
|
|
128
|
-
"--document-name",
|
|
129
|
-
START_SSH_SESSION_DOCUMENT_NAME,
|
|
130
|
-
"--parameters",
|
|
131
|
-
'"portNumber=%p"',
|
|
132
|
-
];
|
|
133
|
-
const commonArgs = [
|
|
134
|
-
...(debug ? ["-v"] : []),
|
|
135
|
-
"-o",
|
|
136
|
-
`ProxyCommand=${ssmCommand.join(" ")}`,
|
|
137
|
-
];
|
|
138
|
-
if ("source" in args) {
|
|
139
|
-
return {
|
|
140
|
-
command: "scp",
|
|
141
|
-
args: [
|
|
142
|
-
...commonArgs,
|
|
143
|
-
// if a response is not received after three 5 minute attempts,
|
|
144
|
-
// the connection will be closed.
|
|
145
|
-
"-o",
|
|
146
|
-
"ServerAliveCountMax=3",
|
|
147
|
-
`-o`,
|
|
148
|
-
"ServerAliveInterval=300",
|
|
149
|
-
...(args.recursive ? ["-r"] : []),
|
|
150
|
-
args.source,
|
|
151
|
-
args.destination,
|
|
152
|
-
],
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
return {
|
|
156
|
-
command: "ssh",
|
|
157
|
-
args: [
|
|
158
|
-
...commonArgs,
|
|
159
|
-
...(args.A ? ["-A"] : []),
|
|
160
|
-
...(args.L ? ["-L", args.L] : []),
|
|
161
|
-
...(args.N ? ["-N"] : []),
|
|
162
|
-
`${data.linuxUserName}@${data.id}`,
|
|
163
|
-
...(args.command ? [args.command] : []),
|
|
164
|
-
...args.arguments.map((argument) =>
|
|
165
|
-
// escape all double quotes (") in commands such as `p0 ssh <instance>> echo 'hello; "world"'` because we
|
|
166
|
-
// need to encapsulate command arguments in double quotes as we pass them along to the remote shell
|
|
167
|
-
`"${String(argument).replace(/"/g, '\\"')}"`),
|
|
168
|
-
],
|
|
169
|
-
};
|
|
170
|
-
};
|
|
171
|
-
/** Converts arguments for manual execution - arguments may have to be quoted or certain characters escaped when executing the commands from a shell */
|
|
172
|
-
const transformForShell = (args) => {
|
|
173
|
-
return args.map((arg) => {
|
|
174
|
-
// The ProxyCommand option must be surrounded by single quotes
|
|
175
|
-
if (arg.startsWith("ProxyCommand=")) {
|
|
176
|
-
const [name, ...value] = arg.split("="); // contains the '=' character in the parameters option: ProxyCommand=aws ssm start-session ... --parameters "portNumber=%p"
|
|
177
|
-
return `${name}='${value.join("=")}'`;
|
|
178
|
-
}
|
|
179
|
-
return arg;
|
|
180
|
-
});
|
|
181
|
-
};
|
|
182
|
-
const sshOrScp = (authn, data, cmdArgs, privateKey) => __awaiter(void 0, void 0, void 0, function* () {
|
|
183
|
-
if (!(yield (0, install_1.ensureSsmInstall)())) {
|
|
184
|
-
throw "Please try again after installing the required AWS utilities";
|
|
185
|
-
}
|
|
186
|
-
if (!privateKey) {
|
|
187
|
-
throw "Failed to load a private key for this request. Please contact support@p0.dev for assistance.";
|
|
188
|
-
}
|
|
189
|
-
const credential = yield (0, aws_1.assumeRoleWithOktaSaml)(authn, {
|
|
190
|
-
account: data.accountId,
|
|
191
|
-
role: data.role,
|
|
192
|
-
});
|
|
193
|
-
return (0, ssh_agent_1.withSshAgent)(cmdArgs, () => __awaiter(void 0, void 0, void 0, function* () {
|
|
194
|
-
const { command, args } = createProxyCommands(data, cmdArgs, cmdArgs.debug);
|
|
195
|
-
if (cmdArgs.debug) {
|
|
196
|
-
const reproCommands = [
|
|
197
|
-
`eval $(ssh-agent)`,
|
|
198
|
-
`ssh-add "${keys_1.PRIVATE_KEY_PATH}"`,
|
|
199
|
-
`eval $(p0 aws role assume ${data.role} --account ${data.accountId})`,
|
|
200
|
-
`${command} ${transformForShell(args).join(" ")}`,
|
|
201
|
-
];
|
|
202
|
-
(0, stdio_1.print2)(`Execute the following commands to create a similar SSH/SCP session:\n*** COMMANDS BEGIN ***\n${reproCommands.join("\n")}\n*** COMMANDS END ***"\n`);
|
|
203
|
-
}
|
|
204
|
-
return spawnSsmNode({
|
|
205
|
-
credential,
|
|
206
|
-
abortController: new AbortController(),
|
|
207
|
-
command,
|
|
208
|
-
args,
|
|
209
|
-
stdio: ["inherit", "inherit", "pipe"],
|
|
210
|
-
});
|
|
211
|
-
}));
|
|
212
|
-
});
|
|
213
|
-
exports.sshOrScp = sshOrScp;
|