예제 #1
0
파일: gutsama.py 프로젝트: Veriny/Solebaga
def pack_sendrecv(sock: ssl.SSLSocket, data: dict, id: int) -> dict:
    """
    Pack a dictionary into a msgpack object, and send it through a socket.

    This then returns the response.
    :param sock: The socket to send through.
    :param data: The data to send.
        This will automatically have the butterfly header attached.
    :param id: The ID of the packet to send.
    :return: The data returned by the server.
    """
    # Add header.
    new_data = {"id": id, "version": 1, "data": data}
    # Pack data.
    packed = msgpack.packb(new_data, use_bin_type=True)
    # Write data.
    sock.write(packed)
    # Read data.
    try:
        recvdata = sock.recv()
    except socket.timeout:
        logger.error("Connection to server timed out.")
        return None
    # Unpack data.
    try:
        unpacked = msgpack.unpackb(recvdata, encoding="utf-8")
        return unpacked
    except (msgpack.UnpackException, ValueError) as e:
        logger.error("Could not unpack message: {}".format(e))
        return None
예제 #2
0
    def close_connection(self, ssock: ssl.SSLSocket):
        if ssock:
            timer = start_timer()
            ssock.shutdown(socket.SHUT_RDWR)
            self.results['ssl.shutdown.time.perf'], self.results[
                'ssl.shutdown.time.process'] = stop_timer(*timer)

            ssock.close()
예제 #3
0
def _write_message(sock: ssl.SSLSocket, message: Any):
    class RequestEncoder(json.JSONEncoder):
        def default(self, o):
            return o.__dict__

    message = json.dumps(message, cls=RequestEncoder).encode()
    sock.sendall(struct.pack(">Q", len(message)))
    sock.sendall(message)
예제 #4
0
def _read_message(sock: ssl.SSLSocket):
    response_len = struct.unpack(">Q", sock.read(8))
    raw = bytearray()
    total_recv = 0
    while total_recv < response_len[0]:
        data = sock.recv()
        total_recv += len(data)
        raw += data
    response = json.loads(raw)
    return response
예제 #5
0
def get_cipher_suite_and_protocol(ssl_socket: ssl.SSLSocket):
    """
    Gather the cipher suite and the protocol from the ssl_socket.

    :param ssl_socket: secure socket
    :return: negotiated cipher suite and the protocol
    """
    cipher_suite = ssl_socket.cipher()[0]
    if '-' in cipher_suite:
        cipher_suite = convert_openssh_to_iana(cipher_suite)
    return cipher_suite, ssl_socket.version()
예제 #6
0
    def connect(self):
        msg = 'getaddrinfo returns an empty list'
        for af, socktype, proto, canonname, addr in getaddrinfo(self.host,
            self.port, 0, SOCK_STREAM):

            try:
                _log.debug('ValidatingHTTPSConnection to %r', addr)
                ssl = SSLSocket(socket(af, socktype, proto),
                    keyfile=self.key_file, certfile=self.cert_file,
                    cert_reqs=self.cert_reqs, ca_certs=self.ca_certs,
                    ssl_version=self.ssl_version)
                ssl.connect(addr)

            except SocketError as e:
                _log.info('ValidatingHTTPSConnection to %r: %s', addr, e)
                msg = e
                self.sock = None
                continue

            server_attrs = ssl.getpeercert()
            # getpeercert() returns {} if the certificate was not verified, in
            # which case it doesn't matter what the name in the certificate is.
            if self.check_hostname and server_attrs:
                self.hostname_matches_cert = False
                names = []

                for gntype, gn in server_attrs.get('subjectAltName', ()):
                    if gntype == 'DNS':
                        self._compare_hostname(gn)
                        names.append(gn)

                    else:
                        _log.warn('ValidatingHTTPSConnection unhandled subjectAltName type: %s=%r', gntype, gn)

                # Only look at attributes in the first rdn.
                for attr,val in server_attrs['subject'][0]:
                    if attr == 'commonName':
                        self._cmp_hostname(val)
                        names.append(val)

                if not self.hostname_matches_cert:
                    raise CertNameMismatchError(self.host, names)

            # Newer ssl object implements makefile, fileno, etc.  No need to
            # use FakeSocket wrapper
            self.sock = ssl
            break

        if not self.sock:
            raise SocketError(msg)
예제 #7
0
파일: connection.py 프로젝트: chfoo/wpull
    def _verify_cert(self, sock: ssl.SSLSocket):
        '''Check if certificate matches hostname.'''
        # Based on tornado.iostream.SSLIOStream
        # Needed for older OpenSSL (<0.9.8f) versions
        verify_mode = self._ssl_context.verify_mode

        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED,
                               ssl.CERT_OPTIONAL), \
            'Unknown verify mode {}'.format(verify_mode)

        if verify_mode == ssl.CERT_NONE:
            return

        cert = sock.getpeercert()

        if not cert and verify_mode == ssl.CERT_OPTIONAL:
            return

        if not cert:
            raise SSLVerificationError('No SSL certificate given')

        try:
            ssl.match_hostname(cert, self._hostname)
        except ssl.CertificateError as error:
            raise SSLVerificationError('Invalid SSL certificate') from error
예제 #8
0
    def _verify_cert(self, sock: ssl.SSLSocket):
        '''Check if certificate matches hostname.'''
        # Based on tornado.iostream.SSLIOStream
        # Needed for older OpenSSL (<0.9.8f) versions
        verify_mode = self._ssl_context.verify_mode

        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED,
                               ssl.CERT_OPTIONAL), \
            'Unknown verify mode {}'.format(verify_mode)

        if verify_mode == ssl.CERT_NONE:
            return

        cert = sock.getpeercert()

        if not cert and verify_mode == ssl.CERT_OPTIONAL:
            return

        if not cert:
            raise SSLVerificationError('No SSL certificate given')

        try:
            ssl.match_hostname(cert, self._hostname)
        except ssl.CertificateError as error:
            raise SSLVerificationError('Invalid SSL certificate') from error
예제 #9
0
def accept_loop(sock: ssl.SSLSocket):
    while True:
        client_sock, addr = sock.accept()

        logging.debug('accepted from %s', addr)

        handler = ConnHandler(client_sock, addr)
        handler.start()
예제 #10
0
def _receive_response(
    secure_socket: ssl.SSLSocket,
) -> Tuple[HeaderLine, Optional[bytes]]:
    line = secure_socket.recv(1029)
    header, remaining = _parse_header(line)

    if header.category == constants.Category.SUCCESS:
        # Get response body.
        body = remaining
        next_payload = secure_socket.recv(4096)
        while len(next_payload) > 0:
            body += next_payload
            next_payload = secure_socket.recv(4096)

        return header, body

    return header, None
예제 #11
0
def _read_http_response_line(sock: ssl.SSLSocket) -> str:
    cs = []
    while True:
        c: str = sock.recv(1).decode("utf-8")
        if c == "\r":
            break
        if c != "\n":
            cs.append(c)
    return "".join(cs)
예제 #12
0
def get_certificate(ssl_socket: ssl.SSLSocket):
    """
    Gather a certificate in a der binary format.

    :param ssl_socket: secured socket
    :return: gathered certificate
    """
    certificate_pem = bytes(ssl_socket.getpeercert(binary_form=True))
    return x509.load_der_x509_certificate(certificate_pem, default_backend())
예제 #13
0
 def _select_and_assign_certificate(self, connection: ssl.SSLSocket,
                                    server_name: str,
                                    ssl_context: SSLContext):
     certificate = self.select_certificate(server_name)
     new_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
     new_context.load_cert_chain(certificate["pem_file"],
                                 certificate["key_file"])
     connection.context = new_context
     self._server_name = certificate["server_name"]
     self._logger.info("Successfully loaded TLS certificate and key")
예제 #14
0
파일: socket.py 프로젝트: sgmenda/stem
    def wrapped_recv(s: ssl.SSLSocket, sf: BinaryIO) -> bytes:
      if timeout is None:
        return s.recv(1024)
      else:
        s.setblocking(False)
        s.settimeout(timeout)

        try:
          return s.recv(1024)
        except (socket.timeout, ssl.SSLError, ssl.SSLWantReadError):
          return None
        finally:
          s.setblocking(True)
예제 #15
0
def nc_read_msg(conn: ssl.SSLSocket):
    buf = ''
    while True:
        data = conn.recv(4096)
        if data:
            buf += data.decode(encoding="utf-8")
            if buf.endswith(MSG_DELIM):
                break
        else:
            break
    return buf
예제 #16
0
파일: tunnel.py 프로젝트: arsit/openuds
 def process(self, remote: ssl.SSLSocket):
     self.server.status = TUNNEL_PROCESSING
     logger.debug('Processing tunnel with ticket %s', self.server.ticket)
     # Process data until stop requested or connection closed
     try:
         while not self.server.stop_flag.is_set():
             r, _w, _x = select.select([self.request, remote], [], [], 1.0)
             if self.request in r:
                 data = self.request.recv(BUFFER_SIZE)
                 if not data:
                     break
                 remote.sendall(data)
             if remote in r:
                 data = remote.recv(BUFFER_SIZE)
                 if not data:
                     break
                 self.request.sendall(data)
         logger.debug('Finished tunnel with ticekt %s', self.server.ticket)
     except Exception as e:
         pass
예제 #17
0
def _main():
	if ( sys.argc != 5):
		_usage();
		exit(-1);
	
	server_ip = sys.argv[1];
	server_port = sys.argv[2];
	certficate = sys.argv[3];
	privatekey = sys.argv[4];

	SSLSocket fd = SSLSocket.socket()
	wrap_socket(sock)
    def doSSLHandshake(self, sock: ssl.SSLSocket) -> None:
        """
		Performs an SSL handshake.

		Note:
			The [`SSLSocket.do_handshake`][1] method is non-blocking and must be retried until it returns successfully.
			See [here][2] for further explanation.
			[1]: <https://docs.python.org/library/ssl.html#ssl.SSLSocket.do_handshake>
			[2]: <https://docs.python.org/library/ssl.html#ssl-nonblocking>

		Args:
			sock: The socket to perform the handshake on.
		"""
        while True:
            try:
                sock.do_handshake()
                break
            except ssl.SSLWantReadError:
                select.select([sock], [], [])
            except ssl.SSLWantWriteError:
                select.select([], [sock], [])
예제 #19
0
def perform_handshake(accepted_socket: ssl.SSLSocket) -> None:
    """
    Tries to perform a TLS handshake, if handshake don't succeed in 10 seconds, it closes the
    connection

    :param accepted_socket: SSLSocket object wrapping an accepted client socket
    :return: None
    """
    accepted_socket.settimeout(src.Constants.HANDSHAKE_TIMEOUT_SECONDS)
    try:
        accepted_socket.do_handshake()
        accepted_socket.settimeout(None)
    except (socket.timeout, ssl.SSLError, OSError):
        accepted_socket.close()
        exit(0)
예제 #20
0
파일: client.py 프로젝트: droope/pyRit
    def connect(self):
        print 'Connecting to region: {0}'.format(self.region)

        self.token = GetLoginToken(self.user, self.password, self.region[2])
        self.socket = SSLSocket(socket(), ssl_version=3)
        self.socket.connect((self.host, self.port))
        self.connected = True

        if not self.doHandshake():
            return False

        self.socket.setblocking(0)
        self.stream = rtmp.decoder.FileBuffer(self.socket.makefile())
        self.reader = rtmp.decoder.PacketReader(self.stream)

        msg = {
            'videoCodecs': 252,
            'audioCodecs': 3575,
            'flashVer': u'WIN 10,6,602,161',
            'app': '',
            'tcUrl': 'rtmps://{0}:2099'.format(self.host),
            'videoFunction': 1,
            'capabilities': 239,
            'pageUrl': '',
            'fpad': False,
            'swfUrl': 'app:/LolClient.swf/[[DYNAMIC]]/32',
            'objectEncoding': 3
        }

        stream = self.encoder.encodeConnect(msg)

        self.writeBytes(stream)
        self.processThread = Thread(target=self._processMessages)
        self.processThread.start()

        return True
예제 #21
0
def recv_ssl_msg(sock: ssl.SSLSocket, delimiter=b'\n'):
    if sock not in socket_buffer_dict.keys():
        socket_buffer_dict[sock] = bytearray()  #('', 'UTF-8')

    buff = socket_buffer_dict[sock]

    while True:
        data = sock.recv()
        buff.extend(data)
        if not data:
            time.sleep(0.1)
        elif delimiter in data:
            break

    pos = buff.index(delimiter)
    res = buff[0:pos]
    del buff[0:pos + 1]
    return base64.standard_b64decode(res)
예제 #22
0
def recv_ssl_msg_timeout(sock: ssl.SSLSocket, delimiter=b'\n', timeout=2):
    if sock not in socket_buffer_dict.keys():
        socket_buffer_dict[sock] = bytearray()

    buff = socket_buffer_dict[sock]
    last = time.time()
    received = False

    sock.setblocking(False)
    sock.settimeout(timeout)
    while True:
        available = select.select([sock], [], [], timeout / 25)
        data = None
        if available[0]:
            data = bytearray()
            subdata = sock.recv()
            while subdata:
                data.extend(subdata)
                try:
                    subdata = sock.recv()
                except socket.timeout:
                    subdata = None

        if not data:
            if (time.time() - last > timeout):
                break
            continue

        last = time.time()
        buff.extend(data)
        if delimiter in buff:
            received = True
            break

    sock.setblocking(True)
    if not received:
        raise TimeoutError

    pos = buff.index(delimiter)
    res = buff[0:pos]
    del buff[0:pos + 1]
    return base64.standard_b64decode(res)
예제 #23
0
파일: monkey_ssl.py 프로젝트: rwangandr/zb
def monkey_wrap_socket(sock,
                       keyfile=None,
                       certfile=None,
                       server_side=False,
                       cert_reqs=CERT_NONE,
                       ssl_version=PROTOCOL_SSLv23,
                       ca_certs=None,
                       do_handshake_on_connect=True,
                       suppress_ragged_eofs=True,
                       ciphers=None):
    ssl_version = ssl.PROTOCOL_TLSv1
    return SSLSocket(sock,
                     keyfile=keyfile,
                     certfile=certfile,
                     server_side=server_side,
                     cert_reqs=cert_reqs,
                     ssl_version=ssl_version,
                     ca_certs=ca_certs,
                     do_handshake_on_connect=do_handshake_on_connect,
                     suppress_ragged_eofs=suppress_ragged_eofs,
                     ciphers=ciphers)
예제 #24
0
파일: ssl_socket.py 프로젝트: planetlab/sfa
    def __init__(self, sock, keyfile=None, certfile=None,
                 server_side=False, cert_reqs=CERT_NONE,
                 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
                 do_handshake_on_connect=True,
                 suppress_ragged_eofs=True):
        socket.__init__(self, _sock=sock._sock)
        # the initializer for socket trashes the methods (tsk, tsk), so...
        self.send = lambda data, flags=0: SSLSocket.send(self, data, flags)
        self.sendto = lambda data, addr, flags=0: SSLSocket.sendto(self, data, addr, flags)
        self.recv = lambda buflen=1024, flags=0: SSLSocket.recv(self, buflen, flags)
        self.recvfrom = lambda addr, buflen=1024, flags=0: SSLSocket.recvfrom(self, addr, buflen, flags)
        self.recv_into = lambda buffer, nbytes=None, flags=0: SSLSocket.recv_into(self, buffer, nbytes, flags)
        self.recvfrom_into = lambda buffer, nbytes=None, flags=0: SSLSocket.recvfrom_into(self, buffer, nbytes, flags)

        if certfile and not keyfile:
            keyfile = certfile
        # see if it's connected
        try:
            socket.getpeername(self)
        except:
            # no, no connection yet
            self._sslobj = None
        else:
            # yes, create the SSL object
            self._sslobj = _ssl.sslwrap(self._sock, server_side,
                                        keyfile, certfile,
                                        cert_reqs, ssl_version, ca_certs)
            if do_handshake_on_connect:
                timeout = self.gettimeout()
                try:
                    if timeout == 0:
                        self.settimeout(None)
                    self.do_handshake()
                finally:
                    self.settimeout(timeout)
        self.keyfile = keyfile
        self.certfile = certfile
        self.cert_reqs = cert_reqs
        self.ssl_version = ssl_version
        self.ca_certs = ca_certs
        self.do_handshake_on_connect = do_handshake_on_connect
        self.suppress_ragged_eofs = suppress_ragged_eofs
        self._makefile_refs = 0
예제 #25
0
    def _update_results(self, context: ssl.SSLContext, ssock: ssl.SSLSocket,
                        success: bool):

        self.results['ssl.success'] = success

        cert = ssock.getpeercert() if success else None
        self.results['ssl.con.cert'] = cert
        self.results['ssl.con.cipher'], self.results[
            'ssl.con.protocol'], self.results[
                'ssl.con.secret_bits'] = ssock.cipher() or (None, None, None)
        self.results['ssl.con.compression'] = ssock.compression() or None
        self.results['ssl.con.alpn_protocol'] = ssock.selected_alpn_protocol(
        ) or None
        self.results['ssl.con.npn_protocol'] = ssock.selected_npn_protocol(
        ) or None
        self.results['ssl.con.ssl_version'] = ssock.version() or None
        self.results['ssl.con.server_hostname'] = ssock.server_hostname or None
        self.results[
            'ssl.con.cert.matches_hostname'] = True if cert is not None and ssl.match_hostname(
                cert, self.host) else False
예제 #26
0
def QueryMessage(secure_sock: ssl.SSLSocket, message_id: str, buffer_size=1048576):
    message_id = str(message_id)
    secure_sock.send(b"2" + bytes(message_id, "utf-8")) # Command ID 2
    print()
    return secure_sock.recv(buffer_size).decode().split(",")
예제 #27
0
def send_ssl_msg(sock: ssl.SSLSocket, msg, delimiter='\n'):
    data = base64.standard_b64encode(msg) + delimiter.encode('UTF-8')
    sock.send(data)
예제 #28
0
def send(irc: ssl.SSLSocket, message: str):
    irc.send(bytes(f'{message}\r\n', 'UTF-8'))
예제 #29
0
파일: client.py 프로젝트: droope/pyRit
class RtmpClient:
    socket = None
    invokeId = 1
    auth = False
    connected = False
    callbacks = {}
    pendingRequests = {}

    def __init__(self, regionId, user, password, version):
        self.region = Region.getRegion(regionId)
        self.user = user
        self.password = password
        self.version = version

        self.host = self.region[0]
        self.port = int(self.region[1])
        self.encoder = rtmp.encoder.AmfEncoder()

    def connect(self):
        print 'Connecting to region: {0}'.format(self.region)

        self.token = GetLoginToken(self.user, self.password, self.region[2])
        self.socket = SSLSocket(socket(), ssl_version=3)
        self.socket.connect((self.host, self.port))
        self.connected = True

        if not self.doHandshake():
            return False

        self.socket.setblocking(0)
        self.stream = rtmp.decoder.FileBuffer(self.socket.makefile())
        self.reader = rtmp.decoder.PacketReader(self.stream)

        msg = {
            'videoCodecs': 252,
            'audioCodecs': 3575,
            'flashVer': u'WIN 10,6,602,161',
            'app': '',
            'tcUrl': 'rtmps://{0}:2099'.format(self.host),
            'videoFunction': 1,
            'capabilities': 239,
            'pageUrl': '',
            'fpad': False,
            'swfUrl': 'app:/LolClient.swf/[[DYNAMIC]]/32',
            'objectEncoding': 3
        }

        stream = self.encoder.encodeConnect(msg)

        self.writeBytes(stream)
        self.processThread = Thread(target=self._processMessages)
        self.processThread.start()

        return True

    def _processMessages(self):
        while True:
            try:
                msg = self.reader.next()
            except SSLError as e:
                print 'An error occurred while attempting to read: {0}'.format(e)
                break

            if msg is None:
                time.sleep(.1)
                continue

            # RTMP initial login
            if msg['msg'] == rtmp.decoder.DataTypes.COMMAND:
                self.dsId = msg['cmd'][3]['id']
                self.login(self.user, self.password)

            if msg['msg'] == rtmp.decoder.DataTypes.INVOKE:
                invokeId = msg['cmd'][1]
                if invokeId in self.callbacks:
                    self.callbacks[invokeId](msg['cmd'][0], msg['cmd'][3])
                    del self.callbacks[invokeId]
                if invokeId in self.pendingRequests:
                    self.pendingRequests[invokeId] = msg


    def getPendingRequest(self, invokeId):
        if invokeId in self.pendingRequests:
            msg = self.pendingRequests[invokeId]

            if msg is None:
                return None

            return {'result': msg['cmd'][0], 'body': msg['cmd'][3].body}
        return -1

    def _heartbeatThread(self):
        heartbeatCount = 1
        while True:
            if self.auth:
                date = datetime.datetime.now().strftime("%d %m %d %Y %H:%M:%S 'GMTZ'")
                id = self.invoke('loginService', 'performLCDSHeartBeat', [self.acctId, self.session, heartbeatCount, date], None)
                del self.pendingRequests[id]
                heartbeatCount += 1

                time.sleep(12)

    def login(self, user, password):
        auth = AuthenticationCredentials(user, password, self.token, self.version)
        self.invoke('loginService', 'login', auth, self.onLogin)

    def onLogin(self, result, msg):
        if result == u'_error':
            print 'Login failed :('
            return

        self.acctId = msg.body['accountSummary']['accountId']
        self.session = msg.body['token']

        msg = self.invokeCommandMessage('auth', CommandMessage.LOGIN_OPERATION, base64.encodestring('{0}:{1}'.format(self.user, self.session)))

        msg.headers['DSSubtopic'] = 'bc'
        msg.clientId = 'bc-{0}'.format(self.acctId)
        self.sendMessage(msg)

        msg.headers['DSSubtopic'] = 'cn'
        msg.clientId = 'cn-{0}'.format(self.acctId)
        self.sendMessage(msg)

        msg.headers['DSSubtopic'] = 'gn'
        msg.clientId = 'gn-{0}'.format(self.acctId)
        self.sendMessage(msg)
        self.auth = True

        self.invoke('summonerService', 'getAllSummonerDataByAccount', [self.acctId], self.onSummonerData)

        print 'Authenticated as user: {0}'.format(self.user)
        Thread(target=self._heartbeatThread).start()

    def onSummonerData(self, result, msg):
        if result == u'_error' or msg.body == None:
            print 'Not summoner set, creating default now so we can use gameService.'
            self.invoke('summonerService', 'createDefaultSummoner', [self.user])
            return

        if msg.body['summoner']['name'] is None:
            print 'Not summoner set, creating default now so we can use gameService.'
            self.invoke('summonerService', 'createDefaultSummoner', [self.user])

    def sendMessage(self, msg):
        invokeId = self.nextInvokeId()
        invoke = self.encoder.encodeInvoke(invokeId, msg)

        self.stream.write(invoke)
        return invokeId

    def invoke(self, destination, operation, body, callback=None):
        headers = TypedObject('')

        headers['DSRequestTimeout'] = 60
        headers['DSId'] = self.dsId
        headers['DSEndpoint'] = 'my-rtmps'

        msg = RemotingMessage(destination=destination, operation=operation, body=body, headers=headers, messageId=str(uuid.uuid4()))

        if callback is not None:
            self.callbacks[self.sendMessage(msg)] = callback
        else:
            invokeId = self.sendMessage(msg)
            self.pendingRequests[invokeId] = None
            return invokeId

    def invokeCommandMessage(self, destination, operation, body):
        headers = TypedObject('')

        headers['DSRequestTimeout'] = 60
        headers['DSId'] = self.dsId
        headers['DSEndpoint'] = 'my-rtmps'

        msg = CommandMessage(destination=destination, operation=operation, body=body, headers=headers, messageId=str(uuid.uuid4()))
        invokeId = self.nextInvokeId()
        invoke = self.encoder.encodeInvoke(invokeId, msg)

        self.stream.write(invoke)

        return msg

    def nextInvokeId(self):
        self.invokeId += 1
        return self.invokeId

    def readBytes(self, size):
        return bytearray(self.socket.read(size))

    def writeBytes(self, data):
        return self.socket.write(data)

    def doHandshake(self):
        syn = bytearray(os.urandom(1537))
        syn[0] = 3

        self.writeBytes(syn)

        version = self.readBytes(1)

        if version[0] != 3:
            print "Invalid server version received"
            return False

        ack = self.readBytes(1536)
        self.writeBytes(ack)

        ack = self.readBytes(1536)

        i = 8
        while i < 1536:
            if syn[i + 1] != ack[i]:
                print 'Invalid ack!'
                return False
            i += 1

        return True
예제 #30
0
파일: ssl.py 프로젝트: ufwt/dizzy
 def open(self):
     try:
         self.s = socket(self.af, SOCK_STREAM)
         if self.dest == "255.255.255.255":
             self.s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
         self.s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
         self.s.settimeout(self.timeout)
         sendbuf = self.s.getsockopt(SOL_SOCKET, SO_SNDBUF)
         if sendbuf < self.maxsize:
             self.maxsize = sendbuf
         if not self.sport is None:
             if self.af == AF_INET:
                 self.s.bind((self.src, self.sport))
             elif self.af == AF_INET6:
                 try:
                     self.s.bind((self.src, self.port, 0, 0))
                 except:
                     if not self.interface is '':
                         (_, _, _, _, addri) = getaddrinfo(
                             "%s%%%s" % (self.src, self.interface),
                             self.sport,
                             family=AF_INET6,
                             proto=IPPROTO_UDP)[0]
                         self.s.bind(addri)
                     else:
                         raise SessionException(
                             "cant bind to ipv6 LL without interface!")
         self.s = SSLSocket(self.s,
                            self.client_key,
                            self.client_cert,
                            ssl_version=3)
         if self.server_side:
             self.s.listen(1)
             (self.cs, (rip, rport)) = self.s.accept()
             if self.dport:
                 while self.dport != rport or self.src != rip:
                     if self.dport != rport:
                         print_dizzy(
                             "session/ssl: remote port %i not destination port %i"
                             % (rport, self.dport), DEBUG)
                     if self.src != rip:
                         print_dizzy(
                             "session/ssl: remote ip %s not destination ip %i"
                             % (rip, self.dst), DEBUG)
                     (self.cs, (sip, rport)) = self.s.accept()
             self.cs.settimeout(self.timeout)
         else:
             connected = False
             attempt = 1
             try:
                 self.s.connect((self.dest, self.dport))
                 connected = True
             except (timeout, SSLError):
                 print_dizzy(
                     "session/ssl: Connection attempt %d timed out." %
                     attempt)
                 while not connected and attempt <= self.connect_retry:
                     try:
                         (r, w, x) = select([], [self.s], [], self.timeout)
                         if self.s in w:
                             connected = True
                     except:
                         pass
                     attempt += 1
                 if not connected:
                     raise SessionException("too much connection attempts")
     except Exception as e:
         raise SessionException("cant open session: %s" % str(e))
     else:
         self.is_open = True
예제 #31
0
def RegisterMessage(secure_sock: ssl.SSLSocket, message_id: bytes):
    #message_id = str(message_id)
    secure_sock.send(message_id) # Command ID 3 but not w/ "3"
예제 #32
0
파일: ssl.py 프로젝트: ufwt/dizzy
class DizzySession(object):
    def __init__(self, section_proxy):
        self.dest = section_proxy.get('target_host')
        self.dport = section_proxy.getint('target_port')
        self.src = section_proxy.get('source_host', '')
        self.sport = section_proxy.getint('source_port')
        self.client_cert = section_proxy.get('certfile')
        self.client_key = section_proxy.get('keyfile')
        self.timeout = section_proxy.getfloat('timeout', 1)
        self.recv_buffer = section_proxy.getfloat('recv_buffer', 4096)
        self.auto_reopen = section_proxy.getboolean('auto_reopen', True)
        self.server_side = section_proxy.getboolean('server', False)
        self.read_first = self.server_side
        self.read_first = section_proxy.getboolean('read_first',
                                                   self.read_first)
        self.connect_retry = section_proxy.getint('retry', 3)
        self.is_open = False

        try:
            inet_aton(self.dest)
            self.af = AF_INET
        except Exception as e:
            try:
                inet_pton(AF_INET6, self.dest)
                self.af = AF_INET6
            except Exception as f:
                raise SessionParseException(
                    "unknown address family: %s: %s, %s" % (self.dest, e, f))
        if self.src != '':
            try:
                inet_aton(self.src)
            except Exception as e:
                try:
                    inet_pton(AF_INET6, self.src)
                except Exception as f:
                    raise SessionParseException(
                        "unknown address family: %s: %s, %s" %
                        (self.src, e, f))
                else:
                    if not self.af == AF_INET6:
                        raise SessionParseException(
                            "address family missmatch: %s - %s" %
                            (self.dest, self.src))
            else:
                if not self.af == AF_INET:
                    raise SessionParseException(
                        "address family missmatch: %s - %s" %
                        (self.dest, self.src))

        self.cs = None
        self.maxsize = 65534

    def open(self):
        try:
            self.s = socket(self.af, SOCK_STREAM)
            if self.dest == "255.255.255.255":
                self.s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
            self.s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            self.s.settimeout(self.timeout)
            sendbuf = self.s.getsockopt(SOL_SOCKET, SO_SNDBUF)
            if sendbuf < self.maxsize:
                self.maxsize = sendbuf
            if not self.sport is None:
                if self.af == AF_INET:
                    self.s.bind((self.src, self.sport))
                elif self.af == AF_INET6:
                    try:
                        self.s.bind((self.src, self.port, 0, 0))
                    except:
                        if not self.interface is '':
                            (_, _, _, _, addri) = getaddrinfo(
                                "%s%%%s" % (self.src, self.interface),
                                self.sport,
                                family=AF_INET6,
                                proto=IPPROTO_UDP)[0]
                            self.s.bind(addri)
                        else:
                            raise SessionException(
                                "cant bind to ipv6 LL without interface!")
            self.s = SSLSocket(self.s,
                               self.client_key,
                               self.client_cert,
                               ssl_version=3)
            if self.server_side:
                self.s.listen(1)
                (self.cs, (rip, rport)) = self.s.accept()
                if self.dport:
                    while self.dport != rport or self.src != rip:
                        if self.dport != rport:
                            print_dizzy(
                                "session/ssl: remote port %i not destination port %i"
                                % (rport, self.dport), DEBUG)
                        if self.src != rip:
                            print_dizzy(
                                "session/ssl: remote ip %s not destination ip %i"
                                % (rip, self.dst), DEBUG)
                        (self.cs, (sip, rport)) = self.s.accept()
                self.cs.settimeout(self.timeout)
            else:
                connected = False
                attempt = 1
                try:
                    self.s.connect((self.dest, self.dport))
                    connected = True
                except (timeout, SSLError):
                    print_dizzy(
                        "session/ssl: Connection attempt %d timed out." %
                        attempt)
                    while not connected and attempt <= self.connect_retry:
                        try:
                            (r, w, x) = select([], [self.s], [], self.timeout)
                            if self.s in w:
                                connected = True
                        except:
                            pass
                        attempt += 1
                    if not connected:
                        raise SessionException("too much connection attempts")
        except Exception as e:
            raise SessionException("cant open session: %s" % str(e))
        else:
            self.is_open = True

    def close(self):
        self.s.close()
        self.s = None
        if self.cs:
            self.cs.close()
            self.cs = None
        self.is_open = False

    def send(self, data):
        try:
            if not self.maxsize is None and len(data) > self.maxsize:
                data = data[:self.maxsize - 1]
                print_dizzy("Truncated data to %d byte." % self.maxsize, DEBUG)
            if self.server_side:
                if not self.cs:
                    raise SessionException("no client connection, cant send")
                self.cs.send(data)
            else:
                self.s.send(data)
        except Exception as e:
            if self.auto_reopen:
                print_dizzy("session got closed '%s', autoreopening..." % e,
                            DEBUG)
                self.close()
                self.open()
            else:
                self.close()
                raise SessionException(
                    "error on sending '%s', connection closed." % e)

    def recv(self):
        if self.server_side:
            return self.cs.recv(self.recv_buffer)
        else:
            return self.s.recv(self.recv_buffer)
예제 #33
0
def GetMessages(secure_sock: ssl.SSLSocket, buffer_size=1048576, hash_size=MSG_HASH_SIZE):
    print("Getting messages")
    secure_sock.send(b"1") # Command ID 1
    return re.findall('.'*hash_size, secure_sock.recv(buffer_size).decode())