예제 #1
0
파일: _core.py 프로젝트: JMaz/athena
    def _validate_header(self, headers, key, subprotocols):
        for k, v in _HEADERS_TO_CHECK.items():
            r = headers.get(k, None)
            if not r:
                return False
            r = r.lower()
            if v != r:
                return False
        
        if subprotocols:
            subproto = headers.get("sec-websocket-protocol", None)
            if not subproto or subproto not in subprotocols:
                logger.error("Invalid subprotocol: " + str(subprotocols))
                return False
            self.subprotocol = subproto


        result = headers.get("sec-websocket-accept", None)
        if not result:
            return False
        result = result.lower()

        if isinstance(result, six.text_type):
            result = result.encode('utf-8')

        value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
        hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
        return hashed == result
예제 #2
0
    def _validate_header(self, headers, key, subprotocols):
        for k, v in _HEADERS_TO_CHECK.items():
            r = headers.get(k, None)
            if not r:
                return False
            r = r.lower()
            if v != r:
                return False

        if subprotocols:
            subproto = headers.get("sec-websocket-protocol", None)
            if not subproto or subproto not in subprotocols:
                logger.error("Invalid subprotocol: " + str(subprotocols))
                return False
            self.subprotocol = subproto

        result = headers.get("sec-websocket-accept", None)
        if not result:
            return False
        result = result.lower()

        if isinstance(result, six.text_type):
            result = result.encode('utf-8')

        value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
        hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
        return hashed == result
예제 #3
0
파일: bhp_bing.py 프로젝트: hristogg1/Tools
    def bing_query(self, bing_query_string):
        print "Performing Bing search: %s" % bing_query_string

        # encode our query
        quoted_query = urllib.quote(bing_query_string)

        host_request = "GET https://api.datamarket.azure.com/Bing/Search/Web?$format=json&$top=20&Query=%s HTTP/1.1\r\n" % quoted_query
        http_request += "Host: api.datamarket.azure.com\r\n"
        http_request += "Connection: close\r\n"
        http_request += "Authorization: Basic %s\r\n" % base64.base64encode(":%s" % bing_api_key)
        http_request += "User-Agent: Blackhat Python\r\n\r\n"

        json_body = self.callbacks.makeHttpRequest("api.datamarket.azure.com", 443, True, http_request).tostring()
        json_body = json_body.split("\r\n\r\n", 1)[1]

        try:
            r = json.loads(json_body)

            if len(r["d"]["results"]):
                for site in r["d"]["results"]:
                    print "*" * 100
                    print site["Title"]
                    print site["Url"]
                    print site["Description"]
                    print "*" * 100

                    j_url = URL(site["Url"])

                    if not self._callbacks.isInScope(j_url):
                        print "Adding to Burp scope"
                        self_callbacks.includeInScope(j_url)
        except:
            print "No results from Bing"

        return
예제 #4
0
파일: _http.py 프로젝트: ShadovvMoon/Spear
def _tunnel(sock, host, port, auth):
    debug("Connecting proxy...")
    connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
    # TODO: support digest auth.
    if auth and auth[0]:
        auth_str = auth[0]
        if auth[1]:
            auth_str += ":" + auth[1]
        encoded_str = base64encode(auth_str.encode()).strip().decode()
        connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str
    connect_header += "\r\n"
    dump("request header", connect_header)

    send(sock, connect_header)

    try:
        status, resp_headers = read_headers(sock)
    except Exception as e:
        raise WebSocketProxyException(str(e))

    if status != 200:
        raise WebSocketProxyException(
            "failed CONNECT via proxy status: %r" % status)
    
    return sock
예제 #5
0
def _validate(headers, key, subprotocols):
    subproto = None
    for k, v in _HEADERS_TO_CHECK.items():
        r = headers.get(k, None)
        if not r:
            return False, None
        r = r.lower()
        if v != r:
            return False, None

    if subprotocols:
        subproto = headers.get("sec-websocket-protocol", None).lower()
        if not subproto or subproto not in [s.lower() for s in subprotocols]:
            error("Invalid subprotocol: " + str(subprotocols))
            return False, None

    result = headers.get("sec-websocket-accept", None)
    if not result:
        return False, None
    result = result.lower()

    if isinstance(result, six.text_type):
        result = result.encode('utf-8')

    value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
    hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
    success = compare_digest(hashed, result)

    if success:
        return True, subproto
    else:
        return False, None
예제 #6
0
def _validate(headers, key, subprotocols):
    subproto = None
    for k, v in _HEADERS_TO_CHECK.items():
        r = headers.get(k, None)
        if not r:
            return False, None
        r = r.lower()
        if v != r:
            return False, None

    if subprotocols:
        subproto = headers.get("sec-websocket-protocol", None).lower()
        if not subproto or subproto not in [s.lower() for s in subprotocols]:
            error("Invalid subprotocol: " + str(subprotocols))
            return False, None

    result = headers.get("sec-websocket-accept", None)
    if not result:
        return False, None
    result = result.lower()

    if isinstance(result, six.text_type):
        result = result.encode('utf-8')

    value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
    hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
    success = compare_digest(hashed, result)

    if success:
        return True, subproto
    else:
        return False, None
예제 #7
0
파일: _http.py 프로젝트: cctvkill1/test
def _tunnel(sock, host, port, auth):
    debug("Connecting proxy...")
    connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
    # TODO: support digest auth.
    if auth and auth[0]:
        auth_str = auth[0]
        if auth[1]:
            auth_str += ":" + auth[1]
        encoded_str = base64encode(auth_str.encode()).strip().decode()
        connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str
    connect_header += "\r\n"
    dump("request header", connect_header)

    send(sock, connect_header)

    try:
        status, resp_headers = read_headers(sock)
    except Exception as e:
        raise WebSocketProxyException(str(e))

    if status != 200:
        raise WebSocketProxyException("failed CONNECT via proxy status: %r" +
                                      status)

    return sock
예제 #8
0
파일: service.py 프로젝트: ChrisX34/stuff
  def UpdateDomainLogo(self, logoImage):
    """Update Domain's Custom Logo

    Args:
      logoImage: binary image data

    Returns: A dict containing the result of the put operation"""

    from base64 import base64encode
    uri = self._serviceUrl('appearance/customLogo')
    properties = {'logoImage': base64encode(logoImage)}
    return self._PutProperties(uri, properties)
예제 #9
0
파일: service.py 프로젝트: DanEble/git-cl
    def UpdateDomainLogo(self, logoImage):
        """Update Domain's Custom Logo

    Args:
      logoImage: binary image data

    Returns: A dict containing the result of the put operation"""

        from base64 import base64encode
        uri = self._serviceUrl('appearance/customLogo')
        properties = {'logoImage': base64encode(logoImage)}
        return self._PutProperties(uri, properties)
예제 #10
0
def send_packet(packet):
    encoded_bytes = base64encode((packet.id + ':' + str(len(packet.data)) +
                                  ':').encode() + packet.data)
    tmr_string = b'[[[' + encoded_bytes + b']]][[[' + encoded_bytes + b']]][[[' + encoded_bytes + b']]]'
    try:
        ser = serial.Serial(serial_port, 4800, timeout=0)
        if ser.isOpen() == False:
            ser.open()
        ser.write(tmr_string)
        ser.flush()
        ser.close()
    except Exception as e:
        raise HWFuncException(
            'Could not send via the serial port "' + serial_port + '"', e)
예제 #11
0
 def encode(self, value, encode_types):
     """根据encode_types对字符串进行编码"""
     if encode_types is []:
         return value
     encode_types = list(reversed(encode_types))
     for encode_type in encode_types:
         if encode_type == 'json':
             value = json.dumps(value)
         if encode_type == 'base64encode':
             value = str(base64encode(value.encode('utf-8')),
                         encoding='utf-8')
         if encode_type == 'urlencode':
             value = urlencode(value)
     return value
예제 #12
0
    def _tunnel(self, host, port, username, password):
        logger.debug("Connecting proxy...")
        connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
        
        if username:
            b64_auth = base64encode("%s:%s" % (username, password or '')).strip()
            connect_header += "Proxy-Authorization: Basic %s\r\n" % b64_auth
        
        connect_header += "\r\n"
        _dump("request header", connect_header)

        self._send(connect_header)

        status, resp_headers = self._read_headers()
        if status != 200:
            raise WebSocketException("failed CONNECT via proxy")
예제 #13
0
    def _tunnel(self, host, port, auth):
        logger.debug("Connecting proxy...")
        connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
        # TODO: support digest auth.
        if auth and auth[0]:
            auth_str = auth[0]
            if auth[1]:
                auth_str += ":" + auth[1]
            encoded_str = base64encode(auth_str.encode()).strip().decode()
            connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str
        connect_header += "\r\n"
        _dump("request header", connect_header)

        self._send(connect_header)

        status, resp_headers = self._read_headers()
        if status != 200:
            raise WebSocketException("failed CONNECT via proxy")
    def _tunnel(self, host, port, auth):
        logger.debug("Connecting proxy...")
        connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
        # TODO: support digest auth.
        if auth and auth[0]:
            auth_str = auth[0]
            if auth[1]:
                auth_str += ":" + auth[1]
            encoded_str = base64encode(auth_str.encode()).strip().decode()
            connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str
        connect_header += "\r\n"
        _dump("request header", connect_header)

        self._send(connect_header)

        status, resp_headers = self._read_headers()
        if status != 200:
            raise WebSocketException("failed CONNECT via proxy")
예제 #15
0
파일: websocket.py 프로젝트: thoscut/deconz
    def connection_made(self, transport):
        """Do the websocket handshake.

        According to https://tools.ietf.org/html/rfc6455
        """
        randomness = os.urandom(16)
        key = base64encode(randomness).decode('utf-8').strip()
        self.transport = transport
        message = "GET / HTTP/1.1\r\n"
        message += "Host: " + self.host + ':' + str(self.port) + '\r\n'
        message += "User-Agent: Python/3.5 websockets/3.4\r\n"
        message += "Upgrade: Websocket\r\n"
        message += "Connection: Upgrade\r\n"
        message += "Sec-WebSocket-Key: " + key + "\r\n"
        message += "Sec-WebSocket-Version: 13\r\n"
        message += "\r\n"
        _LOGGER.debug('Websocket handshake: %s', message)
        self.transport.write(message.encode())
예제 #16
0
 def __init__(self, subdomain, api_key, private_key):
     """
     Creates a REST client for interacting with the Recurly servers.  API
     credentials can be found by logging in at Recurly.com and visiting
     https://yourdomain.recurly.com/developer/api_access (mutatis mutandis)
     """
     self.url = 'https://%s.recurly.com' % subdomain
     self.private_key = private_key
     authstring = 'Basic %s' % base64encode('%s:' % api_key)
     self._session = session(
         headers={
             'Accept': 'application/xml',
             'Content-Type': 'application/xml; charset=utf-8',
             'User-Agent': 'recurlib Python Client',
             'Authorization': authstring,
         })
     self.accounts = AccountManager(self)
     self.charges = ChargeManager(self)
     self.invoices = InvoiceManager(self)
예제 #17
0
 def __init__(self, subdomain, api_key, private_key):
     """
     Creates a REST client for interacting with the Recurly servers.  API
     credentials can be found by logging in at Recurly.com and visiting
     https://yourdomain.recurly.com/developer/api_access (mutatis mutandis)
     """
     self.url = 'https://%s.recurly.com' % subdomain
     self.private_key = private_key
     authstring = 'Basic %s' % base64encode('%s:' % api_key)
     self._session = session(
         headers={
             'Accept': 'application/xml',
             'Content-Type': 'application/xml; charset=utf-8',
             'User-Agent': 'recurlib Python Client',
             'Authorization': authstring,
         })
     self.accounts = AccountManager(self)
     self.charges = ChargeManager(self)
     self.invoices = InvoiceManager(self)
예제 #18
0
def _tunnel(sock, host, port, auth):
    debug("Connecting proxy...")
    connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
    # TODO: support digest auth.
    if auth and auth[0]:
        auth_str = auth[0]
        if auth[1]:
            auth_str += ":" + auth[1]
        encoded_str = base64encode(auth_str.encode()).strip().decode().replace('\n', '')
        connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str
    connect_header += "\r\n"
    dump("request header", connect_header)

    send(sock, connect_header)

    try:
        status, resp_headers, status_message = read_headers(sock)
    except Exception , e:
        raise WebSocketProxyException(str(e))
예제 #19
0
def upload_base64(event, context):
    image = base64.b64decode(
        event['body']) if event['isBase64Encoded'] else event['body']
    with BytesIO(image) as image_buffer:
        print("Do some fancy image processing!")
    return {
        "statusCode":
        200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body":
        json.dumps({
            "message":
            "Image successfully processed!",
            "processed_image":
            base64.base64encode(image).decode("utf-8")
        })
    }
예제 #20
0
    def _validate_header(self, headers, key):
        for k, v in _HEADERS_TO_CHECK.items():
            r = headers.get(k, None)
            if not r:
                return False
            r = r.lower()
            if v != r:
                return False

        result = headers.get("sec-websocket-accept", None)
        if not result:
            return False
        result = result.lower()

        if isinstance(result, six.text_type):
            result = result.encode('utf-8')

        value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
        hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
        return hashed == result
예제 #21
0
    def _tunnel(self, host, port, auth):
        global logger

        logger.debug('Conncting proxy...')
        connect_header = 'CONNECT %s:%d HTTP/1.0\r\n' % (host, port)

        if auth and auth[0]:
            auth_str = auth[0]
            if auth[1]:
                auth_str += ':' + auth[1]
            encoded_str = base64encode(auth_str.encode()).strip().decode()
            connect_header += 'Proxy-Authorization: Basic %s\r\n' % encoded_str
        connect_header += '\r\n'
        _dump('request header', connect_header)

        self._send(connect_header)

        status, resp_headers = self._read_headers()
        if status != 200:
            raise WebSocketException('failed CONNECT via proxy')
예제 #22
0
    def _validate_header(self, headers, key):
        for k, v in _HEADERS_TO_CHECK.items():
            r = headers.get(k, None)
            if not r:
                return False
            r = r.lower()
            if v != r:
                return False

        result = headers.get("sec-websocket-accept", None)
        if not result:
            return False
        result = result.lower()

        if isinstance(result, six.text_type):
            result = result.encode('utf-8')

        value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
        hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
        return hashed == result
예제 #23
0
    def get_encode_types(self, value):
        value = str(value)
        encode_types = []
        if value == '':
            return encode_types
        """判断是否存在urlencode"""
        try:
            url_decode_value = urldecode(value)
        except:
            return False
        if url_decode_value != value:
            encode_types.append('urlencode')
        """判断是否为int或者float,避免后面的base64判断出错"""
        try:
            json_load_value = json.loads(url_decode_value)
            if isinstance(json_load_value, int) or isinstance(
                    json_load_value, float):
                return encode_types
        except:
            pass
        """调用base64decode,判断返回字符串是否在可见范围内"""
        try:
            base64decode_value = base64decode(url_decode_value.encode('utf-8'))
            string_basedecode = base64decode_value.decode()
            for _ in string_basedecode:
                if 32 <= ord(_) <= 126:
                    continue
                else:
                    return encode_types
        except:
            return encode_types
        """判断是否为base64加密"""
        try:
            if str(base64encode(base64decode_value),
                   encoding='utf-8') == url_decode_value:
                encode_types.append("base64encode")
        except:
            return encode_types

        return encode_types
예제 #24
0
    def __signature(self, params):
        sortedParams = sorted(params.items(), key=lambda params: params[0])

        query = ''
        for (k, v) in sortedParams:
            query += '&' + \
                self.__percentEncode(k) + '=' + self.__percentEncode(str(v))

        stringToSign = 'GET&%2F&' + self.__percentEncode(query[1:])
        try:
            if (sys.version_info < (3, 0)):
                h = hmac.new(self.__appsecret + "&", stringToSign,
                             hashlib.sha1)
            else:
                h = hmac.new((self.__appsecret + "&").encode(encoding="utf-8"),
                             stringToSign.encode(encoding="utf-8"),
                             hashlib.sha1)
        except Exception as e:
            self.__logger.error(e)
        signature = base64encode(h.digest()).strip()

        return signature
예제 #25
0
    def _new_conn(self):
        """
		Return a fresh HTTPConnection.
		"""
        self.num_connections += 1
        if self.proxyURL:
            headers = {}
            try:
                url = urlparse.urlparse(self.proxyURL)
                if url.password:
                    logger.setConfidentialStrings(url.password)
                logger.debug(
                    u"Starting new HTTP connection (%d) to %s:%d over proxy-url %s"
                    % (self.num_connections, self.host, self.port,
                       self.proxyURL))

                conn = HTTPConnection(host=url.hostname, port=url.port)
                if url.username and url.password:
                    logger.debug(
                        u"Proxy Authentication detected, setting auth with user: '******'"
                        % url.username)
                    auth = "{username}:{password}".format(
                        username=url.username, password=url.password)
                    headers[
                        'Proxy-Authorization'] = 'Basic ' + base64.base64encode(
                            auth)
                conn.set_tunnel(self.host, self.port, headers)
                logger.debug(u"Connection established to: %s" % self.host)
            except Exception as error:
                logger.error(error)
        else:
            logger.debug(u"Starting new HTTP connection (%d) to %s:%d" %
                         (self.num_connections, self.host, self.port))
            conn = HTTPConnection(host=self.host, port=self.port)
            non_blocking_connect_http(conn, self.connectTimeout)
            logger.debug(u"Connection established to: %s" % self.host)
        return conn
예제 #26
0
def _create_sec_websocket_key():
    randomness = os.urandom(16)
    return base64encode(randomness).decode('utf-8').strip()
예제 #27
0
        })


def introspection():
    modulesetup = {}
    try:
        userConfig
        modulesetup['userConfig'] = userConfig
    except NameError:
        pass
    try:
        inputSource
        modulesetup['inputSource'] = inputSource
    except NameError:
        pass
    return modulesetup


def version():
    moduleinfo['config'] = moduleconfig
    return moduleinfo


if __name__ == '__main__':
    x = open('test.json', 'r')
    q = []
    q['data'] = x.read()
    q = base64.base64encode(q)

    handler(q)
예제 #28
0
        )


def introspection():
    modulesetup = {}
    try:
        userConfig
        modulesetup["userConfig"] = userConfig
    except NameError:
        pass
    try:
        inputSource
        modulesetup["inputSource"] = inputSource
    except NameError:
        pass
    return modulesetup


def version():
    moduleinfo["config"] = moduleconfig
    return moduleinfo


if __name__ == "__main__":
    x = open("test.json", "r")
    q = []
    q["data"] = x.read()
    q = base64.base64encode(q)

    handler(q)
예제 #29
0
crcString = ""

for c in cookie:
	if re.match( r'^\s?incap_ses_', c.name ):
		print( "Incap session cookie: " + c.value  )
		crcTmp = crc( navigatorData + c.value )
		print( "CRC value: " + crcTmp )
		crcString += crcTmp

print( "Resulting CRC: " + crcString )

salt = "813VS3efAyF7csIfnfHiy4wLHigQYLXv2g/ecA=="
hexHash = ""

i = 0
for c in salt:
	hexHash += "{:x}".format( ord( c ) + ord( crcString[ i % len( crcString ) ] ) );

print( "Hash: " + hexHash )

navigarotBase64 = base64.base64encode( navigatorData )
print( "Navigator Base64: " + navigarotBase64 )
navigatorDecoded = decode( navigarotBase64, salt[ 0:5 ] )
print( "Navigator decoded: " + navigatorDecoded )

secret = base64.base64encode( navigatorDecoded + ",digest=" + crcString + ",s=" + hexHash )
print( "Secret: " + secret )


cookie.save( "cookie" )
예제 #30
0
def b64encode(s):
    return bytes_to_str(base64encode(str_to_bytes(s)))
예제 #31
0
def _create_sec_websocket_key():
    uid = uuid.uuid4()
    return base64encode(uid.bytes).decode('utf-8').strip()
예제 #32
0
def _create_sec_websocket_key():
    randomness = os.urandom(16)
    return base64encode(randomness).decode('utf-8').strip()
예제 #33
0
def b64encode(s):
    return bytes_to_str(base64encode(str_to_bytes(s)))
예제 #34
0
def _create_sec_websocket_key():
    uid = uuid.uuid4()
    return base64encode(uid.bytes).decode('utf-8').strip()
예제 #35
0
 def get_secure_key(self):
     randomness = urandom(16)
     return base64encode(randomness).decode('utf-8').strip()
예제 #36
0
def _default_blob_decoder(blob):
    # TODO: verify this is handles all cases
    return base64encode(blob).decode('utf-8')
예제 #37
0
    def _new_conn(self):
        """
		Return a fresh HTTPSConnection.
		"""
        self.num_connections += 1
        if self.proxyURL:
            headers = {}
            try:
                url = urlparse.urlparse(self.proxyURL)
                if url.password:
                    logger.setConfidentialString(url.password)
                logger.debug(
                    u"Starting new HTTPS connection (%d) to %s:%d over proxy-url %s"
                    % (self.num_connections, self.host, self.port,
                       self.proxyURL))
                conn = HTTPSConnection(host=url.hostname, port=url.port)
                if url.username and url.password:
                    logger.debug(
                        u"Proxy Authentication detected, setting auth with user: '******'"
                        % url.username)
                    auth = "{username}:{password}".format(
                        username=url.username, password=url.password)
                    headers[
                        'Proxy-Authorization'] = 'Basic ' + base64.base64encode(
                            auth)
                conn.set_tunnel(self.host, self.port, headers)
                logger.debug(u"Connection established to: %s" % self.host)
            except Exception as e:
                logger.logException(e)
        else:
            logger.debug(u"Starting new HTTPS connection (%d) to %s:%d" %
                         (self.num_connections, self.host, self.port))
            conn = HTTPSConnection(host=self.host, port=self.port)
            logger.debug(u"Connection established to: %s" % self.host)

        if self.verifyServerCert or self.verifyServerCertByCa:
            try:
                non_blocking_connect_https(conn, self.connectTimeout,
                                           self.caCertFile)
                if not self.verifyServerCertByCa:
                    self.serverVerified = True
                    logger.debug("Server verified.")
            except ssl_module.SSLError as error:
                logger.debug(u"Verification failed: {0!r}", error)
                if self.verifyServerCertByCa:
                    raise OpsiServiceVerificationError(
                        u"Failed to verify server cert by CA: %s" % error)

                logger.debug("Going to try a connect without caCertFile...")
                non_blocking_connect_https(conn, self.connectTimeout)
            except Exception as error:
                logger.debug(u"Verification failed: {0!r}", error)
                raise OpsiServiceVerificationError(forceUnicode(error))

        self.peerCertificate = getPeerCertificate(conn, asPEM=True)
        if self.verifyServerCertByCa:
            logger.debug("Attempting to verify server cert by CA...")
            try:
                if self.peerCertificate:
                    commonName = crypto.load_certificate(
                        crypto.FILETYPE_PEM,
                        self.peerCertificate).get_subject().commonName
                    host = self.host
                    if re.search(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',
                                 host):
                        fqdn = socket.getfqdn(host)
                        if fqdn == host:
                            raise OpsiServiceVerificationError(
                                u"Failed to get fqdn for ip %s" % host)
                        host = fqdn
                    if not host or not commonName or (host.lower() !=
                                                      commonName.lower()):
                        raise OpsiServiceVerificationError(
                            u"Host '%s' does not match common name '%s'" %
                            (host, commonName))
                    self.serverVerified = True
                else:
                    raise OpsiServiceVerificationError(
                        u"Failed to get peer certificate")
            except Exception:
                closeConnection(conn)
                raise

        return conn
예제 #38
0
def encryptAES(password,input_text):
    textplain = rightAdjustForAES(input_text)
    secret = rightAdjustForAES(password + admin_secret)
    cipher = AES.new(secret,AES.MODE_ECB)
    result = base64encode(cipher.encrypt(textplain)).decode("utf-8")
    return result