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

Gbanas/psaas 19223 updating dependencies #9

Merged
merged 11 commits into from
Sep 30, 2024
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
23 changes: 13 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
repos:
- repo: https://github.com/phantomcyber/dev-cicd-tools
rev: v1.18
hooks:
- id: org-hook
- id: package-app-dependencies
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
args: ['--no-verify', '--exclude-files', '^dns.json$']
- repo: https://github.com/phantomcyber/dev-cicd-tools
rev: v1.22
hooks:
- id: org-hook
- id: package-app-dependencies
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
args:
- --no-verify
- --exclude-files
- ^dns.json$
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -198,4 +198,4 @@
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.
limitations under the License.
2 changes: 1 addition & 1 deletion NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Copyright (c) 2016-2024 Splunk Inc.
Third-party Software Attributions:

Library: dnspython
Version: 1.16.0
Version: 2.6.1
License: ISC
Copyright 2001-2017 Nominum, Inc
Copyright Dnspython Contributors
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Connector Version: 2.0.25
Product Vendor: Generic
Product Name: DNS
Product Version Supported (regex): ".\*"
Minimum Product Version: 5.1.0
Minimum Product Version: 6.2.1

This app implements investigative actions that return DNS Records for the object queried

Expand Down
20 changes: 10 additions & 10 deletions dns.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"product_vendor": "Generic",
"product_name": "DNS",
"product_version_regex": ".*",
"min_phantom_version": "5.1.0",
"min_phantom_version": "6.2.1",
"fips_compliant": true,
"latest_tested_versions": [
"N/A (Note: tested using Google Public DNS server 8.8.8.8 as of 11/2020)"
Expand All @@ -25,14 +25,6 @@
"phantom_dns"
]
},
"pip_dependencies": {
"wheel": [
{
"module": "dnspython",
"input_file": "wheels/shared/dnspython-1.16.0-py2.py3-none-any.whl"
}
]
},
"configuration": {
"dns_server": {
"description": "IP of the DNS server for lookups",
Expand Down Expand Up @@ -327,5 +319,13 @@
],
"versions": "EQ(*)"
}
]
],
"pip_dependencies": {
"wheel": [
{
"module": "dnspython",
"input_file": "wheels/shared/dnspython-1.16.0-py2.py3-none-any.whl"
}
]
}
}
120 changes: 52 additions & 68 deletions dns_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

import phantom.app as phantom
import requests
# Imports local to this App
from bs4 import UnicodeDammit
from phantom.action_result import ActionResult
from phantom.base_connector import BaseConnector
Expand All @@ -38,8 +37,7 @@ class DNSConnector(BaseConnector):
ACTION_ID_REVERSE_LOOKUP = "reverse_lookup"

def validate_parameters(self, param):
"""This app does it's own validation
"""
"""This app does it's own validation"""
return phantom.APP_SUCCESS

def initialize(self):
Expand All @@ -48,15 +46,13 @@ def initialize(self):
try:
self._python_version = int(sys.version_info[0])
except:
return self.set_status(phantom.APP_ERROR, "Error occurred while getting the Phantom "
"server's Python major version.")
self._server = self._handle_py_ver_compat_for_input_str(config.get('dns_server'))
self._host_name = self._handle_py_ver_compat_for_input_str(config.get('host_name', 'www.splunk.com'))
return self.set_status(phantom.APP_ERROR, "Error occurred while getting the Phantom " "server's Python major version.")
self._server = self._handle_py_ver_compat_for_input_str(config.get("dns_server"))
self._host_name = self._handle_py_ver_compat_for_input_str(config.get("host_name", "www.splunk.com"))

return phantom.APP_SUCCESS

def _handle_py_ver_compat_for_input_str(self, input_str):

"""
This method returns the encoded|original string based on the Python version.

Expand All @@ -66,14 +62,14 @@ def _handle_py_ver_compat_for_input_str(self, input_str):
"""
try:
if input_str and self._python_version < 3:
input_str = UnicodeDammit(input_str).unicode_markup.encode('utf-8')
input_str = UnicodeDammit(input_str).unicode_markup.encode("utf-8")
except:
self.debug_print("Error occurred while handling python 2to3 compatibility for the input string")

return input_str

def _get_error_message_from_exception(self, e):
""" This function is used to get appropriate error message from the exception.
"""This function is used to get appropriate error message from the exception.
:param e: Exception object
:return: error message
"""
Expand Down Expand Up @@ -103,7 +99,6 @@ def _get_error_message_from_exception(self, e):
return "Error Code: {0}. Error Message: {1}".format(error_code, error_msg)

def _is_ip(self, input_ip_address):

"""
Function that checks given address and return True if address is valid IPv4 or IPV6 address.

Expand All @@ -123,26 +118,22 @@ def _test_connectivity(self):
dnslookup.nameservers = [self._handle_py_ver_compat_for_input_str(self._server)]

if dnslookup.nameservers:
self.save_progress("Checking connectivity to your defined lookup server ({0})...".format
(dnslookup.nameservers[0]))
self.save_progress("Checking connectivity to your defined lookup server ({0})...".format(dnslookup.nameservers[0]))
try:
dnslookup.lifetime = 5
response = str(dnslookup.query(self._host_name, 'A')[0])
self.save_progress("Found a record for {0} as {1}...".format(
self._host_name, response))
response = str(dnslookup.query(self._host_name, "A")[0])
self.save_progress("Found a record for {0} as {1}...".format(self._host_name, response))
self.save_progress("Test Connectivity Passed")
return self.set_status_save_progress(phantom.APP_SUCCESS, "Connectivity to dns server was successful.")
except Exception as e:
self.save_progress("Test Connectivity Failed")
self.set_status(phantom.APP_ERROR, SAMPLEDNS_ERR_QUERY, e)
return self.get_status()
else:
self.save_progress(
"Using OS level lookup server ({0})...".format(dnslookup.nameservers[0]))
self.save_progress("Using OS level lookup server ({0})...".format(dnslookup.nameservers[0]))
try:
response = str(resolver.query(self._host_name, 'A')[0])
self.save_progress("Found a record for {0} as {1}...".format(
self._host_name, response))
response = str(resolver.query(self._host_name, "A")[0])
self.save_progress("Found a record for {0} as {1}...".format(self._host_name, response))
self.save_progress("Test Connectivity Passed")
return self.set_status_save_progress(phantom.APP_SUCCESS, "Connectivity to dns server was successful.")
except Exception as e:
Expand All @@ -160,43 +151,39 @@ def _handle_forward_lookup(self, param):

# get the server
server = self._server
host = param.get('domain')
type = 'A'
if param.get('type'):
type = param.get('type')
host = param.get("domain")
type = "A"
if param.get("type"):
type = param.get("type")

try:
dnslookup = resolver.Resolver()
if (server):
if server:
dnslookup.nameservers = [server]
if not self._is_ip(host):
record_infos = []
dns_response = dnslookup.query(host, type)
for item in dns_response:
record_infos.append(str(item))
formed_results = {'total_record_infos': len(record_infos)}
formed_results = {"total_record_infos": len(record_infos)}
action_result.update_summary(formed_results)
try:
action_result.update_summary(
{'cannonical_name': str(dns_response.canonical_name)})
action_result.update_summary(
{'record_info': str(dns_response[0])})
action_result.update_summary({"cannonical_name": str(dns_response.canonical_name)})
action_result.update_summary({"record_info": str(dns_response[0])})
except:
pass
action_result.set_status(phantom.APP_SUCCESS)
else:
action_result.set_status(
phantom.APP_ERROR, "Target is not a hostname")
action_result.set_status(phantom.APP_ERROR, "Target is not a hostname")
return action_result.get_status()
except Exception as e:
error_message = self._get_error_message_from_exception(e)
if ('None of DNS query names exist' in error_message):
if "None of DNS query names exist" in error_message:
return action_result.set_status(phantom.APP_SUCCESS, error_message)
action_result.set_status(phantom.APP_ERROR, SAMPLEDNS_ERR_QUERY, e)
return action_result.get_status()
data = {'record_infos': record_infos}
data['record_info_objects'] = [
{'record_info': x} for x in record_infos]
data = {"record_infos": record_infos}
data["record_info_objects"] = [{"record_info": x} for x in record_infos]
action_result.add_data(data)

return action_result.get_status()
Expand All @@ -211,28 +198,25 @@ def _handle_reverse_lookup(self, param):

# get the server
server = self._server
host = param.get('ip')
host = param.get("ip")

try:
dnslookup = resolver.Resolver()
if (server):
if server:
dnslookup.nameservers = [server]
if self._is_ip(host): # changed module
response = dnslookup.query(
reversename.from_address(host), 'PTR')
response = dnslookup.query(reversename.from_address(host), "PTR")
dns_response = str(response[0])
formed_results = {'ip': host, 'hostname': dns_response}
formed_results = {"ip": host, "hostname": dns_response}
action_result.update_summary(formed_results)
action_result.update_summary(
{'cannonical_name': str(response.canonical_name)})
action_result.update_summary({"cannonical_name": str(response.canonical_name)})
action_result.set_status(phantom.APP_SUCCESS)
else:
action_result.set_status(
phantom.APP_ERROR, "Target is not an IP")
action_result.set_status(phantom.APP_ERROR, "Target is not an IP")
return action_result.get_status()
except Exception as e:
error_message = self._get_error_message_from_exception(e)
if ('does not exist' in error_message):
if "does not exist" in error_message:
return action_result.set_status(phantom.APP_SUCCESS, error_message)
action_result.set_status(phantom.APP_ERROR, SAMPLEDNS_ERR_QUERY, e)
return action_result.get_status()
Expand All @@ -250,17 +234,17 @@ def handle_action(self, param):

self.debug_print("action_id", self.get_action_identifier())

if (action_id == self.ACTION_ID_FORWARD_LOOKUP):
if action_id == self.ACTION_ID_FORWARD_LOOKUP:
ret_val = self._handle_forward_lookup(param)
elif (action_id == self.ACTION_ID_REVERSE_LOOKUP):
elif action_id == self.ACTION_ID_REVERSE_LOOKUP:
ret_val = self._handle_reverse_lookup(param)
elif (action_id == phantom.ACTION_ID_TEST_ASSET_CONNECTIVITY):
elif action_id == phantom.ACTION_ID_TEST_ASSET_CONNECTIVITY:
ret_val = self._test_connectivity()

return ret_val


if __name__ == '__main__':
if __name__ == "__main__":

import argparse

Expand All @@ -270,10 +254,10 @@ def handle_action(self, param):

argparser = argparse.ArgumentParser()

argparser.add_argument('input_test_json', help='Input Test JSON file')
argparser.add_argument('-u', '--username', help='username', required=False)
argparser.add_argument('-p', '--password', help='password', required=False)
argparser.add_argument('-v', '--verify', action='store_true', help='verify', required=False, default=False)
argparser.add_argument("input_test_json", help="Input Test JSON file")
argparser.add_argument("-u", "--username", help="username", required=False)
argparser.add_argument("-p", "--password", help="password", required=False)
argparser.add_argument("-v", "--verify", action="store_true", help="verify", required=False, default=False)

args = argparser.parse_args()
session_id = None
Expand All @@ -282,31 +266,31 @@ def handle_action(self, param):
password = args.password
verify = args.verify

if (username is not None and password is None):
if username is not None and password is None:
# User specified a username but not a password, so ask
import getpass

password = getpass.getpass("Password: ")

if (username and password):
if username and password:
try:
print("Accessing the Login page")
login_url = BaseConnector._get_phantom_base_url() + 'login'
login_url = BaseConnector._get_phantom_base_url() + "login"
r = requests.get(login_url, verify=verify, timeout=SAMPLEDNS_DEFAULT_REQUEST_TIMEOUT)
csrftoken = r.cookies['csrftoken']
csrftoken = r.cookies["csrftoken"]

data = dict()
data['username'] = username
data['password'] = password
data['csrfmiddlewaretoken'] = csrftoken
data["username"] = username
data["password"] = password
data["csrfmiddlewaretoken"] = csrftoken

headers = dict()
headers['Cookie'] = 'csrftoken=' + csrftoken
headers['Referer'] = login_url
headers["Cookie"] = "csrftoken=" + csrftoken
headers["Referer"] = login_url

print("Logging into Platform to get the session id")
r2 = requests.post(login_url, verify=verify, data=data, headers=headers, timeout=SAMPLEDNS_DEFAULT_REQUEST_TIMEOUT)
session_id = r2.cookies['sessionid']
session_id = r2.cookies["sessionid"]
except Exception as e:
print("Unable to get session id from the platfrom. Error: " + str(e))
sys.exit(1)
Expand All @@ -319,9 +303,9 @@ def handle_action(self, param):
connector = DNSConnector()
connector.print_progress_message = True

if (session_id is not None):
in_json['user_session_token'] = session_id
connector._set_csrf_info(csrftoken, headers['Referer'])
if session_id is not None:
in_json["user_session_token"] = session_id
connector._set_csrf_info(csrftoken, headers["Referer"])

ret_val = connector._handle_action(json.dumps(in_json), None)
print(json.dumps(json.loads(ret_val), indent=4))
Expand Down
Loading
Loading