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

SOAR-5457: Enable Black #893

Merged
merged 3 commits into from
Apr 28, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 22 additions & 22 deletions .github/workflows/black.yml
@@ -1,22 +1,22 @@
#name: Lint
#
#on: [push]
#
#jobs:
# lint:
# runs-on: ubuntu-20.04
# steps:
# - uses: actions/checkout@v1
#
# - name: Set up Python 3.7
# uses: actions/setup-python@v2
# with:
# python-version: 3.7
#
# - name: Install dependencies
# run: |
# pip install black
#
# - name: Lint
# run: |
# black . --check
name: Lint

on: [push]

jobs:
lint:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v1

- name: Set up Python 3.7
uses: actions/setup-python@v2
with:
python-version: 3.7

- name: Install dependencies
run: |
pip install black

- name: Lint
run: |
black . --check
@@ -1,6 +1,7 @@
import komand
from .schema import AddUserInput, AddUserOutput
from komand.exceptions import PluginException

# Custom imports below
from ldap3 import extend
from ldap3 import MODIFY_REPLACE
Expand Down Expand Up @@ -64,9 +65,11 @@ def run(self, params={}):
conn.raise_exceptions = True
conn.add(dn, ["person", "user"], parameters)
except LDAPException as e:
raise PluginException(cause="LDAP returned an error message.",
assistance="Creating new user failed, error returned by LDAP.",
data=e)
raise PluginException(
cause="LDAP returned an error message.",
assistance="Creating new user failed, error returned by LDAP.",
data=e,
)
success = True

if ssl:
Expand Down
Expand Up @@ -17,9 +17,6 @@ def __init__(self):
def run(self, params={}):
return {
Output.SUCCESS: ADUtils.change_account_status(
self.connection.conn,
params.get(Input.DISTINGUISHED_NAME),
False,
self.logger
self.connection.conn, params.get(Input.DISTINGUISHED_NAME), False, self.logger
)
}
Expand Up @@ -17,9 +17,6 @@ def __init__(self):
def run(self, params={}):
return {
Output.SUCCESS: ADUtils.change_account_status(
self.connection.conn,
params.get(Input.DISTINGUISHED_NAME),
True,
self.logger
self.connection.conn, params.get(Input.DISTINGUISHED_NAME), True, self.logger
)
}
@@ -1,6 +1,7 @@
import komand
from .schema import ForcePasswordResetInput, ForcePasswordResetOutput
from komand.exceptions import PluginException

# Custom imports below
from komand_active_directory_ldap.util.utils import ADUtils
from ldap3.core.exceptions import LDAPException
Expand Down Expand Up @@ -29,8 +30,10 @@ def run(self, params={}):
conn.raise_exceptions = True
conn.modify(dn=dn, changes=password_expire)
except LDAPException as e:
raise PluginException(cause="LDAP returned an error.",
assistance="Error was returned when trying to force password reset for this user.",
data=e)
raise PluginException(
cause="LDAP returned an error.",
assistance="Error was returned when trying to force password reset for this user.",
data=e,
)

return {"success": True}
Expand Up @@ -35,27 +35,22 @@ def run(self, params={}):
# Check that dn exists in AD
if not ADUtils.check_user_dn_is_valid(conn, dn, search_base):
self.logger.error(f"The DN {dn} was not found")
raise PluginException(
cause="The DN was not found.",
assistance=f"The DN {dn} was not found."
)
raise PluginException(cause="The DN was not found.", assistance=f"The DN {dn} was not found.")

try:
if add_remove == 'add':
if add_remove == "add":
group = extend.ad_add_members_to_groups(conn, dn, group_dn, fix=True, raise_error=True)
else:
group = extend.ad_remove_members_from_groups(conn, dn, group_dn, fix=True, raise_error=True)
except LDAPException as e:
raise PluginException(
cause="Either the user or group distinguished name was not found.",
assistance="Please check that the distinguished names are correct",
data=e
data=e,
)

if group is False:
self.logger.error(f"ModifyGroups: Unexpected result for group. Group was {str(group)}")
raise PluginException(preset=PluginException.Preset.UNKNOWN)

return {
Output.SUCCESS: group
}
return {Output.SUCCESS: group}
@@ -1,5 +1,6 @@
import komand
from .schema import QueryInput, QueryOutput, Input, Output

# Custom imports below
from komand_active_directory_ldap.util.utils import ADUtils
import json
Expand All @@ -9,10 +10,8 @@
class Query(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="query",
description="Run a LDAP query",
input=QueryInput(),
output=QueryOutput())
name="query", description="Run a LDAP query", input=QueryInput(), output=QueryOutput()
)

def run(self, params={}):
formatter = ADUtils()
Expand All @@ -33,17 +32,10 @@ def run(self, params={}):
if not attributes:
attributes = [ldap3.ALL_ATTRIBUTES, ldap3.ALL_OPERATIONAL_ATTRIBUTES]

conn.search(
search_base=params.get(Input.SEARCH_BASE),
search_filter=escaped_query,
attributes=attributes
)
conn.search(search_base=params.get(Input.SEARCH_BASE), search_filter=escaped_query, attributes=attributes)

result_list_json = conn.response_to_json()
result_list_object = json.loads(result_list_json)
entries = result_list_object["entries"]

return {
Output.RESULTS: entries,
Output.COUNT: len(entries)
}
return {Output.RESULTS: entries, Output.COUNT: len(entries)}
Expand Up @@ -8,23 +8,24 @@


class QueryGroupMembership(komand.Action):

def __init__(self):
super(self.__class__, self).__init__(
name='query_group_membership',
name="query_group_membership",
description=Component.DESCRIPTION,
input=QueryGroupMembershipInput(),
output=QueryGroupMembershipOutput())
output=QueryGroupMembershipOutput(),
)

def run(self, params={}):
base = params.get(Input.SEARCH_BASE)
include_groups = params.get(Input.INCLUDE_GROUPS)
expand_nested_groups = params.get(Input.EXPAND_NESTED_GROUPS)
try:
group_dn = self.search_data(
base=base,
filter_query=f"(sAMAccountName={params.get(Input.GROUP_NAME)})"
).get("entries")[0].get("dn")
group_dn = (
self.search_data(base=base, filter_query=f"(sAMAccountName={params.get(Input.GROUP_NAME)})")
.get("entries")[0]
.get("dn")
)
if include_groups and expand_nested_groups:
query = f"(memberOf:1.2.840.113556.1.4.1941:={group_dn})"
elif include_groups:
Expand All @@ -33,26 +34,20 @@ def run(self, params={}):
query = f"(&(objectClass=user)(memberOf:1.2.840.113556.1.4.1941:={group_dn}))"
else:
query = f"(&(objectClass=user)(memberOf:={group_dn}))"
entries = self.search_data(
base=base,
filter_query=query
).get("entries")
return {
Output.RESULTS: entries,
Output.COUNT: len(entries)
}
entries = self.search_data(base=base, filter_query=query).get("entries")
return {Output.RESULTS: entries, Output.COUNT: len(entries)}
except (AttributeError, IndexError) as e:
raise PluginException(
cause="LDAP returned unexpected response.",
assistance="Check that the provided inputs are correct and try again. If the issue persists please "
"contact support.",
data=e
"contact support.",
data=e,
)

def search_data(self, base: str, filter_query: str) -> dict:
self.connection.conn.search(
search_base=base,
search_filter=filter_query,
attributes=[ldap3.ALL_ATTRIBUTES, ldap3.ALL_OPERATIONAL_ATTRIBUTES]
attributes=[ldap3.ALL_ATTRIBUTES, ldap3.ALL_OPERATIONAL_ATTRIBUTES],
)
return json.loads(self.connection.conn.response_to_json())
Expand Up @@ -28,15 +28,18 @@ def run(self, params={}):
self.logger.info(f"Escaped DN {dn}")

if ssl is False:
raise PluginException(cause="SSL must be enabled",
assistance="SSL must be enabled for the reset password action")
raise PluginException(
cause="SSL must be enabled", assistance="SSL must be enabled for the reset password action"
)

try:
conn.raise_exceptions = True
success = extend.ad_modify_password(conn, dn, new_password, old_password=None)
except LDAPException as e:
raise PluginException(cause="LDAP returned an error in the response.",
assistance="LDAP failed to reset the password for this user",
data=e)
raise PluginException(
cause="LDAP returned an error in the response.",
assistance="LDAP failed to reset the password for this user",
data=e,
)

return {"success": success}
Expand Up @@ -25,14 +25,10 @@ def connect(self, params):
password = params.get(Input.USERNAME_PASSWORD).get("password")

host = self.host_formatter(host)
self.logger.info(f'Connecting to {host}:{port}')
self.logger.info(f"Connecting to {host}:{port}")

server = ldap3.Server(
host=host,
port=port,
use_ssl=self.ssl,
allowed_referral_hosts=[("*", True)],
get_info=ldap3.ALL
host=host, port=port, use_ssl=self.ssl, allowed_referral_hosts=[("*", True)], get_info=ldap3.ALL
)

try:
Expand All @@ -42,41 +38,28 @@ def connect(self, params):
password=password,
auto_bind=True,
auto_referrals=referrals,
authentication=ldap3.NTLM
authentication=ldap3.NTLM,
)
except LDAPBindError as e:
raise PluginException(preset=PluginException.Preset.USERNAME_PASSWORD, data=e)
except LDAPAuthorizationDeniedResult as e:
raise PluginException(preset=PluginException.Preset.UNAUTHORIZED, data=e)
except LDAPSocketOpenError as e:
raise PluginException(
preset=PluginException.Preset.SERVICE_UNAVAILABLE,
data=e
)
raise PluginException(preset=PluginException.Preset.SERVICE_UNAVAILABLE, data=e)
except LDAPException:
# An exception here is likely caused because the ldap server dose use NTLM
# A basic auth connection will be tried instead
self.logger.info("Failed to connect to the server with NTLM, attempting to connect with basic auth")
try:
conn = ldap3.Connection(
server=server,
user=user_name,
password=password,
auto_referrals=referrals,
auto_bind=True
server=server, user=user_name, password=password, auto_referrals=referrals, auto_bind=True
)
except LDAPBindError as e:
raise PluginException(
preset=PluginException.Preset.USERNAME_PASSWORD,
data=e
)
raise PluginException(preset=PluginException.Preset.USERNAME_PASSWORD, data=e)
except LDAPAuthorizationDeniedResult as e:
raise PluginException(preset=PluginException.Preset.UNAUTHORIZED, data=e)
except LDAPSocketOpenError as e:
raise PluginException(
preset=PluginException.Preset.SERVICE_UNAVAILABLE,
data=e
)
raise PluginException(preset=PluginException.Preset.SERVICE_UNAVAILABLE, data=e)

self.logger.info("Connected!")
self.conn = conn
Expand All @@ -89,21 +72,21 @@ def host_formatter(self, host: str) -> str:
if colons > 0:
host = host.split(":")
if colons == 1:
if host[1].find('//') != -1:
if host[1].find("//") != -1:
host = host[1][2:]
else:
self.logger.info("Port was provided in hostname, using value from Port field instead")
host = host[0]
elif colons == 2:
self.logger.info("Port was provided in hostname, using value from Port field instead")
host = host[1]
if host.find('//') != -1:
if host.find("//") != -1:
host = host[2:]
else:
raise PluginException(
cause=f"There are too many colons ({colons}) in the host name ({host}).",
assistance="Check that the host name is correct",
data=host
data=host,
)
backslash = host.find("/")
if backslash != -1:
Expand All @@ -114,9 +97,6 @@ def test(self):
try:
self.conn.extend.standard.who_am_i()
except LDAPExtensionError as e:
raise ConnectionTestException(
preset=ConnectionTestException.Preset.UNAUTHORIZED,
data=e
)
raise ConnectionTestException(preset=ConnectionTestException.Preset.UNAUTHORIZED, data=e)

return {"connection": "successful"}
Expand Up @@ -179,7 +179,9 @@ def change_account_status(conn, dn: str, status: bool, logger: Logger) -> bool:

if not ADUtils.check_user_dn_is_valid(conn, dn, search_base):
logger.error(f"The DN {dn} was not found")
raise PluginException(cause=f"The DN {dn} was not found.", assistance=f"Please provide a valid DN and try again.")
raise PluginException(
cause=f"The DN {dn} was not found.", assistance=f"Please provide a valid DN and try again."
)
user_list = [d["attributes"] for d in conn.response if "attributes" in d]
user_control = user_list[0]
try:
Expand Down