-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathvalidateChecksums.js
More file actions
257 lines (228 loc) · 9.61 KB
/
validateChecksums.js
File metadata and controls
257 lines (228 loc) · 9.61 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
const crypto = require('crypto');
const { Crc32 } = require('@aws-crypto/crc32');
const { Crc32c } = require('@aws-crypto/crc32c');
const { CrtCrc64Nvme } = require('@aws-sdk/crc64-nvme-crt');
const { errors: ArsenalErrors } = require('arsenal');
const { config } = require('../../../Config');
const checksumedMethods = Object.freeze({
'completeMultipartUpload': true,
'multiObjectDelete': true,
'bucketPutACL': true,
'bucketPutCors': true,
'bucketPutEncryption': true,
'bucketPutLifecycle': true,
'bucketPutLogging': true,
'bucketPutNotification': true,
'bucketPutPolicy': true,
'bucketPutReplication': true,
'bucketPutTagging': true,
'bucketPutVersioning': true,
'bucketPutWebsite': true,
'objectPutACL': true,
'objectPutLegalHold': true,
'bucketPutObjectLock': true, // PutObjectLockConfiguration
'objectPutRetention': true,
'objectPutTagging': true,
'objectRestore': true,
});
const ChecksumError = Object.freeze({
MD5Mismatch: 'MD5Mismatch',
MD5Invalid: 'MD5Invalid',
XAmzMismatch: 'XAmzMismatch',
MissingChecksum: 'MissingChecksum',
AlgoNotSupported: 'AlgoNotSupported',
AlgoNotSupportedSDK: 'AlgoNotSupportedSDK',
MultipleChecksumTypes: 'MultipleChecksumTypes',
MissingCorresponding: 'MissingCorresponding',
MalformedChecksum: 'MalformedChecksum',
});
const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/;
function uint32ToBase64(num) {
const buf = Buffer.alloc(4);
buf.writeUInt32BE(num, 0);
return buf.toString('base64');
}
const algorithms = Object.freeze({
crc64nvme: {
digest: async data => {
const input = Buffer.isBuffer(data) ? data : Buffer.from(data);
const crc = new CrtCrc64Nvme();
crc.update(input);
const result = await crc.digest();
return Buffer.from(result).toString('base64');
},
isValidDigest: expected => typeof expected === 'string' && expected.length === 12 && base64Regex.test(expected),
},
crc32: {
digest: data => {
const input = Buffer.isBuffer(data) ? data : Buffer.from(data);
return uint32ToBase64(new Crc32().update(input).digest() >>> 0); // >>> 0 coerce number to uint32
},
isValidDigest: expected => typeof expected === 'string' && expected.length === 8 && base64Regex.test(expected),
},
crc32c: {
digest: data => {
const input = Buffer.isBuffer(data) ? data : Buffer.from(data);
return uint32ToBase64(new Crc32c().update(input).digest() >>> 0); // >>> 0 coerce number to uint32
},
isValidDigest: expected => typeof expected === 'string' && expected.length === 8 && base64Regex.test(expected),
},
sha1: {
digest: data => {
const input = Buffer.isBuffer(data) ? data : Buffer.from(data);
return crypto.createHash('sha1').update(input).digest('base64');
},
isValidDigest: expected => typeof expected === 'string' && expected.length === 28 && base64Regex.test(expected),
},
sha256: {
digest: data => {
const input = Buffer.isBuffer(data) ? data : Buffer.from(data);
return crypto.createHash('sha256').update(input).digest('base64');
},
isValidDigest: expected => typeof expected === 'string' && expected.length === 44 && base64Regex.test(expected),
}
});
async function validateXAmzChecksums(headers, body) {
const checksumHeaders = Object.keys(headers).filter(header => header.startsWith('x-amz-checksum-'));
const xAmzChecksumCnt = checksumHeaders.length;
if (xAmzChecksumCnt > 1) {
return { error: ChecksumError.MultipleChecksumTypes, details: { algorithms: checksumHeaders } };
}
if (xAmzChecksumCnt === 0 && 'x-amz-sdk-checksum-algorithm' in headers) {
return {
error: ChecksumError.MissingCorresponding,
details: { expected: headers['x-amz-sdk-checksum-algorithm'] }
};
} else if (xAmzChecksumCnt === 0) {
return { error: ChecksumError.MissingChecksum, details: null };
}
// No x-amz-sdk-checksum-algorithm we expect one x-amz-checksum-[crc64nvme, crc32, crc32C, sha1, sha256].
const algo = checksumHeaders[0].slice('x-amz-checksum-'.length);
if (!(algo in algorithms)) {
return { error: ChecksumError.AlgoNotSupported, details: { algorithm: algo } };;
}
const expected = headers[`x-amz-checksum-${algo}`];
if (!algorithms[algo].isValidDigest(expected)) {
return { error: ChecksumError.MalformedChecksum, details: { algorithm: algo, expected } };
}
const calculated = await algorithms[algo].digest(body);
if (expected !== calculated) {
return { error: ChecksumError.XAmzMismatch, details: { algorithm: algo, calculated, expected } };
}
// AWS checks x-amz-checksum- first and then x-amz-sdk-checksum-algorithm
if ('x-amz-sdk-checksum-algorithm' in headers) {
const sdkAlgo = headers['x-amz-sdk-checksum-algorithm'];
if (typeof sdkAlgo !== 'string') {
return { error: ChecksumError.AlgoNotSupportedSDK, details: { algorithm: sdkAlgo } };
}
const sdkLowerAlgo = sdkAlgo.toLowerCase();
if (!(sdkLowerAlgo in algorithms)) {
return { error: ChecksumError.AlgoNotSupportedSDK, details: { algorithm: sdkAlgo } };
}
// If AWS there is a mismatch, AWS returns the same error as if the algo was invalid.
if (sdkLowerAlgo !== algo) {
return { error: ChecksumError.AlgoNotSupportedSDK, details: { algorithm: sdkAlgo } };
}
}
return null;
}
/**
* validateChecksumsNoChunking - Validate the checksums of a request.
* @param {object} headers - http headers
* @param {Buffer} body - http request body
* @return {object} - error
*/
async function validateChecksumsNoChunking(headers, body) {
if (!headers) {
return { error: ChecksumError.MissingChecksum, details: null };
}
let md5Present = false;
if ('content-md5' in headers) {
if (typeof headers['content-md5'] !== 'string') {
return { error: ChecksumError.MD5Invalid, details: { expected: headers['content-md5'] } };
}
if (headers['content-md5'].length !== 24) {
return { error: ChecksumError.MD5Invalid, details: { expected: headers['content-md5'] } };
}
if (!base64Regex.test(headers['content-md5'])) {
return { error: ChecksumError.MD5Invalid, details: { expected: headers['content-md5'] } };
}
const md5 = crypto.createHash('md5').update(body).digest('base64');
if (md5 !== headers['content-md5']) {
return { error: ChecksumError.MD5Mismatch, details: { calculated: md5, expected: headers['content-md5'] } };
}
md5Present = true;
}
const err = await validateXAmzChecksums(headers, body);
if (err && err.error === ChecksumError.MissingChecksum && md5Present) {
// Don't return MissingChecksum if MD5 is present.
return null;
}
return err;
}
async function defaultValidationFunc(request, body, log) {
const err = await validateChecksumsNoChunking(request.headers, body);
if (!err) {
return null;
}
if (err.error !== ChecksumError.MissingChecksum) {
log.debug('failed checksum validation', { method: request.apiMethod }, err);
}
switch (err.error) {
case ChecksumError.MissingChecksum:
return null;
case ChecksumError.XAmzMismatch: {
const algoUpper = err.details.algorithm.toUpperCase();
return ArsenalErrors.BadDigest.customizeDescription(
`The ${algoUpper} you specified did not match the calculated checksum.`
);
}
case ChecksumError.AlgoNotSupported:
return ArsenalErrors.InvalidRequest.customizeDescription(
'The algorithm type you specified in x-amz-checksum- header is invalid.'
);
case ChecksumError.AlgoNotSupportedSDK:
return ArsenalErrors.InvalidRequest.customizeDescription(
'Value for x-amz-sdk-checksum-algorithm header is invalid.'
);
case ChecksumError.MissingCorresponding:
return ArsenalErrors.InvalidRequest.customizeDescription(
'x-amz-sdk-checksum-algorithm specified, but no corresponding x-amz-checksum-* ' +
'or x-amz-trailer headers were found.'
);
case ChecksumError.MultipleChecksumTypes:
return ArsenalErrors.InvalidRequest.customizeDescription(
'Expecting a single x-amz-checksum- header. Multiple checksum Types are not allowed.'
);
case ChecksumError.MalformedChecksum:
return ArsenalErrors.InvalidRequest.customizeDescription(
`Value for x-amz-checksum-${err.details.algorithm} header is invalid.`
);
case ChecksumError.MD5Invalid:
return ArsenalErrors.InvalidDigest;
default:
return ArsenalErrors.BadDigest;
}
}
/**
* validateMethodChecksumsNoChunking - Validate the checksums of a request.
* @param {object} request - http request
* @param {Buffer} body - http request body
* @param {object} log - logger
* @return {object} - error
*/
async function validateMethodChecksumNoChunking(request, body, log) {
if (config.integrityChecks[request.apiMethod] === false) {
return null;
}
if (request.apiMethod in checksumedMethods) {
return await defaultValidationFunc(request, body, log);
}
return null;
}
module.exports = {
ChecksumError,
validateChecksumsNoChunking,
validateMethodChecksumNoChunking,
checksumedMethods,
};