Esempio n. 1
0
def urandom(n):
    global urandom_source
    if urandom_source is None:
        urandom_source = SecureRandom()
    buffer = jarray.zeros(n, 'b')
    urandom_source.nextBytes(buffer)
    return buffer.tostring()
Esempio n. 2
0
def urandom(n):
    global urandom_source
    if urandom_source is None:
        urandom_source = SecureRandom()
    buffer = jarray.zeros(n, 'b')
    urandom_source.nextBytes(buffer)
    return buffer.tostring()
Esempio n. 3
0
class _UserFriendlyRNG(object):
    def __init__(self):
        self.closed = False
        self.__securerandom = None
        self.reinit()

    def reinit(self):
        self.__securerandom = SecureRandom()

    def close(self):
        self.closed = True
        self.__securerandom = None

    def flush(self):
        pass

    def read(self, N):
        if self.closed:
            raise ValueError("I/O operation on closed file")
        if not isinstance(N, (long, int)):
            raise TypeError("an integer is required")
        if N < 0:
            raise ValueError("cannot read to end of infinite stream")

        result = jarray.zeros(N, 'b')
        self.__securerandom.nextBytes(result)
        return result.tostring()
Esempio n. 4
0
class _UserFriendlyRNG(object):
    def __init__(self):
        self.closed = False
        self.__securerandom = None
        self.reinit()

    def reinit(self):
        self.__securerandom = SecureRandom()

    def close(self):
        self.closed = True
        self.__securerandom = None

    def flush(self):
        pass

    def read(self, N):
        if self.closed:
            raise ValueError("I/O operation on closed file")
        if not isinstance(N, (long, int)):
            raise TypeError("an integer is required")
        if N < 0:
            raise ValueError("cannot read to end of infinite stream")

        result = jarray.zeros(N, 'b')
        self.__securerandom.nextBytes(result)
        return result.tostring()
Esempio n. 5
0
    def ignoreJavaSSL():
        """
        Creates a dummy socket factory that doesn't verify connections.
            HttpsURLConnection.setDefaultSSLSocketFactory(...)
        This code was taken from multiple sources.
        Only makes since in jython (java).  otherwise, just use verify=False!
        """
        import sys
        if not 'java' in sys.platform:
            raise RuntimeError('only use if platform (sys.platform) is java!')
        else:
            #===================================================================
            # set default SSL socket to ignore verification
            #===================================================================
            import javax.net.ssl.X509TrustManager as X509TrustManager # @UnresolvedImport
            class MyTrustManager(X509TrustManager):
                def getAcceptedIssuers(self,*args,**keys):
                    return None
                def checkServerTrusted(self,*args,**keys):
                    pass
                def checkClientTrusted(self,*args,**keys):
                    pass

            import com.sun.net.ssl.internal.ssl.Provider # @UnresolvedImport
            from java.security import Security # @UnresolvedImport

            Security.addProvider(com.sun.net.ssl.internal.ssl.Provider())
            trustAllCerts = [MyTrustManager()]

            import javax.net.ssl.SSLContext as SSLContext # @UnresolvedImport
            sc = SSLContext.getInstance("SSL");

            import java.security.SecureRandom as SecureRandom # @UnresolvedImport
            sc.init(None, trustAllCerts,SecureRandom())

            import javax.net.ssl.HttpsURLConnection as HttpsURLConnection # @UnresolvedImport
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
            #===================================================================
            # Do a test!
            #===================================================================
            '''
            # setup proxy
            import java.net.Proxy as Proxy
            import java.net.InetSocketAddress as InetSocketAddress
            p = Proxy(Proxy.Type.HTTP,InetSocketAddress("host",port))

            import java.net.URL as URL
            u = URL("https://www.google.com/")
            conn = u.openConnection(p)
            print 'server response: %r',conn.getResponseCode()
            '''
            #===================================================================
            # ignore requests's error logging - this is for dev
            #===================================================================
            try:
                import requests.packages.urllib3 as urllib3
                urllib3.disable_warnings()
            except: pass

            return 'SSL verification in Java is disabled!'
Esempio n. 6
0
def use_secure_ssl(client, protocols):
    context = SSLContext.getInstance('SSL')
    context.init(None, [DefaultTrustManager], SecureRandom())
    factory = SSLSocketFactory(protocols)(context)
    https = Scheme('https', factory, 443)
    schemeRegistry = client.getWebConnection().getHttpClient(
    ).getConnectionManager().getSchemeRegistry()
    schemeRegistry.register(https)
Esempio n. 7
0
def use_insecure_ssl(client, protocols):
    """Installs a fake trust manager and hostname verifier on an HTMLUnit
    WebClient, ensuring that it will never balk at poorly set up SSL
    servers.
    """
    context = SSLContext.getInstance('SSL')
    context.init(None, [FakeX509TrustManager()], SecureRandom())
    # Normal factory with SSLv2Hello, SSLv3, TLSv1 enabled
    factory = SSLSocketFactory(protocols)(context)
    factory.setHostnameVerifier(
        org.apache.http.conn.ssl.AllowAllHostnameVerifier())
    https = Scheme('https', factory, 443)
    schemeRegistry = client.getWebConnection().getHttpClient(
    ).getConnectionManager().getSchemeRegistry()
    schemeRegistry.register(https)
Esempio n. 8
0
    def testPage(self, page):
        class MyTrustManager(X509TrustManager):
            def getAcceptedIssuers(self):
                return None

            def checkClientTrusted(self, certs, auth):
                pass

            def checkServerTrusted(self, certs, auth):
                pass

        trustAllCerts = [MyTrustManager()]

        sc = SSLContext.getInstance("SSL")
        sc.init(None, trustAllCerts, SecureRandom())
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())

        class MyHostnameVerifier(HostnameVerifier):
            def verify(self, host, sess):
                return True

        HttpsURLConnection.setDefaultHostnameVerifier(MyHostnameVerifier())

        try:
            httpsURL = 'https://%s:%s/%s' % (self._host, self._port, page)
            url = URL(httpsURL)
            conn = url.openConnection()
            conn.setConnectTimeout(5000)
            conn.setRequestProperty("Accept-encoding", 'gzip,deflate,compress')
            conn.setRequestProperty(
                "User-agent",
                'https://google.com/' if 'google' not in self._host else
                'https://yandex.ru/')  # Use foreign referer

            #ist = conn.getInputStream()
            #isr = InputStreamReader(ist)
            #br = BufferedReader(isr)
            print("[BREACH] Received response: %d" % conn.getResponseCode())
            if conn.getContentEncoding() != None:
                print("[BREACH] Received Content-encoding: %s" %
                      (conn.getContentEncoding()))
                return True
        except:
            print("[BREACH] Socket timeout or an error occurred")
        return False
Esempio n. 9
0
def createSSLSocket(host, port):
    '''
        Creates SSL Socket
        @types: str, int -> javax.net.ssl.SSLSocket
    '''

    # Create own TrustManager to be able to accept all certificates (even invalid)
    # configure the SSLContext with a TrustManager
    ctx = SSLContext.getInstance("TLS")
    keyManagers = jarray(KeyManager)
    trustManagers = jarray(TrustManager)
    trustManagers.append(DefaultTrustManager())

    ctx.init(keyManagers, trustManagers, SecureRandom())

    # Gets the default static SSLSocketFactory that is inherited by new instances of this class.
    # The socket factories are used when creating sockets for secure https URL connections.
    factory = ctx.getSocketFactory()

    # Creates a socket and connects it to the specified remote host at the specified remote
    # port. This socket is configured using the socket options established for this
    # factory.
    return factory.createSocket(host, int(port))
Esempio n. 10
0
    def __activate__(self, context):
        self.velocityContext = context
        self.log = self.vc("log")
        self.systemConfig = self.vc("systemConfig")
        self.session = self.vc("sessionState")
        self.response = self.vc("response")
        self.request = self.vc("request")
        self.msg = ""
        self.appId = None

        uri = URLDecoder.decode(self.request.getAttribute("RequestURI"))
        matches = re.match("^(.*?)/(.*?)/(.*?)/(.*?)/(.*?)$", uri)
        if matches and matches.group(5):
            self.appId = matches.group(5)

        if not self.appId:
            self.msg = "No appId specified"
            self.log.error(self.msg)
            return
        self.log.debug("Getting configuration for: " + self.appId)
        self.consumerName = self.systemConfig.getString(
            None, "authserver", self.appId, "name")
        self.sharedKey = self.systemConfig.getString(None, "authserver",
                                                     self.appId, "sharedKey")
        self.aud = self.systemConfig.getString(None, "authserver", self.appId,
                                               "aud")
        self.iss = self.systemConfig.getString(None, "authserver", self.appId,
                                               "iss")
        self.expiry = self.systemConfig.getInteger(None, "authserver",
                                                   self.appId, "expiry")
        self.logoutUrl = self.systemConfig.getString(None, "authserver",
                                                     self.appId, "logoutUrl")
        logout = self.request.getParameter("logout")
        if logout == "1":
            self.session.invalidate()
            self.response.sendRedirect(self.logoutUrl)
            return
        if not self.consumerName:
            self.msg = "Invalid configuration, no app name"
            self.log.error(self.msg)
            return
        if not self.sharedKey:
            self.msg = "Invalid shared Key"
            self.log.error(self.msg)
            return
        if not self.aud:
            self.msg = "Invalid aud"
            self.log.error(self.msg)
            return
        if not self.iss:
            self.msg = "Invalid iss"
            self.log.error(self.msg)
            return
        if not self.expiry:
            self.msg = "Invalid expiry"
            self.log.error(self.msg)
            return

        # Because we don't trust the configuration
        current_user = self.vc("page").authentication.get_username()
        isAdmin = self.vc("page").authentication.is_admin()
        # Admin only...
        if not isAdmin:
            self.msg = "Sorry, this page is only for administrators."
            self.log.error(self.msg)
            return
        # Get the roles...
        typ = "[\"" + "\",\"".join(
            self.vc("page").authentication.get_roles_list()) + "\"]"
        # Generating signature...
        dtNow = Date().getTime()
        now = dtNow / 1000
        iat = now
        nbf = now - 1
        exp = now + self.expiry
        secRandom = SecureRandom()
        jti = Long.toString(dtNow) + "_" + Integer.toString(
            secRandom.nextInt())
        payload = Payload(
            '{"iss":"%s",  "sub":"%s", "aud":"%s", "iat":"%s", "nbf":"%s", "exp":"%s", "jti":"%s", "typ":%s}'
            % (self.iss, current_user, self.aud, iat, nbf, exp, jti, typ))
        jwsHeader = JWSHeader(JWSAlgorithm.HS256)
        macSigner = MACSigner(self.sharedKey)
        jwsObject = JWSObject(jwsHeader, payload)
        jwsObject.sign(macSigner)
        self.jws = jwsObject.serialize()
Esempio n. 11
0
    def generateSecretKey(self, keyLength):
        bytes = jarray.zeros(keyLength, "b")
        secureRandom = SecureRandom()
        secureRandom.nextBytes(bytes)

        return bytes
Esempio n. 12
0
 def generateNonce(keyLength):
     bytes = jarray.zeros(keyLength, "b")
     secureRandom = SecureRandom()
     secureRandom.nextBytes(bytes)
     return BaseEncoding.base64().omitPadding().encode(bytes)
 def generateSecretKey(self, keyLength):
     bytes = jarray.zeros(keyLength, "b")
     secureRandom = SecureRandom()
     secureRandom.nextBytes(bytes)
     
     return bytes
Esempio n. 14
0
 def reinit(self):
     self.__securerandom = SecureRandom()
 def __activate__(self, context):
     self.velocityContext = context
     self.log = self.vc("log")
     self.systemConfig = self.vc("systemConfig")
     self.session = self.vc("sessionState")
     self.response = self.vc("response")
     self.request = self.vc("request")
     self.msg = ""
     self.appId = None
     
     uri = URLDecoder.decode(self.request.getAttribute("RequestURI"))
     matches = re.match("^(.*?)/(.*?)/(.*?)/(.*?)/(.*?)$", uri)
     if matches and matches.group(5):    
         self.appId = matches.group(5)
         
     if not self.appId:
         self.msg = "No appId specified"
         self.log.error(self.msg)
         return
     self.log.debug("Getting configuration for: " + self.appId)
     self.consumerName = self.systemConfig.getString(None, "authserver", self.appId, "name")
     self.sharedKey = self.systemConfig.getString(None, "authserver", self.appId, "sharedKey")
     self.aud = self.systemConfig.getString(None, "authserver", self.appId, "aud")
     self.iss = self.systemConfig.getString(None, "authserver", self.appId, "iss")
     self.expiry = self.systemConfig.getInteger(None, "authserver", self.appId, "expiry")
     self.logoutUrl = self.systemConfig.getString(None, "authserver", self.appId, "logoutUrl")
     logout = self.request.getParameter("logout")
     if logout == "1":
         self.session.invalidate()
         self.response.sendRedirect(self.logoutUrl)
         return
     if not self.consumerName:
         self.msg = "Invalid configuration, no app name"
         self.log.error(self.msg)
         return
     if not self.sharedKey:
         self.msg = "Invalid shared Key"
         self.log.error(self.msg)
         return
     if not self.aud:
         self.msg = "Invalid aud"
         self.log.error(self.msg)
         return
     if not self.iss:
         self.msg = "Invalid iss"
         self.log.error(self.msg)
         return
     if not self.expiry:
         self.msg = "Invalid expiry"
         self.log.error(self.msg)
         return
                         
     # Because we don't trust the configuration
     current_user = self.vc("page").authentication.get_username()
     isAdmin = self.vc("page").authentication.is_admin()
     # Admin only... 
     if not isAdmin:
         self.msg = "Sorry, this page is only for administrators."
         self.log.error(self.msg)
         return
     # Get the roles...
     typ = "[\"" + "\",\"".join(self.vc("page").authentication.get_roles_list()) + "\"]"
     # Generating signature...
     dtNow = Date().getTime()
     now = dtNow / 1000
     iat = now
     nbf = now - 1
     exp = now + self.expiry
     secRandom = SecureRandom()
     jti = Long.toString(dtNow) + "_" + Integer.toString(secRandom.nextInt())
     payload = Payload('{"iss":"%s",  "sub":"%s", "aud":"%s", "iat":"%s", "nbf":"%s", "exp":"%s", "jti":"%s", "typ":%s}' % (self.iss, current_user, self.aud, iat, nbf, exp, jti, typ))
     jwsHeader = JWSHeader(JWSAlgorithm.HS256)
     macSigner = MACSigner(self.sharedKey)
     jwsObject = JWSObject(jwsHeader, payload)
     jwsObject.sign(macSigner)
     self.jws = jwsObject.serialize()
Esempio n. 16
0
 def reinit(self):
     self.__securerandom = SecureRandom()