Skip to content
This repository has been archived by the owner on Aug 12, 2019. It is now read-only.

Commit

Permalink
Merge pull request #1 from deep-security/include-dependencies
Browse files Browse the repository at this point in the history
Include dependencies
  • Loading branch information
marknca committed Mar 21, 2016
2 parents 16e266a + fd0683c commit be0ce3f
Show file tree
Hide file tree
Showing 59 changed files with 13,919 additions and 24 deletions.
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,6 @@ Deep Security has two APIs that complement each other; one via a SOAP interface

As of version 9.6, most projects using the API are going to interact with both APIs. This SDK presents a unified front so the you don't have to differentiate between the two.

## Pre-Requisites

```bash
pip install -r requirements.txt
```

## Usage

```python
Expand Down
8 changes: 8 additions & 0 deletions deepsecurity/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
# make sure we add the current path structure to sys.path
# this is required to import local dependencies
import sys
import os
current_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(current_path)

# import project files as required
import manager
84 changes: 68 additions & 16 deletions deepsecurity/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
import inspect
import logging
import os
import ssl
import urllib
import urllib2
import xml.etree.ElementTree as ET

# 3rd party libraries
import requests
import suds

# Project libraries
Expand All @@ -25,6 +26,26 @@
import policy
import soap_https_handler

class RequestsProxyResponse(object):
"""
A proxy class to handle requests formatted responses
* The requests library has been removed as a requirement for the library
"""
def __init__(self, text=None, json=None, status=200):
self.text = text
self.json = json
self._status_code = status
self.ok = False

@property
def status_code(self): return self._status_code

@status_code.setter
def status_code(self, value):
self._status_code = int(value)
if self._status_code == 200: self.ok = True

class Manager(object):
"""
Class representing the Deep Security Manager and all of it's
Expand Down Expand Up @@ -150,6 +171,13 @@ def _setup_logging(self):
logging.getLogger('suds.client').setLevel(logging.ERROR)
if self._debug:
logging.getLogger('suds.client').setLevel(logging.DEBUG)
logging.getLogger('suds.transport').setLevel(logging.DEBUG)
#logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG)
#logging.getLogger('suds.wsdl').setLevel(logging.DEBUG)
#logging.getLogger('suds.resolver').setLevel(logging.DEBUG)
#logging.getLogger('suds.xsd.query').setLevel(logging.DEBUG)
#logging.getLogger('suds.xsd.basic').setLevel(logging.DEBUG)
#logging.getLogger('suds.binding.marshaller').setLevel(logging.DEBUG)

# setup module logging
logger = logging.getLogger("DeepSecurity.API")
Expand Down Expand Up @@ -246,25 +274,49 @@ def _make_a_rest_call(self, call):
if v: qs[k] = v
full_url += '?%s' % urllib.urlencode(qs)

# Make the call
if call.has_key('query') and call['query'] and not call.has_key('data'):
# GET
try:
result = requests.get(full_url, headers=headers, verify=not self.ignore_ssl_validation)
except Exception, get_err:
self.log("Failed to get REST call [%s] with query string. Threw exception: /%s" % (call['method'].lstrip('/'), post_err))
# Prep the SSL context
ssl_context = ssl.create_default_context()
if self.ignore_ssl_validation:
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

# Prep the URL opener
url_opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ssl_context))

# Prep the request
request = None
request_type = 'GET'
if call['method'] == 'authentication/logout':
self.log("Ending a REST API session requires a DELETE request")
request = urllib2.Request(full_url, headers=headers)
setattr(request, 'get_method', lambda: 'DELETE') # make this request use the DELETE HTTP verb
request_type = 'DELETE'
elif call.has_key('data') and call['data']:
# POST
try:
result = requests.post(full_url, data=json.dumps(call['data']), headers=headers, verify=not self.ignore_ssl_validation)
except Exception, post_err:
self.log("Failed to post REST call [%s]. Threw exception: /%s" % (call['method'].lstrip('/'), post_err))
request = urllib2.Request(full_url, data=json.dumps(call['data']), headers=headers)
request_type = 'POST'
else:
# default to GET
# GET
request = urllib2.Request(full_url, headers=headers)

# Make the request
response = None
try:
response = url_opener.open(request)
except Exception, url_err:
self.log("Failed to make REST {} call [{}]".format(request_type, call['method'].lstrip('/')), err=url_err)

# Convert the request from JSON
result = RequestsProxyResponse()
result.status_code = response.getcode() if response else None
if response:
result.text = response.read()
try:
result = requests.get(full_url, headers=headers)
except Exception, get_err:
self.log("Failed to get REST call [%s]. Threw exception: /%s" % (call['method'].lstrip('/'), post_err))
result.json = json.loads(result.text)
except Exception, json_err:
# we manually format the exception because it's expected with some REST API calls
# and generally none fatal, no need to output in the log constantly
self.log("Could not convert the response for call {} to JSON. Threw exception:\n\t{}".format(call['method'].lstrip('/'), json_err))

return result

Expand Down
154 changes: 154 additions & 0 deletions deepsecurity/suds/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( jortel@redhat.com )

"""
Suds is a lightweight SOAP python client that provides a
service proxy for Web Services.
"""

import os
import sys

#
# Project properties
#

__version__ = '0.4'
__build__="GA R699-20100913"

#
# Exceptions
#

class MethodNotFound(Exception):
def __init__(self, name):
Exception.__init__(self, "Method not found: '%s'" % name)

class PortNotFound(Exception):
def __init__(self, name):
Exception.__init__(self, "Port not found: '%s'" % name)

class ServiceNotFound(Exception):
def __init__(self, name):
Exception.__init__(self, "Service not found: '%s'" % name)

class TypeNotFound(Exception):
def __init__(self, name):
Exception.__init__(self, "Type not found: '%s'" % tostr(name))

class BuildError(Exception):
msg = \
"""
An error occured while building a instance of (%s). As a result
the object you requested could not be constructed. It is recommended
that you construct the type manually using a Suds object.
Please open a ticket with a description of this error.
Reason: %s
"""
def __init__(self, name, exception):
Exception.__init__(self, BuildError.msg % (name, exception))

class SoapHeadersNotPermitted(Exception):
msg = \
"""
Method (%s) was invoked with SOAP headers. The WSDL does not
define SOAP headers for this method. Retry without the soapheaders
keyword argument.
"""
def __init__(self, name):
Exception.__init__(self, self.msg % name)

class WebFault(Exception):
def __init__(self, fault, document):
if hasattr(fault, 'faultstring'):
Exception.__init__(self, "Server raised fault: '%s'" % fault.faultstring)
self.fault = fault
self.document = document

#
# Logging
#

class Repr:
def __init__(self, x):
self.x = x
def __str__(self):
return repr(self.x)

#
# Utility
#

def tostr(object, encoding=None):
""" get a unicode safe string representation of an object """
if isinstance(object, basestring):
if encoding is None:
return object
else:
return object.encode(encoding)
if isinstance(object, tuple):
s = ['(']
for item in object:
if isinstance(item, basestring):
s.append(item)
else:
s.append(tostr(item))
s.append(', ')
s.append(')')
return ''.join(s)
if isinstance(object, list):
s = ['[']
for item in object:
if isinstance(item, basestring):
s.append(item)
else:
s.append(tostr(item))
s.append(', ')
s.append(']')
return ''.join(s)
if isinstance(object, dict):
s = ['{']
for item in object.items():
if isinstance(item[0], basestring):
s.append(item[0])
else:
s.append(tostr(item[0]))
s.append(' = ')
if isinstance(item[1], basestring):
s.append(item[1])
else:
s.append(tostr(item[1]))
s.append(', ')
s.append('}')
return ''.join(s)
try:
return unicode(object)
except:
return str(object)

class null:
"""
The I{null} object.
Used to pass NULL for optional XML nodes.
"""
pass

def objid(obj):
return obj.__class__.__name__\
+':'+hex(id(obj))


import client
20 changes: 20 additions & 0 deletions deepsecurity/suds/bindings/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( jortel@redhat.com )

"""
Provides modules containing classes to support Web Services (SOAP)
bindings.
"""
Loading

0 comments on commit be0ce3f

Please sign in to comment.