forked from microsoft/security-devops-action
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainer-mapping.ts
More file actions
292 lines (259 loc) · 11.2 KB
/
Copy pathcontainer-mapping.ts
File metadata and controls
292 lines (259 loc) · 11.2 KB
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
292
import { IMicrosoftSecurityDevOps } from "./msdo-interface";
import * as https from "https";
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as os from 'os';
const sendReportRetryCount: number = 1;
const GetScanContextURL: string = "https://dfdinfra-afdendpoint-prod-d5fqbucbg7fue0cf.z01.azurefd.net/github/v1/auth-push/GetScanContext?context=authOnly";
const ContainerMappingURL: string = "https://dfdinfra-afdendpoint-prod-d5fqbucbg7fue0cf.z01.azurefd.net/github/v1/container-mappings";
/**
* Represents the tasks for container mapping that are used to fetch Docker images pushed in a job run.
*/
export class ContainerMapping implements IMicrosoftSecurityDevOps {
readonly succeedOnError: boolean;
constructor() {
this.succeedOnError = true;
}
/**
* Container mapping pre-job commands wrapped in exception handling.
*/
public runPreJob() {
try {
core.info("::group::Microsoft Defender for DevOps container mapping pre-job - https://go.microsoft.com/fwlink/?linkid=2231419");
this._runPreJob();
}
catch (error) {
// Log the error
core.info("Error in Container Mapping pre-job: " + error);
}
finally {
// End the collapsible section
core.info("::endgroup::");
}
}
/*
* Set the start time of the job run.
*/
private _runPreJob() {
const startTime = new Date().toISOString();
core.saveState('PreJobStartTime', startTime);
core.info(`PreJobStartTime: ${startTime}`);
}
/**
* Placeholder / interface satisfier for main operations
*/
public async runMain() {
// No commands
}
/**
* Container mapping post-job commands wrapped in exception handling.
*/
public async runPostJob() {
try {
core.info("::group::Microsoft Defender for DevOps container mapping post-job - https://go.microsoft.com/fwlink/?linkid=2231419");
await this._runPostJob();
} catch (error) {
// Log the error
core.info("Error in Container Mapping post-job: " + error);
} finally {
// End the collapsible section
core.info("::endgroup::");
}
}
/*
* Using the start time, fetch the docker events and docker images in this job run and log the encoded output
* Send the report to Defender for DevOps
*/
private async _runPostJob() {
let startTime = core.getState('PreJobStartTime');
if (startTime.length <= 0) {
startTime = new Date(new Date().getTime() - 10000).toISOString();
core.debug(`PreJobStartTime not defined, using now-10secs`);
}
core.info(`PreJobStartTime: ${startTime}`);
let reportData = {
dockerVersion: "",
dockerEvents: [],
dockerImages: []
};
let bearerToken: string | void = await core.getIDToken()
.then((token) => { return token; })
.catch((error) => {
throw new Error("Unable to get token: " + error);
});
if (!bearerToken) {
throw new Error("Empty OIDC token received");
}
// Don't run the container mapping workload if this caller isn't an active customer.
var callerIsOnboarded: boolean = await this.checkCallerIsCustomer(bearerToken, sendReportRetryCount);
if (!callerIsOnboarded) {
core.info("Client is not onboarded to Defender for DevOps. Skipping container mapping workload.")
return;
}
core.info("Client is onboarded for container mapping.");
// Initialize the commands
let dockerVersionOutput = await exec.getExecOutput('docker --version');
if (dockerVersionOutput.exitCode != 0) {
core.info(`Unable to get docker version: ${dockerVersionOutput}`);
core.info(`Skipping container mapping since docker not found/available.`);
return;
}
reportData.dockerVersion = dockerVersionOutput.stdout.trim();
await this.execCommand(`docker events --since ${startTime} --until ${new Date().toISOString()} --filter event=push --filter type=image --format ID={{.ID}}`, reportData.dockerEvents)
.catch((error) => {
throw new Error("Unable to get docker events: " + error);
});
await this.execCommand(`docker images --format CreatedAt={{.CreatedAt}}::Repo={{.Repository}}::Tag={{.Tag}}::Digest={{.Digest}}`, reportData.dockerImages)
.catch((error) => {
throw new Error("Unable to get docker images: " + error);
});
core.debug("Finished data collection, starting API calls.");
var reportSent: boolean = await this.sendReport(JSON.stringify(reportData), bearerToken, sendReportRetryCount);
if (!reportSent) {
throw new Error("Unable to send report to backend service");
};
core.info("Container mapping data sent successfully.");
}
/**
* Execute command and setup the listener to capture the output
* @param command Command to execute
* @param listener Listener to capture the output
* @returns a Promise
*/
private async execCommand(command: string, listener: string[]): Promise<void> {
return exec.getExecOutput(command)
.then((result) => {
if(result.exitCode != 0) {
return Promise.reject(`Command execution failed: ${result}`);
}
result.stdout.trim().split(os.EOL).forEach(element => {
if(element.length > 0) {
listener.push(element);
}
});
});
}
/**
* Sends a report to Defender for DevOps and retries on the specified count
* @param data the data to send
* @param retryCount the number of time to retry
* @param bearerToken the GitHub-generated OIDC token
* @returns a boolean Promise to indicate if the report was sent successfully or not
*/
private async sendReport(data: string, bearerToken: string, retryCount: number = 0): Promise<boolean> {
core.debug(`attempting to send report: ${data}`);
return await this._sendReport(data, bearerToken)
.then(() => {
return true;
})
.catch(async (error) => {
if (retryCount == 0) {
return false;
} else {
core.info(`Retrying API call due to error: ${error}.\nRetry count: ${retryCount}`);
retryCount--;
return await this.sendReport(data, bearerToken, retryCount);
}
});
}
/**
* Sends a report to Defender for DevOps
* @param data the data to send
* @returns a Promise
*/
private async _sendReport(data: string, bearerToken: string): Promise<void> {
return new Promise(async (resolve, reject) => {
let apiTime = new Date().getMilliseconds();
let options = {
method: 'POST',
timeout: 2500,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + bearerToken,
'Content-Length': data.length
}
};
core.debug(`${options['method'].toUpperCase()} ${ContainerMappingURL}`);
const req = https.request(ContainerMappingURL, options, (res) => {
let resData = '';
res.on('data', (chunk) => {
resData += chunk.toString();
});
res.on('end', () => {
core.debug('API calls finished. Time taken: ' + (new Date().getMilliseconds() - apiTime) + "ms");
core.debug(`Status code: ${res.statusCode} ${res.statusMessage}`);
core.debug('Response headers: ' + JSON.stringify(res.headers));
if (resData.length > 0) {
core.debug('Response: ' + resData);
}
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(`Received Failed Status code when calling url: ${res.statusCode} ${resData}`);
}
resolve();
});
});
req.on('error', (error) => {
reject(new Error(`Error calling url: ${error}`));
});
req.write(data);
req.end();
});
}
/**
* Queries Defender for DevOps to determine if the caller is onboarded for container mapping.
* @param retryCount the number of time to retry
* @param bearerToken the GitHub-generated OIDC token
* @returns a boolean Promise to indicate if the report was sent successfully or not
*/
private async checkCallerIsCustomer(bearerToken: string, retryCount: number = 0): Promise<boolean> {
return await this._checkCallerIsCustomer(bearerToken)
.then(async (statusCode) => {
if (statusCode == 200) { // Status 'OK' means the caller is an onboarded customer.
return true;
} else if (statusCode == 403) { // Status 'Forbidden' means caller is not a customer.
return false;
} else {
core.debug(`Unexpected status code: ${statusCode}`);
return await this.retryCall(bearerToken, retryCount);
}
})
.catch(async (error) => {
core.info(`Unexpected error: ${error}.`);
return await this.retryCall(bearerToken, retryCount);
});
}
private async retryCall(bearerToken: string, retryCount: number): Promise<boolean> {
if (retryCount == 0) {
core.info(`All retries failed.`);
return false;
} else {
core.info(`Retrying checkCallerIsCustomer.\nRetry count: ${retryCount}`);
retryCount--;
return await this.checkCallerIsCustomer(bearerToken, retryCount);
}
}
private async _checkCallerIsCustomer(bearerToken: string): Promise<number> {
return new Promise(async (resolve, reject) => {
let options = {
method: 'GET',
timeout: 2500,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + bearerToken,
}
};
core.debug(`${options['method'].toUpperCase()} ${GetScanContextURL}`);
const req = https.request(GetScanContextURL, options, (res) => {
res.on('end', () => {
resolve(res.statusCode);
});
res.on('data', function(d) {
});
});
req.on('error', (error) => {
reject(new Error(`Error calling url: ${error}`));
});
req.end();
});
}
}