コード例 #1
0
ファイル: __main__.py プロジェクト: jpylypiw/easywall
    def __init__(self, debug: bool = False) -> None:
        """TODO: Doku."""
        self.cfg_log = Config(LOG_CONFIG_PATH)
        loglevel = self.cfg_log.get_value("LOG", "level")
        to_stdout = self.cfg_log.get_value("LOG", "to_stdout")
        to_files = self.cfg_log.get_value("LOG", "to_files")
        logpath = self.cfg_log.get_value("LOG", "filepath")
        logfile = self.cfg_log.get_value("LOG", "filename")
        self.log = Log(str(loglevel), bool(to_stdout), bool(to_files),
                       str(logpath), str(logfile))

        info("starting easywall-web")

        self.cfg = Config(CONFIG_PATH)

        if debug is True:
            info("loading Flask debug configuration")
            APP.config.from_object('easywall.web.__main__.DevelopmentConfig')
        else:
            info("loading Flask production configuration")
            APP.config.from_object('easywall.web.__main__.ProductionConfig')

        self.rules_handler = RulesHandler()

        self.login_attempts = self.cfg.get_value("WEB", "login_attempts")
        self.login_bantime = self.cfg.get_value("WEB", "login_bantime")
        self.ip_ban = IpBan(app=APP,
                            ban_count=self.login_attempts,
                            ban_seconds=self.login_bantime,
                            ipc=True)
        self.ip_ban.url_pattern_add('^/static.*$', match_type='regex')
コード例 #2
0
def login_post(ip_ban: IpBan) -> Union[Response, str]:
    """
    the function handles the login post request and if all information are correct
    a session variable is set to store the login information
    """
    utils = Webutils()
    hostname = platform.node().encode("utf-8")
    salt = hashlib.sha512(hostname).hexdigest()
    pw_hash = hashlib.sha512(
        str(salt + request.form['password']).encode("utf-8")).hexdigest()
    if request.form['username'] == utils.cfg.get_value(
            "WEB", "username") and pw_hash == utils.cfg.get_value(
                "WEB", "password"):
        session.clear()
        session['logged_in'] = True
        session['ip_address'] = request.remote_addr
        session.permanent = True
        info("Successful login for the user {}. ".format(
            request.form['username']) +
             "IP address of the remote device: {}".format(request.remote_addr))
        return redirect("/")
    else:
        warning(
            "Failed login attempt for the user {} detected. ".format(
                request.form['username']) +
            "IP address of the remote device: {}".format(request.remote_addr))
    ip_ban.add(ip=request.remote_addr)
    return login("Wrong username or password.", "danger")
コード例 #3
0
ファイル: __main__.py プロジェクト: ptrifonov/easywall
    def __init__(self, debug: bool = False) -> None:
        self.cfg = Config(CONFIG_PATH)

        loglevel = self.cfg.get_value("LOG", "level")
        to_stdout = self.cfg.get_value("LOG", "to_stdout")
        to_files = self.cfg.get_value("LOG", "to_files")
        logpath = self.cfg.get_value("LOG", "filepath")
        logfile = self.cfg.get_value("LOG", "filename")
        self.log = Log(str(loglevel), bool(to_stdout), bool(to_files), str(logpath), str(logfile))

        self.login_attempts = self.cfg.get_value("WEB", "login_attempts")
        self.login_bantime = self.cfg.get_value("WEB", "login_bantime")
        self.ip_ban = IpBan(app=APP, ban_count=self.login_attempts,
                            ban_seconds=self.login_bantime, ipc=True)
        self.ip_ban.url_pattern_add('^/static.*$', match_type='regex')

        info("starting easywall-web")

        self.rules_handler = RulesHandler()
        self.rules_handler.ensure_files_exist()

        if debug is True:
            port = self.cfg.get_value("WEB", "bindport")
            host = self.cfg.get_value("WEB", "bindip")
            APP.config.from_object('easywall_web.__main__.DevelopmentConfig')
            APP.run(str(host), str(port))
        else:
            APP.config.from_object('easywall_web.__main__.ProductionConfig')
コード例 #4
0
from flask_babelex import Babel
from flask_cors import CORS
from flask_login import LoginManager,current_user
from oauthlib.oauth2 import WebApplicationClient
from flask_restx import Api
from flask_ipban import IpBan
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

app = Flask(__name__, static_folder='../build/static',template_folder='./views/templates')
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
babel = Babel(app)
blueprint = Blueprint('api',__name__,url_prefix='/api')
api = Api(blueprint,doc='/doc/',title = 'WhyDoThat API 문서',description = '모든 API 호출에 대해 정리한 문서 입니다.')
app.register_blueprint(blueprint)
ip_ban = IpBan(ban_seconds=200)
ip_ban.init_app(app)
ip_ban.load_nuisances()
ip_ban.ip_whitelist_add('1.223.233.222')
ip_ban.ip_whitelist_add('172.18.0.4')
ip_ban.url_pattern_add('/.env',match_type='string')
CORS(app,resources={
    r'*':{'origins':'*',
          'methods' : '*',
          'allow-headers':'*',
          'supports_credentials':True
          }
    })

google_oauth = app.config['GOOGLE_OAUTH']
google_client = WebApplicationClient(google_oauth['client_id'])
コード例 #5
0
def natural_keys(text):
    return [ atoi(c) for c in re.split('(\d+)', text) ]


SERVER_PASSWORD = os.environ.get('ANIPOSE_PASSWORD', 'password')

# creates a Flask application, named app
app = Flask(__name__)
# app.config['COMPRESS_LEVEL'] = 8
# app.config['COMPRESS_ALGORITHM'] = 'br'
Compress(app)
# squeeze = Squeeze()
# squeeze.init_app(app)

ip_ban = IpBan(ban_seconds=3600, ban_count=5, persist=True, ipc=True)
ip_ban.init_app(app)
ip_ban.load_nuisances()

def true_basename(fname):
    basename = os.path.basename(fname)
    basename = os.path.splitext(basename)[0]
    return basename

def get_cam_name(cam_regex, fname):
    basename = true_basename(fname)
    match = re.search(cam_regex, basename)
    if not match:
        return None
    else:
        name = match.groups()[0]
コード例 #6
0
#!/usr/bin/env python3
from flask import Flask, make_response, request, send_from_directory, abort
from flask_ipban import IpBan
import os, time
import subprocess
import shlex
import yaml

ip_ban = IpBan()
app = Flask(__name__)
ip_ban.init_app(app)
# ufw allow 6768/tcp


@app.route("/<project>/<region>/<rule>/<port>/<token>", methods=["GET"])
def get_my_ip(project, region, rule, port, token):
    ipaddr = request.remote_addr
    if check_project_port(project, region, rule, port, token):
        print("OK")
        source_env(project, region)
        #add_rule(ipaddr,project,region,rule,port)
        response = make_response(
            "Your IP address: " + ipaddr + " is wite-listed for 24 hours", 200)
    else:
        print("Wrong")
        response = make_response('Wrong', 404)
        abort(404)

    response.mimetype = "text/plain"
    return response
コード例 #7
0
        fn = os.path.join(temp_dir, fn)
        r = pm_nb(collection, template, fn)
    else:
        r = f'bad-url:{dwnurl_str}'
    return r


##############
# Server
#   imports move to top of file
################
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)

oauth = OAuth(app)
ip_ban = IpBan(ban_seconds=200)
ip_ban.init_app(app)
blockip = os.getenv("blockip")
if blockip:
    ip_ban.block(blockip)
app.wsgi_app = ProxyFix(app.wsgi_app, x_prefix=1)


###
## Auth
#########
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # if g.user is None:
        if (AUTH_MODE == 'service'):
コード例 #8
0
import flask, os, parseJson, AppointmentDAO
from flask_ipban import IpBan
from businessDAO import getBusinessById, setBusiness, deleteBusiness
from business_ownerDAO import setBusinessOwner, deleteBusinessOwner
from AppointmentDAO import deleteAppointmentByBusinessId
from flask import request, abort, send_file, jsonify
from qr import createQR, clear, Img
from parseJson import receiveBusinessJson, receiveBusinessOwnerJson, sendAppointmentByTokenJson

app = flask.Flask(__name__)

app.config["DEBUG"] = True

#If an ip make 10 bad request, it will be ban for 300 seconds
ip_ban = IpBan(app=app, ban_seconds=300, ban_count=10)


#this will check if an ip is in the blacklist and will automatically send a 403 forbidden
@app.before_request
def block_method():
    text_file = open('blacklist')
    ip_ban_list = text_file.readlines()
    ip = request.environ.get('REMOTE_ADDR')
    if ip in ip_ban_list:
        abort(403)


#Receives a json file that contains a business owner and send it to the database, return the id
@app.route('/post_business', methods=['POST'])
def postBusiness():
    print(request.is_json)
コード例 #9
0
from jinja2 import Environment, utils
from flask_ipban import IpBan

app = Flask(__name__)

app.config[
    'SECRET_KEY'] = '\x83\xe1\xba%j\x0b\xe5Q\xdeiG\xde\\\xb1\x94\xe4\x0e\x1dk\x99\x1a\xda\xe8x'
app.config['MYSQL_HOST'] = 'db'
# app.config['MYSQL_USER'] = '******'
# app.config['MYSQL_PASSWORD'] = '******'
app.config['MYSQL_USER'] = '******'
app.config['MYSQL_PASSWORD'] = '******'
app.config['MYSQL_DB'] = 'challengedb'
app.config['MAX_CONTENT_PATH'] = 102400

ip_ban = IpBan(ban_seconds=1800, ban_count=2)
ip_ban.init_app(app)

limiter = Limiter(app,
                  key_func=get_remote_address,
                  default_limits=["100 per day", "30 per hour"])

mysql = MySQL(app)
current_user = None

from model import *
from views import *

if __name__ == '__main__':
    ### enabled debug
    # app.run(host='127.0.0.1', debug=True)
コード例 #10
0
from flask import Flask, render_template, request
from flask_ipban import IpBan
import datetime
from html import escape
import os
import base64
import random
import os
import time

app = Flask(__name__)
ip_ban = IpBan(ban_seconds=200)
ip_ban.init_app(app)
# Get amount of replys

ip_post_count = {}
ip_ban_time = {}


def get_current_id():
    try:
        id_file = open("reply/information/current_id", "r")
        id = id_file.read()
        id_file.close()
        return int(id)
    except:
        print("ERROR: reading reply id (using 0)")
        return 0


# Rewrite the amount of replys