def __init__(self, server='127.0.0.1', min_retry_time=2, max_retry_time=60, node_name=None):
        self.id = "{}-{}".format(get_mac(), rand_str(10))
        self.connected = False
        self.min_retry_time = min_retry_time
        self.max_retry_time = max_retry_time
        self.retry_time = self.min_retry_time
        self.server = server

        if not node_name:
            node_name = rand_str(10)
        banned = "/#+"
        self.node_name = "".join(["-" if ch in banned else ch for ch in node_name])

        self.path = "home/{name}/{mac}".format(name=self.node_name, mac=get_mac())

        self.mqttc = mqtt.Client(client_id=self.id, clean_session=True, userdata=self)
        self.mqttc.will_set(
                topic=self.path + "/info/status",
                payload="lost",
                qos=1,
                retain=True)

        self.mqttc.on_message = self._dispatch
        self.mqttc.on_connect = self._on_connect
        self.mqttc.on_disconnect = self._on_disconnect

        self.dispatch_table = dict()
        self.dtlock = Lock()
    def run(self):

        # get playerid based on mac address
        if self.addon.getSetting(
                "disable_auto_mac") == "true" and self.addon.getSetting(
                    "manual_mac"):
            playerid = self.addon.getSetting("manual_mac").decode("utf-8")
        else:
            playerid = get_mac()

        # discover server
        if self.addon.getSetting("disable_auto_lms") == "true":
            # manual server
            lmshost = self.addon.getSetting("lms_hostname")
            lmsport = self.addon.getSetting("lms_port")
            self.lmsserver = LMSServer(lmshost, lmsport, playerid)
        else:
            # auto discovery
            while not self.lmsserver and not self.exit:
                servers = LMSDiscovery().all()
                log_msg("discovery: %s" % servers)
                if servers:
                    server = servers[
                        0]  # for now, just use the first server discovered
                    lmshost = server.get("host")
                    lmsport = server.get("port")
                    self.lmsserver = LMSServer(lmshost, lmsport, playerid)
                    log_msg("LMS server discovered - host: %s - port: %s" %
                            (lmshost, lmsport))
                else:
                    self.kodimonitor.waitForAbort(2)

        if self.lmsserver:
            # publish lmsdetails as window properties for the plugin entry
            self.win.setProperty("lmshost", lmshost)
            self.win.setProperty("lmsport", str(lmsport))
            self.win.setProperty("lmsplayerid", playerid)

            # start squeezelite executable
            self.start_squeezelite()

            # initialize kodi player monitor
            self.kodiplayer = KodiPlayer(lmsserver=self.lmsserver,
                                         webport=self._webport)

            # report player as awake
            self.lmsserver.send_command("power 1")

            # mainloop
            while not self.exit:
                # monitor the LMS state changes
                if not (xbmc.getCondVisibility("System.Platform.Android")
                        and playerid.lower() == get_mac().lower()):
                    # TODO: implement fake OSD for android
                    self.monitor_lms()
                # sleep for 1 second
                self.kodimonitor.waitForAbort(1)
Example #3
0
    def parseData(self, data):
	packet = dpkt.ethernet.Ethernet(data)
	# Skip packets sent from our machine
	if packet.dst == get_mac(self.interface[0]):
		return None
	# ARP
	if packet.type == dpkt.ethernet.ETH_TYPE_ARP:
	    packet.data = dpkt.arp.ARP(str(packet.data))
	# IPv4
	elif packet.type == dpkt.ethernet.ETH_TYPE_IP:
	    packet.data = dpkt.ip.IP(str(packet.data))
	    # UDP
	    if packet.data.p == dpkt.ip.IP_PROTO_UDP:
		packet.data.data = dpkt.udp.UDP(str(packet.data.data))
		# LLMNR (224.0.0.252:5355), same packet format as DNS
		if packet.data.dst == ip_to_bin("224.0.0.252") and packet.data.data.dport == 5355:
		    packet.data.data.data = dpkt.dns.DNS(str(packet.data.data.data))
		# Netbios Name Service (from 137 UDP to 137 UDP)
		if packet.data.data.dport == 137 and packet.data.data.dport == 137:
		    packet.data.data.data = dpkt.netbios.NS(str(packet.data.data.data))
		    
	    # TCP
	    elif packet.data.p == dpkt.ip.IP_PROTO_TCP:
		packet.data.data = dpkt.tcp.TCP(str(packet.data.data))

	return packet
Example #4
0
    def _init_station(self):
        """
        Attempts to initialize this AirStation object.

        This method is used to initialize the various fields and sensors of an AirStation object.
        If the object cannot be initialized then this method returns False, otherwise it returns
        True.

        :return: True if the AirStation could be initialized. False otherwise.
        """
        self._id = utils.get_mac('eth0')
        self._bmp = BMP085.BMP085()
        self._gpsp = utils.GpsPoller()
        self._gpsp.start()  # start polling the GPS sensor
        self._gps = gps.gps("localhost", "2947")
        self._gps.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)

        # Wait a few seconds to ensure a GPS fix
        time.sleep(10)
        (self._lon, self._lat) = self.get_location()
 
        # Open a connection with the PMS3003 sensor
        self._pm = serial.Serial(port="/dev/ttyO1", baudrate=9600, rtscts=True, dsrdtr=True)
        self._pm.close()
        self._pm.open()
        
        return True
Example #5
0
def init():
    global notice_post
    global challenge_mac

    # init admin session
    admin_session = Session.create_sub_session()
    sessions[admin_token] = admin_session

    # add admin notice
    key = admin_token.replace(b'-', b'')
    challenge_mac = get_mac(key, notice_content)
    notice_post = Post.write(
        token=admin_token,
        type_=0,
        idx=0,
        content=notice_content,
    )
    sessions[admin_token].add_post(notice_post)

    # add flag post
    flag = b'SECCON{8e62f74287c22108e82e18b69caa115ceb8fceec532fae97971b7b01912fa313}'
    flag_post = Post.write(
        token=admin_token,
        type_=0,
        idx=1,
        content=flag,
    )
    admin_session.add_post(flag_post)
Example #6
0
 def test_scapy_sr(self, mocked_scapy_sr):
     '''Mock Scapy's sr() return and check that packet parsing returns the expected MAC address'''
     arp_response = namedtuple(
         'arp_response', 'op hwdst pdst hwtype ptype hwlen plen hwsrc psrc')
     responses = [
         arp_response(op='who-has',
                      hwdst='ff:ff:ff:ff:ff:ff',
                      pdst='192.168.7.189',
                      hwtype='',
                      ptype='',
                      hwlen='',
                      plen='',
                      hwsrc='',
                      psrc=''),
         arp_response(op='is-at',
                      hwdst='60:03:08:8c:44:72',
                      pdst='192.168.7.190',
                      hwtype='0x1',
                      ptype='0x800',
                      hwlen=6,
                      plen=4,
                      hwsrc='4c:57:ca:e9:b0:83',
                      psrc='192.168.7.189')
     ]
     unanswered_tuple = ((), )
     responded_tuple = (responses, ())
     mocked_scapy_sr.return_value = (responded_tuple, unanswered_tuple)
     resp, unans = mocked_scapy_sr.return_value
     x = get_mac('192.168.7.189')
     assert x == '4c:57:ca:e9:b0:83'
Example #7
0
    def getAddress(self, targetip):
	address = self.config['address'].get(targetip) or self.config.get("default")
	if address == "default":
	    return utils.get_mac(self.interface[0])

	if not address or address == "none":
	    return None
	return address
Example #8
0
def login():
    user_ip = request.remote_addr
    user_platform = request.user_agent.platform

    data = request.get_json()

    username = data['username']
    password = data['password']

    db_user = db.users.find_one({"username": username})

    if not db_user:
        return jsonify(error="Username not found.")

    db_password = db_user['password']

    if password != db_password:
        error = "Incorrect password."
        return jsonify(error=error)

    session['logged_in'] = True
    session['username'] = username

    try:
        user_mac = get_mac(user_ip)
    except ValueError as e:
        error = "IP not found. Contact IT Department."
        return jsonify(error=error)

    session['this_mac'] = user_mac

    # check if mac alread registered
    for device in db_user['devices']:
        if device['mac'] == user_mac:
            return jsonify(
                message=
                "This device is already registered. You now have internet access."
            )

    if len(db_user['devices']) < db_user['device_limit']:
        # basically, add this mac
        db.users.find_one_and_update(
            {"username": username},
            {"$push": {
                "devices": {
                    "mac": user_mac,
                    "device": user_platform
                }
            }},
            return_document=ReturnDocument.AFTER)
        return jsonify(
            message=
            "Device registered. You now have internet access on this device.")
    else:
        # get device list
        return jsonify(message="Maximum device limit reached.",
                       devices=db_user['devices'],
                       this_mac=user_mac)
Example #9
0
    def write(cls, token, type_, idx, content):
        if type_ == PostType.URL.value:
            content = Post.get_from_url(content)

        if content is None:
            return None

        key = token.replace(b'-', b'')
        mac = get_mac(key, content)
        content += b'\n\nMAC=' + binascii.hexlify(mac)
        content = pickle.dumps(content)
        return cls(token, idx, content, mac)
Example #10
0
def get_admin_token(message):
    global admin_token
    global challenge_mac

    if message == notice_content:
        return None

    key = admin_token.replace(b'-', b'')
    mac = get_mac(key, message)
    if mac != challenge_mac:
        return None

    return admin_token
Example #11
0
    def listen(self, target_ip, target_mac):
        global LOCK_LISTEN
        LOCK_LISTEN = True
        #set_ip_forwarding(1)
        conf.verb = 0
        GATEWAY_MAC = get_mac(GATEWAY)
        packet_count = COUNT
        poison_thread = Job(target=self.poison_target,
                            args=(GATEWAY, GATEWAY_MAC, target_ip, target_mac))
        poison_thread.setDaemon(True)
        poison_thread.start()
        try:
            print "[*] Starting sniffer for %d packets" % packet_count

            bpf_filter = "ip host %s " % target_ip  # 过滤器
            #sniff_thread = Job(target=start_sniff,args=(packet_count,bpf_filter))
            #sniff_thread.setDaemon(True)
            #sniff_thread.start()
            packets = sniff(count=packet_count,
                            filter=bpf_filter,
                            prn=self.stop_sniff
                            )  #,stopper = self.stop_sniff(),stopper_timeout=1)
            #time.sleep(5)
            # 将捕获到的数据包输出到文件

            #global LOCK_LISTEN
            LOCK_LISTEN = False
            poison_thread.stop()
            #sniff_thread.stop()
            wrpcap('{}.pcap'.format(target_ip), packets)
            # 还原网络配置
            restore_target(GATEWAY, GATEWAY_MAC, target_ip, target_mac)
            #set_ip_forwarding(0)
            return True
        except Exception, e:
            LOCK_LISTEN = False
            print e
            # 还原网络配置
            restore_target(GATEWAY, GATEWAY_MAC, target_ip, target_mac)
            return False
Example #12
0
    def init(self):
        #global SERVER_NAME, WORKNAME_NAME

        """ 办理工人注册 """
        #srv_name = config.CONFIG['server']['server_name']
        wk_name =  config.CONFIG['server']['worker_name']
        """检测配置文件
        if srv_name: 
            SERVER_NAME = srv_name
        else:
            config.write('server', 'server_name', SERVER_NAME)
        """
        if wk_name: 
            global_list.WORKNAME_NAME = wk_name
            reg_list = get_reg_list()   
            wk_info = reg_list.get(global_list.WORKNAME_NAME)
            if wk_info and wk_info['sysinfo']['ip'] == global_list.LOCAL_IP:
                return
        
        #global_list.WORKNAME_NAME = str(sum(map(lambda n:int(n),global_list.LOCAL_IP.split('.'))))
        global_list.WORKNAME_NAME = utils.get_mac()
        config.write('server','worker_name',global_list.WORKNAME_NAME)
        #合并线上配置
        reg_list = get_reg_list()
        wk_info = reg_list.get(global_list.WORKNAME_NAME)
        if wk_info and 'doing' in wk_info and wk_info['doing']:
            for k,task in wk_info['doing'].items():                
                if int(task['status']) < 3:
                    get_task_queue(global_list.WORKNAME_NAME).push(task)
        # 报告机器状态
        self.report(self.login_time)
        # 记录系统日志
        system_log = get_system_log_queue()
        system_log.push(dict( host=global_list.LOCAL_IP,
                        name=global_list.WORKNAME_NAME,
                        type='power',
                        timestamp=self.login_time))   
        #注册在线标识
        set_online(global_list.WORKNAME_NAME)   
def create_wifi_data(last_seen, mac_address, ap_mac, ap_name, power):
    class DatetimeEncoder(json.JSONEncoder):
         def default(self, obj):
             if isinstance(obj, datetime):
                 return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
             elif isinstance(obj, date):
                 return obj.strftime('%Y-%m-%d')
             # Let the base class default method raise the TypeError
             return json.JSONEncoder.default(self, obj)

    wifi_data = {}
    last_seen_formated = datetime.datetime.strptime(last_seen, " %Y-%m-%d %H:%M:%S")
    wifi_data['last_seen_time'] = last_seen_formated.isoformat()
    wifi_data['category'] = 'Motherapp_office'
    wifi_data['action'] = 'Check_point'
    wifi_data['label'] = ''
    wifi_data['location_name'] = utils.get_mac()
    wifi_data['device_mac'] = mac_address
    wifi_data['power'] = power
    wifi_data['router_mac'] = ap_mac
    wifi_data['router_name'] = ap_name

    print wifi_data
    return wifi_data
Example #14
0
 def __init__(self, device = "hci0"):
     self._device = device
     self._address = get_mac(self._device)
     self._pairing_thread = None
Example #15
0
from umqtt.simple import MQTTClient
from time import sleep
import utils

from mqtt_config import config

MQTT_BROKER = config['broker']
MQTT_SUB = config['topic_sub']
MQTT_PUB = config['topic_pub']

client = MQTTClient(utils.get_mac(), MQTT_BROKER)


def rcv(topic, msg):
    print("{}: {}".format(topic.decode("utf-8"), msg.decode("utf-8")))
    client.publish(MQTT_PUB, '{"rcv":"' + msg.decode("utf-8") + '"}')


client.set_callback(rcv)
client.set_last_will('test/admin', 'OOPS - ' + utils.get_mac() + ' crashed!')
client.connect()
client.subscribe(MQTT_SUB)


def start_loop():
    try:
        while True:
            client.check_msg()
            sleep(1)
    except KeyboardInterrupt:
        pass