Example #1
0
        /// <summary>
        /// Authenticate against the IoT Hub using an authorization rule.
        /// </summary>
        /// <param name="sasAuthorizationRule">The properties that describe the keys to access the IotHub artifacts.</param>
        public void Authenticate(SharedAccessSignatureAuthorizationRule sasAuthorizationRule)
        {
            if (sasAuthorizationRule == null)
            {
                throw new ArgumentNullException(nameof(sasAuthorizationRule), "The SAS Authorization Rule cannot be null.");
            }
            if (IsExpired())
            {
                throw new UnauthorizedAccessException("The specified SAS token has expired.");
            }

            if (sasAuthorizationRule.PrimaryKey != null)
            {
                string primareyKeyComputedSignature = ComputeSignature(Convert.FromBase64String(sasAuthorizationRule.PrimaryKey));
                if (StringComparer.Ordinal.Equals(Signature, primareyKeyComputedSignature))
                {
                    return;
                }
            }

            if (sasAuthorizationRule.SecondaryKey != null)
            {
                string secondaryKeyComputedSignature = ComputeSignature(Convert.FromBase64String(sasAuthorizationRule.SecondaryKey));
                if (StringComparer.Ordinal.Equals(Signature, secondaryKeyComputedSignature))
                {
                    return;
                }
            }

            throw new UnauthorizedAccessException("The specified SAS token has an invalid signature. It does not match either the primary or secondary key.");
        }
        public void Authenticate(SharedAccessSignatureAuthorizationRule sasAuthorizationRule)
        {
            if (this.IsExpired())
            {
                throw new UnauthorizedAccessException("The specified SAS token is expired.");
            }

            if (sasAuthorizationRule.PrimaryKey != null)
            {
                string primareyKeyComputedSignature = this.ComputeSignature(Convert.FromBase64String(sasAuthorizationRule.PrimaryKey));
                if (string.Equals(this.signature, primareyKeyComputedSignature))
                {
                    return;
                }
            }

            if (sasAuthorizationRule.SecondaryKey != null)
            {
                string secondaryKeyComputedSignature = this.ComputeSignature(Convert.FromBase64String(sasAuthorizationRule.SecondaryKey));
                if (string.Equals(this.signature, secondaryKeyComputedSignature))
                {
                    return;
                }
            }

            throw new UnauthorizedAccessException("The specified SAS token has an invalid signature. It does not match either the primary or secondary key.");
        }
Example #3
0
        public override void ExecuteCmdlet()
        {
            IotHubDescription iotHubDescription;

            if (ParameterSetName.Equals(InputObjectParameterSet))
            {
                this.ResourceGroupName = this.InputObject.Resourcegroup;
                this.IotHubName        = this.InputObject.Name;
                iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
            }
            else
            {
                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                    this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                }

                iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
            }

            IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
            SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
            PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
            RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

            if (this.Name != null)
            {
                this.WriteObject(IotHubDataPlaneUtils.ToPSDeployment(registryManager.GetConfigurationAsync(this.Name).GetAwaiter().GetResult()));
            }
            else
            {
                this.WriteObject(IotHubDataPlaneUtils.ToPSDeployments(registryManager.GetConfigurationsAsync(Int32.MaxValue).GetAwaiter().GetResult()), true);
            }
        }
        public override void ExecuteCmdlet()
        {
            IotHubDescription iotHubDescription;

            if (ParameterSetName.Equals(InputObjectParameterSet))
            {
                this.ResourceGroupName = this.InputObject.Resourcegroup;
                this.IotHubName        = this.InputObject.Name;
                iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
            }
            else
            {
                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                    this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                }

                iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
            }

            IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
            SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
            PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
            RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

            Twin deviceTwin = registryManager.GetTwinAsync(this.DeviceId).GetAwaiter().GetResult();

            if (deviceTwin == null)
            {
                throw new ArgumentException($"The entered device \"{this.DeviceId}\" doesn't exist.");
            }

            this.WriteObject(IotHubDataPlaneUtils.ToPSDeviceTwin(deviceTwin));
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.SetIotHubConfiguration))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                Configuration config = registryManager.GetConfigurationAsync(this.Name).GetAwaiter().GetResult();
                if (config != null && config.Content.ModulesContent != null)
                {
                    PSDeployment psDeployment = IotHubDataPlaneUtils.ToPSDeployment(config);

                    if (this.IsParameterBound(c => c.Priority))
                    {
                        psDeployment.Priority = this.Priority;
                    }

                    if (this.IsParameterBound(c => c.TargetCondition))
                    {
                        psDeployment.TargetCondition = this.TargetCondition;
                    }

                    if (this.IsParameterBound(c => c.Label))
                    {
                        psDeployment.Labels = this.Label;
                    }

                    if (this.IsParameterBound(c => c.Metric))
                    {
                        psDeployment.Metrics.Queries = this.Metric;
                    }

                    this.WriteObject(IotHubDataPlaneUtils.ToPSDeployment(registryManager.UpdateConfigurationAsync(IotHubDataPlaneUtils.ToConfiguration(psDeployment), this.Force.IsPresent).GetAwaiter().GetResult()));
                }
                else
                {
                    throw new ArgumentException("The deployment doesn't exist.");
                }
            }
        }
        public void AuthenticateThrowsInvalidSASTest()
        {
            var sas = SharedAccessSignature.Parse(IOT_HUB_NAME, this.GetNonExpiredToken());

            var rule = new SharedAccessSignatureAuthorizationRule();

            Assert.Throws <UnauthorizedAccessException>(() => sas.Authenticate(rule));
        }
Example #7
0
 public static PSIotHubConnectionString ToPSIotHubConnectionString(this SharedAccessSignatureAuthorizationRule authorizationPolicy, string hostName)
 {
     return(new PSIotHubConnectionString()
     {
         KeyName = authorizationPolicy.KeyName,
         PrimaryConnectionString = String.Format(IotHubConnectionStringTemplate, hostName, authorizationPolicy.KeyName, authorizationPolicy.PrimaryKey),
         SecondaryConnectionString = String.Format(IotHubConnectionStringTemplate, hostName, authorizationPolicy.KeyName, authorizationPolicy.SecondaryKey)
     });
 }
Example #8
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.RemoveIotHubConfiguration))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                try
                {
                    if (this.Name != null)
                    {
                        registryManager.RemoveConfigurationAsync(this.Name).GetAwaiter().GetResult();
                    }
                    else
                    {
                        IEnumerable <Configuration> configs = registryManager.GetConfigurationsAsync(Int32.MaxValue).GetAwaiter().GetResult();
                        foreach (Configuration config in configs)
                        {
                            registryManager.RemoveConfigurationAsync(config).GetAwaiter().GetResult();
                        }
                    }

                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(true);
                    }
                }
                catch
                {
                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(false);
                    }
                }
            }
        }
Example #9
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.AddIotHubConfiguration))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                PSConfiguration psConfiguration = new PSConfiguration();
                psConfiguration.Id              = this.Name;
                psConfiguration.Priority        = this.Priority;
                psConfiguration.TargetCondition = string.IsNullOrEmpty(this.TargetCondition) ? "" : this.TargetCondition;
                psConfiguration.Labels          = new Hashtable();
                psConfiguration.Metrics         = new PSConfigurationMetrics()
                {
                    Queries = new Hashtable(), Results = new Hashtable()
                };
                psConfiguration.Content = new PSConfigurationContent()
                {
                    DeviceContent = new Hashtable(), ModulesContent = new Hashtable()
                };

                if (this.IsParameterBound(c => c.Label))
                {
                    psConfiguration.Labels = this.Label;
                }

                if (this.IsParameterBound(c => c.Metric))
                {
                    psConfiguration.Metrics.Queries = this.Metric;
                }

                psConfiguration.Content.ModulesContent = this.IsParameterBound(c => c.ModulesContent) ? this.ModulesContent : this.GetEdgeConfigurationContent();

                this.WriteObject(IotHubDataPlaneUtils.ToPSDeployment(registryManager.AddConfigurationAsync(IotHubDataPlaneUtils.ToConfiguration(psConfiguration)).GetAwaiter().GetResult()));
            }
        }
        public void AuthenticateThrowsIsExpiredTest()
        {
            var sas = SharedAccessSignature.Parse(IOT_HUB_NAME, this.GetAlmostExpiredToken());

            var rule = new SharedAccessSignatureAuthorizationRule();

            Thread.Sleep(5 * 1000);

            Assert.Throws <UnauthorizedAccessException>(() => sas.Authenticate(rule));
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.ModuleId, Properties.Resources.AddIotHubModule))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);

                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);

                PSAuthenticationMechanism auth = new PSAuthenticationMechanism();
                PSModule module = new PSModule();
                module.Id       = this.ModuleId;
                module.DeviceId = this.DeviceId;
                switch (this.AuthMethod)
                {
                case PSDeviceAuthType.x509_thumbprint:
                    auth.Type           = PSAuthenticationType.SelfSigned;
                    auth.X509Thumbprint = new PSX509Thumbprint();
                    auth.X509Thumbprint.PrimaryThumbprint   = this.authTypeDynamicParameter.PrimaryThumbprint;
                    auth.X509Thumbprint.SecondaryThumbprint = this.authTypeDynamicParameter.SecondaryThumbprint;
                    break;

                case PSDeviceAuthType.x509_ca:
                    auth.Type = PSAuthenticationType.CertificateAuthority;
                    break;

                default:
                    auth.SymmetricKey = new PSSymmetricKey();
                    auth.Type         = PSAuthenticationType.Sas;
                    break;
                }
                module.Authentication = auth;

                RegistryManager registryManager = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);
                this.WriteObject(IotHubDataPlaneUtils.ToPSModule(registryManager.AddModuleAsync(IotHubDataPlaneUtils.ToModule(module)).GetAwaiter().GetResult()));
            }
        }
Example #12
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DeviceId, Properties.Resources.UpdateIotHubDeviceTwin))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                Twin deviceTwin = registryManager.GetTwinAsync(this.DeviceId).GetAwaiter().GetResult();

                if (deviceTwin == null)
                {
                    throw new ArgumentException($"The entered device \"{this.DeviceId}\" doesn't exist.");
                }

                if (this.IsParameterBound(c => c.Tag))
                {
                    deviceTwin.Tags = new TwinCollection(JsonConvert.SerializeObject(this.Tag));
                }

                if (this.IsParameterBound(c => c.Desired))
                {
                    deviceTwin.Properties.Desired = new TwinCollection(JsonConvert.SerializeObject(this.Desired));
                }

                if (this.Partial.IsPresent)
                {
                    this.WriteObject(registryManager.UpdateTwinAsync(this.DeviceId, deviceTwin, deviceTwin.ETag).GetAwaiter().GetResult());
                }
                else
                {
                    this.WriteObject(registryManager.ReplaceTwinAsync(this.DeviceId, deviceTwin, deviceTwin.ETag).GetAwaiter().GetResult());
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DeviceId, Properties.Resources.SetIotHubDistributedTracing))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                PSDistributedTracing psDistributedTracing = new PSDistributedTracing();
                Twin deviceTwin = registryManager.GetTwinAsync(this.DeviceId).GetAwaiter().GetResult();

                IotHubDataPlaneUtils.ValidateDeviceTracing(this.DeviceId, iotHubDescription.Sku.Tier.Value.ToString(), iotHubDescription.Location, deviceTwin.Capabilities.IotEdge);

                if (deviceTwin.Properties.Desired.Contains(IotHubDataPlaneUtils.TracingProperty))
                {
                    psDistributedTracing = JsonConvert.DeserializeObject <PSDistributedTracing>(deviceTwin.Properties.Desired[IotHubDataPlaneUtils.TracingProperty].ToString());
                }

                psDistributedTracing.SamplingMode = this.SamplingMode;

                if (this.SamplingMode.Equals(PSDistributedTracingSamplingMode.Enabled))
                {
                    if (this.IsParameterBound(c => c.SamplingRate))
                    {
                        psDistributedTracing.SamplingRate = this.SamplingRate;
                    }
                }

                deviceTwin.Properties.Desired[IotHubDataPlaneUtils.TracingProperty] = psDistributedTracing;

                deviceTwin = registryManager.UpdateTwinAsync(this.DeviceId, deviceTwin, deviceTwin.ETag).GetAwaiter().GetResult();

                this.WriteObject(IotHubDataPlaneUtils.GetDeviceTracing(this.DeviceId, deviceTwin));
            }
        }
Example #14
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.InvokeIotHubDeviceMethod))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.ServiceConnect);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                ServiceClient            serviceClient            = ServiceClient.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                if (!this.IsParameterBound(c => c.ResponseTimeOut))
                {
                    this.ResponseTimeOut = 10;
                }

                if (!this.IsParameterBound(c => c.ConnectionTimeOut))
                {
                    this.ConnectionTimeOut = 10;
                }

                CloudToDeviceMethod method = new CloudToDeviceMethod(this.Name, new TimeSpan(0, 0, this.ResponseTimeOut), new TimeSpan(0, 0, this.ConnectionTimeOut));
                if (this.IsParameterBound(c => c.Payload))
                {
                    method = method.SetPayloadJson(this.Payload);
                }

                CloudToDeviceMethodResult   result = serviceClient.InvokeDeviceMethodAsync(this.DeviceId, method).GetAwaiter().GetResult();
                PSCloudToDeviceMethodResult psCloudToDeviceMethodResult = new PSCloudToDeviceMethodResult()
                {
                    Status  = result.Status,
                    Payload = result.GetPayloadAsJson()
                };
                this.WriteObject(psCloudToDeviceMethodResult);
            }
        }
Example #15
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(KeyName, Properties.Resources.NewIotHubKey))
            {
                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.HubId);
                    this.Name = IotHubUtils.GetIotHubName(this.HubId);
                }

                var regeneratedAuthRule = new PSSharedAccessSignatureAuthorizationRule();

                IotHubDescription iothubDesc = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.Name);
                IList <SharedAccessSignatureAuthorizationRule> authRules = (List <SharedAccessSignatureAuthorizationRule>) this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.Name).ToList();

                foreach (var authRule in authRules)
                {
                    if (authRule.KeyName.Equals(this.KeyName, StringComparison.OrdinalIgnoreCase))
                    {
                        regeneratedAuthRule = IotHubUtils.ToPSSharedAccessSignatureAuthorizationRule(authRule);
                        authRules.Remove(authRule);
                        break;
                    }
                }

                switch (RenewKey.ToLower(CultureInfo.InvariantCulture))
                {
                case "primary":
                    regeneratedAuthRule.PrimaryKey = this.RegenerateKey();
                    break;

                case "secondary":
                    regeneratedAuthRule.SecondaryKey = this.RegenerateKey();
                    break;

                case "swap":
                    var temp = regeneratedAuthRule.PrimaryKey;
                    regeneratedAuthRule.PrimaryKey   = regeneratedAuthRule.SecondaryKey;
                    regeneratedAuthRule.SecondaryKey = temp;
                    break;
                }

                authRules.Add(IotHubUtils.ToSharedAccessSignatureAuthorizationRule(regeneratedAuthRule));
                iothubDesc.Properties.AuthorizationPolicies = authRules;

                this.IotHubClient.IotHubResource.CreateOrUpdate(this.ResourceGroupName, this.Name, iothubDesc);
                IEnumerable <SharedAccessSignatureAuthorizationRule> updatedAuthRules = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.Name);

                SharedAccessSignatureAuthorizationRule authPolicy = this.IotHubClient.IotHubResource.GetKeysForKeyName(this.ResourceGroupName, this.Name, this.KeyName);
                this.WriteObject(IotHubUtils.ToPSSharedAccessSignatureAuthorizationRule(authPolicy), false);
            }
        }
Example #16
0
 public override void ExecuteCmdlet()
 {
     if (KeyName != null)
     {
         SharedAccessSignatureAuthorizationRule authPolicy = this.IotHubClient.IotHubResource.GetKeysForKeyName(this.ResourceGroupName, this.Name, this.KeyName);
         this.WriteObject(IotHubUtils.ToPSSharedAccessSignatureAuthorizationRule(authPolicy), false);
     }
     else
     {
         IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.Name);
         this.WriteObject(IotHubUtils.ToPSSharedAccessSignatureAuthorizationRules(authPolicies), true);
     }
 }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DeviceId, Properties.Resources.AddIotHubDevice))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                Device childDevice  = registryManager.GetDeviceAsync(this.DeviceId).GetAwaiter().GetResult();
                Device parentDevice = registryManager.GetDeviceAsync(this.ParentDeviceId).GetAwaiter().GetResult();

                if (childDevice.Capabilities.IotEdge)
                {
                    throw new ArgumentException($"The entered device \"{this.DeviceId}\" should be non-edge device.");
                }

                if (!parentDevice.Capabilities.IotEdge)
                {
                    throw new ArgumentException($"The entered parent device \"{this.ParentDeviceId}\" should be edge device.");
                }

                if (!string.IsNullOrEmpty(childDevice.Scope) && !childDevice.Scope.Equals(parentDevice.Scope) && !this.Force.IsPresent)
                {
                    throw new ArgumentException($"The entered device \"{this.DeviceId}\" already has a parent device, please use '-Force' to overwrite.");
                }

                childDevice.Scope = parentDevice.Scope;

                this.WriteObject(IotHubDataPlaneUtils.ToPSDevice(registryManager.UpdateDeviceAsync(childDevice).GetAwaiter().GetResult()));
            }
        }
        public override void ExecuteCmdlet()
        {
            IotHubDescription iotHubDescription;

            if (ParameterSetName.Equals(InputObjectParameterSet))
            {
                this.ResourceGroupName = this.InputObject.Resourcegroup;
                this.IotHubName        = this.InputObject.Name;
                iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
            }
            else
            {
                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                    this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                }

                iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
            }

            IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
            SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryRead);
            PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
            RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

            if (this.DeviceId != null)
            {
                this.WriteObject(IotHubDataPlaneUtils.ToPSDevice(registryManager.GetDeviceAsync(this.DeviceId).GetAwaiter().GetResult()));
            }
            else
            {
                IList <Device>       devices       = new List <Device>();
                IEnumerable <string> deviceResults = registryManager.CreateQuery("Select * from Devices").GetNextAsJsonAsync().GetAwaiter().GetResult();
                foreach (string deviceResult in deviceResults)
                {
                    Device d = JsonConvert.DeserializeObject <Device>(deviceResult);
                    devices.Add(registryManager.GetDeviceAsync(d.Id).GetAwaiter().GetResult());
                }

                if (devices.Count == 1)
                {
                    this.WriteObject(IotHubDataPlaneUtils.ToPSDevice(devices[0]));
                }
                else
                {
                    this.WriteObject(IotHubDataPlaneUtils.ToPSDevices(devices), true);
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            IotHubDescription iotHubDescription;

            if (ParameterSetName.Equals(InputObjectParameterSet))
            {
                this.ResourceGroupName = this.InputObject.Resourcegroup;
                this.IotHubName        = this.InputObject.Name;
                iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
            }
            else
            {
                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                    this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                }

                iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
            }

            IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
            SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryRead);
            PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
            RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);
            Device device = registryManager.GetDeviceAsync(this.DeviceId).GetAwaiter().GetResult();

            if (device != null)
            {
                List <Module> modules = registryManager.GetModulesOnDeviceAsync(this.DeviceId).GetAwaiter().GetResult().ToList();
                if (this.ModuleId != null)
                {
                    if (modules.Any(m => m.Id.Equals(this.ModuleId)))
                    {
                        this.WriteObject(GetModuleConnectionString(modules.FirstOrDefault(m => m.Id.Equals(this.ModuleId)), iotHubDescription.Properties.HostName));
                    }
                }
                else
                {
                    IList <PSModuleConnectionString> psModuleConnectionStringCollection = new List <PSModuleConnectionString>();
                    foreach (Module module in modules)
                    {
                        psModuleConnectionStringCollection.Add(GetModuleConnectionString(module, iotHubDescription.Properties.HostName));
                    }

                    this.WriteObject(psModuleConnectionStringCollection, true);
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DeviceId, Properties.Resources.SendIotHubD2CMessage))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);

                Devices.Client.TransportType transportType = (Devices.Client.TransportType)Enum.Parse(typeof(Devices.Client.TransportType), this.TransportType.ToString());
                Devices.Client.Message       message       = new Devices.Client.Message(new MemoryStream(Encoding.UTF8.GetBytes(this.Message)));

                try
                {
                    DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString, this.DeviceId, transportType);

                    deviceClient.SendEventAsync(message).GetAwaiter().GetResult();

                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(true);
                    }
                }
                catch
                {
                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(false);
                    }
                }
            }
        }
Example #21
0
        private static async Task ObserveIoTHub(Config config, CancellationToken cancellationToken)
        {
            string previousState           = null;
            string previousEndpointAddress = null;

            IotHubClient iotHubClient = await GetIotHubClientAsync(config);

            SharedAccessSignatureAuthorizationRule sasAuthorizationRule = await GetIotHubKeyAsync(iotHubClient, config, cancellationToken);

            while (!cancellationToken.IsCancellationRequested)
            {
                IotHubDescription iotHubDescription = await GetIotHubDescriptionAsync(iotHubClient, config, cancellationToken);

                var currentState           = iotHubDescription.Properties.State;
                var currentEndpointAddress = iotHubDescription.Properties.EventHubEndpoints["events"].Endpoint;
                var currentEndpointPath    = iotHubDescription.Properties.EventHubEndpoints["events"].Path;

                var stateChanged    = currentState != previousState;
                var endpointChanged = currentEndpointAddress != previousEndpointAddress;

                if (stateChanged || endpointChanged)
                {
                    // print changes
                    Console.WriteLine();
                    Console.WriteLine($"-----------------------------------------------------------");
                    Console.WriteLine($"Date time:             {DateTime.Now}");
                    Console.WriteLine($"Status changed:        {previousState} => {currentState}");
                    Console.WriteLine($"Endpoint Address:      {currentEndpointAddress}");
                    Console.WriteLine($"Endpoint Path:         {currentEndpointPath}");

                    if (endpointChanged)
                    {
                        var connectionString = BuildEventHubConnectionString(iotHubDescription, sasAuthorizationRule);
                        Console.WriteLine($"Endpoint new/changed");
                        Console.WriteLine($"new connection string: {connectionString}");
                    }
                }
                else
                {
                    // print indicator that application is running
                    Console.Write(".");
                }

                previousState           = currentState;
                previousEndpointAddress = currentEndpointAddress;

                await Task.Delay(1000);
            }
        }
        public override void ExecuteCmdlet()
        {
            // Fetch the hostname
            IotHubDescription iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.Name);
            var hostName = iotHubDescription.Properties.HostName;

            if (KeyName != null)
            {
                SharedAccessSignatureAuthorizationRule authPolicy = this.IotHubClient.IotHubResource.GetKeysForKeyName(this.ResourceGroupName, this.Name, this.KeyName);
                this.WriteObject(authPolicy.ToPSIotHubConnectionString(hostName), false);
            }
            else
            {
                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.Name);
                this.WriteObject(IotHubUtils.ToPSIotHubConnectionStrings(authPolicies, hostName), true);
            }
        }
        public override void ExecuteCmdlet()
        {
            IotHubDescription iotHubDescription;

            if (ParameterSetName.Equals(InputObjectParameterSet))
            {
                this.ResourceGroupName = this.InputObject.Resourcegroup;
                this.IotHubName        = this.InputObject.Name;
                iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
            }
            else
            {
                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                    this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                }

                iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
            }

            IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
            SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryRead);
            PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
            RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

            Device childDevice = registryManager.GetDeviceAsync(this.DeviceId).GetAwaiter().GetResult();

            if (childDevice.Capabilities.IotEdge)
            {
                throw new ArgumentException($"The entered device \"{this.DeviceId}\" should be non-edge device.");
            }

            if (string.IsNullOrEmpty(childDevice.Scope))
            {
                throw new ArgumentException($"The entered device \"{this.DeviceId}\" doesn\'t support parent device functionality.");
            }

            string parentDeviceId = childDevice.Scope.Substring(Properties.Resources.DEVICE_DEVICESCOPE_PREFIX.Length, childDevice.Scope.LastIndexOf("-") - Properties.Resources.DEVICE_DEVICESCOPE_PREFIX.Length);

            this.WriteObject(IotHubDataPlaneUtils.ToPSDevice(registryManager.GetDeviceAsync(parentDeviceId).GetAwaiter().GetResult()));
        }
Example #24
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.InvokeIotHubQuery))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryRead);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                IQuery query;
                if (this.IsParameterBound(c => c.Top))
                {
                    query = registryManager.CreateQuery(this.Query, this.Top);
                }
                else
                {
                    query = registryManager.CreateQuery(this.Query);
                }

                this.WriteObject(query.GetNextAsJsonAsync().GetAwaiter().GetResult(), true);
            }
        }
            /// <summary>
            /// Create iot hub
            /// </summary>
            /// <param name="manager"></param>
            /// <param name="resourceGroup"></param>
            /// <param name="name"></param>
            /// <param name="properties"></param>
            /// <param name="rule"></param>
            /// <param name="logger"></param>
            public IoTHubResource(IoTHubFactory manager,
                                  IResourceGroupResource resourceGroup, string name,
                                  IotHubProperties properties, ILogger logger,
                                  SharedAccessSignatureAuthorizationRule rule)
            {
                _resourceGroup = resourceGroup;
                Name           = name;

                _manager    = manager;
                _properties = properties;
                _logger     = logger;

                PrimaryConnectionString = ConnectionString.CreateServiceConnectionString(
                    properties.HostName, rule.KeyName, rule.PrimaryKey).ToString();
                SecondaryConnectionString = ConnectionString.CreateServiceConnectionString(
                    properties.HostName, rule.KeyName, rule.SecondaryKey).ToString();

                if (properties.EventHubEndpoints.TryGetValue("events", out var evtHub))
                {
                    EventHubConnectionString = ConnectionString.CreateEventHubConnectionString(
                        evtHub.Endpoint, rule.KeyName, rule.PrimaryKey).ToString();
                }
            }
Example #26
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.SetIotHubEdgeModules))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                PSConfigurationContent content = new PSConfigurationContent()
                {
                    DeviceContent = null, ModulesContent = this.ModulesContent
                };

                registryManager.ApplyConfigurationContentOnDeviceAsync(this.DeviceId, IotHubUtils.ConvertObject <PSConfigurationContent, ConfigurationContent>(content)).GetAwaiter().GetResult();

                this.WriteObject(IotHubDataPlaneUtils.ToPSModules(registryManager.GetModulesOnDeviceAsync(this.DeviceId).GetAwaiter().GetResult()), true);
            }
        }
        bool ValidateTokenWithSecurityIdentity(SharedAccessSignature sharedAccessSignature, ServiceIdentity serviceIdentity)
        {
            if (serviceIdentity.Authentication.Type != ServiceAuthenticationType.SymmetricKey)
            {
                Events.InvalidServiceIdentityType(serviceIdentity);
                return(false);
            }

            if (serviceIdentity.Status != ServiceIdentityStatus.Enabled)
            {
                Events.ServiceIdentityNotEnabled(serviceIdentity);
                return(false);
            }

            return(serviceIdentity.Authentication.SymmetricKey.Map(
                       s =>
            {
                var rule = new SharedAccessSignatureAuthorizationRule
                {
                    PrimaryKey = s.PrimaryKey,
                    SecondaryKey = s.SecondaryKey
                };

                try
                {
                    sharedAccessSignature.Authenticate(rule);
                    return true;
                }
                catch (UnauthorizedAccessException e)
                {
                    Events.KeysMismatch(serviceIdentity.Id, e);
                    return false;
                }
            })
                   .GetOrElse(() => throw new InvalidOperationException($"Unable to validate token because the service identity has empty symmetric keys")));
        }
Example #28
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.InvokeIotHubConfigurationMetricsQuery))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                Configuration config = registryManager.GetConfigurationAsync(this.Name).GetAwaiter().GetResult();
                if (config != null && config.Content.ModulesContent != null)
                {
                    PSDeployment psDeployment = IotHubDataPlaneUtils.ToPSDeployment(config);
                    Hashtable    queries;
                    string       metricKey = this.MetricName;
                    if (this.MetricType.Equals(PSConfigurationMetricType.System))
                    {
                        if (this.MetricName.Equals("targeted", StringComparison.OrdinalIgnoreCase))
                        {
                            metricKey = "targetedCount";
                        }

                        if (this.MetricName.Equals("applied", StringComparison.OrdinalIgnoreCase))
                        {
                            metricKey = "appliedCount";
                        }

                        if (this.MetricName.Equals("reporting success", StringComparison.OrdinalIgnoreCase))
                        {
                            metricKey = "reportedSuccessfulCount";
                        }

                        if (this.MetricName.Equals("reporting failure", StringComparison.OrdinalIgnoreCase))
                        {
                            metricKey = "reportedFailedCount";
                        }

                        queries = psDeployment.SystemMetrics.Queries;
                    }
                    else
                    {
                        queries = psDeployment.Metrics.Queries;
                    }

                    if (queries.ContainsKey(metricKey))
                    {
                        PSConfigurationMetricsResult psConfigurationMetricsResult = new PSConfigurationMetricsResult();
                        psConfigurationMetricsResult.Name     = this.MetricName;
                        psConfigurationMetricsResult.Criteria = queries[metricKey].ToString();
                        IQuery metricQuery = registryManager.CreateQuery(queries[metricKey].ToString());
                        psConfigurationMetricsResult.Result = metricQuery.GetNextAsJsonAsync().GetAwaiter().GetResult().ToList();
                        this.WriteObject(psConfigurationMetricsResult);
                    }
                    else
                    {
                        throw new ArgumentException(string.Format("The metric '{0}' is not defined in the deployment '{1}'", this.MetricName, this.Name));
                    }
                }
                else
                {
                    throw new ArgumentException("The deployment doesn't exist.");
                }
            }
        }
Example #29
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.NewIotHubSasToken))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                if (this.IsParameterBound(c => c.ModuleId) && !this.IsParameterBound(c => c.DeviceId))
                {
                    throw new ArgumentException("You are unable to get sas token for module without device information.");
                }

                if (!this.IsParameterBound(c => c.Duration))
                {
                    this.Duration = 3600;
                }

                string resourceUri = string.Empty;
                string keyName     = string.Empty;
                string key         = string.Empty;

                if (this.IsParameterBound(c => c.DeviceId))
                {
                    IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                    SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryRead);
                    PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                    RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                    if (this.IsParameterBound(c => c.ModuleId))
                    {
                        Module module = registryManager.GetModuleAsync(this.DeviceId, this.ModuleId).GetAwaiter().GetResult();
                        if (module != null)
                        {
                            if (module.Authentication.Type.Equals(AuthenticationType.Sas))
                            {
                                resourceUri = string.Format("{0}/devices/{1}/modules/{2}", iotHubDescription.Properties.HostName, this.DeviceId, this.ModuleId);
                                key         = this.KeyType.Equals(PSKeyType.primary) ? module.Authentication.SymmetricKey.PrimaryKey : module.Authentication.SymmetricKey.SecondaryKey;
                            }
                            else
                            {
                                throw new ArgumentException("This module does not support SAS auth.");
                            }
                        }
                        else
                        {
                            throw new ArgumentException($"The entered module \"{this.ModuleId}\" doesn't exist.");
                        }
                    }
                    else
                    {
                        Device device = registryManager.GetDeviceAsync(this.DeviceId).GetAwaiter().GetResult();
                        if (device != null)
                        {
                            if (device.Authentication.Type.Equals(AuthenticationType.Sas))
                            {
                                resourceUri = string.Format("{0}/devices/{1}", iotHubDescription.Properties.HostName, this.DeviceId);
                                key         = this.KeyType.Equals(PSKeyType.primary) ? device.Authentication.SymmetricKey.PrimaryKey : device.Authentication.SymmetricKey.SecondaryKey;
                            }
                            else
                            {
                                throw new ArgumentException("This device does not support SAS auth.");
                            }
                        }
                        else
                        {
                            throw new ArgumentException($"The entered device \"{this.DeviceId}\" doesn't exist.");
                        }
                    }
                }
                else
                {
                    if (!this.IsParameterBound(c => c.KeyName))
                    {
                        this.KeyName = "iothubowner";
                    }
                    SharedAccessSignatureAuthorizationRule authPolicy = this.IotHubClient.IotHubResource.GetKeysForKeyName(this.ResourceGroupName, this.IotHubName, this.KeyName);
                    resourceUri = iotHubDescription.Properties.HostName;
                    keyName     = authPolicy.KeyName;
                    key         = this.KeyType.Equals(PSKeyType.primary) ? authPolicy.PrimaryKey : authPolicy.SecondaryKey;
                }

                this.WriteObject(this.createToken(resourceUri, keyName, key, this.Duration));
            }
        }
Example #30
0
 public static PSSharedAccessSignatureAuthorizationRule ToPSSharedAccessSignatureAuthorizationRule(SharedAccessSignatureAuthorizationRule authorizationPolicy)
 {
     return(ConvertObject <SharedAccessSignatureAuthorizationRule, PSSharedAccessSignatureAuthorizationRule>(authorizationPolicy));
 }
        public void Authenticate(SharedAccessSignatureAuthorizationRule sasAuthorizationRule)
        {
            if (this.IsExpired())
            {
                throw new UnauthorizedAccessException("The specified SAS token is expired.");
            }

            if (sasAuthorizationRule.PrimaryKey != null)
            {
                string primareyKeyComputedSignature = this.ComputeSignature(Convert.FromBase64String(sasAuthorizationRule.PrimaryKey));
                if (string.Equals(this.signature, primareyKeyComputedSignature))
                {
                    return;
                }
            }

            if (sasAuthorizationRule.SecondaryKey != null)
            {
                string secondaryKeyComputedSignature = this.ComputeSignature(Convert.FromBase64String(sasAuthorizationRule.SecondaryKey));
                if (string.Equals(this.signature, secondaryKeyComputedSignature))
                {
                    return;
                }
            }

            throw new UnauthorizedAccessException("The specified SAS token has an invalid signature. It does not match either the primary or secondary key.");
        }