def handle_command(self, command):
        """Reacts to received commands (callback).
        Will separate args and call appropriate handlers."""

        # Meanwhile, go on with commands...
        RemoteListener.STREAM.read_until(b'\n', self.handle_command)

        command = command.strip('\n')

        if command:
            args = command.split(b' ')
            action = args[0]
            try:
                handler = RemoteListener.ACTIONS[action]
            except KeyError:
                LOG.warning('Remote received unknown command `%s`', args)
            else:
                # Execute handler (index 0) with args (index 1->end)
                try:
                    handler(*args[1:])
                except TypeError:
                    LOG.error(
                        'Command `%s` called with wrong number of args', action
                    )
        else:
            LOG.warning('Remote received empty command.')
Exemple #2
0
def main():
    """Entry point for bitsd."""
    enable_pretty_logging()

    try:
        parse_config_file('/etc/bitsd.conf')
    except IOError:
        LOG.warning('Config file not found, using defaults and command line.')

    try:
        parse_command_line()
    except tornado.options.Error as error:
        sys.stderr.write('{}\n'.format(error))
        sys.exit(0)

    persistence.start()
    server.start()
    listener.start()

    # Add signal handlers...
    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)

    if not options.log_requests:
        logging.getLogger("tornado.access").setLevel(logging.WARNING)

    tornado.ioloop.IOLoop.instance().start()
def main():
    """Entry point for bitsd."""
    enable_pretty_logging()

    try:
        parse_config_file('/etc/bitsd.conf')
    except IOError:
        LOG.warning('Config file not found, using defaults and command line.')

    try:
        parse_command_line()
    except tornado.options.Error as error:
        sys.stderr.write('{}\n'.format(error))
        sys.exit(0)

    persistence.start()
    server.start()
    listener.start()

    # Add signal handlers...
    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)

    if not options.log_requests:
        logging.getLogger("tornado.access").setLevel(logging.WARNING)

    tornado.ioloop.IOLoop.instance().start()
Exemple #4
0
def sig_handler(sig, frame):
    """Catch signal and init callback.

    Reference:
    http://codemehanika.org/blog/2011-10-28-graceful-stop-tornado.html
    """
    LOG.warning('Caught signal: %s', sig)
    tornado.ioloop.IOLoop.instance().add_callback(shutdown)
def sig_handler(sig, frame):
    """Catch signal and init callback.

    Reference:
    http://codemehanika.org/blog/2011-10-28-graceful-stop-tornado.html
    """
    LOG.warning('Caught signal: %s', sig)
    tornado.ioloop.IOLoop.instance().add_callback(shutdown)
 def handle_stream(self, stream, address):
     """Handles inbound TCP connections asynchronously."""
     LOG.info("New connection from Fonera.")
     if address[0] != options.control_remote_address:
         LOG.error(
             "Connection from `%s`, expected from `%s`. Ignoring.",
                 address,
                 options.control_remote_address
         )
         return
     if RemoteListener.STREAM is not None:
         LOG.warning("Another connection was open, closing the previous one.")
         RemoteListener.STREAM.close()
     RemoteListener.STREAM = stream
     RemoteListener.STREAM.read_until(b'\n', self.handle_command)
    def post(self):
        username = self.get_argument("username")
        password = self.get_argument("password")
        ip_address = self.request.remote_ip
        next = self.get_argument("next", "/")
        captcha_challenge = self.get_argument("recaptcha_challenge_field", "")
        captcha_response = self.get_argument("recaptcha_response_field", "")
        has_recaptcha = captcha_challenge or captcha_response

        with session_scope() as session:
            try:
                verified = verify(session, username, password, ip_address, has_recaptcha, captcha_challenge, captcha_response)
            except DoSError as error:
                LOG.warning("DoS protection: %s", error)
                self.log_offender_details()
                self.render(
                    'templates/login.html',
                    next=next,
                    message="Tentativi dal tuo IP over 9000...",
                    show_recaptcha=True,
                    previous_attempt_incorrect=has_recaptcha
                )
                return

        if verified:
            self.set_secure_cookie(
                self.USER_COOKIE_NAME,
                username,
                expires_days=options.cookie_max_age_days
            )
            LOG.info("Authenticating user %r", username)
            self.redirect(next)
        else:
            LOG.warning("Failed authentication for user %r", username)
            self.log_offender_details()
            self.render(
                'templates/login.html',
                next=next,
                message="Password/username sbagliati!",
                show_recaptcha=has_recaptcha,
                # If we have a captcha at this point, it means we already failed once
                previous_attempt_incorrect=True
            )
Exemple #8
0
    def post(self):
        username = self.get_argument("username", None)
        password = self.get_argument("password", None)
        next = self.get_argument("next", "/")

        with session_scope() as session:
            authenticated = verify(session, username, password)

        if authenticated:
            self.set_secure_cookie(self.USER_COOKIE_NAME,
                                   username,
                                   expires_days=options.cookie_max_age_days)
            LOG.info("Authenticating user `{}`".format(username))
            self.redirect(next)
        else:
            LOG.warning("Wrong authentication for user `{}`".format(username))
            self.render('templates/login.html',
                        next=next,
                        message="Password/username sbagliati!")
Exemple #9
0
    def post(self):
        username = self.get_argument("username", None)
        password = self.get_argument("password", None)
        next = self.get_argument("next", "/")

        with session_scope() as session:
            authenticated = verify(session, username, password)

        if authenticated:
            self.set_secure_cookie(
                self.USER_COOKIE_NAME,
                username,
                expires_days=options.cookie_max_age_days
            )
            LOG.info("Authenticating user `{}`".format(username))
            self.redirect(next)
        else:
            LOG.warning("Wrong authentication for user `{}`".format(username))
            self.render(
                'templates/login.html',
                next=next,
                message="Password/username sbagliati!"
            )
    def post(self):
        now = datetime.now()
        remote_ip = self.request.remote_ip

        with session_scope() as session:
            last = query.get_last_login_attempt(session, remote_ip)
            if last is None:
                last = LoginAttempt(None, remote_ip)
                persist(session, last)
            else:
                if (now - last.timestamp) < timedelta(seconds=options.mac_update_interval):
                    LOG.warning("Too frequent attempts to update, remote IP address is %s", remote_ip)
                    raise HTTPError(403, "Too frequent")
                else:
                    last.timestamp = now
                    persist(session, last)

        try:
            password = self.get_argument("password")
            macs = self.get_argument("macs")
        except MissingArgumentError:
            LOG.warning("MAC update received malformed parameters: %s", self.request.arguments)
            raise HTTPError(400, "Bad parameters list")

        if not secure_compare(password, options.mac_update_password):
            LOG.warning("Client provided wrong password for MAC update!")
            raise HTTPError(403, "Wrong password")

        LOG.info("Authorized request to update list of checked-in users from IP address %s", remote_ip)

        macs = json.loads(macs)

        with session_scope() as session:
            names = session.\
                query(distinct(User.name)).\
                filter(User.userid == MACToUser.userid).\
                filter(MACToUser.mac_hash .in_ (macs)).\
                all()

        MACUpdateHandler.ROSTER = [n[0] for n in names]
        LOG.debug("Updated list of checked in users: %s", MACUpdateHandler.ROSTER)
Exemple #11
0
 def on_message(self, message):
     """Disconnect clients sending data (they should not)."""
     LOG.warning('Client sent a message: disconnected.')
 def log_offender_details(self):
     userAgent = self.request.headers.get("User-Agent", '<unknown>')
     remoteIp = self.request.remote_ip
     LOG.warning("Request came from %s, user agent is '%s'", remoteIp, userAgent)
Exemple #13
0
 def on_message(self, message):
     """Disconnect clients sending data (they should not)."""
     LOG.warning('Client sent a message: disconnected.')