public IHttpActionResult CreateDeviceCertificate([FromBody] DeviceCertificateModel.Format_Create dataModel)
        {
            string logForm = "Form : " + JsonConvert.SerializeObject(dataModel);
            string logAPI  = "[Post] " + Request.RequestUri.ToString();

            if (!ModelState.IsValid || dataModel == null)
            {
                Global._appLogger.Warn(logAPI + " || Input Parameter not expected || " + logForm);
                return(Content(HttpStatusCode.BadRequest, HttpResponseFormat.InvaildData()));
            }

            try
            {
                int companyId = Global.GetCompanyIdFromToken();
                DeviceCertificateModel model = new DeviceCertificateModel();
                int id = model.Create(companyId, dataModel);
                return(Content(HttpStatusCode.OK, HttpResponseFormat.Success(id)));
            }
            catch (CDSException cdsEx)
            {
                return(Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)));
            }
            catch (Exception ex)
            {
                StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
                logMessage.AppendLine(logForm);
                Global._appLogger.Error(logAPI + logMessage);

                return(Content(HttpStatusCode.InternalServerError, ex));
            }
        }
        public IHttpActionResult GetAllDeviceCertificate()
        {
            int companyId = Global.GetCompanyIdFromToken();
            DeviceCertificateModel model = new DeviceCertificateModel();

            return(Content(HttpStatusCode.OK, model.GetAllByCompanyId(companyId)));
        }
Esempio n. 3
0
        public async Task <ResultCommand> ProvisionDevice(RequestCommandProvisionDevice requestProvisionDevice, string password)
        {
            try
            {
                DeviceCertificateModel certificateInfo = requestProvisionDevice.DeviceCertificateInformation;

                //Load certificate chain
                var(deviceCertificate, collectionCertificates) =
                    LoadCertificateFromPfx(Convert.FromBase64String(certificateInfo.Certificate), password);

                //Save certificate in store
                if (!await SaveCertificateInStore(deviceCertificate))
                {
                    return(ResultCommand.CreateFailedCommand($"Error while saving User Certificate in Store."));
                }

                using (var securityProvider = new SecurityProviderX509Certificate(deviceCertificate, collectionCertificates))
                {
                    using (var transport = new ProvisioningTransportHandlerHttp())
                    {
                        ProvisioningDeviceClient provClient =
                            ProvisioningDeviceClient.Create(certificateInfo.DpsInstance, certificateInfo.DpsIdScope, securityProvider, transport);
                        DeviceRegistrationResult result = await provClient.RegisterAsync();

                        if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                        {
                            DebugHelper.LogError($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
                            return(ResultCommand.CreateFailedCommand($"Error during registration: {result.Status}, {result.ErrorMessage}"));
                        }

                        //Test the connection
                        if (!await TestDeviceConnection(result.DeviceId, result.AssignedHub, deviceCertificate))
                        {
                            return(ResultCommand.CreateFailedCommand($"Error while testing the device connection."));
                        }

                        //Persist provision in TPM/HSM
                        SimulatedDevice.ProvisionDevice(result.AssignedHub, result.DeviceId);

                        //Provisioned!
                        SimulatedDevice.IsProvisioned = true;
                    }
                }
                if (deviceCertificate != null)
                {
                    deviceCertificate.Dispose();
                }

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error ProvisionDevice: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error ProvisionDevice: {e.Message}."));
            }
        }
 public IHttpActionResult GetDeviceCertificateById(int id)
 {
     try
     {
         DeviceCertificateModel model = new DeviceCertificateModel();
         return(Content(HttpStatusCode.OK, model.GetById(id)));
     }
     catch (CDSException cdsEx)
     {
         return(Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)));
     }
     catch (Exception ex)
     {
         return(Content(HttpStatusCode.InternalServerError, ex));
     }
 }
Esempio n. 5
0
        private async Task <bool> ProvisionWithCloud()
        {
            if (csrResult == null)
            {
                return(await ProvisionDeviceFail());
            }

            // provision device with azure
            SetPairingStatusText("Provisioning device with the mothership...");

            certificateResponse = await deviceProvisioningRestService.GenerateDeviceCertificate(new DeviceCertificateRequestModel
            {
                Csr        = csrResult?.Csr ?? "MIIBbjCB2AIBADAvMS0wKwYDVQQDEyQ4OTJlYWM5YS1iOWFkLTQ0NDgtYWEwYS0wOTI0MDE1YWMwMWEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALeqOH+XoeXXERg8neKzr3IumxTDMKsPzKjZ/kfE1gu/FHmr1ugPuRTtQzP5WFVD5lWqtEKJyX+YDCjNevKeHBSpHTAAdVR8GbpDdvRvij0k6yrmrjTRVohO5bTaE611KNzXOW5K4Y8PhoTHasNnMEydfAh4ysut92lWObmg2CG1AgMBAAGgADANBgkqhkiG9w0BAQsFAAOBgQCg8dbM4gMxChp4MF67B/0ARv5Ezq3423v/Tkj5KOMxFql+NeYtM9JpIWABMw2xlARl+agp9e8eaj503grhHjYeGV0afC2/8AA2o/PyZOrS80QViDK6Z4cY+zUO5hp3darGCEH14fuAHKwrokSQxYReqdBELyT3r4ZnCdbi+NUx7A==",
                DeviceType = deviceSetupService.DeviceTypeAsString,
            });

            if (certificateResponse == null)
            {
                return(await ProvisionDeviceFail());
            }

            generateKeysResponse = await deviceProvisioningRestService.GenerateDeviceKeys(deviceSetupService.CurrentDeviceModel.DeviceId, deviceSetupService.CurrentDeviceModel.SSID);

            if (generateKeysResponse == null)
            {
                return(await ProvisionDeviceFail());
            }

            await Task.Delay(2000);

            SetPairingStatusText("Reconnecting to device and finishing up! Sit tight...");

            State = RegistrationState.ConnectingConnectingToDeviceSecondTime;
            // reconnect to device to set device type
            var reconnectSuccess = await wifiService.ConnectToWifiNetwork(deviceSetupService.CurrentDeviceModel.SSID, deviceSetupService.DefaultPassword);

            if (!reconnectSuccess)
            {
                return(await ProvisionDeviceFail());
            }
            return(true);
        }
 public IHttpActionResult DeleteDeviceCertificate(int id)
 {
     try
     {
         DeviceCertificateModel model = new DeviceCertificateModel();
         model.DeleteById(id);
         return(Content(HttpStatusCode.OK, HttpResponseFormat.Success()));
     }
     catch (CDSException cdsEx)
     {
         return(Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)));
     }
     catch (Exception ex)
     {
         string        logAPI     = "[Delete] " + Request.RequestUri.ToString();
         StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
         Global._appLogger.Error(logAPI + logMessage);
         return(Content(HttpStatusCode.InternalServerError, ex));
     }
 }