示例#1
0
 def refresh_devices(self):
     self.settings.devices = self.devices
     devices = get_devices(self.settings.devices)
     if self.settings.index > len(self.devices) - 1:
         self.settings.index = 0
     self.settings.save()
     return devices
示例#2
0
def validate_profile(updated_profile, uci):
    """validate the JSON structure of an updated profile"""
    valid = True
    try:
        valid &= validate_option("string", updated_profile["name"])
        valid &= validate_option("string", updated_profile["type"])
        valid &= updated_profile["type"] in ["standard", "parental"]
        valid &= isinstance(updated_profile["ssh"], dict)
        valid &= validate_option("boolean", updated_profile["ssh"]["enabled"])
        valid &= isinstance(updated_profile["deviceBlocking"], dict)
        valid &= validate_option("boolean",
                                 updated_profile["deviceBlocking"]["enabled"])
        all_devices = devices.get_devices(uci)
        for device_id, rules in updated_profile["deviceBlocking"][
                "deviceRules"].items():
            try:
                next(device for device in all_devices
                     if device["id"] == device_id)
            except StopIteration:
                valid = False
            for rule in rules:
                if "startTime" in rule or "stopTime" in rule:
                    valid &= validate_option("time", rule["startTime"])
                    valid &= validate_option("time", rule["stopTime"])
                if "days" in rule:
                    valid &= validate_option("day_list", rule["days"])
        valid &= isinstance(updated_profile["siteBlocking"], dict)
        valid &= validate_option("boolean",
                                 updated_profile["siteBlocking"]["enabled"])
        valid &= validate_option(
            "string_list", updated_profile["siteBlocking"]["blacklistIds"])
        blacklists = get_blacklists(uci)["blacklists"]
        for blacklist_id in updated_profile["siteBlocking"]["blacklistIds"]:
            try:
                next(blacklist for blacklist in blacklists
                     if blacklist["id"] == blacklist_id)
            except StopIteration:
                valid = False
        valid &= validate_option("string_list",
                                 updated_profile["siteBlocking"]["sites"])
        valid &= isinstance(updated_profile["deviceAccess"], dict)
        valid &= validate_option("boolean",
                                 updated_profile["deviceAccess"]["enabled"])
        valid &= validate_option("string_list",
                                 updated_profile["deviceAccess"]["devices"])
        for device_id in updated_profile["deviceAccess"]["devices"]:
            try:
                next(device for device in all_devices
                     if device["id"] == device_id)
            except StopIteration:
                valid = False
    except KeyError:
        valid = False
    return valid
示例#3
0
def new_refresh_token(uci):
    """Authorisation point - used to get a refresh token"""
    try:
        client_ip = request.environ.get("REMOTE_ADDR")
        host = request.environ.get("HTTP_HOST")
        devices = get_devices(uci, True)
        try:
            device_id = next(
                device["id"] for device in devices
                if "ipAddress" in device and device["ipAddress"] == client_ip)
        except StopIteration:
            device_id = None
        ua_dict = user_agent_parser.Parse(
            request.environ.get("HTTP_USER_AGENT"))
        created_token = {
            ".type": "refresh_token",
            "id": uuid4().hex,
            "user": str(request.get_user()["id"]),
            "token": uuid4().hex,
            "ua_brand": ua_dict["device"]["brand"] or "Other",
            "ua_family": ua_dict["device"]["family"] or "Other",
            "ua_model": ua_dict["device"]["model"] or "Other",
            "ua_os": ua_dict["os"]["family"] or "Other",
            "ua_agent": ua_dict["user_agent"]["family"] or "Other",
            "device_id": device_id if device_id else "None"
        }
        uci.add_config(REST_API_PKG, created_token)
        uci.persist(REST_API_PKG)
        # next line - see https://github.com/bottlepy/bottle/pull/983 until 0.13 release
        Morsel._reserved["same-site"] = "SameSite"  # pylint: disable=protected-access
        response.set_cookie(f"refresh_{AUTH_APP.ib_identifier}",
                            created_token["token"],
                            path="/api/auth/access_token",
                            domain=host,
                            httponly=True,
                            same_site="strict")
        return {
            "id": created_token["id"],
            "user": created_token["user"],
            "userAgent": {
                "device": {
                    "brand": created_token["ua_brand"],
                    "family": created_token["ua_family"],
                    "model": created_token["ua_model"]
                },
                "os": created_token["ua_os"],
                "agent": created_token["ua_agent"]
            },
            "deviceId": device_id
        }
    except (UciException, TypeError):
        response.status = 400
        return "Error creating a refresh token"
示例#4
0
def update_profile_network(uci, network_id, current_profile, new_profile):
    """ helper function which will change from the current profile to the new profile for a specific network """
    reload_dropbear, reload_firewall = (False, False)
    if new_profile["ssh"] != current_profile["ssh"]:
        uci.set_option(SSH_PKG, network_id, "enable",
                       "1" if new_profile["ssh"]["enabled"] else "0")
        uci.persist(SSH_PKG)
        reload_dropbear = True
    update_blocking = new_profile["deviceBlocking"] != current_profile[
        "deviceBlocking"]
    update_access = new_profile["deviceAccess"] != current_profile[
        "deviceAccess"]
    if update_blocking or update_access:
        for rule in uci.get_package(FIREWALL_PKG):
            if ".type" in rule and rule[
                    ".type"] == "rule" and "id" in rule and rule["id"]:
                is_blocking_rule = update_blocking and "src_mac" in rule and "src" in rule and rule[
                    "src"] == network_id
                is_access_rule = update_access and "set_mark" in rule and rule[
                    "set_mark"] == NETWORK_MARKS[network_id]
                if is_blocking_rule or is_access_rule:
                    uci.delete_config(FIREWALL_PKG, rule["id"])
        if new_profile["deviceBlocking"]["enabled"] or new_profile[
                "deviceAccess"]["enabled"]:
            all_devices = devices.get_devices(uci)
        if update_blocking and new_profile["deviceBlocking"]["enabled"]:
            for device_id, rules in new_profile["deviceBlocking"][
                    "deviceRules"].items():
                device = next(device for device in all_devices
                              if device["id"] == device_id)
                for rule in rules:
                    create_blocking_rule(uci, network_id, device["macAddress"],
                                         rule)
        if update_access and new_profile["deviceAccess"]["enabled"]:
            for device_id in sorted(set(
                    new_profile["deviceAccess"]["devices"])):
                device = next(device for device in all_devices
                              if device["id"] == device_id)
                create_device_access_rule(uci, network_id,
                                          device["macAddress"])
        uci.persist(FIREWALL_PKG)
        reload_firewall = True
    if new_profile["siteBlocking"] != current_profile["siteBlocking"]:
        rebuild_site_blocking(uci, network_id, new_profile)
    return reload_dropbear, reload_firewall
示例#5
0
from devices import get_devices
import sys

print("Parametros: ", sys.argv)
device_name = sys.argv[1]
for device in get_devices():
    if device.name == device_name:
        #         print(device)
        #         pass
        device.swap_state()
示例#6
0
    def __init__(self, pool, args):
        start = args.start
        end = args.end
        gain = args.gain
        dwell = args.dwell
        nfft = args.fft
        lo = args.lo
        index = args.index
        remote = args.remote
        directory, filename = os.path.split(args.file)
        _null, ext = os.path.splitext(args.file)

        self.lock = threading.Lock()

        self.stepsTotal = 0
        self.steps = 0

        self.spectrum = {}
        self.settings = Settings(load=False)

        self.queue = Queue.Queue()

        error = None

        if end <= start:
            error = "Start should be lower than end"
        elif dwell <= 0:
            error = "Dwell should be positive"
        elif nfft <= 0:
            error = "FFT bins should be positive"
        elif ext != ".rfs" and File.get_export_type(ext) == -1:
            error = "File extension should be .rfs, "
            error += File.get_export_pretty()
        else:
            device = Device()
            if remote is None:
                self.settings.devices = get_devices()
                count = len(self.settings.devices)
                if index > count - 1:
                    error = "Device not found ({0} devices in total):\n".format(count)
                    for device in self.settings.devices:
                        error += "\t{0}: {1}\n".format(device.index,
                                                       device.name)
            else:
                device.isDevice = False
                url = urlparse('//' + remote)
                if url.hostname is not None:
                        device.server = url.hostname
                else:
                    error = "Invalid hostname"
                if url.port is not None:
                    device.port = url.port
                else:
                    device.port = 1234
                self.settings.devices.append(device)
                index = len(self.settings.devices) - 1

        if error is not None:
            print "Error: {0}".format(error)
            exit(1)

        if end - 1 < start:
            end = start + 1
        if remote is None:
            gain = nearest(gain, self.settings.devices[index].gains)

        self.settings.start = start
        self.settings.stop = end
        self.settings.dwell = calc_real_dwell(dwell)
        self.settings.nfft = nfft
        self.settings.devices[index].gain = gain
        self.settings.devices[index].lo = lo

        print "{0} - {1}MHz".format(start, end)
        print "{0}dB Gain".format(gain)
        print "{0}s Dwell".format(self.settings.dwell)
        print "{0} FFT points".format(nfft)
        print "{0}MHz LO".format(lo)
        if remote is not None:
            print remote
        else:
            print self.settings.devices[index].name

        self.scan(self.settings, index, pool)

        if ext == ".rfs":
            scanInfo = ScanInfo()
            scanInfo.setFromSettings(self.settings)
            save_plot(directory, filename, scanInfo, self.spectrum)
        else:
            exportType = File.get_export_type(ext)
            export_plot(directory, filename, exportType, self.spectrum)

        print "Done"
示例#7
0
    def __init__(self, title, pool):

        self.grid = True

        self.pool = pool
        self.lock = threading.Lock()
        self.threadScan = None
        self.threadPlot = None
        self.stepsTotal = 0
        self.steps = 0
        self.pendingScan = False
        self.pendingPlot = Plot.NONE
        self.stopAtEnd = False
        self.stopScan = False

        self.dlgCal = None

        self.menuOpen = None
        self.menuSave = None
        self.menuExport = None
        self.menuProperties = None
        self.menuStart = None
        self.menuStop = None
        self.menuStopEnd = None
        self.menuPref = None
        self.menuCompare = None
        self.menuCal = None

        self.popupMenu = None
        self.popupMenuStart = None
        self.popupMenuStop = None
        self.popupMenuStopEnd = None

        self.panel = None
        self.graph = None
        self.canvas = None
        self.buttonStart = None
        self.buttonStop = None
        self.choiceMode = None
        self.choiceDwell = None
        self.choiceNfft = None
        self.spinCtrlStart = None
        self.spinCtrlStop = None
        self.checkUpdate = None
        self.checkGrid = None

        self.filename = ""
        self.dirname = "."

        self.spectrum = {}
        self.scanInfo = ScanInfo()
        self.isSaved = True

        self.settings = Settings()
        self.devices = get_devices(self.settings.devices)
        self.oldCal = 0

        displaySize = wx.DisplaySize()
        wx.Frame.__init__(self, None, title=title, size=(displaySize[0] / 1.5,
                                                         displaySize[1] / 2))

        self.Bind(wx.EVT_CLOSE, self.on_exit)

        self.status = Statusbar(self)
        self.SetStatusBar(self.status)

        self.create_widgets()
        self.create_menu()
        self.create_popup_menu()
        self.set_control_state(True)
        self.Show()

        size = self.panel.GetSize()
        size[1] += displaySize[1] / 4
        self.SetMinSize(size)

        self.Connect(-1, -1, EVT_THREAD_STATUS, self.on_event)

        self.SetDropTarget(DropTarget(self))
示例#8
0
    def __init__(self, title, pool):

        self.grid = True

        self.pool = pool
        self.lock = threading.Lock()

        self.sdr = None
        self.threadScan = None
        self.threadUpdate = None

        self.stopAtEnd = False
        self.stopScan = False

        self.dlgCal = None

        self.menuOpen = None
        self.menuSave = None
        self.menuExport = None
        self.menuProperties = None
        self.menuPref = None
        self.menuAdvPref = None
        self.menuClearSelect = None
        self.menuShowMeasure = None
        self.menuDevices = None
        self.menuStart = None
        self.menuStop = None
        self.menuStopEnd = None
        self.menuCompare = None
        self.menuCal = None

        self.popupMenu = None
        self.popupMenuStart = None
        self.popupMenuStop = None
        self.popupMenuStopEnd = None
        self.popupMenuRangeLim = None
        self.popupMenuPointsLim = None
        self.popupMenuClearSelect = None
        self.popupMenuShowMeasure = None

        self.graph = None
        self.toolbar = None
        self.canvas = None
        self.mouseZoom = None
        self.mouseSelect = None

        self.buttonStart = None
        self.buttonStop = None
        self.controlGain = None
        self.choiceMode = None
        self.choiceDwell = None
        self.choiceNfft = None
        self.spinCtrlStart = None
        self.spinCtrlStop = None
        self.checkUpdate = None
        self.checkGrid = None

        self.spectrum = {}
        self.scanInfo = ScanInfo()
        self.isSaved = True

        self.settings = Settings()
        self.devices = get_devices(self.settings.devices)
        self.filename = ""
        self.oldCal = 0

        wx.Frame.__init__(self, None, title=title)

        self.Bind(wx.EVT_CLOSE, self.on_exit)

        self.status = Statusbar(self)
        self.SetStatusBar(self.status)

        add_colours()
        self.create_widgets()
        self.create_menu()
        self.create_popup_menu()
        self.set_control_state(True)
        self.Show()

        displaySize = wx.DisplaySize()
        toolbarSize = self.toolbar.GetBestSize()
        self.SetClientSize((toolbarSize[0] + 10, displaySize[1] / 2))
        self.SetMinSize((displaySize[0] / 4, displaySize[1] / 4))

        self.Connect(-1, -1, EVT_THREAD_STATUS, self.on_event)

        self.SetDropTarget(DropTarget(self))
示例#9
0
def args_parser(caller):

    # Instantiate parser object
    parser = argparse.ArgumentParser()

    # Arg for version number.
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version=__VERSION__)

    # Arg for channel.
    parser.add_argument("-c",
                        "--channel",
                        action="store",
                        default=[],
                        dest="channel",
                        nargs="*",
                        help="select a channel")

    # Flag for kill commands.
    parser.add_argument("-k",
                        "--kill",
                        action="store_true",
                        dest="kill",
                        help="sudo kill interfering processes.")

    # Start monitor args:
    if caller == "monitor":
        parser.add_argument("-n",
                            "--name",
                            action="store",
                            default=None,
                            dest="name",
                            help="select a new card name")

        # Arg for interface.
        parser.add_argument("-i",
                            "--interface",
                            action="store",
                            dest="interface",
                            help="select an interface",
                            choices=devices.get_devices(),
                            required=True)

    elif caller == "deauth":
        parser.add_argument("-s",
                            "--skip",
                            action="store",
                            default=None,
                            dest="skip",
                            help="Mac to not deauth (Usually your own...)")

        parser.add_argument(
            "-p",
            "--packets",
            action="store",
            default=5,
            dest="packets",
            help=
            "How many deauth packets to send, more than 5 is usually unneccessary."
        )

    elif caller == "sniffer":
        # Flag for unassociated clients.
        parser.add_argument("-u",
                            "--unassociated",
                            action="store_true",
                            dest="unassociated",
                            help="Whether to show unassociated clients.")

        # No show client or open networks.
        parser.add_argument("-N",
                            "--No-clients",
                            action="store_true",
                            default=False,
                            dest="clients",
                            help="Switch for displaying any clients at all")

        parser.add_argument("-O",
                            "--No-open",
                            action="store_true",
                            default=False,
                            dest="open",
                            help="Switch for displaying open networks")

        # Arg for diagnostic mode.
        parser.add_argument("-D",
                            "--Diagnose",
                            action="store_true",
                            default=False,
                            dest="diagnose",
                            help="Switch for diagnostic mode.")

    if caller == "monitor" or caller == "sniffer":
        parser.add_argument("-m",
                            "--mac",
                            action="store",
                            dest="mac",
                            default=None,
                            help="Set Mac Address.")

    if caller == "deauth" or caller == "sniffer":
        # Arg for interface.
        parser.add_argument("-i",
                            "--interface",
                            action="store",
                            dest="interface",
                            help="select an interface",
                            choices=devices.get_mon_devices(),
                            required=True)

        # Arg for frequency.
        parser.add_argument("-f",
                            "--frequency",
                            action="store",
                            default="2",
                            dest="freq",
                            help="select a frequency (2/5/all)",
                            choices=["2", "5", "all"])

        # Arg for target to sniff.
        parser.add_argument("-t",
                            "--target",
                            action="store",
                            default=[],
                            dest="target",
                            nargs="*",
                            help="Command for targeting a specific network.")

        parser.add_argument(
            "-T",
            "--Timeout",
            action="store",
            default=None,
            type=int,
            dest="time",
            help="Command for killing after a certain amount of time.")

    # return dict of args.
    return vars(parser.parse_args())
示例#10
0
def access_token(uci):
    """Authorisation point - used to get an access token from a refresh token (cookie)"""
    try:
        try:
            token_cookie = next(value
                                for name, value in request.cookies.iteritems()  # pylint: disable=no-member
                                if name == f"refresh_{AUTH_APP.ib_identifier}")
        except StopIteration:
            # Old cookie format for IB firmware <= 0.1.7
            token_cookie = next(value
                                for name, value in request.cookies.iteritems()
                                if name == "api_refresh")  # pylint: disable=no-member
        try:
            client_ip = request.environ.get("REMOTE_ADDR")
            devices = get_devices(uci, True)
            device_id = next(
                device["id"] for device in devices
                if "ipAddress" in device and device["ipAddress"] == client_ip)
        except StopIteration:
            device_id = None
        rest_uci = uci.get_package(REST_API_PKG)
        ua_dict = user_agent_parser.Parse(
            request.environ.get("HTTP_USER_AGENT"))
        try:
            token = next(
                token for token in rest_uci
                if token[".type"] == "refresh_token"
                and token["token"] == token_cookie and token["ua_brand"] == (
                    ua_dict["device"]["brand"] or "Other")
                and token["ua_family"] == (ua_dict["device"]["family"]
                                           or "Other") and token["ua_model"] ==
                (ua_dict["device"]["model"] or "Other") and token["ua_os"] ==
                (ua_dict["os"]["family"] or "Other") and token["ua_agent"] == (
                    ua_dict["user_agent"]["family"] or "Other") and (
                        device_id is None or token["device_id"] == ""
                        or token["device_id"] == device_id))
        except StopIteration:
            response.status = 400
            return "Error validating the refresh token"
        if device_id and token["device_id"] == "":
            uci.set_option(REST_API_PKG, token["id"], "device_id", device_id)
            uci.persist(REST_API_PKG)
        try:
            user = next(
                {
                    "id": int(user["id"]),
                    "username": user["name"]
                } for user in rest_uci
                if user[".type"] == "user" and user["id"] == token["user"])
        except StopIteration:
            response.status = 400
            return "Error validating the refresh token"
        new_access_tk, expires = JWT_PLUGIN.provider.create_token(user)
        return {
            "token": new_access_tk,
            "expires": str(expires),
            "refresh_token_id": token["id"]
        }
    except (StopIteration, UciException, TypeError):
        response.status = 400
        return "Error validating the refresh token"
示例#11
0
#!/usr/bin/env python

from jsonrpclib import Server
from devices import get_devices

devices = get_devices()
#devices = {
##        '10.10.0.99':{'user':'******', 'password':'******'},
#        '10.10.0.41':{'user':'******', 'password':'******'},
##        '10.10.0.42':{'user':'******', 'password':'******'},
#        '10.10.0.43':{'user':'******', 'password':'******'},
#        '10.10.0.11':{'user':'******', 'password':'******'},
#        '10.10.0.12':{'user':'******', 'password':'******'},
#}

backbone_ports = [
    '10.10.0.11-po2',
    '10.10.0.11-po3',
    '10.10.0.11-po4',
    '10.10.0.11-po5',
    '10.10.0.12-po2',
    '10.10.0.41-po4',
    '10.10.0.41-po6',
    '10.10.0.41-po8',
    '10.10.0.42-po8',
    '10.10.0.43-po6',
]


def getUnicastMacs(ip, user, password, macs):
    connectionString = "http://%s:%s@%s/command-api" % (user, password, ip)
示例#12
0
def main(argv):
    base_dir = '/sys/bus/w1/devices/'
    slave_path = '/w1_slave'
    matching_string = '28*'
    sleep_time = 1
    server = os.getenv('PITEMP_SQLSERVER')
    user = os.getenv('PITEMP_SQLUSER')
    password = os.getenv('PITEMP_SQLPASSWORD')
    database = os.getenv('PITEMP_SQLDB')

    try:
        opts, args = getopt.getopt(argv, "hi:b:s:u:p:d:",
                                   ["interval=", "base_dir=", "server="])
    except getopt.GetoptError:
        print('main.py -i <interval> -s <server> -b <base_dir>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('main.py -i <interval> -s <server> -b <base_dir>')
            sys.exit()
        elif opt in ("-i", "--interval"):
            sleep_time = float(arg)
        elif opt in ("-b", "--base_dir"):
            base_dir = arg
        elif opt in ("-s", "--server"):
            server = arg
        elif opt in ("-u", "--user"):
            user = arg
        elif opt in ("-p", "--password"):
            password = arg
        elif opt in ("-d", "--database"):
            database = arg

    log.info("Starting pi-temp with interval of " + str(sleep_time) +
             " seconds")
    initial_devices = get_devices(base_dir, slave_path, matching_string)
    log.info("Reading from " + str(len(initial_devices)) + " devices:")
    for device in initial_devices:
        log.info(device.serial)
    while True:
        start_time = datetime.now()
        current_devices = get_devices(base_dir, slave_path, matching_string)
        if current_devices != initial_devices:
            initial_devices = current_devices
            log.info("devices changed, new devices:")
            for device in current_devices:
                log.info(device.serial)

        for device in current_devices:
            try:
                temperature_reading = read_temp(device)
                log.debug('{0}, {1}, {2}'.format(
                    temperature_reading.serial,
                    temperature_reading.temperature_celcius,
                    temperature_reading.datetime))
                # upload to database
                save_to_sql(server, user, password, database,
                            temperature_reading)
            except:
                log.exception("Exception reading temp or writing to DB")

        true_sleep = sleep_time - (datetime.now() - start_time).total_seconds()
        if true_sleep < 0:
            true_sleep = 0

        time.sleep(true_sleep)
示例#13
0
import socket
import os
import time
import devices
import sys
import check_port
reload(sys)
sys.setdefaultencoding('utf-8')


iplist=[]
iplist = socket.gethostbyname_ex(socket.gethostname())
ip=iplist[2][0]
divlist=devices.get_devices()
print divlist
port=4723
bport=5723
conf="..\\conf\\appium_cf.json"

def check_ip_port(ipv,portv):
    if check_port.IsOpen(ipv,portv)==True:
        portv=portv+1
        return check_ip_port(ipv,portv)
    else: 
        return portv
           
        
for div in divlist:
    port=check_ip_port(ip,port)
    bport=check_ip_port(ip,bport)
    run_app='start run_appium.bat {0} {1} {2} {3} {4}'.format(ip,port,bport,div,conf)
示例#14
0
#!/usr/bin/env python

from jsonrpclib import Server
from devices import get_devices

devices = get_devices()
#devices = {
##        '10.10.0.99':{'user':'******', 'password':'******'},
#        '10.10.0.41':{'user':'******', 'password':'******'},
##        '10.10.0.42':{'user':'******', 'password':'******'},
#        '10.10.0.43':{'user':'******', 'password':'******'},
#        '10.10.0.11':{'user':'******', 'password':'******'},
#        '10.10.0.12':{'user':'******', 'password':'******'},
#}

backbone_ports = [
	'10.10.0.11-po2',
	'10.10.0.11-po3',
	'10.10.0.11-po4',
	'10.10.0.11-po5',

	'10.10.0.12-po2',

	'10.10.0.41-po4',
	'10.10.0.41-po6',
	'10.10.0.41-po8',

	'10.10.0.42-po8',

	'10.10.0.43-po6',
]