Skip to content

Instantly share code, notes, and snippets.

@jorge-lavin
Created October 13, 2014 13:05
Show Gist options
  • Save jorge-lavin/cd7114e2fdac0ce1bc48 to your computer and use it in GitHub Desktop.
Save jorge-lavin/cd7114e2fdac0ce1bc48 to your computer and use it in GitHub Desktop.
import sys
def force_trust():
'''Checks if we need to trust all certificates
#FIXME: Not only check Jython, check if Jython was compiled with SSL support'''
if 'java' in sys.platform:
return True
else:
return False
def certificate_manager(f):
'''Decorator function that will make it so the context of the decorated method
will run with our TrustManager that accepts all certificates'''
def wrapped(*args, **kwargs):
# Only do this if running under Jython
if force_trust():
from javax.net.ssl import TrustManager, X509TrustManager
from jarray import array
from javax.net.ssl import SSLContext
class TrustAllX509TrustManager(X509TrustManager):
'''Define a custom TrustManager which will blindly accept all certificates'''
def checkClientTrusted(self, chain, auth):
pass
def checkServerTrusted(self, chain, auth):
pass
def getAcceptedIssuers(self):
return None
# Create a static reference to an SSLContext which will use
# our custom TrustManager
trust_managers = array([TrustAllX509TrustManager()], TrustManager)
TRUST_ALL_CONTEXT = SSLContext.getInstance("SSL")
TRUST_ALL_CONTEXT.init(None, trust_managers, None)
# Keep a static reference to the JVM's default SSLContext for restoring
# at a later time
DEFAULT_CONTEXT = SSLContext.getDefault()
SSLContext.setDefault(TRUST_ALL_CONTEXT)
try:
res = f(*args, **kwargs)
return res
finally:
SSLContext.setDefault(DEFAULT_CONTEXT)
else:
return f(*args, **kwargs)
return wrapped
class WebService(object):
def __init__(self, *args):
pass
@certificate_manager
def connect(self, args):
print('Connecting to {ws}'.format(ws=args))
if __name__ == '__main__':
ws = WebService()
ws.connect('bsa')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment