1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83import { CodeBuilder } from '../../helpers/code-builder';
import { escapeString } from '../../helpers/escape';
import { getHeader } from '../../helpers/headers';
import { Converter } from '../targets';
export type PowershellCommand = 'Invoke-RestMethod' | 'Invoke-WebRequest';
export const generatePowershellConvert = (command: PowershellCommand) => {
const convert: Converter<any> = ({
method,
headersObj,
cookies,
uriObj,
fullUrl,
postData,
allHeaders,
}) => {
const { push, join } = new CodeBuilder();
const methods = [
'DEFAULT',
'DELETE',
'GET',
'HEAD',
'MERGE',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'TRACE',
];
const methodArg = methods.includes(method.toUpperCase()) ? '-Method' : '-CustomMethod';
const commandOptions = [];
// Add headers, including the cookies
const headers = Object.keys(headersObj);
// construct headers
if (headers.length) {
push('$headers=@{}');
headers.forEach(key => {
if (key !== 'connection') {
// Not allowed
push(`$headers.Add("${key}", "${escapeString(headersObj[key], { escapeChar: '`' })}")`);
}
});
commandOptions.push('-Headers $headers');
}
// construct cookies
if (cookies.length) {
push('$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession');
cookies.forEach(cookie => {
push('$cookie = New-Object System.Net.Cookie');
push(`$cookie.Name = '${cookie.name}'`);
push(`$cookie.Value = '${cookie.value}'`);
push(`$cookie.Domain = '${uriObj.host}'`);
push('$session.Cookies.Add($cookie)');
});
commandOptions.push('-WebSession $session');
}
if (postData.text) {
commandOptions.push(
`-ContentType '${escapeString(getHeader(allHeaders, 'content-type'), {
delimiter: "'",
escapeChar: '`',
})}'`,
);
commandOptions.push(`-Body '${postData.text}'`);
}
push(
`$response = ${command} -Uri '${fullUrl}' ${methodArg} ${method} ${commandOptions.join(' ')}`,
);
return join();
};
return convert;
};