Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance security: Cloudfront distributions should use security response headers #529

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions backend/dataall/api/Objects/DatasetTable/resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from ....db import permissions, models
from ....db.api import ResourcePolicy, Glossary
from ....searchproxy import indexers
from ....utils import json_utils
from ....utils import json_utils, sql_utils

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -141,7 +141,9 @@ def preview(context, source, tableUri: str = None):
)
cursor = connection.cursor()

SQL = f'select * from "{table.GlueDatabaseName}"."{table.GlueTableName}" limit 50' # nosec
SQL = 'select * from {table_identifier} limit 50'.format(
table_identifier=sql_utils.Identifier(table.GlueDatabaseName, table.GlueTableName)
)
cursor.execute(SQL)
fields = []
for f in cursor.description:
Expand Down
22 changes: 22 additions & 0 deletions backend/dataall/utils/sql_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import re


class Identifier:
def __init__(self, *identifiers) -> None:
if not identifiers:
raise TypeError("Identifier cannot be empty")

for id in identifiers:
if not isinstance(id, str):
raise TypeError("SQL identifier parts must be strings")
if re.search(r"\W", id):
raise TypeError(f"SQL identifier contains invalid characters: {id}")

self._identifiers = identifiers

@property
def identifiers(self) -> str:
return self._identifiers

def __repr__(self) -> str:
return ".".join(self._identifiers)
224 changes: 85 additions & 139 deletions deploy/stacks/cloudfront.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
aws_ssm as ssm,
aws_s3 as s3,
aws_cloudfront as cloudfront,
aws_cloudfront_origins as origins,
aws_certificatemanager as acm,
aws_route53 as route53,
aws_route53_targets as route53_targets,
Expand Down Expand Up @@ -285,43 +286,24 @@ def __init__(
)
)

cloudfront_distribution = cloudfront.CloudFrontWebDistribution(
cloudfront_distribution = cloudfront.Distribution(
self,
'CloudFrontDistribution',
viewer_certificate=frontend_alias_configuration,
origin_configs=[
cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=cloudfront_bucket,
origin_access_identity=origin_access_identity,
),
behaviors=[
cloudfront.Behavior(
is_default_behavior=True, default_ttl=Duration.hours(1)
)
],
)
],
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
default_root_object='index.html',
error_configurations=[
cloudfront.CfnDistribution.CustomErrorResponseProperty(
error_code=404,
response_code=404,
error_caching_min_ttl=0,
response_page_path='/index.html',
certificate=frontend_alias_configuration,
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(
bucket=cloudfront_bucket,
origin_access_identity=origin_access_identity
),
cloudfront.CfnDistribution.CustomErrorResponseProperty(
error_code=403,
response_code=403,
error_caching_min_ttl=0,
response_page_path='/index.html',
),
],
web_acl_id=acl.get_att('Arn').to_string(),
logging_config=cloudfront.LoggingConfiguration(
bucket=logging_bucket, prefix='cloudfront-logs/frontend'
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
response_headers_policy=cloudfront.ResponseHeadersPolicy.SECURITY_HEADERS,
cache_policy=cloudfront.CachePolicy.CACHING_OPTIMIZED,
),
default_root_object='index.html',
error_responses=self.error_responses(),
web_acl_id=acl.get_att('Arn').to_string(),
log_bucket=logging_bucket,
log_file_prefix='cloudfront-logs/frontend',
)

ssm_distribution_id = ssm.StringParameter(
Expand Down Expand Up @@ -558,120 +540,47 @@ def build_static_site(

cloudfront_bucket.grant_read(origin_access_identity)

cloudfront_distribution = cloudfront.CloudFrontWebDistribution(
cloudfront_distribution = cloudfront.Distribution(
self,
f'{construct_id}Distribution',
viewer_certificate=alias_configuration,
origin_configs=[
cloudfront.SourceConfiguration(
custom_origin_source=cloudfront.CustomOriginConfig(
domain_name='example.org',
origin_protocol_policy=cloudfront.OriginProtocolPolicy.MATCH_VIEWER,
),
behaviors=[
cloudfront.Behavior(
path_pattern='/parseauth',
compress=True,
forwarded_values=cloudfront.CfnDistribution.ForwardedValuesProperty(
query_string=True
),
lambda_function_associations=[
cloudfront.LambdaFunctionAssociation(
event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
lambda_function=_lambda.Version.from_version_arn(
self,
f'{construct_id}ParserV',
version_arn=parse,
),
)
],
),
cloudfront.Behavior(
path_pattern='/refreshauth',
compress=True,
forwarded_values=cloudfront.CfnDistribution.ForwardedValuesProperty(
query_string=True
),
lambda_function_associations=[
cloudfront.LambdaFunctionAssociation(
event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
lambda_function=_lambda.Version.from_version_arn(
self,
f'{construct_id}RefresherV',
version_arn=refresh,
),
)
],
),
cloudfront.Behavior(
path_pattern='/signout',
compress=True,
forwarded_values=cloudfront.CfnDistribution.ForwardedValuesProperty(
query_string=True
),
lambda_function_associations=[
cloudfront.LambdaFunctionAssociation(
event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
lambda_function=_lambda.Version.from_version_arn(
self,
f'{construct_id}SingouterV',
version_arn=signout,
),
)
],
),
],
certificate=alias_configuration,
default_behavior=cloudfront.BehaviorOptions(
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
response_headers_policy=cloudfront.ResponseHeadersPolicy.SECURITY_HEADERS,
cache_policy=cloudfront.CachePolicy.CACHING_OPTIMIZED,
compress=True,
origin=origins.S3Origin(
bucket=cloudfront_bucket,
origin_access_identity=origin_access_identity
),
cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=cloudfront_bucket,
origin_access_identity=origin_access_identity,

edge_lambdas=[
cloudfront.EdgeLambda(
event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
function_version=self.func_version(f'{construct_id}CheckerV', check)
),
behaviors=[
cloudfront.Behavior(
is_default_behavior=True,
compress=True,
forwarded_values=cloudfront.CfnDistribution.ForwardedValuesProperty(
query_string=True
),
lambda_function_associations=[
cloudfront.LambdaFunctionAssociation(
event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
lambda_function=_lambda.Version.from_version_arn(
self,
f'{construct_id}CheckerV',
version_arn=check,
),
),
cloudfront.LambdaFunctionAssociation(
event_type=cloudfront.LambdaEdgeEventType.ORIGIN_RESPONSE,
lambda_function=self.http_header_func.current_version,
),
],
),
],
cloudfront.EdgeLambda(
event_type=cloudfront.LambdaEdgeEventType.VIEWER_RESPONSE,
function_version=self.http_header_func.current_version,
),
],
),
additional_behaviors={
'/parseauth': self.additional_documentation_behavior(
self.func_version(f'{construct_id}ParserV', parse)
),
],
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
default_root_object='index.html',
error_configurations=[
cloudfront.CfnDistribution.CustomErrorResponseProperty(
error_code=404,
response_code=404,
error_caching_min_ttl=0,
response_page_path='/index.html',
'/refreshauth': self.additional_documentation_behavior(
self.func_version(f'{construct_id}RefresherV', refresh)
),
cloudfront.CfnDistribution.CustomErrorResponseProperty(
error_code=403,
response_code=403,
error_caching_min_ttl=0,
response_page_path='/index.html',
'/signout': self.additional_documentation_behavior(
self.func_version(f'{construct_id}SingouterV', signout)
),
],
},
default_root_object='index.html',
error_responses=self.error_responses(),
web_acl_id=acl.get_att('Arn').to_string(),
logging_config=cloudfront.LoggingConfiguration(
bucket=logging_bucket, prefix=f'cloudfront-logs/{construct_id}'
),
log_bucket=logging_bucket,
log_file_prefix=f'cloudfront-logs/{construct_id}'
)

param_path = f'/dataall/{envname}/cloudfront/docs/user'
Expand Down Expand Up @@ -702,3 +611,40 @@ def store_distribution_params(
parameter_name=f'{param_path}/CloudfrontDistributionBucket',
string_value=cloudfront_bucket.bucket_name,
)

@staticmethod
def additional_documentation_behavior(func) -> cloudfront.BehaviorOptions:
return cloudfront.BehaviorOptions(
origin=origins.HttpOrigin('example.org'),
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
compress=True,
cache_policy=cloudfront.CachePolicy.CACHING_OPTIMIZED,
response_headers_policy=cloudfront.ResponseHeadersPolicy.SECURITY_HEADERS,

edge_lambdas=[
cloudfront.EdgeLambda(
event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
function_version=func
)
],
)

def func_version(self, name, arn):
return _lambda.Version.from_version_arn(self, name, version_arn=arn)

@staticmethod
def error_responses():
return [
cloudfront.ErrorResponse(
http_status=404,
response_http_status=404,
ttl=Duration.seconds(0),
response_page_path='/index.html',
),
cloudfront.ErrorResponse(
http_status=403,
response_http_status=403,
ttl=Duration.seconds(0),
response_page_path='/index.html',
),
]
12 changes: 9 additions & 3 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@
},
"dependencies": {
"@apollo/client": "^3.3.19",
"@appbaseio/reactivesearch": "^3.29.1",
"@appbaseio/reactivesearch": "^3.43.10",
"@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1",
"@monaco-editor/react": "^4.3.1",
"@mui/icons-material": "^5.5.1",
"@mui/x-date-pickers": "^5.0.0",
"@mui/lab": "^5.0.0-alpha.74",
"@mui/material": "^5.5.2",
"@mui/styles": "^5.5.1",
Expand All @@ -29,7 +30,7 @@
"amazon-quicksight-embedding-sdk": "^1.18.1",
"apexcharts": "^3.33.2",
"apollo-boost": "^0.4.9",
"aws-amplify": "^4.3.17",
"aws-amplify": "^5.2.6",
"axios": "^0.26.1",
"classnames": "^2.3.1",
"date-fns": "^2.28.0",
Expand All @@ -53,12 +54,17 @@
"react-redux": "^7.2.6",
"react-router": "6.0.0",
"react-router-dom": "6.0.0",
"react-scripts": "^5.0.0",
"react-scripts": "^5.0.1",
"simplebar": "^5.3.6",
"simplebar-react": "^2.3.6",
"web-vitals": "^2.1.4",
"yup": "^0.32.11"
},
"overrides" : {
"@appbaseio/reactivesearch": {
"react-redux": "^7.2.6"
}
},
"resolutions": {
"nth-check": "^2.0.1"
},
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/contexts/AmplifyContext.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createContext, useEffect, useReducer } from 'react';
import PropTypes from 'prop-types';
import Amplify, { Auth } from 'aws-amplify';
import { Amplify, Auth } from 'aws-amplify';
import { SET_ERROR } from '../store/errorReducer';

Amplify.configure({
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import ReactDOM from 'react-dom';
import { HelmetProvider } from 'react-helmet-async';
import { BrowserRouter } from 'react-router-dom';
import { Provider as ReduxProvider } from 'react-redux';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import StyledEngineProvider from '@mui/material/StyledEngineProvider';
import App from './App';
import { AuthProvider } from './contexts/AmplifyContext';
Expand Down
Loading