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

Private messaging is in using specified tags and sending only the nes… #6

Open
wants to merge 90 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
90 commits
Select commit Hold shift + click to select a range
1911b1b
azure - review wrong schema_alias (#6569)
logachev Mar 26, 2021
85e82a7
aws - ec2 svc id prefix for more resources (#6566)
kapilt Mar 29, 2021
1846776
gcp - service account key resource (#6591)
anovis Mar 31, 2021
002fa72
aws - handle deprecated services and mark additional global resources…
kapilt Apr 1, 2021
7ec3efa
core - offhours support for fallback schedule when missing tag (#6603)
bcsaller Apr 3, 2021
b846a03
aws - ecs-task-definition - config support (#6561)
PratMis Apr 3, 2021
2cb537f
releng - prep 0.9.12, rebase deps (#6606)
kapilt Apr 4, 2021
bb5d7f6
aws - network firewall resource (#6463)
kapilt Apr 4, 2021
ebbc7cf
gcp - pass project id into credentials constructor (#6608)
anovis Apr 6, 2021
274b94d
aws - config support for ecs service & eks cluster (#6605)
kapilt Apr 7, 2021
5bb1c86
gcp - metrics filter (#6595)
anovis Apr 19, 2021
cd6bd9c
azure - Ensure subscription override for all cases (#6629)
logachev Apr 20, 2021
43ddab1
azure - remove jsonpickle (#6632)
logachev Apr 21, 2021
b21ecd8
aws - support phd mode sans detail (#6639)
kapilt Apr 21, 2021
9898093
azure - sql filters (#6640)
stefangordon Apr 22, 2021
be00024
gcp - filter - scc findings (#6630)
anovis Apr 24, 2021
6411e35
aws - batch - fix subnet and sg filters related resource expressions …
kylejohnson514 Apr 24, 2021
b9acf7c
aws - kms - doc unification (#6626)
ajkerrigan Apr 25, 2021
42d011d
aws - asg - add update action to set max lifetime and other settings …
tjstansell Apr 25, 2021
a4394b4
aws - cloud watch alarms - tag augment (#6598)
gswai123 Apr 25, 2021
0026ce6
gcp - instance effective firewall filter (#6586)
anovis Apr 25, 2021
44ac77d
cli - report - strip date portion from s3 output dir (#6593)
ajkerrigan Apr 25, 2021
a36cdf0
releng - include license in generated setup and dep update (#6648)
kapilt Apr 25, 2021
b4881c5
azure - custodian and c7n-org azure multi cloud bug fixes (#6614)
d-van Apr 26, 2021
9b3414d
gcp - security-center execution mode (#6568)
anovis Apr 26, 2021
2775228
releng - static analyzers in ci (#6649)
kapilt Apr 26, 2021
b22cc7f
azure - sql vulnerability scan filter (#6651)
stefangordon Apr 27, 2021
1691f84
revert API version change in favor of resource graph (#6655)
stefangordon Apr 28, 2021
c08e27f
docs - add example to aws tag action (#6653)
trastle Apr 28, 2021
2c02335
c7n-org - name templates for azure script (#6661)
stefangordon Apr 29, 2021
f4d18ea
azure - data mask policy filter (#6665)
stefangordon May 3, 2021
ea33b4c
aws - secrets manager - tag augmentation fix (#6663)
trastle May 6, 2021
0ecb480
gcp - dataflow - augment per api changes (#6652)
anovis May 7, 2021
4239c2f
emr - use cluster state query from policy, if provided (#6675)
ajkerrigan May 12, 2021
6734a45
core - fix value filters that specify a value type but no op (#6682)
ajkerrigan May 17, 2021
097a06f
releng - dockerpkg - work around azure pipeline regression and docker…
kapilt May 19, 2021
6e4f729
aws - kinesis Analytics V2, subnet filter and delete action (#6689)
PratMis May 19, 2021
b9756b2
releng - github actions docker build fix (#6697)
kapilt May 20, 2021
48715a3
core - log policy exceptions before closing log stream (#6698)
tjstansell May 21, 2021
5fa087c
tools/c7n_mailer - add formatting for rds-cluster resources (#6700)
rvandegrift May 21, 2021
edb3ce1
aws - kms - more resilient key lookups, fix for keyarn/arn behaviors,…
ajkerrigan May 22, 2021
62778ba
azure - vm extensions filter (#6702)
stefangordon May 25, 2021
eb4f148
aws - ecs-task-definition - fix get_resources exception due to double…
tjstansell May 27, 2021
8fad4f4
aws - ami deregister exception when snapshot in use (#6706)
tjstansell May 27, 2021
9fae2f1
azure - fix delete action for resource groups (#6730)
aluong Jun 5, 2021
a471775
adding disable,enable,delete service account actions (#6650)
anovis Jun 7, 2021
bb5dc8d
aws - ebs - modify action - add gp3 ebs type to schema (#6753)
circa10a Jun 17, 2021
43d4a3c
aws - dax fix tagging action (#6754)
PratMis Jun 17, 2021
3190522
aws - fix datapipeline id field (#6746)
kapilt Jun 17, 2021
7889fb5
aws - glue connections - default describe parameters for omitting pas…
PratMis Jun 17, 2021
05ba41b
Private messaging is in using specified tags and sending only the nes…
CurtisAndersenSysdig Jun 21, 2021
17c5307
Made some changes to the Readme and also made it so that if the owner…
CurtisAndersenSysdig Jun 22, 2021
d00095a
Rolling back
CurtisAndersenSysdig Jun 22, 2021
7953131
Have one tag messinging functional
CurtisAndersenSysdig Jun 23, 2021
d2a9d67
Reformated the system to work with the slack://owner system so this s…
CurtisAndersenSysdig Jun 24, 2021
9089093
Merge branch 'AWS-private-owner-messaging' of https://github.com/drai…
CurtisAndersenSysdig Jun 24, 2021
1226a7c
found some un saved systems that need to be pushed
CurtisAndersenSysdig Jun 24, 2021
2e8c497
Adding the current branch in to the testing branches
CurtisAndersenSysdig Jun 24, 2021
0e96758
Made some changes allowing to become compliante with some of the chec…
CurtisAndersenSysdig Jun 24, 2021
1e45813
More white space and small formating errors for lint
CurtisAndersenSysdig Jun 24, 2021
0109abe
Setting the systems back to how they were
CurtisAndersenSysdig Jun 24, 2021
07ea8fa
Update tasks.json
CurtisAndersenSysdig Jun 24, 2021
57a0add
Removed a broken section of the code for the -slack notify
CurtisAndersenSysdig Aug 2, 2021
a2b73d9
commiting push
CurtisAndersenSysdig Aug 2, 2021
10746a7
Merge branch 'AWS-private-owner-messaging' of https://github.com/drai…
CurtisAndersenSysdig Aug 2, 2021
7309bd3
fixes to pass test
CurtisAndersenSysdig Aug 2, 2021
bff9bd8
compliance fix
CurtisAndersenSysdig Aug 2, 2021
c852efd
seeing if tasks fixes the error
CurtisAndersenSysdig Aug 3, 2021
c44e327
Update Makefile
CurtisAndersenSysdig Aug 3, 2021
6ea1036
trying to fix tests
CurtisAndersenSysdig Aug 3, 2021
e0ec8b8
roll back cahnge
CurtisAndersenSysdig Aug 3, 2021
e0b518e
checking if a test is the problem
CurtisAndersenSysdig Aug 3, 2021
0bc1bbd
undoing some changes
CurtisAndersenSysdig Aug 3, 2021
716544f
trying to fix a cli null connection error
CurtisAndersenSysdig Aug 3, 2021
e664f7f
fixing some thing
CurtisAndersenSysdig Aug 3, 2021
5afdd7f
added owners test
Aug 4, 2021
5b977fa
realized a mistake
Aug 4, 2021
d4c0c21
intents fixed
Aug 4, 2021
4368b38
more linting indent fixes
Aug 4, 2021
d61974c
to many blank lines fix
Aug 4, 2021
39324c5
adding build file test
Aug 5, 2021
a16b8ee
testing github work flow
Aug 5, 2021
d536106
testing
Aug 5, 2021
22d3b70
there was an error with self hosted?
Aug 5, 2021
b70963b
ubuntu latest
Aug 5, 2021
b2ae49a
building tox
Aug 5, 2021
ff6ab44
testing git
Aug 5, 2021
137f627
removing artifactory command
Aug 5, 2021
f2fa0f8
adding a test file to make sure that i grab the right thing
Aug 12, 2021
dcdce86
putting the upload test in the right place
Aug 12, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
7 changes: 3 additions & 4 deletions .azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ jobs:
architecture: 'x64'
# bin directory is in .dockerignore
- script: |
python -m pip install --upgrade pip
pip install docker click pytest pyyaml
python3 -m pip install --upgrade pip
pip3 install docker click pytest pyyaml six
# build a docker image and sanity test
- script: |
python tools/dev/dockerpkg.py build -t build --verbose --test -i cli

python3 tools/dev/dockerpkg.py build -t build --verbose --test -i cli
22 changes: 22 additions & 0 deletions .github/workflows/ci-master.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ jobs:
bash <(curl -s https://codecov.io/bash) -Z \
-v -f coverage.xml

- name: License Check
if: contains(matrix.tox-target, 'py39')
run: |
./.tox/${{ matrix.tox-target }}/bin/python tools/dev/license-check.py

Test-Windows:
# windows can't use the fast cache technique we use in our matrix builds
# where we cache the entire tox virtualenv directory, without error.
Expand Down Expand Up @@ -116,6 +121,23 @@ jobs:
run: |
tox -e py37

Analyzer:
runs-on: ubuntu-latest
needs: Lint
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v1
with:
python-version: 3.9
- name: Run Bandit
run: |
python -m pip install bandit
make analyzer-bandit
- name: Run Semgrep
run: |
python -m pip install semgrep
make analyzer-semgrep

Docs:
# todo, figure out how to fast cache the tox directory here.
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
# bin directory is in .dockerignore
run: |
python -m pip install --upgrade pip
pip install docker click pytest pyyaml
pip install docker click pytest pyyaml six
mkdir -p bin
wget -q -O bin/trivy.tgz https://github.com/aquasecurity/trivy/releases/download/v0.5.4/trivy_0.5.4_Linux-64bit.tar.gz
cd bin && tar xzf trivy.tgz
Expand Down
4 changes: 2 additions & 2 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"version": "2.0.0",
"command": "make",
"isShellCommand": true,
"echoCommand": true,
Expand All @@ -13,4 +13,4 @@
{"taskName": "coverage",
"args": ["coverage"]}
]
}
}
1 change: 1 addition & 0 deletions Curtis_upload_test
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
make sure this works
File renamed without changes.
25 changes: 25 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,28 @@ lint:

clean:
rm -rf .tox .Python bin include lib pip-selfcheck.json

analyzer-bandit:
bandit -i -s B101,B311 \
-r tools/c7n_azure/c7n_azure \
tools/c7n_gcp/c7n_gcp \
tools/c7n_terraform/c7n_terraform \
tools/c7n_guardian/c7n_guardian \
tools/c7n_org/c7n_org \
tools/c7n_mailer/c7n_mailer \
tools/c7n_policystream/policystream.py \
tools/c7n_trailcreator/c7n_trailcreator \
c7n


analyzer-semgrep:
semgrep --error --verbose --config p/security-audit \
tools/c7n_azure/c7n_azure \
tools/c7n_gcp/c7n_gcp \
tools/c7n_terraform/c7n_terraform \
tools/c7n_guardian/c7n_guardian \
tools/c7n_org/c7n_org \
tools/c7n_mailer/c7n_mailer \
tools/c7n_policystream/policystream.py \
tools/c7n_trailcreator/c7n_trailcreator \
c7n
16 changes: 8 additions & 8 deletions c7n/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""Provide basic caching services to avoid extraneous queries over
multiple policies on the same resource type.
"""
import pickle
import pickle # nosec nosemgrep

import os
import logging
Expand Down Expand Up @@ -65,10 +65,10 @@ def load(self):
return True

def get(self, key):
return self.data.get(pickle.dumps(key))
return self.data.get(pickle.dumps(key)) # nosemgrep

def save(self, key, data):
self.data[pickle.dumps(key)] = data
self.data[pickle.dumps(key)] = data # nosemgrep

def size(self):
return sum(map(len, self.data.values()))
Expand All @@ -86,7 +86,7 @@ def __init__(self, config):
self.data = {}

def get(self, key):
k = pickle.dumps(key)
k = pickle.dumps(key) # nosemgrep
return self.data.get(k)

def load(self):
Expand All @@ -98,17 +98,17 @@ def load(self):
return False
with open(self.cache_path, 'rb') as fh:
try:
self.data = pickle.load(fh)
self.data = pickle.load(fh) # nosec nosemgrep
except EOFError:
return False
log.debug("Using cache file %s" % self.cache_path)
return True

def save(self, key, data):
try:
with open(self.cache_path, 'wb') as fh:
self.data[pickle.dumps(key)] = data
pickle.dump(self.data, fh, protocol=2)
with open(self.cache_path, 'wb') as fh: # nosec
self.data[pickle.dumps(key)] = data # nosemgrep
pickle.dump(self.data, fh, protocol=2) # nosemgrep
except Exception as e:
log.warning("Could not save cache %s err: %s" % (
self.cache_path, e))
Expand Down
3 changes: 2 additions & 1 deletion c7n/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,8 @@ def validate(options):

with open(config_file) as fh:
if fmt in ('yml', 'yaml', 'json'):
data = yaml.load(fh.read(), Loader=DuplicateKeyCheckLoader)
# our loader is safe loader derived.
data = yaml.load(fh.read(), Loader=DuplicateKeyCheckLoader) # nosec nosemgrep
else:
log.error("The config file must end in .json, .yml or .yaml.")
raise ValueError("The config file must end in .json, .yml or .yaml.")
Expand Down
2 changes: 1 addition & 1 deletion c7n/filters/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ def match(self, i):
return op(r, v)
except TypeError:
return False
elif r == self.v:
elif r == v:
return True

return False
Expand Down
50 changes: 40 additions & 10 deletions c7n/filters/kms.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from botocore.exceptions import ClientError
from .core import ValueFilter
from .related import RelatedResourceFilter
from c7n.utils import local_session, type_schema
from c7n.utils import type_schema


class KmsRelatedFilter(RelatedResourceFilter):
Expand All @@ -13,15 +12,31 @@ class KmsRelatedFilter(RelatedResourceFilter):

:example:

Match a specific key alias:

.. code-block:: yaml

policies:
- name: dms-encrypt-key-check
resource: dms-instance
filters:
- type: kms-key
key: c7n:AliasName
key: "c7n:AliasName"
value: alias/aws/dms

Or match against native key attributes such as ``KeyManager``, which
more explicitly distinguishes between ``AWS`` and ``CUSTOMER``-managed
keys. The above policy can also be written as:

.. code-block:: yaml

policies:
- name: dms-aws-managed-key
resource: dms-instance
filters:
- type: kms-key
key: KeyManager
value: AWS
"""

schema = type_schema(
Expand All @@ -31,6 +46,24 @@ class KmsRelatedFilter(RelatedResourceFilter):
RelatedResource = "c7n.resources.kms.Key"
AnnotationKey = "matched-kms-key"

def get_related(self, resources):
resource_manager = self.get_resource_manager()
related_ids = self.get_related_ids(resources)
if len(related_ids) < self.FetchThreshold:
related = resource_manager.get_resources(list(related_ids))
else:
related = resource_manager.resources()
related_map = {}

# A resource's key property may point to an explicit ID or a key alias.
# Be sure that a related key lookup covers both cases.
for r in related:
related_map[r['KeyId']] = r
for alias in r.get('AliasNames', []):
related_map[alias] = r

return related_map

def get_related_ids(self, resources):
related_ids = super().get_related_ids(resources)
normalized_ids = []
Expand All @@ -42,13 +75,10 @@ def get_related_ids(self, resources):
return normalized_ids

def process(self, resources, event=None):
client = local_session(self.manager.session_factory).client('kms')
related = self.get_related(resources)
for r in related.values():
try:
alias_info = self.manager.retry(client.list_aliases, KeyId=r.get('KeyId'))
except ClientError as e:
self.log.warning(e)
continue
r['c7n:AliasName'] = alias_info.get('Aliases')[0].get('AliasName', '')
# `AliasNames` is set when we fetch keys, but only for keys
# which have aliases defined. Fall back to an empty string
# to avoid lookup errors in filters.
r['c7n:AliasName'] = r.get('AliasNames', ('',))[0]
return [r for r in resources if self.process_resource(r, related)]
13 changes: 11 additions & 2 deletions c7n/filters/offhours.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
- **weekends-only**: default false, whether to turn the resource off only on
the weekend
- **default_tz**: which timezone to utilize when evaluating time **(REQUIRED)**
- **fallback-schedule**: If a resource doesn't support tagging or doesn't provide
a tag you can supply a default schedule that will be used. When the tag is provided
this will be ignored. See :ref:`ScheduleParser Time Specifications <scheduleparser-time-spec>`.
- **tag**: which resource tag name to use for per-resource configuration
(schedule and timezone overrides and opt-in/opt-out); default is
``maid_offhours``.
Expand Down Expand Up @@ -61,6 +64,7 @@
onhour: 8
offhour: 20


Tag Based Configuration
=======================

Expand Down Expand Up @@ -94,6 +98,9 @@
supported by :py:class:`c7n.filters.offhours.ScheduleParser` as described
in the next section.


.. _scheduleparser-time-spec:

ScheduleParser Time Specifications
----------------------------------

Expand Down Expand Up @@ -255,6 +262,7 @@ class Time(Filter):
'properties': {
'tag': {'type': 'string'},
'default_tz': {'type': 'string'},
'fallback_schedule': {'type': 'string'},
'weekends': {'type': 'boolean'},
'weekends-only': {'type': 'boolean'},
'opt-out': {'type': 'boolean'},
Expand Down Expand Up @@ -315,6 +323,7 @@ def __init__(self, data, manager=None):
self.weekends_only = self.data.get('weekends-only', False)
self.opt_out = self.data.get('opt-out', False)
self.tag_key = self.data.get('tag', self.DEFAULT_TAG).lower()
self.fallback_schedule = self.data.get('fallback-schedule', None)
self.default_schedule = self.get_default_schedule()
self.parser = ScheduleParser(self.default_schedule)

Expand Down Expand Up @@ -438,12 +447,12 @@ def match(self, now, schedule):
def get_tag_value(self, i):
"""Get the resource's tag value specifying its schedule."""
# Look for the tag, Normalize tag key and tag value
found = False
found = self.fallback_schedule
for t in i.get('Tags', ()):
if t['Key'].lower() == self.tag_key:
found = t['Value']
break
if found is False:
if found in (False, None):
return False
# enforce utf8, or do translate tables via unicode ord mapping
value = found.lower().encode('utf8').decode('utf8')
Expand Down
2 changes: 1 addition & 1 deletion c7n/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def init_config(policy_config):

# a cli local directory doesn't translate to lambda
if not exec_options.get('output_dir', '').startswith('s3'):
exec_options['output_dir'] = '/tmp'
exec_options['output_dir'] = '/tmp' # nosec

account_id = None
# we can source account id from the cli parameters to avoid the sts call
Expand Down
8 changes: 5 additions & 3 deletions c7n/mu.py
Original file line number Diff line number Diff line change
Expand Up @@ -1078,6 +1078,8 @@ def render_event_pattern(self):
})
if self.data.get('categories', []):
payload['detail']['eventTypeCategory'] = self.data['categories']
if not payload['detail']:
payload.pop('detail')
elif event_type == 'hub-finding':
payload['source'] = ['aws.securityhub']
payload['detail-type'] = ['Security Hub Findings - Imported']
Expand Down Expand Up @@ -1160,13 +1162,13 @@ def update(self, func):
def pause(self, func):
try:
self.client.disable_rule(Name=func.name)
except Exception:
except ClientError:
pass

def resume(self, func):
try:
self.client.enable_rule(Name=func.name)
except Exception:
except ClientError:
pass

def remove(self, func):
Expand Down Expand Up @@ -1663,7 +1665,7 @@ def delta(rule, params):
if ('MaximumExecutionFrequency' in params and
rule['MaximumExecutionFrequency'] != params['MaximumExecutionFrequency']):
return True
if rule.get('Description', '') != rule.get('Description', ''):
if rule.get('Description', '') != params.get('Description', ''):
return True
return False

Expand Down
2 changes: 1 addition & 1 deletion c7n/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,9 +330,9 @@ def __enter__(self):
return self

def __exit__(self, exc_type=None, exc_value=None, exc_traceback=None):
self.leave_log()
if exc_type is not None:
log.exception("Error while executing policy")
self.leave_log()

def join_log(self):
self.handler = self.get_handler()
Expand Down
6 changes: 5 additions & 1 deletion c7n/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,11 @@ def _load_resource_tags(self, resource, item):
if isinstance(stags, str):
stags = json.loads(stags)
if isinstance(stags, list):
resource['Tags'] = [{u'Key': t['key'], u'Value': t['value']} for t in stags]
resource['Tags'] = [
{u'Key': t.get('key', t.get('tagKey')),
u'Value': t.get('value', t.get('tagValue'))}
for t in stags
]
elif isinstance(stags, dict):
resource['Tags'] = [{u'Key': k, u'Value': v} for k, v in stags.items()]

Expand Down
Loading