示例#1
0
def login_for_apps():
    """Login for API access only"""
    if request.method == "GET":
        session['unsigned_access_token'] = random_token()
        session['logged_in'] = False
        return jsonify({
            "token":
            session['unsigned_access_token'],
            "signature":
            server_key.sign_message(session['unsigned_access_token'])
        })
    elif request.method == "POST":
        # Client posts it's login name and a signed token.
        data = request.get_json()
        # Verify signed token against stored public key for that name.
        pubkey = APIKey(db.get_pub_key(data['login'])['pubkey'])
        try:
            pubkey.verify_message(session['unsigned_access_token'],
                                  data['signature'])
        except Exception, e:
            session['logged_in'] = False
            del session['unsigned_access_token']
            return make_response(jsonify({'error': 'Bad token signature.'}),
                                 401)
        # Token has valid signature, grant login:
        session['user_id'] = data['login']
        session['logged_in'] = True
        # Mark this session as safe to bypass csrf protection, due to the ECDSA authentication:
        session['bypass_csrf'] = True
        return jsonify({'success': 'Logged in'})
示例#2
0
 def __authenticate(self, command):
     """Sign the token the server asked us to sign.
     Send it back.
     Give the server a token of our own to sign.
     Verify it."""
     assert command.get('action') == 'authenticate'
     data = {'signature': self.__client_key.sign_message(command['token']),
             'cluster':   self.__cluster_name}
     response = command.respond(**data)
     if not response.get('authenticated'):
         raise UnauthenticatedError("Our peer could not validate our signed auth token")
     # cool, the server authenticated us, now we need to
     # authenticate the server:
     token = random_token()
     cmd = Command.new(self.socket(), action='authenticate', token=token)
     response = cmd.send()
     signature = response['signature']
     # Verify the signature, raises BadSignatureError if it fails:
     try:
         self.__server_key.verify_message(token, signature)
     except:
         response.respond(message='Bad Signature of token for authentication', done=True)
         log.error('server provided bad signature for auth token')
         raise
     response.respond(authenticated=True, done=True)
示例#3
0
 def __authenticate(self, command):
     """Sign the token the server asked us to sign.
     Send it back.
     Give the server a token of our own to sign.
     Verify it."""
     assert command.get('action') == 'authenticate'
     data = {'signature' :self.__client_key.sign_message(command['token']),
             'cluster': self.__cluster_name}
     response = command.respond(**data)
     if response.get('authenticated') != True:
         raise UnauthenticatedError("Our peer could not validate our signed auth token")
     # cool, the server authenticated us, now we need to
     # authenticate the server:
     token = random_token()
     cmd = Command.new(self.ws, action='authenticate', token=token)
     response = cmd.send()
     signature = response['signature']
     # Verify the signature, raises BadSignatureError if it fails:
     try:
         self.__server_key.verify_message(token, signature)
     except:
         response.respond(message='Bad Signature of token for authentication', done=True)
         log.error('server provided bad signature for auth token')
         raise
     response.respond(authenticated=True, done=True)
示例#4
0
def login_for_apps():
    """Login for API access only"""
    if request.method == "GET":
        session["unsigned_access_token"] = random_token()
        session["logged_in"] = False
        return jsonify(
            {
                "token": session["unsigned_access_token"],
                "signature": server_key.sign_message(session["unsigned_access_token"]),
            }
        )
    elif request.method == "POST":
        # Client posts it's login name and a signed token.
        data = request.get_json()
        # Verify signed token against stored public key for that name.
        pubkey = APIKey(db.get_pub_key(data["login"])["pubkey"])
        try:
            pubkey.verify_message(session["unsigned_access_token"], data["signature"])
        except Exception, e:
            session["logged_in"] = False
            del session["unsigned_access_token"]
            return make_response(jsonify({"error": "Bad token signature."}), 401)
        # Token has valid signature, grant login:
        session["user_id"] = data["login"]
        session["logged_in"] = True
        # Mark this session as safe to bypass csrf protection, due to the ECDSA authentication:
        session["bypass_csrf"] = True
        return jsonify({"success": "Logged in"})
示例#5
0
    def authenticate():
        token_to_sign = random_token()
        cmd = Command.new(ws, action='authenticate', token=token_to_sign)
        response = cmd.send()
        context['cluster'] = cluster = response['cluster']
        client_pubkey = db.get_pub_key(cluster)
        client_apikey = APIKey(client_pubkey['pubkey'])
        
        # Verify the client correctly signed the token:
        try:
            client_apikey.verify_message(token_to_sign, response.get('signature'))
        except:
            response.respond(message='Bad Signature of token for authentication', done=True)
            log.error('client provided bad signature for auth token')
            raise

        response.respond(authenticated=True, done=True)

        # Client will ask us to authenticate too:
        command = receive_data(ws)
        assert command.get('action') == 'authenticate'
        data = {'signature' :context['apikey'].sign_message(command['token'])}
        response = command.respond(**data)
        if response.get('authenticated') != True:
            raise UnauthenticatedError("Our peer could not validate our signed auth token")
示例#6
0
    def authenticate():
        token_to_sign = random_token()
        cmd = Command.new(ws, action='authenticate', token=token_to_sign)
        response = cmd.send()
        context['cluster'] = cluster = response['cluster']
        client_pubkey = db.get_pub_key(cluster)
        client_apikey = APIKey(client_pubkey['pubkey'])

        # Verify the client correctly signed the token:
        try:
            client_apikey.verify_message(token_to_sign,
                                         response.get('signature'))
        except:
            response.respond(
                message='Bad Signature of token for authentication', done=True)
            log.error('client provided bad signature for auth token')
            raise

        response.respond(authenticated=True, done=True)

        # Client will ask us to authenticate too:
        command = receive_data(ws)
        assert command.get('action') == 'authenticate'
        data = {'signature': context['apikey'].sign_message(command['token'])}
        response = command.respond(**data)
        if response.get('authenticated') != True:
            raise UnauthenticatedError(
                "Our peer could not validate our signed auth token")
示例#7
0
def create_app_config(config_path=SERVER_CONFIG_PATH):
    config = ConfigParser.RawConfigParser()
    config.read(config_path)
    # Ensure app has secret key for signing cookies:
    if not config.has_section('server'):
        config.add_section('server')
    if not config.has_option('server','app_secret'):
        config.set('server','app_secret', random_token())
    # Ensure app has server url:
    if not config.has_option('server', 'url'):
        config.set('server', 'url', 'http://localhost:8000')
    with open(config_path, 'w') as f:
        config.write(f)
    return config
示例#8
0
def create_app_config(config_path=SERVER_CONFIG_PATH):
    config = ConfigParser.RawConfigParser()
    config.read(config_path)
    # Ensure app has secret key for signing cookies:
    if not config.has_section('server'):
        config.add_section('server')
    if not config.has_option('server', 'app_secret'):
        config.set('server', 'app_secret', random_token())
    # Ensure app has server url:
    if not config.has_option('server', 'url'):
        config.set('server', 'url', 'http://localhost:8000')
    with open(config_path, 'w') as f:
        config.write(f)
    return config
示例#9
0
 def generate_csrf_token():
     if '_csrf_token' not in session:
         session['_csrf_token'] = random_token()
     return session['_csrf_token']
示例#10
0
 def generate_csrf_token():
     if '_csrf_token' not in session:
         session['_csrf_token'] = random_token()
     return session['_csrf_token']