Ejemplo n.º 1
0
def check_env():
    if "HOST_ADDRESS" not in os.environ:
        raise Exception("\"HOST_ADDRESS\" was not found")

    if "FAUXAPI_KEY" not in os.environ:
        raise Exception("\"FAUXAPI_KEY\" was not found")

    if "FAUXAPI_SECRET" not in os.environ:
        raise Exception("\"FAUXAPI_SECRET\" was not found")

    host = os.getenv("HOST_ADDRESS")
    valid_host: bool = False

    if ip_address.ipv4(host):
        valid_host = True

    if ip_address.ipv6(host):
        valid_host = True

    if domain(host):
        valid_host = True

    if not valid_host:
        raise Exception("Please verify \"HOST_ADDRESS\" was entered correctly")

    key = os.getenv("FAUXAPI_KEY")
    if not length(key, min=12, max=40) or not key.startswith("PFFA"):
        raise Exception("Please verify \"FAUXAPI_KEY\" was entered correctly")

    secret = os.getenv("FAUXAPI_SECRET")
    if not length(secret, min=40, max=128):
        raise Exception("Please verify \"FAUXAPI_SECRET\" was entered correctly")
Ejemplo n.º 2
0
def GetMatch(iplist , exit_nodes_list):
	hits = []
	
	for i in iplist:
		if i in exit_nodes_list and ip_address.ipv4( i ):
			print ("[+] Hit: The IP [" + i + "] is an exit node")
			hits.append( i )	
	return hits
Ejemplo n.º 3
0
 def _constraint_ip(self):
     if not self.ip:
         return
     ret = ip_address.ipv4(self.ip)
     if not ret:
         # 返回一个ValidationFailure对象: https://validators.readthedocs.io/en/latest/
         raise ValidationError(_('is NOT valid IP Address!'))
     if self.port <= 0:
         raise ValidationError(_('Port must be greater than ZERO!'))
Ejemplo n.º 4
0
def GetExitNodes(exit_node):
    f_exit_nodes = open(exit_node, 'r')
    exit_nodes_list = []
    for l in f_exit_nodes.readlines():
        l = l.strip()
        if ip_address.ipv4(l):
            exit_nodes_list.append(l)

    f_exit_nodes.close()
    return exit_nodes_list
Ejemplo n.º 5
0
def GetMatch(iplist, exit_nodes_list):
    hits = []

    for i in iplist:
        if i in exit_nodes_list and ip_address.ipv4(i):
            print "[+] Hit: The IP [" + i + "] is an exit node"
            hits.append(i)
        #else:
        #print "[-] check: IP [" + i + "]"
    return hits
Ejemplo n.º 6
0
 def parse_resolvers(self, resolvers):
     '''Parses IP addresses from the configuration file'''
     # TODO: Change this to IPSet()
     result = []
     # Strip whitespaces
     resolvers_list = [x.strip() for x in resolvers.split(',')]
     # Validate IP addresses
     for ip_address in resolvers_list:
         # If the IP is valid, add to the results
         if ipv4(ip_address):
             result.append(ip_address)
         else:
             raise Exception(
                 "Invalid IP address in configuration file: {}".format(
                     ip_address))
     return result
Ejemplo n.º 7
0
    def parse_blockpages(self, blockpages):
        '''
        Parses 'blockpages =' entry from the configuration file

        Get the IP address or domain name from the config file of the blocked pages
        and add them into an IPSet.
        '''
        result = IPSet()
        # Split entries from the config file and strip whitespaces
        blockpages_list = [x.strip() for x in blockpages.split(',')]
        # Process the IP addresses and domains
        for blockpage in blockpages_list:
            # If the DNS server blocks the query with NXDOMAIN
            if blockpage == 'NXDOMAIN':
                # Represent NXDOMAIN with 255.255.255.255/32
                result.add('255.255.255.255/32')
            # If the block page is hosted on a simple IP address
            elif ipv4(blockpage):
                result.add(blockpage)
            # If the block page is hosted somewhere on a subnet
            elif re.match('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:/\d{1,2}|)',
                          blockpage):
                result.add(blockpage)
            # If the block page is hosted under a CNAME record
            elif domain(blockpage):
                try:
                    result = self.dns_resolver.get_ip_address(blockpage)
                except Exception as e:
                    print(
                        "\nDNS resolution error while retrieving list of block pages: {}\n"
                        .format(e))
                    exit(1)
            # If the 'blockpage = ' has a 'none' value (e.g. Google DNS doesn't have a block page)
            elif blockpage == 'none':
                pass
            # Throw exception if an invalid entry is found
            else:
                raise Exception("Invalid entry found: {}".format(blockpage))
        return result
def monitorRequest():
    # - endpoint to register an app to monitor
    global appsMonitored

    # check that the minimal required info is passed
    appname = request.form['appname']
    monitorUrl = request.form['url']
    if appname is None or monitorUrl is None:
        logging.error(
            f"`{appname}` tried to register without the minimum parameters.")
        return make_response(
            f"Invalid parameters for app `{appname}`.\nMinimal request should have `appname` and `url` defined.",
            status.HTTP_400_BAD_REQUEST,
        )

    # if the app is trying to register again then there probably is something
    # wrong with the app.  Possibly erroring out and restarting?
    if appname in appsMonitored:
        logging.warning(f"`{appname}` tried to reregister again.")
        appData = appsMonitored[appname]
        appData.healthState.unhealthyCheck()
        sched.resume_job(job_id=appname)
        return make_response(f"`{appname}` is already being monitored",
                             status.HTTP_302_FOUND)

    appname = request.form['appname']
    monitorUrl = request.form['url']
    if not url(monitorUrl) and not ip_address.ipv4(
            monitorUrl) and not ip_address.ipv6(monitorUrl):
        return make_response(f"`{monitorUrl}` is not a valid url",
                             status.HTTP_400_BAD_REQUEST)

    emailAddr = request.form['email']
    if not email(emailAddr):
        return make_response(f"`{emailAddr}` is not a valid email",
                             status.HTTP_400_BAD_REQUEST)

    #   Response Timeout: 5 sec (2-60sec)
    timeout = int(request.form['timeout'])
    #   HealthCheck Interval: 30 sec (5-300sec)
    interval = int(request.form['interval'])
    #   Unhealthy Threshold: 2 times (2-10)
    unhealthy_threshold = int(request.form['unhealthy_threshold'])
    #   Healthy Threshold: 10 time (2-10)
    healthy_threshold = int(request.form['healthy_threshold'])

    # make sure the parameters are sane
    if (MonitorValues.MIN_TIMEOUT >= timeout <= MonitorValues.MAX_TIMEOUT
            and MonitorValues.MIN_INTERVAL >= interval <=
            MonitorValues.MAX_INTERVAL and MonitorValues.MIN_HEALTHY_THRESHOLD
            >= healthy_threshold <= MonitorValues.MAX_HEALTHY_THRESHOLD
            and MonitorValues.MIN_UNHEALTHY_THRESHOLD >= unhealthy_threshold <=
            MonitorValues.MAX_UNHEALTHY_THRESHOLD):
        # store off the parameters for the job
        appsMonitored[appname] = AppData(
            monitorUrl, timeout, interval,
            Health(unhealthyThreshold=unhealthy_threshold,
                   healthyThreshold=healthy_threshold))

        # if there is an email register it with the statemachine
        if emailAddr and gmail:
            logging.info(f"Registering email for `{appname}` to {emailAddr}.")
            appsMonitored[appname].healthState.registerEmail(
                appname=appname, emailAddr=emailAddr, emailCallback=sendEmail)

        # create a job with the above parameters
        logging.info(
            f"Scheduling health check job for `{appname}` to {monitorUrl} at {interval} seconds intervals."
        )
        sched.add_job(lambda: healthCheck(appname),
                      "interval",
                      seconds=interval,
                      id=appname)

        # return request created
        return make_response(
            f"App `{appname}` is scheduled for health check monitoring.",
            status.HTTP_201_CREATED,
        )
    else:
        # return error processing
        logging.error(
            f"`{appname}` tried to register with the invalid parameters.")
        return make_response(
            f"One or more parameters for app `{appname}` out of range.\nPlease refer to docs for valid parameter ranges.",
            status.HTTP_406_NOT_ACCEPTABLE,
        )