Пример #1
0
def parse_beacon(dtg, addr, ssid):
    device = get_device(addr)
    
    recent = Device.objects(Q(events__timestamp__gte=datetime.utcnow() - timedelta(minutes=10)) | Q(events__ssid__ne=ssid), mac=addr)
    if len(recent) == 0:
        event = Beacon()
        event.ssid = ssid
        event.timestamp = datetime.utcnow()
        device.events.append(event)
        device.save()

        dev = selector.select('Device', mac=addr).first()
        if dev == None:
            dev = Node('Device', mac=addr, last_seen=str(datetime.utcnow()), vendor=device.vendor)
            graph.create(dev)
        
        ss = selector.select('SSID', ssid=ssid).first()
        if ss == None:
            ss = Node('SSID', ssid=ssid, timestamp=str(datetime.utcnow()))
            graph.create(ss)

        if len(list(graph.match(start_node=dev, rel_type='beacon', end_node=ss))) == 0:
            rel = Relationship(dev, 'beacon', ss)
            graph.create(rel)
        
        print("%s[+] (%s) AP beacon: %s (%s) -> '%s'" % (Term.GREEN, dtg, addr, device.vendor, ssid))
Пример #2
0
def parse_response(dtg, addr, dest, ssid):
    device = get_device(addr)

    recent = Device.objects(Q(events__timestamp__gte=datetime.utcnow() - timedelta(minutes=10)) | Q(events__dest__ne=ssid), mac=addr)
    if len(recent) == 0:
        event = Beacon()
        event.timestamp = datetime.utcnow()
        event.ssid = ssid
        device.events.append(event)
        device.save()

        dev = selector.select('Device', mac=dest).first()
        if dev == None:
            dev = Node('Device', mac=dest, last_seen=str(datetime.utcnow()), vendor=device.vendor)
            graph.create(dev)

        ss = selector.select('SSID', ssid=ssid).first()
        if ss == None:
            ss = Node('SSID', ssid=ssid, timestamp=str(datetime.utcnow()))
            graph.create(ss)

        if len(list(graph.match(start_node=dev, rel_type='probe', end_node=ss))) == 0:
            rel = Relationship(dev, 'response', ss)
            graph.create(rel)
            print('Hidden SSID Discovered %s -> %s' % (dest, ssid))    
Пример #3
0
 def setUp(self):
     self.cleanbeacon = Beacon(name='sink',
                          is_clean = True,
                          beacon_id='123'
                          )
     self.cleanbeacon.save()
     self.dirtybeacon= Beacon(name='door',
                          is_clean = False,
                          beacon_id='345'
                          )
     self.dirtybeacon.save()
Пример #4
0
class ReportScore(TestCase):
    def setUp(self):
        self.cleanbeacon = Beacon(name='sink', is_clean=True, beacon_id='123')
        self.cleanbeacon.save()
        self.dirtybeacon = Beacon(name='door', is_clean=False, beacon_id='345')
        self.dirtybeacon.save()

    def test_simple(self):
        check1 = BeaconCheckin(user='******', beacon=self.cleanbeacon)
        check1.save()
        testuser = User.objects.get(name='julz')
        self.assertEqual(testuser.name, 'julz')
Пример #5
0
    def setUp(self):
        # create a user
        user = User.objects.create_user('john', '*****@*****.**',
                                        'johnpassword')

        # create a map
        map = FloorMap(name="test map",
                       length=10,
                       width=10,
                       nconst=1.1,
                       owner=user)
        map.save()

        # create nodes attached to the map
        # # expected location point x=2, y=7
        Node.objects.create(name="node1",
                            floor_map=map,
                            rssi_1m=-45.8,
                            x_loc=2,
                            y_loc=8,
                            owner=user)
        Node.objects.create(name="node2",
                            floor_map=map,
                            rssi_1m=-45.8,
                            x_loc=2,
                            y_loc=5,
                            owner=user)
        Node.objects.create(name="node3",
                            floor_map=map,
                            rssi_1m=-45.8,
                            x_loc=5,
                            y_loc=7,
                            owner=user)

        # create a beacon
        beacon = Beacon(uuid='00001803-494C-4F47-4943-544543480000',
                        majorid='1',
                        minorid='2',
                        floor_map=map,
                        owner=user)
        beacon.save()
        self.beacon = beacon

        # create measurements using the above beacon/nodes/map
        csvpath = os.path.join(os.path.dirname(__file__), 'test_resources',
                               'custom-measurements-20180306.csv')
        with open(csvpath, 'r') as f:
            csv_reader = csv.reader(f)
            for line in csv_reader:
                measurement = self.get_measurement_fromline(line)
                measurement.save()
Пример #6
0
def add_beacon(*args, **kwargs):
    b = Beacon(**kwargs)
    db.session.add(b)
    db.session.commit()
    #subscriptions[g.user.guid].put({'beacons': [(b.serialized)]})
    log.message('Target location identified as Lat: {}, Lng: {}'.format(
        kwargs['lat'], kwargs['lng']))
Пример #7
0
class ReportScore(TestCase):
    def setUp(self):
        self.cleanbeacon = Beacon(name='sink',
                             is_clean = True,
                             beacon_id='123'
                             )
        self.cleanbeacon.save()
        self.dirtybeacon= Beacon(name='door',
                             is_clean = False,
                             beacon_id='345'
                             )
        self.dirtybeacon.save()

    def test_simple(self):
        check1 = BeaconCheckin(user='******',beacon=self.cleanbeacon)
        check1.save()
        testuser = User.objects.get(name='julz')
        self.assertEqual(testuser.name, 'julz')
Пример #8
0
 def consume(self, id, vars={} , type="GET"):
     self.response.headers['Content-Type'] = 'text/plain'
     self.response.out.write('Consuming.... --%s-- nom nom nom...' % (id))
     self.response.out.write(vars)
     b = Beacon(IP = self.request.remote_addr, type=type, testid=id)
     b.useragent = self.GetHeader("User-Agent")
     b.refer = self.GetHeader("Referer")
     for var in vars:
         self.response.out.write("\n")
         self.response.out.write(var + ": " + vars[var])
         setattr(b, "custom__" + var, vars[var])
         
     b.put()
     self.response.out.write("\n\n")
     self.response.out.write(b)
Пример #9
0
    def get(self, id, format="html"):
#        self.response.out.write('showing.... --%s-- ...' % (id))
        query = Beacon.all()
        query.filter('testid =', id).order('-timestamp')
        beacons = []
        for be in query.fetch(10, 0):
            customvars = []
            for prop in be.dynamic_properties():
                customvars += [{
                                "varname": prop.replace("custom__",""),
                                "varvalue" :  getattr(be, prop)
                                }]

            beacon = {'timestamp' : be.timestamp,
                         'type': be.type,
                         'IP': be.IP,
                         'refer': be.refer,
                         'useragent': be.useragent,
                         'customvars': customvars,
                         }
                
            beacons += [beacon]
        pp = pprint.PrettyPrinter(indent=4)
#        print pp.pprint(beacons)
        if self.request.get("format") == "json":
            #todo process and output json
            self.response.headers['Content-Type'] = 'application/json'
            j = JSONEncoder().encode(beacons)
            self.response.out.write(j)
        else:
            #todo make and render into html template
            template_values = { 'testid': id,
                               'beacons': beacons,
                               }
            path = os.path.join(os.path.dirname(__file__), 'templates/show.html')
            self.response.out.write(template.render(path, template_values))
Пример #10
0
def trigger(request, target_type, target_id, source_type=None, source_id=None, 
    entity_type=None, entity_id=None, ignore_errors=False, pixel=False):
    """ Takes a set of beaconing criteria and creates a beacon from the current
    request. """

    target = None
    entity = None
    beacon = None
    source = None

    if pixel == False and (target_type is not None and target_id is not None):
        target = get_object_or_404(target_type, pk=target_id)

    # If we were passed a valid beacon source, we need to make use of it.
    if source_type is not None and source_id is not None:
        try:
            source = source_type.objects.get(pk=source_id)
        except:
            if ignore_errors is False:
                raise Http404('The specified source could not be retreived.')

    # If we were asked to use an entity, do that too.
    if entity_type is not None:
        # The system attempts to use preexisting entities when possible
        if entity_id is not None:
            entity, created = entity_type.objects.get_or_create(pk=entity_id)
        else:
            entity = entity_type()

        # TODO: Find a better name for beacon_update. update is too generic.
        if hasattr(entity, 'beacon_update') and callable(entity.beacon_update):
            entity.beacon_update(request)

        entity.save()

    # Generate an argument list for unpacking into our class constructor later
    beacon_arguments = {}

    # If we need to supply a target for this tracking instance, supply it.
    if target is not None:
        beacon_arguments.update({
            'target_type': ContentType.objects.get_for_model(target_type),
            'target_id': target.pk,
        })

    # Sometimes people want a bug and they don't need to link it to a source.
    if source is not None:
        beacon_arguments.update({
            'source_type': ContentType.objects.get_for_model(source_type),
            'source_id': source.pk,
        })

    # Sometimes a more descript entity isn't needed to webbug our entity
    if entity is not None:
        beacon_arguments.update({
            'entity_type': ContentType.objects.get_for_model(entity_type),
            'entity_id': entity.pk,
        })

    try:
        beacon = Beacon(**beacon_arguments)
        beacon.save()
    except:
        if ignore_errors is False:
            raise Http404('The requested beacon could not be created.')

    try:
        if pixel:
            return HttpResponse(base64.decodestring(transparent_gif_contents), mimetype='image/gif')
        else:
            beacon_final_url = beacon.get_absolute_url()

            # This will attempt to detect whether or not this URL is part of the current system.
            # If it is part of the current system, we don't need to redirect at all :)
            if getattr(settings, 'IGNORE_LOCAL_REDIRECTS', True):
                resolve_match = resolve(beacon_final_url)

                if resolve_match:
                    return resolve_match.func(request, *match.args, **match.kwargs)

            return HttpResponseRedirect(beacon_final_url)
    except:
        try:
            # Attempt to redirect to the target if the beacon had issues
            return HttpResponseRedirect(target.get_absolute_url())
        except:
            # We can't ignore this error, because we have no valid target
            raise Http404('The specified target was not found.')
Пример #11
0
 def setUp(self):
     self.cleanbeacon = Beacon(name='sink', is_clean=True, beacon_id='123')
     self.cleanbeacon.save()
     self.dirtybeacon = Beacon(name='door', is_clean=False, beacon_id='345')
     self.dirtybeacon.save()
Пример #12
0
def register_new_device(beacon_string=None, location_string=None):
	beacon = Beacon(beacon_identifier=beacon_string, location=location_string)
	db.session.add(beacon)
	db.session.commit()

	return "OK"
Пример #13
0
def trigger(request,
            target_type,
            target_id,
            source_type=None,
            source_id=None,
            entity_type=None,
            entity_id=None,
            ignore_errors=False,
            pixel=False):
    """ Takes a set of beaconing criteria and creates a beacon from the current
    request. """

    target = None
    entity = None
    beacon = None
    source = None

    if pixel == False and (target_type is not None and target_id is not None):
        target = get_object_or_404(target_type, pk=target_id)

    # If we were passed a valid beacon source, we need to make use of it.
    if source_type is not None and source_id is not None:
        try:
            source = source_type.objects.get(pk=source_id)
        except:
            if ignore_errors is False:
                raise Http404('The specified source could not be retreived.')

    # If we were asked to use an entity, do that too.
    if entity_type is not None:
        # The system attempts to use preexisting entities when possible
        if entity_id is not None:
            entity, created = entity_type.objects.get_or_create(pk=entity_id)
        else:
            entity = entity_type()

        # TODO: Find a better name for beacon_update. update is too generic.
        if hasattr(entity, 'beacon_update') and callable(entity.beacon_update):
            entity.beacon_update(request)

        entity.save()

    # Generate an argument list for unpacking into our class constructor later
    beacon_arguments = {}

    # If we need to supply a target for this tracking instance, supply it.
    if target is not None:
        beacon_arguments.update({
            'target_type':
            ContentType.objects.get_for_model(target_type),
            'target_id':
            target.pk,
        })

    # Sometimes people want a bug and they don't need to link it to a source.
    if source is not None:
        beacon_arguments.update({
            'source_type':
            ContentType.objects.get_for_model(source_type),
            'source_id':
            source.pk,
        })

    # Sometimes a more descript entity isn't needed to webbug our entity
    if entity is not None:
        beacon_arguments.update({
            'entity_type':
            ContentType.objects.get_for_model(entity_type),
            'entity_id':
            entity.pk,
        })

    try:
        beacon = Beacon(**beacon_arguments)
        beacon.save()
    except:
        if ignore_errors is False:
            raise Http404('The requested beacon could not be created.')

    try:
        if pixel:
            return HttpResponse(base64.decodestring(transparent_gif_contents),
                                mimetype='image/gif')
        else:
            beacon_final_url = beacon.get_absolute_url()

            # This will attempt to detect whether or not this URL is part of the current system.
            # If it is part of the current system, we don't need to redirect at all :)
            if getattr(settings, 'IGNORE_LOCAL_REDIRECTS', True):
                resolve_match = resolve(beacon_final_url)

                if resolve_match:
                    return resolve_match.func(request, *match.args,
                                              **match.kwargs)

            return HttpResponseRedirect(beacon_final_url)
    except:
        try:
            # Attempt to redirect to the target if the beacon had issues
            return HttpResponseRedirect(target.get_absolute_url())
        except:
            # We can't ignore this error, because we have no valid target
            raise Http404('The specified target was not found.')