Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Commit

Permalink
merge with develop
Browse files Browse the repository at this point in the history
  • Loading branch information
piontec committed Oct 6, 2017
2 parents 82dd312 + 1324991 commit d49435d
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 4 deletions.
14 changes: 12 additions & 2 deletions docker_enforcer.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,13 @@ def authz_response():
@app.route("/AuthZPlugin.AuthZReq", methods=['POST'])
def authz_request():
app.logger.debug("New AuthZ Request: {}".format(request.data))
json_data = json.loads(request.data.decode(request.charset))
url = parse.urlparse(json_data["RequestUri"])
try:
json_data = json.loads(request.data.decode(request.charset))
url = parse.urlparse(json_data["RequestUri"])
except Exception as e:
app.logger.error("Error while trying to parse incoming message, resolving to default action. Error was: {}"
.format(e))
return get_default_response()
json_data["ParsedUri"] = url
if config.log_authz_requests:
log_authz_req(json_data)
Expand All @@ -229,6 +234,11 @@ def authz_request():
return to_formatted_json(json.dumps({"Allow": True}))


def get_default_response():
resp = {"Allow": True} if config.default_allow else {"Allow": False, "Msg": "Denied as default action"}
return to_formatted_json(json.dumps(resp))


def log_authz_req(json_data):
user_info = json_data["User"] if 'UserAuthNMethod' in json_data else '[unknown]'
app.logger.info("[AUTHZ_REQ] New auth request: user: {}, method: {}, uri: {}"
Expand Down
3 changes: 2 additions & 1 deletion dockerenforcer/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import copy
from typing import Dict

version = "0.8.4"
version = "0.8.5"


class Mode(Enum):
Expand Down Expand Up @@ -32,6 +32,7 @@ def __init__(self) -> None:
self.immediate_periodical_start: bool = bool(os.getenv('IMMEDIATE_PERIODICAL_START', 'False') == 'True')
self.stop_on_first_violation: bool = bool(os.getenv('STOP_ON_FIRST_VIOLATION', 'True') == 'True')
self.log_authz_requests: bool = bool(os.getenv('LOG_AUTHZ_REQUESTS', 'False') == 'True')
self.default_allow: bool = bool(os.getenv('DEFAULT_ACTION_ALLOW', 'True') == 'True')
self.version: str = version
self.white_list_separator: str = "|"

Expand Down
2 changes: 1 addition & 1 deletion dockerenforcer/docker_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(self, cid: str, params: Dict[str, Any], metrics: Dict[str, Any], po
self.owner: str = owner

def __str__(self, *args, **kwargs) -> str:
return self.params['Name'] if self.params['Name'] else self.cid
return self.params.get('Name', self.cid)


class DockerHelper:
Expand Down
3 changes: 3 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ stop containers running on a single host, but not obeying rules configured by th
* [How - Configuring and Running](#how-configuring-and-running)
* [Preparing the rules file](#preparing-the-rules-file)
* [Configuration options](#configuration-options)
* [Running custom code for whitelist evaluation](running-custom-code-for-whitelist-evaluation)
* [Running additional actions when a rule violation is detected](#running-additional-actions-when-a-rule-violation-is-detected)
* [Filtering docker API requests](#filtering-docker-api-requests)
* [Run modes](#run-modes)
Expand Down Expand Up @@ -139,6 +140,8 @@ checking all the rules and have all the violations, not only the first one, logg
- "LOG_AUTHZ_REQUESTS=False" - log all incoming docker API requests received in Authz mode. This logs
username (if available - only when TLS auth is used), HTTP method and URI for each received authorization
request. Of course, works only in Authz plugin mode.
- "DEFAULT_ACTION_ALLOW=True" - if any request is malformed and can't be parsed and evaluated, docker
enforcer allows this request if set to `True` and denies when `False`
- "WHITE_LIST=docker-enforcer,docker_enforcer" - pipe ('|') separated list of container name based white
list definitions, which allow to define a whitelist based on a container name. Each definition can be
(like in a sample value: "docker.\*,docker-enforcer|steal socket,docker.\*|steal socket"):
Expand Down
20 changes: 20 additions & 0 deletions test/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,26 @@ def test_killed_check_api_log(self):
self.assertEqual(det["violated_rule"], "must have memory limit")
self.assertEqual(det["owner"], "client")

def test_handles_empty_when_default_action_accept(self):
config.default_allow = True
res = self.app.post('/AuthZPlugin.AuthZReq', data=ApiTestHelper.authz_req_empty)
self._check_response(res, True)

def test_handles_empty_when_default_action_deny(self):
config.default_allow = False
res = self.app.post('/AuthZPlugin.AuthZReq', data=ApiTestHelper.authz_req_empty)
self._check_response(res, False, "Denied as default action")

def test_handles_malformed_when_default_action_accept(self):
config.default_allow = True
res = self.app.post('/AuthZPlugin.AuthZReq', data=ApiTestHelper.authz_req_malformed)
self._check_response(res, True)

def test_handles_malformed_when_default_action_deny(self):
config.default_allow = False
res = self.app.post('/AuthZPlugin.AuthZReq', data=ApiTestHelper.authz_req_malformed)
self._check_response(res, False, "Denied as default action")


class ApiInfoTest(unittest.TestCase):
def setUp(self):
Expand Down
4 changes: 4 additions & 0 deletions test/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ def get_verdicts(self):


class ApiTestHelper:
# empty request
authz_req_empty = b''
# malformed request
authz_req_malformed = b'{"Request'
# docker run -it alpine sh
authz_req_plain_run = b'{"RequestMethod":"POST","RequestUri":"/v1.30/containers/create","RequestBody":"eyJIb3N0bmFtZSI6IiIsIkRvbWFpbm5hbWUiOiIiLCJVc2VyIjoiIiwiQXR0YWNoU3RkaW4iOnRydWUsIkF0dGFjaFN0ZG91dCI6dHJ1ZSwiQXR0YWNoU3RkZXJyIjp0cnVlLCJUdHkiOnRydWUsIk9wZW5TdGRpbiI6dHJ1ZSwiU3RkaW5PbmNlIjp0cnVlLCJFbnYiOltdLCJDbWQiOlsic2giXSwiSW1hZ2UiOiJhbHBpbmUiLCJWb2x1bWVzIjp7fSwiV29ya2luZ0RpciI6IiIsIkVudHJ5cG9pbnQiOm51bGwsIk9uQnVpbGQiOm51bGwsIkxhYmVscyI6e30sIkhvc3RDb25maWciOnsiQmluZHMiOm51bGwsIkNvbnRhaW5lcklERmlsZSI6IiIsIkxvZ0NvbmZpZyI6eyJUeXBlIjoiIiwiQ29uZmlnIjp7fX0sIk5ldHdvcmtNb2RlIjoiZGVmYXVsdCIsIlBvcnRCaW5kaW5ncyI6e30sIlJlc3Rhc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CwiS2VybmVsTWVtb3J5IjowLCJNZW1vcnlSZXNlcnZhdGlvbiI6MCwiTWVtb3J5U3dhcCI6MCwiTWVtb3J5U3dhcHBpbmVzcyI6LTEsIk9vbUtpbGxEaXNhYmxlIjpmYWxzZSwiUGlkc0xpbWl0IjowLCJVbGltaXRzIjpudWxsLCJDcHVDb3VudCI6MCwiQ3B1UGVyY2VudCI6MCwiSU9NYXhpbXVtSU9wcyI6MCwiSU9NYXhpbXVtQmFuZHdpZHRoIjowfSwiTmV0d29ya2luZ0NvbmZpZyI6eyJFbmRwb2ludHNDb25maWciOnt9fX0K","RequestHeaders":{"Content-Length":"1425","Content-Type":"application/json","User-Agent":"Docker-Client/17.06.0-ce (linux)"}}\n'
# docker run -it alpine sh
Expand Down

0 comments on commit d49435d

Please sign in to comment.