-
Notifications
You must be signed in to change notification settings - Fork 73
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update package versions and remove cloud-run-proxy (#60)
Implement a reverse authenticating proxy in node. Fixes multiple CVEs * refactor config and proxy-server into separate files
- Loading branch information
Showing
8 changed files
with
667 additions
and
3,087 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/* | ||
* Copyright 2022 Google LLC | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
const {Storage} = require('@google-cloud/storage'); | ||
const {logger} = require('./logger.js'); | ||
const pkgJson = require('./package.json'); | ||
|
||
|
||
/** | ||
* Configuration object. | ||
* | ||
* Values are read from the JSON configuration file. | ||
* See {@link readAndVerifyConfig}. | ||
* | ||
* @typedef {{ | ||
* buckets: Array< | ||
* { | ||
* unscanned: string, | ||
* clean: string, | ||
* quarantined: string | ||
* }>, | ||
* ClamCvdMirrorBucket: string | ||
* }} | ||
*/ | ||
const Config = null; | ||
|
||
const storage = new Storage({userAgent: `${pkgJson.name}/${pkgJson.version}`}); | ||
|
||
/** | ||
* Read configuration from JSON configuration file, verify | ||
* and return a Config object | ||
* | ||
* @async | ||
* @param {string} configFile | ||
* @return {Config} | ||
*/ | ||
async function readAndVerifyConfig(configFile) { | ||
logger.info(`Using configuration file: ${configFile}`); | ||
|
||
|
||
/** @type {Config} */ | ||
let config; | ||
|
||
try { | ||
config = require(configFile); | ||
delete config.comments; | ||
} catch (e) { | ||
logger.fatal({err: e}, `Unable to read JSON file from ${configFile}`); | ||
throw new Error(`Invalid configuration ${configFile}`); | ||
} | ||
|
||
if (config.buckets.length === 0) { | ||
logger.fatal(`No buckets configured for scanning in ${configFile}`); | ||
throw new Error('No buckets configured'); | ||
} | ||
|
||
logger.info('BUCKET_CONFIG: ' + JSON.stringify(config, null, 2)); | ||
|
||
// Check buckets are specified and exist. | ||
let success = true; | ||
for (let x = 0; x < config.buckets.length; x++) { | ||
const buckets = config.buckets[x]; | ||
for (const bucketType of ['unscanned', 'clean', 'quarantined']) { | ||
if (!(await checkBucketExists( | ||
buckets[bucketType], `config.buckets[${x}].${bucketType}`))) { | ||
success = false; | ||
} | ||
} | ||
if (buckets.unscanned === buckets.clean || | ||
buckets.unscanned === buckets.quarantined || | ||
buckets.clean === buckets.quarantined) { | ||
logger.fatal( | ||
`Error in ${configFile} buckets[${x}]: bucket names are not unique`); | ||
success = false; | ||
} | ||
} | ||
if (!(await checkBucketExists( | ||
config.ClamCvdMirrorBucket, 'ClamCvdMirrorBucket'))) { | ||
success = false; | ||
} | ||
|
||
if (!success) { | ||
throw new Error('Invalid configuration'); | ||
} | ||
return config; | ||
} | ||
|
||
|
||
/** | ||
* Check that given bucket exists. Returns true on success | ||
* | ||
* @param {string} bucketName | ||
* @param {string} configName | ||
* @return {Promise<boolean>} | ||
*/ | ||
async function checkBucketExists(bucketName, configName) { | ||
if (!bucketName) { | ||
logger.fatal(`Error in config: no "${configName}" bucket defined`); | ||
success = false; | ||
} | ||
// Check for bucket existence by listing files in bucket, will throw | ||
// an exception if the bucket is not readable. | ||
// This is used in place of Bucket.exists() to avoid the need for | ||
// Project/viewer permission. | ||
try { | ||
await storage.bucket(bucketName) | ||
.getFiles({maxResults: 1, prefix: 'zzz', autoPaginate: false}); | ||
return true; | ||
} catch (e) { | ||
logger.fatal(`Error in config: cannot view files in "${configName}" : ${ | ||
bucketName} : ${e.message}`); | ||
logger.debug({err: e}); | ||
return false; | ||
} | ||
} | ||
|
||
exports.Config = Config; | ||
exports.readAndVerifyConfig = readAndVerifyConfig; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
/* | ||
* Copyright 2022 Google LLC | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
const {GoogleAuth} = require('google-auth-library'); | ||
const {logger} = require('./logger.js'); | ||
// eslint-disable-next-line no-unused-vars | ||
const {Config, readAndVerifyConfig} = require('./config.js'); | ||
const httpProxy = require('http-proxy'); | ||
|
||
const TOKEN_REFRESH_THRESHOLD_MILLIS = 60000; | ||
|
||
const googleAuth = new GoogleAuth(); | ||
|
||
|
||
// access token for GCS requests - will be refreshed shortly before it expires | ||
let accessToken; | ||
let accessTokenRefreshTimeout; | ||
let clamCvdMirrorBucket = 'uninitialized'; | ||
|
||
/** | ||
* Check to see when access token expires and refresh it just before. | ||
* This is required because proxy requires access token to be available | ||
* synchronously, but getAccessToken() is async. | ||
* So a 'current' access token needs to be available. | ||
*/ | ||
async function accessTokenRefresh() { | ||
if (accessTokenRefreshTimeout) { | ||
clearTimeout(accessTokenRefreshTimeout); | ||
accessTokenRefreshTimeout = null; | ||
} | ||
|
||
const client = await googleAuth.getClient(); | ||
if (!client.credentials?.expiry_date || | ||
client.credentials.expiry_date <= | ||
new Date().getTime() + TOKEN_REFRESH_THRESHOLD_MILLIS) { | ||
accessToken = await googleAuth.getAccessToken(); | ||
logger.info(`Access token expires at ${ | ||
new Date(client.credentials.expiry_date).toISOString()}`); | ||
} | ||
const nextCheckDate = | ||
new Date(client.credentials.expiry_date - TOKEN_REFRESH_THRESHOLD_MILLIS); | ||
logger.debug( | ||
`Next access token refresh check at ${nextCheckDate.toISOString()}`); | ||
accessTokenRefreshTimeout = setTimeout( | ||
accessTokenRefresh, nextCheckDate.getTime() - new Date().getTime()); | ||
} | ||
|
||
/** | ||
* Handle any internal proxy errors by returning a 500 | ||
* | ||
* @param {!Error} err | ||
* @param {!IncomingMessage} req The request payload | ||
* @param {!ServerResponse} res The HTTP response object | ||
*/ | ||
function handleProxyError(err, req, res) { | ||
logger.error( | ||
`Failed to proxy to GCS for path ${req.url}, returning code 500: ${err}`); | ||
res.writeHead(500, { | ||
'Content-Type': 'text/plain', | ||
}); | ||
res.end(`Failed to proxy to GCS: internal error\n`); | ||
} | ||
|
||
/** | ||
* Handle proxy requests - check path, and add Authorization header. | ||
* | ||
* @param {!Request} proxyReq | ||
* @param {!IncomingMessage} req The request payload | ||
* @param {!ServerResponse} res The HTTP response object | ||
*/ | ||
function handleProxyReq(proxyReq, req, res) { | ||
if (proxyReq.path.startsWith('/' + clamCvdMirrorBucket + '/')) { | ||
logger.info(`Proxying request for ${proxyReq.path} to GCS`); | ||
proxyReq.setHeader('Authorization', 'Bearer ' + accessToken); | ||
} else { | ||
logger.error(`Denying Proxy request for ${proxyReq.path} to GCS`); | ||
res.writeHead(403, { | ||
'Content-Type': 'text/plain', | ||
}); | ||
res.end('Failed to proxy to GCS - unauthorzied path: status 403\n'); | ||
} | ||
} | ||
|
||
/** | ||
* Set up a reverse proxy to add authentication to HTTP requests from | ||
* freshclam and proxy it to the GCS API | ||
*/ | ||
async function setupGcsReverseProxy() { | ||
const proxy = httpProxy.createProxyServer({ | ||
target: 'https://storage.googleapis.com/', | ||
changeOrigin: true, | ||
autoRewrite: true, | ||
secure: true, | ||
ws: false, | ||
}); | ||
|
||
proxy.on('error', handleProxyError); | ||
proxy.on('proxyReq', handleProxyReq); | ||
|
||
const PROXY_PORT = process.env.PROXY_PORT || 8888; | ||
|
||
proxy.listen(PROXY_PORT, 'localhost'); | ||
logger.info(`GCS authenticating reverse proxy listenting on port ${ | ||
PROXY_PORT} for requests to ${clamCvdMirrorBucket}`); | ||
} | ||
|
||
/** | ||
* Perform async setup and start the app. | ||
* | ||
* @async | ||
*/ | ||
async function run() { | ||
let configFile; | ||
if (process.argv.length >= 3) { | ||
configFile = process.argv[2]; | ||
} else { | ||
configFile = './config.json'; | ||
} | ||
|
||
/** @type {Config} */ | ||
const config = await readAndVerifyConfig(configFile); | ||
|
||
clamCvdMirrorBucket = config.ClamCvdMirrorBucket; | ||
|
||
await accessTokenRefresh(); | ||
await setupGcsReverseProxy(config.ClamCvdMirrorBucket); | ||
} | ||
|
||
// Start the service, exiting on error. | ||
run().catch((e) => { | ||
logger.fatal(e); | ||
logger.fatal('Exiting'); | ||
process.exit(1); | ||
}); |
Oops, something went wrong.