Exemplo n.º 1
0
    def handle(self, *args, **options):
        err = SystemExit(
            'refused to create example objects outside of demo mode')
        try:
            if not settings.DEMO_MODE:
                raise err
        except AttributeError:
            raise err
        Lageruser.objects.create_superuser('admin', 'admin@localhost', 'admin')
        Section.objects.create(name='Headquarters')
        Building.objects.create(name='Hall A')
        Room.objects.create(name='23',
                            building=Building.objects.first(),
                            section=Section.objects.first())
        Room.objects.create(name='24',
                            building=Building.objects.first(),
                            section=Section.objects.first())

        Manufacturer.objects.create(name='Apple')
        Devicegroup.objects.create(name='Human Resources')
        Type.objects.create(name='Notebook')
        device = Device(name='MacBook Pro 15 with Retina (mid-2015)',
                        room=Room.objects.first(),
                        devicetype=Type.objects.first(),
                        manufacturer=Manufacturer.objects.first(),
                        serialnumber='C02VK000000',
                        inventorynumber='4117')
        device.save()

        Lending.objects.create(owner=Lageruser.objects.first(),
                               device=Device.objects.first(),
                               duedate=date.today() + timedelta(days=1))
        device.currentlending = Lending.objects.first()
        device.save()
Exemplo n.º 2
0
    def create(self, validated_data):
        device = Device(device_id=validated_data['device_id'],
                        info=validated_data['info'])
        device.save()

        if validated_data['apps']:
            for item in validated_data['apps']:
                device.apps.add(item['id'])
            device.save()

        if validated_data['installed_apps']:
            for item in validated_data['installed_apps']:
                find = DeviceApp.objects.filter(
                    package_name=item['package_name'])
                if find.count() == 1:
                    app = find.first()
                else:
                    app = DeviceApp.objects.create(**item)
                device.installed_apps.add(app.id)
        if validated_data['white_list']:
            for item in validated_data['white_list']:
                find = DeviceApp.objects.filter(
                    package_name=item['package_name'])
                if find.count() == 1:
                    app = find.first()
                else:
                    app = DeviceApp.objects.create(**item)
                device.white_list.add(app.id)
        return device
Exemplo n.º 3
0
    def create(self, request):
        if not request.user.is_superuser:
            return HttpResponse(status=403)

        device = Device()
        device.save()
        return HttpResponse(status=200)
Exemplo n.º 4
0
def scan():
    """
    Scan the network

    Args:
        None
    Returns:
        None
    """
    print("SCAN")
    local_scanner = network_scan.NetworkScanner(network_scan.get_local_ip())
    arp_output = local_scanner.get_devices_on_network("-sn", "-a -n")
    ips = local_scanner.format_to_get_ip(arp_output)[:-2]
    macs = local_scanner.format_to_get_mac(arp_output)[:-2]
    vendors = local_scanner.get_vendor_by_mac(macs)
    mobile, iphone, android = network_scan.NetworkScanner.detect_mobile(ips)
    print(arp_output)
    print(ips)
    print(macs)
    print(vendors)

    for i in range(len(ips)):
        device = Device()
        device.ip_address = ips[i]
        device.mac_address = macs[i]
        device.vendor = vendors[i]
        device.mobile = mobile[i]
        device.port = 22
        device, created = Device.objects.update_or_create(
            ip_address=device.ip_address,
            mac_address=device.mac_address,
            vendor=device.vendor,
            mobile=device.mobile,
            port=device.port)
Exemplo n.º 5
0
    def enrollment_complete(self, enrollment, data):
        with transaction.atomic():
            assert enrollment.status == Enrollment.STATUS_IN_PROGRESS
            assert not enrollment.is_expired()

            # mark the enrollment as failed
            enrollment.status = Enrollment.STATUS_FAILED

            private_details, err = self.get_enrollment_private_details_model(
                enrollment.private_details)
            if err:
                logger.error(
                    'failed to retrieve private details for OTP enrollment `{0}`: {1}'
                    .format(enrollment.pk, err))
                return False, err

            # create the provisioning uri
            totp = pyotp.TOTP(s=private_details['secret'],
                              digits=private_details['digits'],
                              interval=private_details['interval'])

            ok = totp.verify(data['token'],
                             valid_window=self._configuration['valid_window'])
            if not ok:
                logger.error(
                    'failed to verify OTP `{0}` as valid for enrollment `{1}`'.
                    format(data['token'], enrollment.pk))
                return False, errors.MFASecurityError(
                    'token mismatch: `{0}` is not a valid OTP token for enrollment `{1}`'
                    .format(data['token'], enrollment.pk))

            # extract the device details
            details = OTPDeviceDetails(
                data={
                    'issuer_name': private_details['issuer_name'],
                    'digits': private_details['digits'],
                    'interval': private_details['interval'],
                    'secret': private_details['secret'],
                    'valid_window': private_details['valid_window'],
                    'algorithm': private_details['algorithm']
                })

            if not details.is_valid():
                logger.info(
                    'could not validate OTP device details: {0}'.format(
                        details.errors))

            # create the device
            device = Device()
            device.name = 'OTP [{0}]'.format(enrollment.username)
            device.kind = enrollment.device_selection.kind
            device.enrollment = enrollment

            # save the device details
            device.details = details.validated_data

            return device, None
Exemplo n.º 6
0
def fake_device(inventorynumber, word):
    return Device(created_at=fake.past_date(start_date="-600d"),
                  creator=Lageruser.objects.order_by('?').first(),
                  name=word.title(),
                  inventorynumber=inventorynumber,
                  serialnumber=random.randint(1, 1000),
                  manufacturer=Manufacturer.objects.order_by('?').first(),
                  devicetype=Type.objects.order_by('?').first(),
                  room=Room.objects.order_by('?').first(),
                  group=Devicegroup.objects.order_by('?').first(),
                  department=Department.objects.order_by('?').first())
Exemplo n.º 7
0
def add(device_name):
    try:
        device = Device(
            name=device_name,
            address=g.data['address'],
            user_id=g.auth['sub']
        )
        db.session.add(device)
        db.session.commit()
    except IntegrityError as e:
        raise AlreadyExistsError(device_name)
    return ('', HTTPStatus.NO_CONTENT)
Exemplo n.º 8
0
def setup_device():
        device = Device()
        device.user = setup_admin()
        device.name = 'Testdevice'
        device.type = 'RPB'
        device.wifi_chip = 'Atheros'
        device.os = 'Debian'
        device.description = 'This is a test device.'
        device.tags = ['test','zurich','othertag']
        device.latitude = '40.0'
        device.longitude = '83.0'
        device.save()
        return device
Exemplo n.º 9
0
 def test_device_is_related_to_location(self):
     ## 38°09'56.7"S+146°41'56.0"E
     # West and South are negative. North and East are positive
     location_ = Location.objects.create(name="Field A",
                                         longitude=-38.1665936,
                                         latitude=146.6989864,
                                         altitude=80.00)
     device = Device(name="device_a",
                     description="device description",
                     serial_id="abc",
                     address="abc")
     device.location = location_
     device.save()
     self.assertIn(device, location_.device_set.all())
Exemplo n.º 10
0
    def enrollment_complete(self, enrollment, data):
        assert enrollment.status == Enrollment.STATUS_IN_PROGRESS
        assert not enrollment.is_expired()

        # compare given token to privately stored token
        private_details = EmailDeviceEnrollmentPrivateDetails(
            data=enrollment.private_details)
        if not private_details.is_valid():
            return None, errors.MFAInconsistentStateError(
                'enrollment private details is invalid: {0}'.format(
                    private_details.errors))

        # if the token don't match, fail.
        if private_details.validated_data['token'] != data['token']:
            return None, errors.MFASecurityError(
                'token mismatch, expected `{0}` however received `{1}`'.format(
                    private_details.validated_data['token'], data['token']))

        # extract the device details
        details = EmailDeviceDetails(
            data={'address': private_details.validated_data['address']})

        assert details.is_valid()

        # create the device
        device = Device()

        device.name = u'Email [@{0}]'.format(
            EmailDeviceKindModule.mask_address(
                private_details.validated_data['address']))

        device.kind = enrollment.device_selection.kind
        device.enrollment = enrollment

        # save the device details
        device.details = details.validated_data

        return device, None
Exemplo n.º 11
0
    def post(self, request, *args, **kwargs):
        data = Data()

        result = check_device(**request.POST)

        if result:
            try:
                device = Device.objects.get(device_mac=result["device_mac"])
            except Device.DoesNotExist:
                device = Device(**result)
                device.save()

            device_enabled = device.enabled
            if device_enabled:
                result = check_data(**request.POST)
                if result:
                    data.data_value = result["data_value"]
                    data.device = device
                    data.date = datetime.datetime.now(
                    )  #TODO: Device sends real datetime
                    data.save()

        return JsonResponse({'status': True})
Exemplo n.º 12
0
 def handle(self, *args, **options):
     device = Device()
     device.save()
Exemplo n.º 13
0
def device_add(request, os, model):
    device = Device(os=os, model=model)
    device.save()
    return HttpResponse("created device {}".format(device))
Exemplo n.º 14
0
    ip_address = str(process.read())[:-1]  #Removes the space at the end
    return ip_address


local_device_ip = get_local_ip()
local_scanner = NetworkScanner(get_local_ip())
arp_output = local_scanner.get_devices_on_network("-sn", "-a -n")
ips = local_scanner.format_to_get_ip(arp_output)[:-2]
# ips = local_scanner.check_if_identifier_broadcast(ips)
macs = local_scanner.format_to_get_mac(arp_output)[:-2]
vendors = local_scanner.get_vendor_by_mac(macs)
mobile, iphone, android = NetworkScanner.detect_mobile(ips)
ports_open = local_scanner.detect_open_common_ports(ips)
print(arp_output)
print(ips)
print(macs)
print(vendors)

for i in range(len(ips)):
    device = Device()
    device.ip_address = ips[i]
    device.mac_address = macs[i]
    device.vendor = vendors[i]
    device.mobile = mobile[i]
    device.port = ports_open[i]
    device, created = Device.objects.update_or_create(
        ip_address=device.ip_address,
        mac_address=device.mac_address,
        vendor=device.vendor,
        mobile=device.mobile,
        port=device.port)
Exemplo n.º 15
0
#!/usr/bin/env python3

from devices.models import Device, Sensor, Measurement
import random

device1 = Device(name="DummyDevice1",
                 id="cbb4f156-70ba-453c-ba47-4ec2301b654c",
                 description="Dummy device for displaying fake data.")
device1.save()

sensor11 = Sensor(name="DummySensor1", parent=device1)
sensor11.save()

for _ in range(45):
    value = random.randint(15, 30)
    m = Measurement(value=value, unit="C", sensor=sensor11)
    m.save()

device2 = Device(name="DummyDevice2",
                 id="0bc25db7-c44e-4e94-9305-b377bd5f6e72",
                 description="Dummy device for displaying fake data.")
device2.save()

sensor21 = Sensor(name="DummySensor1", parent=device2)
sensor21.save()

for _ in range(45):
    value = random.randint(-15, 15)
    m = Measurement(value=value, unit="C", sensor=sensor21)
    m.save()
Exemplo n.º 16
0
 def test_registered_is_false_by_default(self):
     device = Device(name="device_a",
                     description="device description",
                     serial_id="abc",
                     address="abc")
     self.assertFalse(device.registered)
Exemplo n.º 17
0
 def test_cannot_save_with_blank_columns(self):
     device = Device(name="device_a", description="device description")
     with self.assertRaises(ValidationError):
         device.save()
         device.full_clean()