Example #1
0
def wshandler(request):
    logger.info('new connection')
    ws_response = web.WebSocketResponse()
    yield from ws_response.prepare(request)
    pub_key = ""
    session = ssession.ssession(b'server', server_private_key, Transport())
    authorized = False
    while True:
        message = yield from ws_response.receive()
        if message.tp == web.MsgType.text:
            msg = session.unwrap(base64.b64decode(message.data))
            if msg.is_control:
                ws_response.send_str(base64.b64encode(msg).decode("UTF-8"))
            else:
                #                logger.info('request:' + msg.decode("UTF-8"))
                msg = msg.decode("UTF-8").split()
                authorized = handlers_map[msg[0]](msg, ws_response, session,
                                                  authorized)
        elif message.tp == web.MsgType.closed or message.tp == web.MsgType.close:
            if pub_key in online:
                del online[pub_key]
                logger.info('connection closed')
            break
        else:
            ws_response.send_str('{} malformed request'.format(COMMAND.ERROR))
            if 'msg' in locals():
                logger.info('error:{}'.format(msg))
                if pub_key in online:
                    del online[pub_key]
                    logger.info('closed')
    return ws_response
Example #2
0
def wshandler(request):
    logger.info('new connection')
    ws_response = web.WebSocketResponse()
    yield from ws_response.prepare(request)
    pub_key = ""
    session = ssession.ssession(b'server', server_private_key, Transport())
    authorized = False
    while True:
        message = yield from ws_response.receive()
        if message.tp == web.MsgType.text:
            msg = session.unwrap(base64.b64decode(message.data))
            if msg.is_control:
               ws_response.send_str(base64.b64encode(msg).decode("UTF-8"));
            else:
#                logger.info('request:' + msg.decode("UTF-8"))
                msg = msg.decode("UTF-8").split();
                authorized = handlers_map[msg[0]](msg, ws_response, session, authorized)
        elif message.tp == web.MsgType.closed or message.tp == web.MsgType.close:
            if pub_key in online:
                del online[pub_key]
                logger.info('connection closed')
            break
        else:
            ws_response.send_str('{} malformed request'.format(COMMAND.ERROR))
            if 'msg' in locals():
                logger.info('error:{}'.format(msg))
                if pub_key in online:
                    del online[pub_key]
                    logger.info('closed')
    return ws_response
Example #3
0
 def server(self):
     server_transport = send_receive_transport(q2, q1)
     session = ssession.ssession(b"server", self.server_priv,
                                 transport(self.pub_ids))
     while True:
         server_transport.send(session.unwrap(server_transport.receive()))
         if session.is_established() == 1:
             break
     self.assertEqual(self.message,
                      session.unwrap(server_transport.receive()))
     server_transport.send(session.wrap(self.message))
Example #4
0
 def server(self):
     server_transport = send_receive_transport(q2, q1)
     session = ssession.ssession(b"server", self.server_priv,
                                 transport(self.pub_ids))
     while True:
         server_transport.send(session.unwrap(server_transport.receive()))
         if session.is_established() == 1:
             break
     self.assertEqual(self.message,
                      session.unwrap(server_transport.receive()))
     server_transport.send(session.wrap(self.message))
Example #5
0
    def client(self):
        client_transport = send_receive_transport(q1, q2)
#        with self.assertRaises(TypeError):
#            session=ssession.ssession('client', None, transport(self.pub_ids))
#        with self.assertRaises(themis_exception):
#            session=ssession.ssession('client', "", transport(self.pub_ids))
#            session.connect_request()
        session = ssession.ssession(b"client", self.client_priv,
                                    transport(self.pub_ids))
        control_message = session.connect_request()
        while session.is_established() != 1:
            client_transport.send(control_message)
            control_message = session.unwrap(client_transport.receive())
        client_transport.send(session.wrap(self.message))
        self.assertEqual(self.message,
                         session.unwrap(client_transport.receive()))
Example #6
0
 def client(self):
     client_transport = send_receive_transport(q1, q2)
     #        with self.assertRaises(TypeError):
     #            session=ssession.ssession('client', None, transport(self.pub_ids))
     #        with self.assertRaises(themis_exception):
     #            session=ssession.ssession('client', "", transport(self.pub_ids))
     #            session.connect_request()
     session = ssession.ssession(b"client", self.client_priv,
                                 transport(self.pub_ids))
     control_message = session.connect_request()
     while session.is_established() != 1:
         client_transport.send(control_message)
         control_message = session.unwrap(client_transport.receive())
     client_transport.send(session.wrap(self.message))
     self.assertEqual(self.message,
                      session.unwrap(client_transport.receive()))
Example #7
0
def message(request):
    global sessions
    global history
    data = yield from request.post()
    print(data)
    print(request.cookies)
    if 'message' not in data or 'client_name' not in data:
        return web.Response(status=500, text="incorrect request")
    if 'session_id' not in request.cookies:
        session = ssession.ssession(b'server', server_private_key, Transport())
        msg = session.unwrap(base64.b64decode(data['message']))
        if msg.is_control:
            session_id = str(uuid.uuid4())
            sessions[session_id] = {
                'start': time.time(),
                'last': time.time(),
                'session': session
            }
            print(base64.b64encode(msg).decode("UTF-8"))
            resp = web.Response(text=base64.b64encode(msg).decode("UTF-8"))
            resp.set_cookie("session_id", session_id)
            return resp
    else:
        session_id = request.cookies['session_id']
        session = sessions[session_id]['session']
        msg = session.unwrap(base64.b64decode(data['message']))
        print(msg)
        if msg.is_control:
            sessions[session_id]['last'] = time.time()
            print(base64.b64encode(msg).decode("UTF-8"))
            resp = web.Response(text=base64.b64encode(msg).decode("UTF-8"))
            resp.set_cookie("session_id", session_id)
            return resp
        else:
            history.append({
                'name':
                data['client_name'],
                'time':
                datetime.datetime.fromtimestamp(
                    time.time()).strftime('%Y-%m-%d %H:%M:%S'),
                'message':
                msg.decode("UTF-8")
            })
            reply_msg = "Your message received! " + msg.decode("UTF-8")
            reply_msg_enc = session.wrap(reply_msg.encode("UTF-8"))
            return web.Response(
                text=base64.b64encode(reply_msg_enc).decode("UTF-8"))
Example #8
0
def wshandler(request):
    logger.info('new connection')
    ws_response = web.WebSocketResponse()
    yield from ws_response.prepare(request)
    pub_key = ""
    session = ssession.ssession(b'server', server_private_key, Transport())
    while True:
        message = yield from ws_response.receive()
        if message.tp == web.MsgType.text:
            msg = session.unwrap(base64.b64decode(message.data))
            if msg.is_control:
               ws_response.send_str(base64.b64encode(msg).decode("UTF-8"));
            else:
                msg = msg.decode("UTF-8")
                logger.info('request:' + msg)
                message_params = msg.split()
                if message_params[0] == COMMAND.NEW_ROOM and pub_key:
                    new_room_id = generate_id()
                    rooms[new_room_id] = {'owner': pub_key, 'users': [pub_key]}
                    ws_response.send_str(base64.b64encode(session.wrap('{} {}'.format(COMMAND.ROOM_CREATED, new_room_id).encode("UTF-8"))).decode("UTF-8"))
                elif message_params[0] == COMMAND.INVITE and pub_key:
                    if (message_params[2] in rooms and
                        message_params[1] == rooms[message_params[2]]['owner'] and
                        message_params[1] in online):
                        online[message_params[1]]['socket'].send_str(base64.b64encode(online[message_params[1]]['session'].wrap(msg.encode("UTF-8"))).decode("UTF-8"))
                    else:
                        ws_response.send_str(base64.b64encode(session.wrap('{} {}'.format(COMMAND.INVALID_INVITE, message_params[1]).encode("UTF-8"))).decode("UTF-8"))
                elif message_params[0] == COMMAND.INVITE_RESPONSE and pub_key:
                    if (message_params[2] in rooms and
                        message_params[1] in online and
                        pub_key == rooms[message_params[2]]['owner']):
                        rooms[message_params[2]]['users'].append(message_params[1])
                        online[message_params[1]]['socket'].send_str(base64.b64encode(online[message_params[1]]['session'].wrap(msg.encode("UTF-8"))).decode("UTF-8"))
                        if message_params[2] in rooms_history:
                            for history_message in rooms_history[message_params[2]]:
                                online[message_params[1]]['socket'].send_str(base64.b64encode(online[message_params[1]]['session'].wrap(history_message.encode("UTF-8"))).decode("UTF-8"))
                elif message_params[0] == COMMAND.OPEN_ROOM and pub_key:
                    if (message_params[1] in rooms and
                        pub_key in rooms[message_params[1]]['users']):
                        ws_response.send_str(base64.b64encode(session.wrap('{} 111'.format(COMMAND.OPENED_ROOM).encode("UTF-8"))).decode("UTF-8"))
                    else:
                        ws_response.send_str(base64.b64encode(session.wrap('{} {}'.format(COMMAND.ERROR_ROOM, message_params[1]).encode("UTF-8"))).decode("UTF-8"))
                elif message_params[0] == COMMAND.MESSAGE and pub_key:
                    if (message_params[1] in rooms and
                        pub_key in rooms[message_params[1]]['users']):
                        if message_params[1] in rooms_history:
                            rooms_history[message_params[1]].append(msg)
                        else:
                            rooms_history[message_params[1]]=[msg]
                        for user_public_key in rooms[message_params[1]]['users']:
                            if (user_public_key in online and
                                user_public_key != pub_key):
                                online[user_public_key]['socket'].send_str(base64.b64encode(online[user_public_key]['session'].wrap(msg.encode("UTF-8"))).decode("UTF-8"))
                            else:
                                if user_public_key in history:
                                    history[user_public_key].append(msg)
                                else:
                                    history[user_public_key] = [msg]
                    else:
                        ws_response.send_str('{} {}'.format(COMMAND.MESSAGE_ERROR,
                                                            message_params[1]))
                elif message_params[0] == COMMAND.MESSAGE_KEY_ROTATE and pub_key:
                    if (message_params[1] in rooms and
                        pub_key == rooms[message_params[1]]['owner']):
                        rooms_history[message_params[1]]=[msg]
                        for user_public_key in rooms[message_params[1]]['users']:
                            if (user_public_key in online and
                                user_public_key != pub_key):
                                online[user_public_key]['socket'].send_str(base64.b64encode(online[user_public_key]['session'].wrap(msg.encode("UTF-8"))).decode("UTF-8"))
                            else:
                                if user_public_key in history:
                                    history[user_public_key].append(msg)
                                else:
                                    history[user_public_key] = [msg]
                    else:
                        ws_response.send_str('{} {}'.format(COMMAND.MESSAGE_ERROR,
                                                            message_params[1]))
                elif message_params[0] == COMMAND.PUBLIC_KEY:
                    pub_key = message_params[1]
                    online[pub_key] = {'socket': ws_response, 'session': session}
                    if pub_key in history:
                        for history_message in history[pub_key]:
                            ws_response.send_str(base64.b64encode(session.wrap(history_message.encode("UTF-8"))).decode("UTF-8"))
                        history[pub_key] = []
                else:
                    ws_response.send_str(base64.b64encode(session.wrap('{} malformed request'.format(COMMAND.ERROR).encode("UTF-8"))).decode("UTF-8"))
        elif message.tp == web.MsgType.closed or message.tp == web.MsgType.close:
            if pub_key in online:
                del online[pub_key]
                logger.info('connection closed')
                break
            else:
                ws_response.send_str('{} malformed request'.format(COMMAND.ERROR))
                if 'msg' in locals():
                    logger.info('error:{}'.format(msg))
                    if pub_key in online:
                        del online[pub_key]
                        logger.info('closed')
    return ws_response
from pythemis import ssession;
import tornado.ioloop
import tornado.web

client_pub = str('\x55\x45\x43\x32\x00\x00\x00\x2d\x13\x8b\xdf\x0c\x02\x1f\x09\x88\x39\xd9\x73\x3a\x84\x8f\xa8\x50\xd9\x2b\xed\x3d\x38\xcf\x1d\xd0\xce\xf4\xae\xdb\xcf\xaf\xcb\x6b\xa5\x4a\x08\x11\x21');

server_priv= str('\x52\x45\x43\x32\x00\x00\x00\x2d\x49\x87\x04\x6b\x00\xf2\x06\x07\x7d\xc7\x1c\x59\xa1\x8f\x39\xfc\x94\x81\x3f\x9e\xc5\xba\x70\x6f\x93\x08\x8d\xe3\x85\x82\x5b\xf8\x3f\xc6\x9f\x0b\xdf');


class transport(ssession.mem_transport):
    def get_pub_key_by_id(self, user_id):	#necessary callback function
        if user_id != "client":			#we have only one peer with id "client"
            raise Exception("no such id");
        return client_pub; 

session=ssession.ssession("server", server_priv, transport());

class MainHandler(tornado.web.RequestHandler):        
    def post(self):
	print repr(self.request.body);
        message = session.unwrap(self.request.body);	#decrypt received message
        if message.is_control:				#if status==1 then session is not ectablish yet
            self.write(message);			#send unwraped message to client as is
        else:						#if status!=1 then session is established
            print message;				#print accepted plain message
            self.write(session.wrap(message));		#encrypt and send reply message 
application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
Example #10
0
from pythemis import ssession;
import tornado.ioloop
import tornado.web

client_pub = b"\x55\x45\x43\x32\x00\x00\x00\x2d\x13\x8b\xdf\x0c\x02\x1f\x09\x88\x39\xd9\x73\x3a\x84\x8f\xa8\x50\xd9\x2b\xed\x3d\x38\xcf\x1d\xd0\xce\xf4\xae\xdb\xcf\xaf\xcb\x6b\xa5\x4a\x08\x11\x21"

server_priv= b"\x52\x45\x43\x32\x00\x00\x00\x2d\x49\x87\x04\x6b\x00\xf2\x06\x07\x7d\xc7\x1c\x59\xa1\x8f\x39\xfc\x94\x81\x3f\x9e\xc5\xba\x70\x6f\x93\x08\x8d\xe3\x85\x82\x5b\xf8\x3f\xc6\x9f\x0b\xdf"


class transport(ssession.mem_transport):
    def get_pub_key_by_id(self, user_id):        #necessary callback function
        if user_id != b"client":                        #we have only one peer with id "client"
            raise Exception("no such id");
        return client_pub; 

session=ssession.ssession(b"server", server_priv, transport());

class MainHandler(tornado.web.RequestHandler):        
    def post(self):
        print(repr(self.request.body));
        message = session.unwrap(self.request.body);        #decrypt received message
        if message.is_control:                                #if status==1 then session is not ectablish yet
            self.write(message);                        #send unwraped message to client as is
        else:                                                #if status!=1 then session is established
            print(message);                                #print accepted plain message
            self.write(session.wrap(message));                #encrypt and send reply message 
application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
Example #11
0
from pythemis import ssession
import base64
import time


class transport(ssession.mem_transport):
    def get_pub_key_by_id(self, user_id):  #necessary callback function
        if user_id != b"nXQpVsglEGFJgfK":  #we have only one peer with id "server"
            raise Exception("no such id")
        return base64.b64decode(
            "VUVDMgAAAC2yfQpBAzarlWrwxjlDduEH6Wdfah46bDVLGGCAqYYkVS+dlrcV")


session = ssession.ssession(
    b"gounDbllopcCcVB",
    base64.b64decode(
        "UkVDMgAAAC1whm6SAJ7vIP18Kq5QXgLd413DMjnb6Z5jAeiRgUeekMqMC0+x"),
    transport())
data = session.connect_request()
params = urllib.urlencode({'message': base64.b64encode(data)})
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPSConnection("themis.cossacklabs.com")
print(params)
conn.request("POST", "/api/gounDbllopcCcVB/", params, headers)
resp = conn.getresponse()
print(resp.status)
response_msg = session.unwrap(resp.read())
while response_msg.is_control:
    params = urllib.urlencode({'message': base64.b64encode(response_msg)})
    print(params)
    conn.request("POST", "/api/gounDbllopcCcVB/", params, headers)
Example #12
0
 def __init__(self):
     self.transport_=transport();
     self.session=ssession.ssession(b"server", server_priv, self.transport_);
Example #13
0
#!/usr/bin/python

import httplib, urllib
from pythemis import ssession
import base64
import time;


class transport(ssession.mem_transport):
    def get_pub_key_by_id(self, user_id):        #necessary callback function
        if user_id != b"nXQpVsglEGFJgfK":                        #we have only one peer with id "server"
            raise Exception("no such id");
        return base64.b64decode("VUVDMgAAAC2yfQpBAzarlWrwxjlDduEH6Wdfah46bDVLGGCAqYYkVS+dlrcV"); 

session=ssession.ssession(b"gounDbllopcCcVB",base64.b64decode("UkVDMgAAAC1whm6SAJ7vIP18Kq5QXgLd413DMjnb6Z5jAeiRgUeekMqMC0+x"), transport())
data = session.connect_request()
params = urllib.urlencode({'message': base64.b64encode(data)})
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPSConnection("themis.cossacklabs.com")
print params
conn.request("POST", "/api/gounDbllopcCcVB/", params, headers)
resp= conn.getresponse()
print resp.status
response_msg = session.unwrap(resp.read())
while response_msg.is_control:
    params = urllib.urlencode({'message': base64.b64encode(response_msg)})
    print params
    conn.request("POST", "/api/gounDbllopcCcVB/", params, headers)
    resp= conn.getresponse()
    print resp.status
    response_msg = session.unwrap(resp.read())
from pythemis import ssession;
import tornado.ioloop
import tornado.httpclient;

client_priv = str('\x52\x45\x43\x32\x00\x00\x00\x2d\x51\xf4\xaa\x72\x00\x9f\x0f\x09\xce\xbe\x09\x33\xc2\x5e\x9a\x05\x99\x53\x9d\xb2\x32\xa2\x34\x64\x7a\xde\xde\x83\x8f\x65\xa9\x2a\x14\x6d\xaa\x90\x01');

server_pub  = str('\x55\x45\x43\x32\x00\x00\x00\x2d\x75\x58\x33\xd4\x02\x12\xdf\x1f\xe9\xea\x48\x11\xe1\xf9\x71\x8e\x24\x11\xcb\xfd\xc0\xa3\x6e\xd6\xac\x88\xb6\x44\xc2\x9a\x24\x84\xee\x50\x4c\x3e\xa0');

class transport(ssession.mem_transport):
    def get_pub_key_by_id(self, user_id):	#necessary callback function
        if user_id != "server":			#we have only one peer with id "server"
            raise Exception("no such id");
        return server_pub; 

http_client = tornado.httpclient.HTTPClient();
session=ssession.ssession("client", client_priv, transport());
try:
    aaa=session.connect_request();
    response = http_client.fetch(tornado.httpclient.HTTPRequest("http://127.0.0.1:26260", "POST", None, aaa));#, follow_redirects=False)); #send initial message to server
    message=session.unwrap(response.body);		#decrypt accepted message
    while message.is_control:					#if status==1 then session is not established yet
        response = http_client.fetch(tornado.httpclient.HTTPRequest("http://127.0.0.1:26260", "POST", None, message)); #send unwrapped message to server as is
        message = session.unwrap(response.body);	#decrypt accepted message

    response = http_client.fetch(tornado.httpclient.HTTPRequest("http://127.0.0.1:26260", "POST", None, session.wrap("This is test message")));#wrap and send inform message
    message = session.unwrap(response.body);	#decrypt accepted message
    print message;					#print accepted plain message
    
except tornado.httpclient.HTTPError as e:
    print("Error: " + str(e));
except Exception as e:
 def __init__(self):
     self.transport_ = transport()
     self.session = ssession.ssession(b"server", server_priv,
                                      self.transport_)
Example #16
0
 def __init__(self, user_id, sign_key, transport):
     self.session=ssession.ssession(user_id, sign_key, transport);
     self.session.connect();				#1. establish session
     while self.session.is_established()!=True:	#2  establish session
         self.session.receive();			#3. establish session
Example #17
0
 def __init__(self, user_id, sign_key, transport):
     self.session = ssession.ssession(user_id, sign_key, transport)
     self.session.connect()
     #1. establish session
     while self.session.is_established() != True:  #2  establish session
         self.session.receive()
Example #18
0
class Transport(ssession.mem_transport):
    def get_pub_key_by_id(self, user_id):
        if user_id == b'server':
            return base64.b64decode(urllib.parse.unquote(server_pub_key))


params = urllib.parse.urlencode({'client_name': client_name, 'public_key': base64.b64encode(client_public_key)})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = http.client.HTTPConnection(url, port)
conn.request("POST", "/connect_request", params, headers)
response = conn.getresponse()
if response.status == 200:
    print(response.read())
    print(response.getheaders())
    
    session = ssession.ssession(client_name.encode("UTF-8"), client_private_key, Transport())
    msg = session.connect_request()
    while True:
        params = urllib.parse.urlencode({'client_name': client_name,'message': base64.b64encode(msg)})
        conn.request("POST", "/message", params, headers)
        response = conn.getresponse()
        msg = response.read()    
        if response.status == 200:
            print(msg)
            print(response.getheaders())
            cookie = http.cookies.SimpleCookie()
            headers["Cookie"] = ""
            for header in response.getheaders():
                if header[0] == 'Set-Cookie':
                    cookie.load(header[1])
                    headers["Cookie"] = "session_id="+cookie['session_id'].value
import tornado.httpclient

client_priv = b"\x52\x45\x43\x32\x00\x00\x00\x2d\x51\xf4\xaa\x72\x00\x9f\x0f\x09\xce\xbe\x09\x33\xc2\x5e\x9a\x05\x99\x53\x9d\xb2\x32\xa2\x34\x64\x7a\xde\xde\x83\x8f\x65\xa9\x2a\x14\x6d\xaa\x90\x01"

server_pub = b"\x55\x45\x43\x32\x00\x00\x00\x2d\x75\x58\x33\xd4\x02\x12\xdf\x1f\xe9\xea\x48\x11\xe1\xf9\x71\x8e\x24\x11\xcb\xfd\xc0\xa3\x6e\xd6\xac\x88\xb6\x44\xc2\x9a\x24\x84\xee\x50\x4c\x3e\xa0"


class transport(ssession.mem_transport):
    def get_pub_key_by_id(self, user_id):  #necessary callback function
        if user_id != b"server":  #we have only one peer with id "server"
            raise Exception("no such id")
        return server_pub


http_client = tornado.httpclient.HTTPClient()
session = ssession.ssession(b"client", client_priv, transport())
try:
    aaa = session.connect_request()
    response = http_client.fetch(
        tornado.httpclient.HTTPRequest("http://127.0.0.1:26260", "POST", None,
                                       aaa))
    #, follow_redirects=False)); #send initial message to server
    message = session.unwrap(response.body)
    #decrypt accepted message
    while message.is_control:  #if status==1 then session is not established yet
        response = http_client.fetch(
            tornado.httpclient.HTTPRequest("http://127.0.0.1:26260", "POST",
                                           None, message))
        #send unwrapped message to server as is
        message = session.unwrap(response.body)
        #decrypt accepted message
Example #20
0
def wshandler(request):
    logger.info('new connection')
    ws_response = web.WebSocketResponse()
    yield from ws_response.prepare(request)
    pub_key = ""
    session = ssession.ssession(b'server', server_private_key, Transport())
    while True:
        message = yield from ws_response.receive()
        if message.tp == web.MsgType.text:
            msg = session.unwrap(base64.b64decode(message.data))
            if msg.is_control:
                ws_response.send_str(base64.b64encode(msg).decode("UTF-8"))
            else:
                msg = msg.decode("UTF-8")
                logger.info('request:' + msg)
                message_params = msg.split()
                if message_params[0] == COMMAND.NEW_ROOM and pub_key:
                    new_room_id = generate_id()
                    rooms[new_room_id] = {'owner': pub_key, 'users': [pub_key]}
                    ws_response.send_str(
                        base64.b64encode(
                            session.wrap('{} {}'.format(
                                COMMAND.ROOM_CREATED,
                                new_room_id).encode("UTF-8"))).decode("UTF-8"))
                elif message_params[0] == COMMAND.INVITE and pub_key:
                    if (message_params[2] in rooms and message_params[1]
                            == rooms[message_params[2]]['owner']
                            and message_params[1] in online):
                        online[message_params[1]]['socket'].send_str(
                            base64.b64encode(
                                online[message_params[1]]['session'].wrap(
                                    msg.encode("UTF-8"))).decode("UTF-8"))
                    else:
                        ws_response.send_str(
                            base64.b64encode(
                                session.wrap('{} {}'.format(
                                    COMMAND.INVALID_INVITE,
                                    message_params[1]).encode(
                                        "UTF-8"))).decode("UTF-8"))
                elif message_params[0] == COMMAND.INVITE_RESPONSE and pub_key:
                    if (message_params[2] in rooms
                            and message_params[1] in online
                            and pub_key == rooms[message_params[2]]['owner']):
                        rooms[message_params[2]]['users'].append(
                            message_params[1])
                        online[message_params[1]]['socket'].send_str(
                            base64.b64encode(
                                online[message_params[1]]['session'].wrap(
                                    msg.encode("UTF-8"))).decode("UTF-8"))
                        if message_params[2] in rooms_history:
                            for history_message in rooms_history[
                                    message_params[2]]:
                                online[message_params[1]]['socket'].send_str(
                                    base64.b64encode(online[
                                        message_params[1]]['session'].wrap(
                                            history_message.encode(
                                                "UTF-8"))).decode("UTF-8"))
                elif message_params[0] == COMMAND.OPEN_ROOM and pub_key:
                    if (message_params[1] in rooms
                            and pub_key in rooms[message_params[1]]['users']):
                        ws_response.send_str(
                            base64.b64encode(
                                session.wrap('{} 111'.format(
                                    COMMAND.OPENED_ROOM).encode(
                                        "UTF-8"))).decode("UTF-8"))
                    else:
                        ws_response.send_str(
                            base64.b64encode(
                                session.wrap('{} {}'.format(
                                    COMMAND.ERROR_ROOM,
                                    message_params[1]).encode(
                                        "UTF-8"))).decode("UTF-8"))
                elif message_params[0] == COMMAND.MESSAGE and pub_key:
                    if (message_params[1] in rooms
                            and pub_key in rooms[message_params[1]]['users']):
                        if message_params[1] in rooms_history:
                            rooms_history[message_params[1]].append(msg)
                        else:
                            rooms_history[message_params[1]] = [msg]
                        for user_public_key in rooms[
                                message_params[1]]['users']:
                            if (user_public_key in online
                                    and user_public_key != pub_key):
                                online[user_public_key]['socket'].send_str(
                                    base64.b64encode(
                                        online[user_public_key]
                                        ['session'].wrap(msg.encode(
                                            "UTF-8"))).decode("UTF-8"))
                            else:
                                if user_public_key in history:
                                    history[user_public_key].append(msg)
                                else:
                                    history[user_public_key] = [msg]
                    else:
                        ws_response.send_str('{} {}'.format(
                            COMMAND.MESSAGE_ERROR, message_params[1]))
                elif message_params[
                        0] == COMMAND.MESSAGE_KEY_ROTATE and pub_key:
                    if (message_params[1] in rooms
                            and pub_key == rooms[message_params[1]]['owner']):
                        rooms_history[message_params[1]] = [msg]
                        for user_public_key in rooms[
                                message_params[1]]['users']:
                            if (user_public_key in online
                                    and user_public_key != pub_key):
                                online[user_public_key]['socket'].send_str(
                                    base64.b64encode(
                                        online[user_public_key]
                                        ['session'].wrap(msg.encode(
                                            "UTF-8"))).decode("UTF-8"))
                            else:
                                if user_public_key in history:
                                    history[user_public_key].append(msg)
                                else:
                                    history[user_public_key] = [msg]
                    else:
                        ws_response.send_str('{} {}'.format(
                            COMMAND.MESSAGE_ERROR, message_params[1]))
                elif message_params[0] == COMMAND.PUBLIC_KEY:
                    pub_key = message_params[1]
                    online[pub_key] = {
                        'socket': ws_response,
                        'session': session
                    }
                    if pub_key in history:
                        for history_message in history[pub_key]:
                            ws_response.send_str(
                                base64.b64encode(
                                    session.wrap(
                                        history_message.encode(
                                            "UTF-8"))).decode("UTF-8"))
                        history[pub_key] = []
                else:
                    ws_response.send_str(
                        base64.b64encode(
                            session.wrap('{} malformed request'.format(
                                COMMAND.ERROR).encode("UTF-8"))).decode(
                                    "UTF-8"))
        elif message.tp == web.MsgType.closed or message.tp == web.MsgType.close:
            if pub_key in online:
                del online[pub_key]
                logger.info('connection closed')
                break
            else:
                ws_response.send_str('{} malformed request'.format(
                    COMMAND.ERROR))
                if 'msg' in locals():
                    logger.info('error:{}'.format(msg))
                    if pub_key in online:
                        del online[pub_key]
                        logger.info('closed')
    return ws_response
        self.socket.sendall(message);

    def receive(self, buffer_length):                        #receive callback
        a=self.socket.recv(buffer_length);
        return a;

    def get_pub_key_by_id(self, user_id):                #necessary callback
        return user_id; 


start=time.time();
for i in range(1, 10000):
        transport_ = transport();
        alg="EC";
        obj = skeygen.themis_gen_key_pair(alg);
        session=ssession.ssession(obj.export_public_key(), obj.export_private_key(), transport_);
        data = session.connect();
        while session.is_established() != True:
            data = session.receive();


        comparator=scomparator.scomparator(b"password");
        data=comparator.begin_compare()
        session.send(("GET /themis-sc-auth/ HTTP/1.1\r\nUser-Agent: curl/7.38.0\r\nAuthorization: Themis andrey "+base64.b64encode(data).decode("UTF-8")+"\r\nHost: 127.0.0.1:8080\r\nAccept: */*\r\n\r\n").encode("UTF-8"));
        headers= session.receive().decode("UTF-8").split('\r\n');
        data = comparator.proceed_compare(base64.b64decode(dict(x.split(':') for x in headers[1:-4])["Authorization"]))
        session.send(("GET /themis-sc-auth/ HTTP/1.1\r\nUser-Agent: curl/7.38.0\r\nAuthorization: Themis "+base64.b64encode(data).decode("UTF-8")+"\r\nHost: 127.0.0.1:8080\r\nAccept: */*\r\n\r\n").encode("UTF-8"));
        headers= session.receive().decode("UTF-8").split('\r\n');
        data = comparator.proceed_compare(base64.b64decode(dict(x.split(':') for x in headers[1:-6])["Authorization"]))

        if comparator.result() == scomparator.SCOMPARATOR_CODES.NOT_MATCH: