Пример #1
0
        /// <summary>
        /// Adds a device to the Device Identity Store and Device Registry
        /// </summary>
        /// <param name="device">Device to add to the underlying repositories</param>
        /// <returns>Device created along with the device identity store keys</returns>
        public async Task <DeviceWithKeys> AddDeviceAsync(dynamic device)
        {
            // Validation logic throws an exception if it finds a validation error
            await ValidateDevice(device);

            SecurityKeys generatedSecurityKeys = _securityKeyGenerator.CreateRandomKeys();

            dynamic savedDevice = await AddDeviceToRepositoriesAsync(device, generatedSecurityKeys);

            return(new DeviceWithKeys(savedDevice, generatedSecurityKeys));
        }
Пример #2
0
        /// <summary>
        /// Generates N devices with random data and properties for testing
        /// NOTE: Adds the devices to both the device registry and device identity repository
        /// </summary>
        /// <param name="deviceCount">Number of devices to generate</param>
        /// <returns></returns>
        /// <remarks>TEMPORARY DEVICE GENERATION CODE FOR TESTING PURPOSES!</remarks>
        public async Task GenerateNDevices(int deviceCount)
        {
            Random randomNumber = new Random();

            for (int i = 0; i < deviceCount; i++)
            {
                SecurityKeys generatedSecurityKeys = _securityKeyGenerator.CreateRandomKeys();
                dynamic      device = SampleDeviceFactory.GetSampleDevice(randomNumber, generatedSecurityKeys);
                await AddDeviceToRepositoriesAsync(device, generatedSecurityKeys);
            }
        }
Пример #3
0
        public void Load()
        {
            string bios = RandomFunctions.GetBIOSSerialNumber();

            string _uKey = "UN_" + bios;

            _username = Encryption.DecryptStringFromBytes(SecurityKeys.StringToByteArray((string)Registry.GetValue(RegSaveBase, "DAT_B", null)), SecurityKeys.GenerateKey(_uKey), SecurityKeys.GenerateIV(_uKey));

            string _pKey = "PD_" + bios;

            _password = Encryption.DecryptStringFromBytes(SecurityKeys.StringToByteArray((string)Registry.GetValue(RegSaveBase, "DAT_A", null)), SecurityKeys.GenerateKey(_pKey), SecurityKeys.GenerateIV(_pKey));
        }
Пример #4
0
        public void Save()
        {
            string bios = RandomFunctions.GetBIOSSerialNumber();

            string _uKey = "UN_" + bios;

            Registry.SetValue(RegSaveBase, "DAT_B", SecurityKeys.ByteArrayToString(Encryption.EncryptStringToBytes(_username, SecurityKeys.GenerateKey(_uKey), SecurityKeys.GenerateIV(_uKey))));

            string _pKey = "PD_" + bios;

            Registry.SetValue(RegSaveBase, "DAT_A", SecurityKeys.ByteArrayToString(Encryption.EncryptStringToBytes(_password, SecurityKeys.GenerateKey(_pKey), SecurityKeys.GenerateIV(_pKey))));
        }
        public async Task <List <string> > BootstrapDefaultDevices()
        {
            List <string> sampleIds = SampleDeviceFactory.GetDefaultDeviceNames();

            foreach (string id in sampleIds)
            {
                DeviceModel  device = DeviceCreatorHelper.BuildDeviceStructure(id, true, null);
                SecurityKeys generatedSecurityKeys = _securityKeyGenerator.CreateRandomKeys();
                await this.AddDeviceToRepositoriesAsync(device, generatedSecurityKeys);
            }
            return(sampleIds);
        }
Пример #6
0
        public static dynamic GetSampleDevice(Random randomNumber, SecurityKeys keys)
        {
            string deviceId = string.Format("00000-DEV-{0}C-{1}LK-{2}D-{3}",
                                            MAX_COMMANDS_SUPPORTED, randomNumber.Next(99999));
            dynamic device = DeviceSchemaHelper.BuildDeviceStructure(deviceId, false);

            device.ObjectName = "IoT Device Description";

            AssignDeviceProperties(deviceId, device);
            AssignCommands(device);

            return(device);
        }
Пример #7
0
        public async Task OnGet_GivenUserHasDevices_ExpectPopulatedDevicesList()
        {
            var userQueries = new Mock <IUserQueries>();

            userQueries.Setup(x => x.GetDeviceInfoForCurrentUser())
            .ReturnsAsync(Maybe.From(new List <DeviceInfo>
            {
                new DeviceInfo(
                    TestVariables.AuthenticatorDeviceId,
                    "name",
                    TestVariables.Now.AddMinutes(-60),
                    TestVariables.Now),
            }));

            var page = new SecurityKeys(userQueries.Object);
            await page.OnGet();

            Assert.Single(page.DeviceInfos);
        }
        /// <summary>
        /// Adds the provided device to the IoT hub with the provided security keys
        /// </summary>
        /// <param name="device"></param>
        /// <param name="securityKeys"></param>
        /// <returns></returns>
        public async Task<dynamic> AddDeviceAsync(dynamic device, SecurityKeys securityKeys)
        {
            Device iotHubDevice = new Device(DeviceSchemaHelper.GetDeviceID(device));

            var authentication = new AuthenticationMechanism
            {
                SymmetricKey = new SymmetricKey
                {
                    PrimaryKey = securityKeys.PrimaryKey,
                    SecondaryKey = securityKeys.SecondaryKey
                }
            };

            iotHubDevice.Authentication = authentication;

            await AzureRetryHelper.OperationWithBasicRetryAsync(async () =>
                await _deviceManager.AddDeviceAsync(iotHubDevice));

            return device;
        }
        /// <summary>
        ///     Adds the provided device to the IoT hub with the provided security keys
        /// </summary>
        /// <param name="device"></param>
        /// <param name="securityKeys"></param>
        /// <returns></returns>
        public async Task <DeviceModel> AddDeviceAsync(DeviceModel device, SecurityKeys securityKeys)
        {
            var iotHubDevice = new Device(device.DeviceProperties.DeviceID);

            var authentication = new AuthenticationMechanism
            {
                SymmetricKey = new SymmetricKey
                {
                    PrimaryKey   = securityKeys.PrimaryKey,
                    SecondaryKey = securityKeys.SecondaryKey
                }
            };

            iotHubDevice.Authentication = authentication;

            await AzureRetryHelper.OperationWithBasicRetryAsync(async() =>
                                                                await this._deviceManager.AddDeviceAsync(iotHubDevice));

            return(device);
        }
Пример #10
0
        /// <summary>
        /// Adds the provided device to the IoT hub with the provided security keys
        /// </summary>
        /// <param name="device"></param>
        /// <param name="securityKeys"></param>
        /// <returns></returns>
        public async Task <dynamic> AddDeviceAsync(dynamic device, SecurityKeys securityKeys)
        {
            Azure.Devices.Device iotHubDevice = new Azure.Devices.Device(DeviceSchemaHelper.GetDeviceID(device));

            var authentication = new AuthenticationMechanism
            {
                SymmetricKey = new SymmetricKey
                {
                    PrimaryKey   = securityKeys.PrimaryKey,
                    SecondaryKey = securityKeys.SecondaryKey
                }
            };

            iotHubDevice.Authentication = authentication;

            await AzureRetryHelper.OperationWithBasicRetryAsync <Azure.Devices.Device>(async() =>
                                                                                       await _deviceManager.AddDeviceAsync(iotHubDevice));

            return(device);
        }
Пример #11
0
        public static DeviceModel GetSampleDevice(Random randomNumber, SecurityKeys keys)
        {
            var deviceId = string.Format(
                CultureInfo.InvariantCulture,
                "00000-DEV-{0}C-{1}LK-{2}D-{3}",
                MAX_COMMANDS_SUPPORTED,
                randomNumber.Next(99999),
                randomNumber.Next(99999),
                randomNumber.Next(99999));

            var device = DeviceCreatorHelper.BuildDeviceStructure(deviceId, false, null);

            device.ObjectName = "IoT Device Description";

            AssignDeviceProperties(device);
            AssignTelemetry(device);
            AssignCommands(device);

            return(device);
        }
Пример #12
0
        private void ShowActivateResult(bool value, string msg)
        {
            if (value)
            {
                // If on Vista or newer, we need to elevate to activate.
                if (Environment.OSVersion.Version >= OSVersions.Win_Vista)
                {
                    IsEnabled = false;

                    try
                    {
                        ProcessStartInfo pInfo = new ProcessStartInfo(Process.GetCurrentProcess().MainModule.FileName);
                        pInfo.Verb = "runas";

                        string key = Activation.Key;
                        pInfo.Arguments = "/activate " +
                                          Convert.ToBase64String(Encryption.EncryptStringToBytes(key, SecurityKeys.GenerateKey(key), SecurityKeys.GenerateIV(key)));

                        Process proc = Process.Start(pInfo);
                        proc.EnableRaisingEvents = true;
                        proc.Exited += proc_Exited;
                    }
                    catch (Win32Exception)
                    {
                        Thread deActivate = new Thread(() =>
                        {
                            try
                            {
                                Activation.Free(Activation.Key);
                            }
                            catch { }
                        });
                        deActivate.Start();

                        animation.Stop();
                        message.Text               = "Error: Activation could not be completed due to insufficient privileges.";
                        retryButton.Visibility     = Visibility.Visible;
                        closeButton.Visibility     = Visibility.Visible;
                        changeProductKey.IsEnabled = true;

                        DialogResult = false;
                    }
                }
                else
                {
                    Activation.Activate();
                    DialogResult = true;
                }
            }
            else
            {
                animation.Stop();
                message.Text               = "Error: " + msg;
                retryButton.Visibility     = Visibility.Visible;
                closeButton.Visibility     = Visibility.Visible;
                changeProductKey.IsEnabled = true;
            }
        }
 public DeviceWithKeys(DeviceModel device, SecurityKeys securityKeys)
 {
     Device       = device;
     SecurityKeys = securityKeys;
 }
Пример #14
0
 public DeviceWithKeys(dynamic device, SecurityKeys securityKeys)
 {
     Device       = device;
     SecurityKeys = securityKeys;
 }
Пример #15
0
 private AsyncParseService(SecurityKeys securityKeys_)
 {
     _securityKeys = securityKeys_;
     ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
 }
Пример #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpreedlyService" /> class.
 /// </summary>
 /// <param name="securityKeys">The security keys.</param>
 private SpreedlyService(SecurityKeys securityKeys)
 {
     this.securityKeys = securityKeys;
     ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
 }
        /// <summary>
        /// Adds the given device and assigned keys to the underlying repositories
        /// </summary>
        /// <param name="device">Device to add to repositories</param>
        /// <param name="securityKeys">Keys to assign to the device</param>
        /// <returns>Device that was added to the device registry</returns>
        private async Task <DeviceModel> AddDeviceToRepositoriesAsync(DeviceModel device, SecurityKeys securityKeys)
        {
            DeviceModel           registryRepositoryDevice = null;
            ExceptionDispatchInfo capturedException        = null;

            // if an exception happens at this point pass it up the stack to handle it
            // (Making this call first then the call against the Registry removes potential issues
            // with conflicting rollbacks if the operation happens to still be in progress.)
            await _iotHubRepository.AddDeviceAsync(device, securityKeys);

            try
            {
                registryRepositoryDevice = await _deviceRegistryCrudRepository.AddDeviceAsync(device);
            }
            catch (Exception ex)
            {
                // grab the exception so we can attempt an async removal of the device from the IotHub
                capturedException = ExceptionDispatchInfo.Capture(ex);
            }

            //Create a device in table storage if it is a simulated type of device
            //and the document was stored correctly without an exception
            bool isSimulatedAsBool = false;

            try
            {
                isSimulatedAsBool = (bool)device.IsSimulatedDevice;
            }
            catch (InvalidCastException ex)
            {
                Trace.TraceError("The IsSimulatedDevice property was in an invalid format. Exception Error Message: {0}", ex.Message);
            }
            if (capturedException == null && isSimulatedAsBool)
            {
                try
                {
                    await _virtualDeviceStorage.AddOrUpdateDeviceAsync(new InitialDeviceConfig()
                    {
                        DeviceId = device.DeviceProperties.DeviceID,
                        HostName = _configProvider.GetConfigurationSettingValue("iotHub.HostName"),
                        Key      = securityKeys.PrimaryKey
                    });
                }
                catch (Exception ex)
                {
                    //if we fail adding to table storage for the device simulator just continue
                    Trace.TraceError("Failed to add simulated device : {0}", ex.Message);
                }
            }


            // Since the rollback code runs async and async code cannot run within the catch block it is run here
            if (capturedException != null)
            {
                // This is a lazy attempt to remove the device from the Iot Hub.  If it fails
                // the device will still remain in the Iot Hub.  A more robust rollback may be needed
                // in some scenarios.
                await _iotHubRepository.TryRemoveDeviceAsync(device.DeviceProperties.DeviceID);

                capturedException.Throw();
            }

            return(registryRepositoryDevice);
        }
Пример #18
0
        public async void AddDeviceAsyncTest()
        {
            var d1 = this.fixture.Create <DeviceModel>();

            this._iotHubRepositoryMock.Setup(x => x.AddDeviceAsync(It.IsAny <DeviceModel>(), It.IsAny <SecurityKeys>()))
            .ReturnsAsync(d1);

            //Add device without DeviceProperties
            d1.DeviceProperties = null;
            await Assert.ThrowsAsync <ValidationException>(async() => await this._deviceLogic.AddDeviceAsync(d1));

            //Add device with Null or empty DeviceId
            d1.DeviceProperties          = this.fixture.Create <DeviceProperties>();
            d1.DeviceProperties.DeviceID = null;
            await Assert.ThrowsAsync <ValidationException>(async() => await this._deviceLogic.AddDeviceAsync(d1));

            d1.DeviceProperties.DeviceID = "";
            await Assert.ThrowsAsync <ValidationException>(async() => await this._deviceLogic.AddDeviceAsync(d1));

            //Add existing device
            var d2 = this.fixture.Create <DeviceModel>();

            this._deviceRegistryCrudRepositoryMock.Setup(x => x.GetDeviceAsync(d2.DeviceProperties.DeviceID))
            .ReturnsAsync(d2);
            await Assert.ThrowsAsync <ValidationException>(async() => await this._deviceLogic.AddDeviceAsync(d2));

            d1.DeviceProperties.DeviceID = this.fixture.Create <string>();
            var keys = new SecurityKeys("fbsIV6w7gfVUyoRIQFSVgw ==", "1fLjiNCMZF37LmHnjZDyVQ ==");

            this._securityKeyGeneratorMock.Setup(x => x.CreateRandomKeys()).Returns(keys);
            var hostname = this.fixture.Create <string>();

            this._configProviderMock.Setup(x => x.GetConfigurationSettingValue(It.IsAny <string>())).Returns(hostname);

            //Device registry throws exception
            this._deviceRegistryCrudRepositoryMock.Setup(x => x.AddDeviceAsync(It.IsAny <DeviceModel>()))
            .ThrowsAsync(new Exception());
            this._iotHubRepositoryMock.Setup(x => x.TryRemoveDeviceAsync(It.IsAny <string>())).ReturnsAsync(true).Verifiable();
            await Assert.ThrowsAsync <Exception>(async() => await this._deviceLogic.AddDeviceAsync(d1));

            this._virtualDeviceStorageMock.Verify(x => x.AddOrUpdateDeviceAsync(It.IsAny <InitialDeviceConfig>()),
                                                  Times.Never());
            this._iotHubRepositoryMock.Verify(x => x.TryRemoveDeviceAsync(d1.DeviceProperties.DeviceID), Times.Once());

            //Custom device
            d1.IsSimulatedDevice = false;
            this._deviceRegistryCrudRepositoryMock.Setup(x => x.AddDeviceAsync(It.IsAny <DeviceModel>())).ReturnsAsync(d1);
            var ret = await this._deviceLogic.AddDeviceAsync(d1);

            this._virtualDeviceStorageMock.Verify(x => x.AddOrUpdateDeviceAsync(It.IsAny <InitialDeviceConfig>()),
                                                  Times.Never());
            Assert.NotNull(ret);
            Assert.Equal(d1, ret.Device);
            Assert.Equal(keys, ret.SecurityKeys);

            //Simulated device
            this._deviceRegistryCrudRepositoryMock.Setup(x => x.AddDeviceAsync(It.IsAny <DeviceModel>())).ReturnsAsync(d1);
            this._virtualDeviceStorageMock.Setup(x => x.AddOrUpdateDeviceAsync(It.IsAny <InitialDeviceConfig>())).Verifiable();
            d1.IsSimulatedDevice = true;
            ret = await this._deviceLogic.AddDeviceAsync(d1);

            this._virtualDeviceStorageMock.Verify(x => x.AddOrUpdateDeviceAsync(It.IsAny <InitialDeviceConfig>()),
                                                  Times.Once());
            Assert.NotNull(ret);
            Assert.Equal(d1, ret.Device);
            Assert.Equal(keys, ret.SecurityKeys);
        }
Пример #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConfigsSeivce(Configuration);
            //读取设置配置项
            JwtParameterConfiguration jwtParameterConfig = new JwtParameterConfiguration();

            Configuration.Bind("JwtParameters", jwtParameterConfig);
            services.AddSingleton(jwtParameterConfig);
            ExpiresTime expiresTime = new ExpiresTime();

            Configuration.Bind("ExpiresTime", expiresTime);
            services.AddSingleton(expiresTime);
            SecurityKeys securityKeys = new SecurityKeys();

            Configuration.Bind("SecurityKeys", securityKeys);
            services.AddSingleton(securityKeys);
            AppInfo appInfo = new AppInfo();

            Configuration.Bind("AppInfo", appInfo);
            services.AddSingleton(appInfo);

            //生成RsaSecurityKey用于JWT Token签名
            var rsaKeyBytes = Convert.FromBase64String(securityKeys.RSAKey);
            var rsaProvider = new RSACryptoServiceProvider();

            rsaProvider.ImportCspBlob(rsaKeyBytes);
            RSAParameters rsaParams      = rsaProvider.ExportParameters(true);
            var           rsaSecurityKey = new RsaSecurityKey(rsaParams);

            services.AddSingleton(rsaSecurityKey);

            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, option =>
            {
                option.Authority                 = jwtParameterConfig.Issuer;
                option.RequireHttpsMetadata      = false;
                option.Audience                  = jwtParameterConfig.Audience;
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name,
                    RoleClaimType = JwtClaimTypes.Role,
                };
                option.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        if (context.Request.Headers.TryGetValue("Authorization", out var tokenInfo))
                        {
                            context.Token = tokenInfo[0].Split(" ")[1];
                        }
                        else if (context.Request.Cookies.TryGetValue(jwtParameterConfig.CookieName, out var token))
                        {
                            context.Token = token;
                        }
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                                       new TokenValidatedInvoker().Invoke(context),
                };
            });
Пример #20
0
 private SpreedlyService(SecurityKeys securityKeys)
 {
     _securityKeys = securityKeys;
     ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
 }
Пример #21
0
        public static void Main()
        {
            try
            {
                string[] args = Environment.GetCommandLineArgs();

                if (args.Length >= 2)
                {
                    switch (args[1].ToLower())
                    {
                    case "/update":
                        string localPath = (new FileInfo(Process.GetCurrentProcess().MainModule.FileName)).DirectoryName;
                        string oldFile   = localPath + "\\UpdateManager.exe";
                        string tempDir   = Data.UpdatesWorkingDirectory;
                        string newFile   = tempDir + "\\~UpdateManager.exe";

                        try
                        {
                            File.Delete(oldFile);
                            File.Move(newFile, oldFile);
                        }
                        catch { }

                        if (Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories).Length == 0)
                        {
                            Directory.Delete(tempDir, true);
                        }

                        return;

                    case "/nosingleinstance":
                        try { DisableProcessWindowsGhosting(); }
                        catch { }

                        if (Settings.FirstRun)
                        {
                            FirstRun();
                        }

                        args = null;

                        new App().Run();

                        return;

                    case "/setkey":
                        Activation.ActivationGracePeriodStart = DateTime.Now;
                        Activation.Key = args[2];
                        return;

                    case "/activate":
                        string keyHash = args[2];
                        string key     = Activation.Key;
                        if (Encryption.DecryptStringFromBytes(Convert.FromBase64String(keyHash),
                                                              SecurityKeys.GenerateKey(key), SecurityKeys.GenerateIV(key))
                            == key)
                        {
                            Activation.Activate();
                        }
                        return;

                    default:
                        break;
                    }
                }

                if (SingleInstance <App> .InitializeAsFirstInstance(AssemblyAttributeAccessors.AssemblyTitle + "_" + AssemblyAttributeAccessors.AssemblyVersion))
                {
                    try { DisableProcessWindowsGhosting(); }
                    catch { }

                    if (Settings.FirstRun)
                    {
                        FirstRun();
                    }

                    args = null;

                    new App().Run();

                    // Allow single instance code to perform cleanup operations
                    SingleInstance <App> .Cleanup();
                }
            }
            catch (Exception exc)
            {
                // Log the exception
                Log(exc);

                // Restart
                Process.Start(Process.GetCurrentProcess().MainModule.FileName, string.Join(" ", Environment.GetCommandLineArgs()));

                // Shutdown
                Environment.Exit(-1);
            }
        }