Exemple #1
0
    def start_listening(self):
        def run_bash(cmd):
            return subprocess.check_output(['bash', '-c', cmd])

        def get_pack(msg):
            porta = self.MCAST_PORT
            ram = run_bash("head -2 /proc/meminfo | grep -Po '[0-9]+'"
                           + "|sed -e ':a' -e 'N' -e '$!ba' -e 's/\\n/ /g'"
                           + "|awk -F ' ' '{print ((($1 - $2) / $1) * 100)}'")

            bandwidth = int(run_bash("netstat | grep tcp | wc -l")
                            ) / int(run_bash("ulimit -n")) * 100
            cpu = run_bash(
             "uptime | awk -F'[a-z]:' '{ print $2}' | awk -F ',' '{print $1}'")
            return create_packet({'ip': "", 'porta': str(porta), 'ram': ram.decode('utf-8'),
                                  'cpu': cpu.decode('utf-8'), 'rtt': msg['rtt'],
                                  'bandwidth': bandwidth})
        while True:
            request, to = self.socket.recvfrom(10240)
            packet = json.loads(decrypt(request).decode())
            request = check_packet(packet)
            if request:
                if request['n_packet'] > self.n_packet:
                    self.n_packet = request['n_packet']
                    print(request, to)
                    msg = (str(get_pack(request))).encode()
                    time.sleep(randint(0, 10))
                    self.socket.sendto(encrypt(msg), to)
Exemple #2
0
    def get(self, encrypted_credentials):

        error = {}

        log.debug(f'encrypted_credentials: {encrypted_credentials}')
        try:
            credentials = json.loads(auth.decrypt(encrypted_credentials))
            verified = users_table.verify(credentials['usr'],
                                          credentials['psw'])
            assert (verified), 'unverified user or password'
            token = auth.encode_auth_token(credentials['sys'],
                                           credentials['usr'],
                                           credentials['psw'],
                                           credentials['grp'])
            log.debug(f'credentials: {credentials}, verified: {verified}')

        except Exception as e:
            error['authorization'] = str(e)
        finally:
            if len(error) > 0:
                abort(401, description=error)
        result = {'token': token}
        log.debug('')

        response = make_response(json.dumps(result))
        return response
Exemple #3
0
def test():
  print "DATABASE TESTS\n"
  conn = auth.initDB("test.db")
  random_number = random.randint(0, 500)
  print "Set salt: %d" % random_number
  auth.setHex(conn, auth.SALT, "Mr. Mustafa", random_number)
  retrieved_random_number = auth.getHex(conn, auth.SALT, "Mr. Mustafa")
  print "Got salt: %d" % retrieved_random_number
  assert (retrieved_random_number == random_number), "setHex/getHex do not match"
  
  print "\n\nKEY GENERATION TESTS\n"
  keydict = auth.generateKey(conn, "Mr. Mustafa", random.randint(0, 500))
  print "Generated session key %s" % auth.hexify(keydict["K"])
  print "Verification hash is %d" % keydict["M"]

  print "\n\nENCRYPTION TESTS\n"
  message = """
    And Aaron would have to explain
    about the modular design of the coffins
    and how they could be folded up
    and put inside one another
    "They are not one use only", he would say
    "They are recyclable"
  """
  
  print "\nTrue encryption\n"
  
  encrypted = auth.encrypt(keydict["K"], message)
  print "Encrypted to \"%s\"" % encrypted
  decrypted = auth.decrypt(keydict["K"], encrypted)
  print "Decrypted to \"%s\"" % decrypted
  assert (decrypted == message), "encrypt/decrypt do not match"
  
  print "\nFalse encryption\n"

  encrypted = auth.encrypt("Incorrect keyIncorrect keyIncorr", message)
  print "False encrypted to \"%s\"" % encrypted
  decrypted = auth.decrypt(keydict["K"], encrypted)
  assert (decrypted == None), "Accepted false information"
  if (decrypted == None):
    print "Rejected false information"
Exemple #4
0
 def response(self):
     while True:
         p, ip = self.s.recvfrom(1024)
         p = eval(decrypt(p).decode())
         msg = check_packet((p))
         if msg:
             msg['rtt'] = (float(time.time()) - float(msg['rtt']))
             msg['ip'] = ip[0]
             msg['auth'] = p['auth']
             server_info = self.table.build_server(**msg)
             print(server_info)
             self.table.add_server(server_info)
Exemple #5
0
def index():
    if 'user_id' not in session and app.config[
            'COOKIE_NAME'] in request.cookies:
        session['facebook_token'] = (decrypt(
            request.cookies.get(app.config['COOKIE_NAME'])), '')

        try:
            get_facebook_data()
        except:
            pass

    return render_template('index.html')
Exemple #6
0
Fichier : app.py Projet : hmac/msg
def login2():
    name = request.form['username']
    p2 = request.form['server_secret']
    sig = request.form['signature']
    server_secret = auth.decrypt(b64d(p2))
    genuine = auth.verify(key_for(name), server_secret, b64d(sig))
    if genuine:
        session['username'] = name
        app.logger.info("%s successfully logged in" % (name,))
        return "Success"
    else:
        abort(401)
Exemple #7
0
def mypage():
    if 'user_id' not in session:
        if app.config['COOKIE_NAME'] in request.cookies:
            session['facebook_token'] = (decrypt(
                request.cookies.get(app.config['COOKIE_NAME'])), '')

            try:
                get_facebook_data()
            except:
                pass
        else:
            return redirect(url_for('index'))

    return render_template('index.html')
Exemple #8
0
def login():
    global cookie
    resp = post("login", {'username': username})
    if resp.status_code != 200:
      return False
    data = json.loads(resp.text)
    client_secret = b64d(data['client_secret'])
    secret = auth.decrypt(client_secret)
    sig = auth.sign(secret)
    resp = post("authorise", {'username': username, 'server_secret': data['server_secret'], 'signature': b64e(str(sig))})
    if resp.status_code == 200:
      cookie = resp.cookies
      return True
    return False
Exemple #9
0
def get_user_details(github_token=None, auth_token=None, bypass_cache=False, _cache={}):

    """ auth_token is simply github_token encrypted """

    if not config.GITHUB_AUTH_ENABLED:
        return {
            "login": config.LOCAL_LOGIN,
            "name": config.LOCAL_USERNAME,
            "email": config.LOCAL_EMAIL,
            "avatar_url": "",
        }

    if auth_token and auth_token in _cache:
        return _cache[auth_token]

    if not github_token:
        if not auth_token:
            auth_token = request.headers.get("x-bilara-auth-token")
            print(auth_token)

        github_token = auth.decrypt(auth_token)

    if github_token:
        try:
            gh = Github(github_token)
            gh_user = gh.get_user()
            user = {
                "login": gh_user.login,
                "name": gh_user.name or gh_user.login,
                "avatar_url": gh_user.avatar_url,
            }
        except BadCredentialsException as e:
            logging.exception(e)
            raise

        try:
            gh_emails = gh_user.get_emails()
            if gh_emails:
                user["email"] = gh_emails[0]["email"]

        except BadCredentialsException as e:
            logging.exception(e)
            user["email"] = ""
    else:
        raise ValueError("No github token but GITHUB_AUTH_ENABLED is True")

    if auth_token:
        _cache[auth_token] = user
    return user
Exemple #10
0
Fichier : app.py Projet : hmac/msg
def authenticate_message(form):
    keyB = auth.decrypt(b64d(form['key']))
    payload = b64d(form['payload'])
    payload = auth.aes_decrypt(payload, keyB)
    payload = json.loads(payload)
    sender, recipient, body, keyA, sig, keyA2 = payload['sender'], payload['recipient'], payload['body'], payload['key'], payload['signature'], payload['sender_key']
    sender_user = db.get_user(sender)
    recipient_user = db.get_user(recipient)
    if not (sender_user and recipient_user):
        return (False,)
    sig = b64d(sig)
    if auth.verify(key_for(sender), sender+recipient+body, sig):
        return (True, (sender, recipient, body, keyA, keyA2))
    else:
        return (False,())
def receive(token, queue, retry, debug=False):
    '''
    Get the message from the queue, display the decrypted text.
    '''
    if status(debug):
        LOGGER.info('[keybase-status] client-up; signed-in')
    else:
        LOGGER.error('[keybase-status] client-down/sigend-out')
        return

    try:
        while True:
            job = queue.get_job(['in'], count=1, nohang=False)

            # Wait for a valid job.
            if len(job) > 0:
                queue.ack_job(job[0][1])
                LOGGER.info('[received-job]: %s', repr(job[0]))
                signed = get(job[0][2].strip(), token, debug)
                # Check for a valid signature.
                if signed is None:
                    LOGGER.error('[gist-fetch] %s not found!', job[0][2])
                    continue
                # If the message is verified, decrypt it.
                flag, who, encrypted = verify(signed, debug)

                if flag:
                    LOGGER.info('[keybase-verify] message signed by %s', who)
                    who, text = decrypt(encrypted, debug)

                    if who is not None:
                        LOGGER.info(('[keybase-decrypt] message encrypted'
                                     ' by %s'), who)
                        LOGGER.info(('[keybase-decrypt] plain-text content: '
                                     '\n%s'), text)
                    else:
                        LOGGER.error('[keybase-decrypt] un-trusted encryption')
                        continue
                else:
                    LOGGER.error('[keybase-verify] unable to verify')
                    continue
            time.sleep(retry)

    except Exception:
        LOGGER.error('[queue] unable to fetch jobs from \'in\'')
Exemple #12
0
    CREATE TABLE IF NOT EXISTS team (id INTEGER PRIMARY KEY ASC, uname TEXT, projects TEXT)
  """)
    u.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT);
  """)

    u.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"], ))

    keyrow = u.fetchone()

    result = {"success": True}

    if keyrow is not None:
        project = auth.decrypt(base64.b64decode(keyrow[2]), qwargs["project"])
        name = qwargs["uname"]

        # Add this project to this user's list of projects
        u.execute("""
      SELECT * FROM team WHERE uname=?
    """, (name, ))
        row = u.fetchone()

        if row is not None:
            current_projects = json.loads(row[2])
            if project in current_projects:
                current_projects = filter(lambda x: x != project,
                                          current_projects)
                u.execute(
                    """
Exemple #13
0
  conn = auth.initDB("/home/daemon/ecc-index/db/users.db")
  c = conn.cursor()
  
  c.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT)
  """)

  c.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"],))

  keyrow = c.fetchone()
  
  if keyrow is not None:
    key = base64.b64decode(keyrow[2])
    new_keyset = json.loads(auth.decrypt(key, qwargs["info"]))
    if new_keyset is not None:
      auth.setHex(conn, auth.VERIFIER, qwargs["uname"], new_keyset["verifier"])
      auth.setHex(conn, auth.SALT, qwargs["uname"], new_keyset["salt"])
      print auth.encrypt(key, json.dumps({
        "success": True
      }))
    else:
      print auth.encrypt(key, json.dumps({
        "success": False,
        "error": "DATA CORRUPTION"
      }))
  else:
    print json.dumps({
      "success": False,
      "error": "NO ESTABLISHED SESSKEY"
Exemple #14
0
  uconn = auth.initDB("/home/daemon/ecc-index/db/users.db")
  
  #Create the session key table if it's not there yet, and delete any old session keys
  u = uconn.cursor()
  u.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT);
  """)
  u.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"],))
  
  keyrow = u.fetchone()

  if keyrow is not None:
    key = base64.b64decode(keyrow[2])
    info = json.loads(auth.decrypt(key, pargs["info"]))
    
    n.execute("""
      INSERT INTO news (title, body, timestamp) VALUES (?, ?, ?)
    """, (info["title"], info["body"], time.time()))
  
    nconn.commit()

    print "Content-type: application/json"
    print ""
    print auth.encrypt(key, json.dumps({
      "success": True
    }))
  else:
    print "Content-type: application/json"
    print ""
Exemple #15
0
  u.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT);
  """)

  u.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"],))

  keyrow = u.fetchone()

  result = {
    "success": True
  }

  if keyrow is not None:
    request_data = json.loads(auth.decrypt(base64.b64decode(keyrow[2]), qwargs["info"]))
    
    if request_data is not None:
      name = request_data["target"]
      project = request_data["project"]
      

      # Add this project to this user's list of projects
      u.execute("""
        SELECT * FROM team WHERE uname=?
      """, (name,))
      row = u.fetchone()

      if row is not None:
        current_projects = json.loads(row[2])
        if project not in current_projects:
Exemple #16
0
def decrypt_message(msg, key):
  key = auth.decrypt(b64d(key))
  return auth.aes_decrypt(b64d(msg), key)
Exemple #17
0
  u.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT);
  """)

  u.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"],))

  keyrow = u.fetchone()

  result = {
    "success": True
  }

  if keyrow is not None:
    project = auth.decrypt(base64.b64decode(keyrow[2]), qwargs["project"])
    name = qwargs["uname"]

    # Add this project to this user's list of projects
    u.execute("""
      SELECT * FROM team WHERE uname=?
    """, (name,))
    row = u.fetchone()

    if row is not None:
      current_projects = json.loads(row[2])
      if project in current_projects:
        current_projects = filter(lambda x: x != project, current_projects)
        u.execute("""
          UPDATE team SET projects=? WHERE id=?
        """, (json.dumps(current_projects), row[0]))
Exemple #18
0
    def processTraditionalRequest(self, request, data):
        client = self.client_address
        events = self.container.events
        clients = self.container.clients

        # check if the request is an event call
        if (events.contains(data['cmd'])):
            func = events.get(data['cmd'])

            response = func(data)
            # send the result to the caller
            request.sendall(createMessage(result=response))

        # check if the request is a query for the service role
        # (PUBLISHER | SUBSCRIBER)
        elif (data['cmd'] == 'ROLE'):
            message = createMessage(role=self.container.role)
            request.sendall(message.encode('UTF8'))

        # check if the caller is requesting a nonce for authorization
        elif (data['cmd'] == 'AUTH'):
            nonce = auth.generateNonce()
            self.container._nonce = nonce
            request.sendall(createMessage(nonce=nonce))

        # check if the caller is requesting authorization for subscription
        elif (data['cmd'] == 'SUBSCRIBE'):
            r = data['nonce'].encode('UTF8')
            m = auth.decrypt(r).decode('UTF8')
            if (m == self.container._nonce):
                # we can consider this subscriber to be authentic
                if (len(data) == 5):  # should be 5 values
                    # data[3] is the group name
                    if (clients.contains(data['group'])):
                        c = clients.get(data['group'])
                        c.append((data['ip'], data['port']))
                    else:
                        c = [(data['ip'], int(data['port']))]
                        clients.append((data['group'], c))
            request.sendall(createMessage(result=0))

        # check if the caller is sending a heartbeat
        elif (data['cmd'] == 'HEARTBEAT'):
            # check if the client is still registered
            response = data['cmd']
            if (len(clients.collection()) == 0):
                response = 'SUBSCRIBE'
            else:
                found = False
                for group in clients.collection():
                    for ip in clients.get(group):
                        if (ip[0] == data['ip'] and ip[1] == data['port']):
                            found = True
                if (not found):
                    response = 'SUBSCRIBE'
            message = createMessage(result=response)
            request.sendall(message)

        elif (data['cmd'] == 'UPDATERAIN'):
            myConnector = mysql(self.container.addr[0], 3306)
            myConnector.connect()
            myConnector.updateWeights('balance', data['constants'])
            myConnector.disconnect()
            message = createMessage(result=0)
            request.sendall(message)

        elif (data['cmd'] == 'CHANGELBMODE'):
            mode = data['mode']
            try:
                self.lbMode = LBMode[mode]
                fp = open('lb.conf', 'w')
                fp.write(mode)
                fp.close()
            except:
                print(mode, "is not a valid load balance mode.")
            message = createMessage(result=0)
            request.sendall(message)

        # check if an instance is running
        elif (data['cmd'] == 'CHECKINSTANCE'):
            virtcon = libvirt.openReadOnly(None)
            error = createMessage(result='error')
            success = createMessage(result='success')
            if (virtcon == None):
                request.sendall(error)
            try:
                virtcon.lookupByName(data['domain'])
                request.sendall(success)
            except:
                request.sendall(error)
            virtcon.close()

        else:
            print('DATA:', data)

        request.close()
        return
Exemple #19
0
  #Enforce one value per query string argument
  for key in qwargs:
    qwargs[key] = qwargs[key][0]
  
  #Connect to the users database
  conn = auth.initDB("/home/daemon/ecc-index/db/users.db")
  
  #Create the session key table if it's not there yet, and delete any old session keys
  c = conn.cursor()
  c.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"],))
  
  key = base64.b64decode(c.fetchone()[2])
  
  print "Content-Type: application/json"
  print ""

  decrypted = auth.decrypt(key, qwargs["message"])

  if decrypted == "SRP_CLIENT_SUCCESS_MESSAGE":
    print json.dumps({
      "message": auth.encrypt(key, "SRP_SERVER_SUCCESS_MESSAGE")
    })
  else:
    print json.dumps({
      "error":True,
      "decrypted":decrypted
    })
Exemple #20
0
  """)
    u.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT);
  """)

    u.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"], ))

    keyrow = u.fetchone()

    result = {"success": True}

    if keyrow is not None:
        request_data = json.loads(
            auth.decrypt(base64.b64decode(keyrow[2]), qwargs["info"]))

        if request_data is not None:
            name = request_data["target"]
            project = request_data["project"]

            # Add this project to this user's list of projects
            u.execute("""
        SELECT * FROM team WHERE uname=?
      """, (name, ))
            row = u.fetchone()

            if row is not None:
                current_projects = json.loads(row[2])
                if project not in current_projects:
                    current_projects.append(project)
Exemple #21
0
    conn = auth.initDB("/home/daemon/ecc-index/db/users.db")
    c = conn.cursor()

    c.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT)
  """)

    c.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"], ))

    keyrow = c.fetchone()

    if keyrow is not None:
        key = base64.b64decode(keyrow[2])
        sig = auth.decrypt(key, qwargs["signature"])
        if sig == "SRP_LOGOUT_COMMAND":
            c.execute("""
        DELETE FROM keys WHERE uname=?
      """, (qwargs["uname"], ))
            conn.commit()
            print json.dumps({"success": True})
        else:
            # The client's session key is already expired, so we do not log them out on the server.
            # However, the client can feel safe that thier session key is no longer needed.
            print json.dumps({"success": True, "error": "NO KEY DELETED"})
    else:
        # There is no server key to match the client one, so something has gone very wrong.
        print json.dumps({
            "success": False,
            "error": "NO ESTABLISHED SESSKEY",
Exemple #22
0
  conn = auth.initDB("/home/daemon/ecc-index/db/users.db")
  c = conn.cursor()
  
  c.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT)
  """)

  c.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"],))

  keyrow = c.fetchone()
  
  if keyrow is not None:
    key = base64.b64decode(keyrow[2])
    sig = auth.decrypt(key, qwargs["signature"])
    if sig == "SRP_LOGOUT_COMMAND":
      c.execute("""
        DELETE FROM keys WHERE uname=?
      """, (qwargs["uname"],))
      conn.commit()
      print json.dumps({
        "success": True
      })
    else:
      # The client's session key is already expired, so we do not log them out on the server.
      # However, the client can feel safe that thier session key is no longer needed.
      print json.dumps({
        "success": True,
        "error": "NO KEY DELETED"
      })
Exemple #23
0
  def do_GET(self):
    conn = auth.initDB("test.db")
    parsed_url = urlparse.urlparse(self.path)
    path = parsed_url.path.split("/")
    qwargs = urlparse.parse_qs(parsed_url.query)
      
    #Enforce one value per query string arg
    for key in qwargs:
      qwargs[key] = qwargs[key][0]
    
    if (len(path) == 0 or path[1] == "index.html"):
      self.send_response(200)
      self.send_header("Content-Type", "text/html")
      self.end_headers()
      
      index_file = open("test.html", "r")
      self.wfile.write(index_file.read())
      index_file.close()
    elif (path[1] == "jslib"):
      self.send_response(200)
      self.send_header("Content-Type", "text/html")
      self.end_headers()
      
      js_file = open("/".join(path), "r")
      self.wfile.write(js_file.read())
      js_file.close()
    elif (path[1] == "register"):
      self.send_response(200)
      self.send_header("Content-Type", "application/json")
      self.end_headers()
      
      self.wfile.write(json.dumps({
        "success": auth.createUser(conn, qwargs["uname"], qwargs["verifier"], qwargs["salt"])
      }))
    elif (path[1] == "authenticate"):
      self.send_response(200)
      self.send_header("Content-Type", "application/json")
      self.end_headers()

      kdict = auth.generateKey(conn, qwargs["uname"], int(qwargs["A"], 16))
      session_keys[qwargs["uname"]] = kdict["K"]
      key_verifiers[qwargs["uname"]] = kdict["M"]

      print "Generated sesssion key %s." % auth.hexify(kdict["K"])

      self.wfile.write(json.dumps({
        "s": kdict["s"],
        "B": kdict["B"]
      }))
    elif (path[1] == "echo"):
      self.send_response(200)
      self.send_header("Content-Type", "application/json")
      self.end_headers()

      self.wfile.write(json.dumps({
        "cleartext":auth.decrypt(session_keys[qwargs["uname"]], qwargs["message"])
      }))
    else:
      self.send_response(404)
      self.send_header("Content-Type", "text/plain")
      self.end_headers()

      self.wfile.write("What are you talking about")
Exemple #24
0
    def processTraditionalRequest(self, request, data):
        client = self.client_address
        events = self.container.events
        clients = self.container.clients

        # check if the request is an event call
        if (events.contains(data['cmd'])):
            func = events.get(data['cmd'])

            response = func(data)
            # send the result to the caller
            request.sendall(createMessage(result=response))

        # check if the request is a query for the service role
        # (PUBLISHER | SUBSCRIBER)
        elif (data['cmd'] == 'ROLE'):
            message = createMessage(role=self.container.role)
            request.sendall(message.encode('UTF8'))

        # check if the caller is requesting a nonce for authorization
        elif (data['cmd'] == 'AUTH'):
            nonce = auth.generateNonce()
            self.container._nonce = nonce
            request.sendall(createMessage(nonce=nonce))

        # check if the caller is requesting authorization for subscription
        elif (data['cmd'] == 'SUBSCRIBE'):
            r = data['nonce'].encode('UTF8')
            m = auth.decrypt(r).decode('UTF8')
            if (m == self.container._nonce):
                # we can consider this subscriber to be authentic
                if (len(data) == 5): # should be 5 values
                    # data[3] is the group name
                    if (clients.contains(data['group'])):
                        c = clients.get(data['group'])
                        c.append((data['ip'], data['port']))
                    else:
                        c = [(data['ip'], int(data['port']))]
                        clients.append((data['group'], c))
            request.sendall(createMessage(result=0)) 

        # check if the caller is sending a heartbeat
        elif (data['cmd'] == 'HEARTBEAT'):
            # check if the client is still registered
            response = data['cmd']
            if (len(clients.collection()) == 0):
               response = 'SUBSCRIBE'
            else:
               found = False
               for group in clients.collection():
                  for ip in clients.get(group):
                     if (ip[0] == data['ip'] and ip[1] == data['port']):
                        found = True
               if (not found):
                  response = 'SUBSCRIBE'
            message = createMessage(result=response)
            request.sendall(message)

        elif (data['cmd'] == 'UPDATERAIN'):
            myConnector = mysql(self.container.addr[0], 3306)
            myConnector.connect()
            myConnector.updateWeights('balance', data['constants'])
            myConnector.disconnect()
            message = createMessage(result=0)
            request.sendall(message)

        elif (data['cmd'] == 'CHANGELBMODE'):
            mode = data['mode']
            try:
               self.lbMode = LBMode[mode] 
               fp = open('lb.conf', 'w')
               fp.write(mode)
               fp.close()
            except:
               print(mode,"is not a valid load balance mode.")
            message = createMessage(result=0)
            request.sendall(message)

        # check if an instance is running
        elif (data['cmd'] == 'CHECKINSTANCE'):
            virtcon = libvirt.openReadOnly(None)
            error = createMessage(result='error')
            success = createMessage(result='success')
            if (virtcon == None):
               request.sendall(error)
            try:
               virtcon.lookupByName(data['domain'])
               request.sendall(success)
            except:
               request.sendall(error)
            virtcon.close()

        else:
            print('DATA:',data)

        request.close()
        return
Exemple #25
0
    conn = auth.initDB("/home/daemon/ecc-index/db/users.db")
    c = conn.cursor()

    c.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT)
  """)

    c.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"], ))

    keyrow = c.fetchone()

    if keyrow is not None:
        key = base64.b64decode(keyrow[2])
        info = json.loads(auth.decrypt(key, qwargs["info"]))

        if info is not None:
            #Create the user and tell the client whether or not this was successfull
            print auth.encrypt(
                key,
                json.dumps({
                    "success":
                    auth.createUser(conn, info["uname"], info["verifier"],
                                    info["salt"])
                }))

            conn.commit()
            conn.close()
        else:
            print auth.encrypt(key, json.dumps({"error": "DATA CORRUPTION"}))
Exemple #26
0
    conn = auth.initDB("/home/daemon/ecc-index/db/users.db")
    c = conn.cursor()

    c.execute("""
    CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT)
  """)

    c.execute("""
    SELECT * FROM keys WHERE uname=?
  """, (qwargs["uname"], ))

    keyrow = c.fetchone()

    if keyrow is not None:
        key = base64.b64decode(keyrow[2])
        new_keyset = json.loads(auth.decrypt(key, qwargs["info"]))
        if new_keyset is not None:
            auth.setHex(conn, auth.VERIFIER, qwargs["uname"],
                        new_keyset["verifier"])
            auth.setHex(conn, auth.SALT, qwargs["uname"], new_keyset["salt"])
            print auth.encrypt(key, json.dumps({"success": True}))
        else:
            print auth.encrypt(
                key, json.dumps({
                    "success": False,
                    "error": "DATA CORRUPTION"
                }))
    else:
        print json.dumps({"success": False, "error": "NO ESTABLISHED SESSKEY"})