diff --git a/lib/api/initiateMultipartUpload.js b/lib/api/initiateMultipartUpload.js index 20a3b2228d..5775ed36f0 100644 --- a/lib/api/initiateMultipartUpload.js +++ b/lib/api/initiateMultipartUpload.js @@ -6,6 +6,7 @@ const getMetaHeaders = s3middleware.userMetadata.getMetaHeaders; const convertToXml = s3middleware.convertToXml; const { pushMetric } = require('../utapi/utilities'); const collectCorsHeaders = require('../utilities/collectCorsHeaders'); +const aclUtils = require('../utilities/aclUtils'); const { hasNonPrintables } = require('../utilities/stringChecks'); const { cleanUpBucket } = require('./apiUtils/bucket/bucketCreation'); const constants = require('../../constants'); @@ -88,6 +89,11 @@ function initiateMultipartUpload(authInfo, request, log, callback) { log.debug(`invalid x-amz-website-redirect-location value ${websiteRedirectHeader}`, { error: err }); return callback(err); } + if (!aclUtils.checkGrantHeaderValidity(request.headers)) { + log.trace('invalid acl header'); + monitoring.promMetrics('PUT', bucketName, 400, 'initiateMultipartUpload'); + return callback(errors.InvalidArgument); + } const checksumConfig = areChecksumsEnabled() ? getChecksumDataFromMPUHeaders(request.headers) : null; if (checksumConfig && checksumConfig.error) { const checksumErr = arsenalErrorFromChecksumError(checksumConfig); diff --git a/lib/api/objectCopy.js b/lib/api/objectCopy.js index 59af0b7275..c57e79f771 100644 --- a/lib/api/objectCopy.js +++ b/lib/api/objectCopy.js @@ -7,6 +7,7 @@ const validateHeaders = s3middleware.validateConditionalHeaders; const constants = require('../../constants'); const collectCorsHeaders = require('../utilities/collectCorsHeaders'); +const aclUtils = require('../utilities/aclUtils'); const locationConstraintCheck = require('./apiUtils/object/locationConstraintCheck'); const { checkQueryVersionId, versioningPreprocessing, decodeVID } = require('./apiUtils/object/versioning'); const getReplicationInfo = require('./apiUtils/object/getReplicationInfo'); @@ -569,6 +570,13 @@ function objectCopy(authInfo, request, sourceBucket, sourceObject, sourceVersion monitoring.promMetrics('PUT', destBucketName, err.code, 'copyObject'); return callback(err); } + // We check the grant headers before we copy the data. The ACL is parsed + // only when we store the metadata, after the copy. + if (!aclUtils.checkGrantHeaderValidity(request.headers)) { + log.trace('invalid acl header'); + monitoring.promMetrics('PUT', destBucketName, 400, 'copyObject'); + return callback(errors.InvalidArgument); + } const { error: checksumAlgoErr, algorithm: requestedAlgo } = areChecksumsEnabled() ? getCopyObjectChecksumAlgorithm(request.headers) : { error: null, algorithm: null }; diff --git a/lib/metadata/acl.js b/lib/metadata/acl.js index ab8a7e8884..523594131f 100644 --- a/lib/metadata/acl.js +++ b/lib/metadata/acl.js @@ -131,6 +131,10 @@ const acl = { return cb(errors.InvalidArgument); } + if (!aclUtils.checkGrantHeaderValidity(headers)) { + return cb(errors.InvalidArgument); + } + // parse grant headers const grantReadHeader = aclUtils.parseGrant(headers['x-amz-grant-read'], 'READ'); let grantWriteHeader = []; diff --git a/lib/utilities/aclUtils.js b/lib/utilities/aclUtils.js index 796a2129cc..d926999aa9 100644 --- a/lib/utilities/aclUtils.js +++ b/lib/utilities/aclUtils.js @@ -165,27 +165,48 @@ aclUtils.getPermissionType = function getPermissionType(identifier, resourceACL, return permission; }; +/** + * splitGrant - splits one grant of an x-amz-grant-* header into its type and + * its identifier, and removes the quotes around the identifier. + * Example: 'uri="http://acs.amazonaws.com/groups/global/AllUsers"' gives + * { userIDType: 'uri', identifier: 'http://acs.amazonaws.com/groups/global/AllUsers' }. + * We return null when the grant is not one type=identifier pair. + * Example: 'x', '' or 'id=a=b'. + * @param {string} grant - one grant, as found between the commas of the header + * @returns {object|null} the type and the identifier, or null if malformed + */ +function splitGrant(grant) { + const parts = grant.split('='); + if (parts.length !== 2) { + return null; + } + const userIDType = parts[0].trim(); + let identifier = parts[1].trim(); + if (identifier.length >= 2 && identifier.startsWith('"') && identifier.endsWith('"')) { + identifier = identifier.slice(1, -1); + } + // AWS accepts a canonical id in upper case and stores it in lower case. + // The permission checks compare ids in lower case, so we do the same. + if (userIDType.toLowerCase() === 'id') { + identifier = identifier.toLowerCase(); + } + return { userIDType, identifier }; +} + aclUtils.parseGrant = function parseGrant(grantHeader, grantType) { - if (grantHeader === undefined) { + // AWS ignores an empty grant header, so we treat it as a missing one. + if (grantHeader === undefined || grantHeader === '') { return undefined; } - const grantArray = grantHeader.split(','); - let itemArray; - let userIDType; - let identifier; - return grantArray.map(item => { - itemArray = item.split('='); - userIDType = itemArray[0].trim(); - identifier = itemArray[1].trim(); - if (identifier[0] === '"') { - identifier = identifier.substr(1, identifier.length - 2); - } - return { - userIDType, - identifier, - grantType, - }; - }); + // We skip a malformed grant instead of throwing: some APIs parse the + // headers before they check them, and a throw there kills the worker. + // checkGrantHeaderValidity refuses the request later, so a skipped grant + // is never stored. + return grantHeader + .split(',') + .map(splitGrant) + .filter(grant => grant !== null) + .map(({ userIDType, identifier }) => ({ userIDType, identifier, grantType })); }; aclUtils.isValidCanonicalId = function isValidCanonicalId(canonicalID) { @@ -282,12 +303,12 @@ aclUtils.checkGrantHeaderValidity = function checkGrantHeaderValidity(headers) { if (grantHeader) { const grantHeaderArr = grantHeader.split(','); for (let j = 0; j < grantHeaderArr.length; j++) { - const singleGrantArr = grantHeaderArr[j].split('='); - if (singleGrantArr.length !== 2) { + const grant = splitGrant(grantHeaderArr[j]); + if (grant === null) { return false; } - const identifier = singleGrantArr[0].trim().toLowerCase(); - const value = singleGrantArr[1].trim(); + const identifier = grant.userIDType.toLowerCase(); + const value = grant.identifier; if (identifier === 'uri') { if ( value !== constants.publicId && diff --git a/tests/functional/raw-node/test/aclGrantHeaders.js b/tests/functional/raw-node/test/aclGrantHeaders.js new file mode 100644 index 0000000000..1f4eb7b414 --- /dev/null +++ b/tests/functional/raw-node/test/aclGrantHeaders.js @@ -0,0 +1,128 @@ +const assert = require('assert'); + +const { makeS3Request } = require('../utils/makeRequest'); + +const authCredentials = { + accessKey: 'accessKey1', + secretKey: 'verySecretKey1', +}; +const bucket = 'rawnode-acl-grant-headers'; +const allUsers = 'http://acs.amazonaws.com/groups/global/AllUsers'; +// The canonical id of accessKey2. +const otherId = '79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2bf'; + +// We use raw requests because an SDK refuses to send most of these headers. +// A worker that crashes closes the socket, so the request fails with no +// status code. +function request(params) { + const headers = { 'content-length': Buffer.byteLength(params.requestBody || ''), ...params.headers }; + return new Promise(resolve => { + makeS3Request({ authCredentials, bucket, ...params, headers }, (err, res) => resolve({ err, res })); + }); +} + +function assertError({ err, res }, statusCode, code) { + assert(res, `expected a ${statusCode} ${code}, got ${err && err.message}`); + assert.strictEqual(res.statusCode, statusCode); + assert.strictEqual(err && err.code, code); +} + +function assertOk({ err, res }) { + assert(res, `expected a 200, got ${err && err.message}`); + assert.strictEqual(res.statusCode, 200, err && err.code); +} + +const apis = [ + { name: 'PutBucketAcl', params: { method: 'PUT', queryObj: { acl: '' } } }, + { name: 'PutObject', params: { method: 'PUT', objectKey: 'put' } }, + { name: 'PutObjectAcl', params: { method: 'PUT', objectKey: 'src', queryObj: { acl: '' } } }, + { + name: 'CopyObject', + params: { method: 'PUT', objectKey: 'copy', headers: { 'x-amz-copy-source': `/${bucket}/src` } }, + }, + { name: 'CreateMultipartUpload', params: { method: 'POST', objectKey: 'mpu', queryObj: { uploads: '' } } }, +]; + +function withGrant(params, value) { + return { ...params, headers: { ...params.headers, 'x-amz-grant-read': value } }; +} + +describe('grant headers that are not type=identifier pairs', () => { + before(async () => { + assertOk(await request({ method: 'PUT' })); + assertOk(await request({ method: 'PUT', objectKey: 'src', requestBody: 'body' })); + }); + + after(async () => { + const list = await request({ method: 'GET', queryObj: { uploads: '' } }); + const uploads = [...list.res.body.matchAll(/([^<]*)<\/Key>([^<]*)<\/UploadId>/g)]; + for (const [, key, uploadId] of uploads) { + await request({ method: 'DELETE', objectKey: key, queryObj: { uploadId } }); + } + for (const key of ['src', 'put', 'copy']) { + await request({ method: 'DELETE', objectKey: key }); + } + await request({ method: 'DELETE' }); + }); + + const malformed = { + 'no equal sign': 'x', + 'two equal signs': 'id=a=b', + 'a trailing comma': `uri=${allUsers},`, + }; + Object.entries(malformed).forEach(([name, value]) => { + apis.forEach(api => { + it(`should return InvalidArgument on ${api.name} for a grant with ${name}`, async () => { + assertError(await request(withGrant(api.params, value)), 400, 'InvalidArgument'); + }); + }); + + it(`should answer an anonymous PutBucketAcl with ${name} on a missing bucket`, async () => { + const result = await new Promise(resolve => { + makeS3Request( + { + method: 'PUT', + bucket: 'rawnode-acl-grant-headers-missing', + queryObj: { acl: '' }, + headers: { 'x-amz-grant-read': value }, + }, + (err, res) => resolve({ err, res }), + ); + }); + assert(result.res, `expected an error response, got ${result.err && result.err.message}`); + assert(result.res.statusCode >= 400 && result.res.statusCode < 500, `${result.res.statusCode}`); + }); + }); + + ['CopyObject', 'CreateMultipartUpload'].forEach(name => { + it(`should return InvalidArgument on ${name} for a grant to id=123`, async () => { + const api = apis.find(a => a.name === name); + assertError(await request(withGrant(api.params, 'id=123')), 400, 'InvalidArgument'); + }); + }); + + it('should ignore an empty grant header on PutObject', async () => { + assertOk(await request(withGrant(apis[1].params, ''))); + }); + + // An empty header is no ACL at all, so PutObjectAcl has nothing to apply. + it('should return MalformedXML on PutObjectAcl with only an empty grant header', async () => { + assertError(await request(withGrant(apis[2].params, '')), 400, 'MalformedXML'); + }); + + it('should accept a quoted identifier on PutObject', async () => { + assertOk(await request(withGrant(apis[1].params, `uri="${allUsers}"`))); + }); + + apis.forEach(api => { + it(`should accept a canonical id in upper case on ${api.name}`, async () => { + assertOk(await request(withGrant(api.params, `id=${otherId.toUpperCase()}`))); + }); + }); + + it('should store a canonical id given in upper case in lower case on CopyObject', async () => { + assertOk(await request(withGrant(apis[3].params, `id=${otherId.toUpperCase()}`))); + const { res } = await request({ method: 'GET', objectKey: 'copy', queryObj: { acl: '' } }); + assert(res.body.includes(`${otherId}`), res.body); + }); +}); diff --git a/tests/unit/api/aclGrantHeaders.js b/tests/unit/api/aclGrantHeaders.js new file mode 100644 index 0000000000..4ac5f75332 --- /dev/null +++ b/tests/unit/api/aclGrantHeaders.js @@ -0,0 +1,193 @@ +const assert = require('assert'); + +const { bucketPut } = require('../../../lib/api/bucketPut'); +const bucketPutACL = require('../../../lib/api/bucketPutACL'); +const initiateMultipartUpload = require('../../../lib/api/initiateMultipartUpload'); +const objectCopy = require('../../../lib/api/objectCopy'); +const objectPut = require('../../../lib/api/objectPut'); +const objectPutACL = require('../../../lib/api/objectPutACL'); +const constants = require('../../../constants'); +const metadata = require('../metadataswitch'); +const DummyRequest = require('../DummyRequest'); +const { cleanup, DummyRequestLogger, makeAuthInfo } = require('../helpers'); + +const log = new DummyRequestLogger(); +const authInfo = makeAuthInfo('accessKey1'); +const anonymousAuthInfo = makeAuthInfo(constants.publicId); +const namespace = 'default'; +const bucketName = 'bucketname'; +const objectKey = 'objectname'; +const copyKey = 'copyname'; +const validId = '79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2bf'; + +const crashingGrants = { + 'no equal sign': 'x', + 'a trailing comma': `uri=${constants.publicId},`, +}; + +function bucketPutRequest() { + return new DummyRequest({ + bucketName, + namespace, + headers: { host: `${bucketName}.s3.amazonaws.com` }, + url: '/', + }); +} + +function objectPutRequest(key, headers = {}) { + return new DummyRequest( + { + bucketName, + namespace, + objectKey: key, + headers: { host: `${bucketName}.s3.amazonaws.com`, ...headers }, + url: `/${bucketName}/${key}`, + }, + Buffer.from('body', 'utf8'), + ); +} + +function aclRequest(headers, key) { + return new DummyRequest({ + bucketName, + namespace, + objectKey: key, + headers: { host: `${bucketName}.s3.amazonaws.com`, ...headers }, + url: key ? `/${bucketName}/${key}?acl` : '/?acl', + query: { acl: '' }, + }); +} + +function assertNoObject(key, done) { + metadata.getObjectMD(bucketName, key, {}, log, err => { + assert(err && err.is.NoSuchKey, `expected no object ${key}, got ${err}`); + done(); + }); +} + +describe('grant headers that are not type=identifier pairs', () => { + beforeEach(done => { + cleanup(); + bucketPut(authInfo, bucketPutRequest(), log, err => { + if (err) { + return done(err); + } + return objectPut(authInfo, objectPutRequest(objectKey), undefined, log, done); + }); + }); + + after(() => cleanup()); + + function copyObject(headers, cb) { + const request = new DummyRequest({ + bucketName, + namespace, + objectKey: copyKey, + headers: { host: `${bucketName}.s3.amazonaws.com`, ...headers }, + url: `/${bucketName}/${copyKey}`, + socket: {}, + }); + objectCopy(authInfo, request, bucketName, objectKey, undefined, log, cb); + } + + function createMultipartUpload(headers, cb) { + const request = { + bucketName, + namespace, + objectKey, + headers: { host: `${bucketName}.s3.amazonaws.com`, ...headers }, + url: `/${objectKey}?uploads`, + socket: { remoteAddress: '1.1.1.1' }, + actionImplicitDenies: false, + }; + initiateMultipartUpload(authInfo, request, log, cb); + } + + Object.entries(crashingGrants).forEach(([name, value]) => { + const headers = { 'x-amz-grant-read': value }; + + it(`PutBucketAcl returns InvalidArgument for ${name} and keeps the ACL`, done => { + bucketPutACL(authInfo, aclRequest(headers), log, err => { + assert(err && err.is.InvalidArgument, `expected InvalidArgument, got ${err}`); + metadata.getBucket(bucketName, log, (err, bucket) => { + assert.ifError(err); + assert.deepStrictEqual(bucket.getAcl().READ, []); + done(); + }); + }); + }); + + it(`PutBucketAcl by an anonymous user on a missing bucket answers for ${name}`, done => { + const request = aclRequest(headers); + request.bucketName = 'nosuchbucket'; + bucketPutACL(anonymousAuthInfo, request, log, err => { + assert(err && err.is.NoSuchBucket, `expected NoSuchBucket, got ${err}`); + done(); + }); + }); + }); + + Object.entries({ ...crashingGrants, 'two equal signs': `id=${validId}=x` }).forEach(([name, value]) => { + const headers = { 'x-amz-grant-read': value }; + + it(`CopyObject returns InvalidArgument for ${name} and stores nothing`, done => { + copyObject(headers, err => { + assert(err && err.is.InvalidArgument, `expected InvalidArgument, got ${err}`); + assertNoObject(copyKey, done); + }); + }); + + it(`CreateMultipartUpload returns InvalidArgument for ${name}`, done => { + createMultipartUpload(headers, err => { + assert(err && err.is.InvalidArgument, `expected InvalidArgument, got ${err}`); + done(); + }); + }); + }); + + it('PutObject ignores an empty grant header', done => { + objectPut(authInfo, objectPutRequest('emptygrant', { 'x-amz-grant-read': '' }), undefined, log, err => { + assert.ifError(err); + metadata.getObjectMD(bucketName, 'emptygrant', {}, log, (err, md) => { + assert.ifError(err); + assert.deepStrictEqual(md.acl.READ, []); + done(); + }); + }); + }); + + // An empty header is no ACL at all, so PutObjectAcl has nothing to apply. + it('PutObjectAcl with only an empty grant header keeps the ACL', done => { + objectPutACL(authInfo, aclRequest({ 'x-amz-grant-read': '' }, objectKey), log, err => { + assert(err && err.is.MalformedXML, `expected MalformedXML, got ${err}`); + metadata.getObjectMD(bucketName, objectKey, {}, log, (err, md) => { + assert.ifError(err); + assert.deepStrictEqual(md.acl.READ, []); + done(); + }); + }); + }); + + it('PutObject applies a grant with a quoted identifier', done => { + const headers = { 'x-amz-grant-read': `uri="${constants.publicId}"` }; + objectPut(authInfo, objectPutRequest('quoted', headers), undefined, log, err => { + assert.ifError(err); + metadata.getObjectMD(bucketName, 'quoted', {}, log, (err, md) => { + assert.ifError(err); + assert.deepStrictEqual(md.acl.READ, [constants.publicId]); + done(); + }); + }); + }); + + it('CopyObject stores a canonical id given in upper case in lower case', done => { + copyObject({ 'x-amz-grant-read': `id=${validId.toUpperCase()}` }, err => { + assert.ifError(err); + metadata.getObjectMD(bucketName, copyKey, {}, log, (err, md) => { + assert.ifError(err); + assert.deepStrictEqual(md.acl.READ, [validId]); + done(); + }); + }); + }); +});