Beispiel #1
0
        public async Task CreateWithSimpleParameters(IAsyncCmdlet adapter)
        {
            var parameters = new Parameters(this, WebsitesClient);
            var client     = new WebClient(DefaultContext);
            var output     = await client.RunAsync(client.SubscriptionId, parameters, adapter);

            output.SiteConfig = WebsitesClient
                                .WrappedWebsitesClient
                                .WebApps()
                                .GetConfiguration(output.ResourceGroup, output.Name)
                                .ConvertToSiteConfig();

            try
            {
                var appSettings = WebsitesClient
                                  .WrappedWebsitesClient
                                  .WebApps()
                                  .ListApplicationSettings(output.ResourceGroup, output.Name);
                output.SiteConfig.AppSettings = appSettings
                                                .Properties
                                                .Select(s => new NameValuePair {
                    Name = s.Key, Value = s.Value
                })
                                                .ToList();
                var connectionStrings = WebsitesClient.WrappedWebsitesClient.WebApps().ListConnectionStrings(
                    output.ResourceGroup, output.Name);
                output.SiteConfig.ConnectionStrings = connectionStrings
                                                      .Properties
                                                      .Select(s => new ConnStringInfo()
                {
                    Name             = s.Key,
                    ConnectionString = s.Value.Value,
                    Type             = s.Value.Type
                }).ToList();
            }
            catch
            {
                //ignore if this call fails as it will for reader RBAC
            }

            string userName = null, password = null;

            try
            {
                var scmHostName = output.EnabledHostNames.FirstOrDefault(s => s.Contains(".scm."));
                if (!string.IsNullOrWhiteSpace(scmHostName))
                {
                    var profile = await WebsitesClient.WrappedWebsitesClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(output.ResourceGroup, output.Name, new CsmPublishingProfileOptions { Format = "WebDeploy" });

                    var doc = new XmlDocument();
                    doc.Load(profile);
                    userName = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userName").Value;
                    password = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userPWD").Value;
                    var newOutput = new PSSite(output)
                    {
                        GitRemoteUri      = $"https://{scmHostName}",
                        GitRemoteUsername = userName,
                        GitRemotePassword = SecureStringExtensions.ConvertToSecureString(password)
                    };
                    output = newOutput;
                    var git        = new GitCommand(SessionState.Path, GitRepositoryPath);
                    var repository = await git.VerifyGitRepository();

                    if (repository != null)
                    {
                        if (!await git.CheckExistence())
                        {
                            adapter.WriteWarning(git.InstallationInstructions);
                        }
                        else if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
                        {
                            await git.AddRemoteRepository("azure", $"https://{userName}:{password}@{scmHostName}");

                            adapter.WriteVerbose(Properties.Resources.GitRemoteMessage);
                            newOutput.GitRemoteName = "azure";
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                // do not write errors for problems with adding git repository
                var repoPath = GitRepositoryPath ?? SessionState?.Path?.CurrentFileSystemLocation?.Path;
                adapter.WriteWarning(string.Format(
                                         Properties.Resources.GitRemoteAddFailure,
                                         repoPath,
                                         exception.Message));
            }
            adapter.WriteObject(new PSSite(output));
        }
Beispiel #2
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                if (!this.IsParameterBound(c => c.EndDate))
                {
                    WriteVerbose(Resources.Properties.Resources.DefaultEndDateUsed);
                    EndDate = StartDate.AddYears(1);
                }

                if (this.IsParameterBound(c => c.ApplicationObject))
                {
                    ObjectId = ApplicationObject.ObjectId;
                }
                else if (this.IsParameterBound(c => c.ApplicationId))
                {
                    ObjectId = ActiveDirectoryClient.GetAppObjectIdFromApplicationId(ApplicationId);
                }
                else if (this.IsParameterBound(c => c.DisplayName))
                {
                    ObjectId = ActiveDirectoryClient.GetAppObjectIdFromDisplayName(DisplayName);
                }

                if (Password != null && Password.Length > 0)
                {
                    string decodedPassword = SecureStringExtensions.ConvertToString(Password);
                    // Create object for password credential
                    var passwordCredential = new PasswordCredential()
                    {
                        EndDate   = EndDate,
                        StartDate = StartDate,
                        KeyId     = KeyId == default(Guid) ? Guid.NewGuid().ToString() : KeyId.ToString(),
                        Value     = decodedPassword
                    };
                    if (!String.IsNullOrEmpty(CustomKeyIdentifier))
                    {
                        passwordCredential.CustomKeyIdentifier = Encoding.UTF8.GetBytes(CustomKeyIdentifier);
                    }
                    if (ShouldProcess(target: ObjectId, action: string.Format("Adding a new password to application with objectId {0}", ObjectId)))
                    {
                        WriteObject(ActiveDirectoryClient.CreateAppPasswordCredential(ObjectId, passwordCredential));
                    }
                }
                else if (CertValue != null)
                {
                    // Create object for key credential
                    var keyCredential = new KeyCredential()
                    {
                        EndDate             = EndDate,
                        StartDate           = StartDate,
                        KeyId               = KeyId == default(Guid) ? Guid.NewGuid().ToString() : KeyId.ToString(),
                        Value               = CertValue,
                        Type                = "AsymmetricX509Cert",
                        Usage               = "Verify",
                        CustomKeyIdentifier = CustomKeyIdentifier
                    };
                    if (ShouldProcess(target: ObjectId, action: string.Format("Adding a new certificate to application with objectId {0}", ObjectId)))
                    {
                        WriteObject(ActiveDirectoryClient.CreateAppKeyCredential(ObjectId, keyCredential));
                    }
                }
                else
                {
                    throw new InvalidOperationException("No valid keyCredential or passwordCredential to update!!");
                }
            });
        }
        public override void Execute()
        {
            base.Execute();

            if (!this.IsVirtualNetworkGatewayPresent(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name))
            {
                throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound, this.VirtualNetworkGateway.Name));
            }

            if (this.EnableActiveActiveFeature.IsPresent && this.DisableActiveActiveFeature.IsPresent)
            {
                throw new ArgumentException("Both EnableActiveActiveFeature and DisableActiveActiveFeature Parameters can not be passed.");
            }

            if (this.EnableActiveActiveFeature.IsPresent)
            {
                this.VirtualNetworkGateway.ActiveActive = true;
            }

            if (this.DisableActiveActiveFeature.IsPresent)
            {
                this.VirtualNetworkGateway.ActiveActive = false;
            }


            if (!string.IsNullOrEmpty(GatewaySku))
            {
                this.VirtualNetworkGateway.Sku      = new PSVirtualNetworkGatewaySku();
                this.VirtualNetworkGateway.Sku.Tier = this.GatewaySku;
                this.VirtualNetworkGateway.Sku.Name = this.GatewaySku;
            }

            if (this.VirtualNetworkGateway.ActiveActive && !this.VirtualNetworkGateway.VpnType.Equals(MNM.VpnType.RouteBased))
            {
                throw new ArgumentException("Virtual Network Gateway VpnType should be " + MNM.VpnType.RouteBased + " when Active-Active feature flag is set to True.");
            }

            if (this.GatewayDefaultSite != null)
            {
                this.VirtualNetworkGateway.GatewayDefaultSite    = new PSResourceId();
                this.VirtualNetworkGateway.GatewayDefaultSite.Id = this.GatewayDefaultSite.Id;
            }


            if ((this.VpnClientAddressPool != null ||
                 this.VpnClientRootCertificates != null ||
                 this.VpnClientRevokedCertificates != null ||
                 this.RadiusServerAddress != null ||
                 this.RadiusServerSecret != null ||
                 (this.VpnClientIpsecPolicy != null && this.VpnClientIpsecPolicy.Count != 0)) &&
                this.VirtualNetworkGateway.VpnClientConfiguration == null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration = new PSVpnClientConfiguration();
            }

            if (this.VpnClientAddressPool != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace();
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool;
            }

            if (this.VpnClientProtocol != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientProtocols = this.VpnClientProtocol;
            }

            if (this.VpnClientRootCertificates != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRootCertificates = this.VpnClientRootCertificates;
            }

            if (this.VpnClientRevokedCertificates != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRevokedCertificates = this.VpnClientRevokedCertificates;
            }

            if (this.VpnClientIpsecPolicy != null && this.VpnClientIpsecPolicy.Count != 0)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientIpsecPolicies = this.VpnClientIpsecPolicy;
            }

            if ((this.RadiusServerAddress != null && this.RadiusServerSecret == null) ||
                (this.RadiusServerAddress == null && this.RadiusServerSecret != null))
            {
                throw new ArgumentException("Both radius server address and secret must be specified if external radius is being configured");
            }

            if (this.RadiusServerAddress != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerAddress = this.RadiusServerAddress;
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerSecret  = SecureStringExtensions.ConvertToString(this.RadiusServerSecret);
            }

            if ((this.Asn > 0 || this.PeerWeight > 0) && this.VirtualNetworkGateway.BgpSettings == null)
            {
                this.VirtualNetworkGateway.BgpSettings = new PSBgpSettings();
                this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddress = null; // The gateway's BGP peering address (private IP address assigned within the vnet) can't be changed
            }

            if (this.Asn > 0)
            {
                this.VirtualNetworkGateway.BgpSettings.Asn = this.Asn;
            }

            if (this.PeerWeight > 0)
            {
                this.VirtualNetworkGateway.BgpSettings.PeerWeight = this.PeerWeight;
            }
            else if (this.PeerWeight < 0)
            {
                throw new ArgumentException("PeerWeight must be a positive integer");
            }

            // Map to the sdk object
            MNM.VirtualNetworkGateway sdkVirtualNetworkGateway = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualNetworkGateway>(this.VirtualNetworkGateway);
            sdkVirtualNetworkGateway.Tags = TagsConversionHelper.CreateTagDictionary(this.VirtualNetworkGateway.Tag, validate: true);

            string shouldProcessMessage = string.Format("Execute AzureRmVirtualNetworkGateway for ResourceGroupName {0} VirtualNetworkGateway {1}", this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name);

            if (ShouldProcess(shouldProcessMessage, VerbsCommon.Set))
            {
                this.VirtualNetworkGatewayClient.CreateOrUpdate(this.VirtualNetworkGateway.ResourceGroupName,
                                                                this.VirtualNetworkGateway.Name, sdkVirtualNetworkGateway);

                var getVirtualNetworkGateway =
                    this.GetVirtualNetworkGateway(this.VirtualNetworkGateway.ResourceGroupName,
                                                  this.VirtualNetworkGateway.Name);

                WriteObject(getVirtualNetworkGateway);
            }
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                if (!this.IsParameterBound(c => c.EndDate))
                {
                    WriteVerbose(Resources.Properties.Resources.DefaultEndDateUsed);
                    EndDate = StartDate.AddYears(1);
                }

                if (this.IsParameterBound(c => c.ServicePrincipalObject))
                {
                    ObjectId = ServicePrincipalObject.Id;
                }

                if (this.IsParameterBound(c => c.ServicePrincipalName))
                {
                    ObjectId = ActiveDirectoryClient.GetObjectIdFromSPN(ServicePrincipalName);
                }

                if (Password != null && Password.Length > 0)
                {
                    string decodedPassword = SecureStringExtensions.ConvertToString(Password);
                    // Create object for password credential
                    var passwordCredential = new PasswordCredential()
                    {
                        EndDate   = EndDate,
                        StartDate = StartDate,
                        KeyId     = Guid.NewGuid().ToString(),
                        Value     = decodedPassword
                    };
                    if (ShouldProcess(target: ObjectId.ToString(), action: string.Format("Adding a new password to service principal with objectId {0}", ObjectId)))
                    {
                        WriteObject(ActiveDirectoryClient.CreateSpPasswordCredential(ObjectId, passwordCredential));
                    }
                }
                else if (this.IsParameterBound(c => c.CertValue))
                {
                    // Create object for key credential
                    var keyCredential = new KeyCredential()
                    {
                        EndDate   = EndDate,
                        StartDate = StartDate,
                        KeyId     = Guid.NewGuid().ToString(),
                        Value     = CertValue,
                        Type      = "AsymmetricX509Cert",
                        Usage     = "Verify"
                    };

                    if (ShouldProcess(target: ObjectId.ToString(), action: string.Format("Adding a new caertificate to service principal with objectId {0}", ObjectId)))
                    {
                        WriteObject(ActiveDirectoryClient.CreateSpKeyCredential(ObjectId, keyCredential));
                    }
                }
                else
                {
                    // If no credentials provided, set the password to a randomly generated GUID
                    Password = Guid.NewGuid().ToString().ConvertToSecureString();

                    string decodedPassword = SecureStringExtensions.ConvertToString(Password);

                    var passwordCredential = new PasswordCredential()
                    {
                        EndDate   = EndDate,
                        StartDate = StartDate,
                        KeyId     = Guid.NewGuid().ToString(),
                        Value     = decodedPassword
                    };
                    if (ShouldProcess(target: ObjectId.ToString(), action: string.Format("Adding a new password to service principal with objectId {0}", ObjectId)))
                    {
                        var spCred    = new PSADCredentialWrapper(ActiveDirectoryClient.CreateSpPasswordCredential(ObjectId, passwordCredential));
                        spCred.Secret = Password;
                        WriteObject(spCred);
                    }
                }
            });
        }
Beispiel #5
0
        public override void Execute()
        {
            base.Execute();

            if (ParameterSetName.Equals(CortexParameterSetNames.ByVpnConnectionName, StringComparison.OrdinalIgnoreCase))
            {
                this.ResourceGroupName  = this.ResourceGroupName;
                this.ParentResourceName = this.ParentResourceName;
                this.Name = this.Name;
            }
            else if (ParameterSetName.Equals(CortexParameterSetNames.ByVpnConnectionObject, StringComparison.OrdinalIgnoreCase))
            {
                this.ResourceId = this.InputObject.Id;

                if (string.IsNullOrWhiteSpace(this.ResourceId))
                {
                    throw new PSArgumentException(Properties.Resources.VpnConnectionNotFound);
                }

                var parsedResourceId = new ResourceIdentifier(this.ResourceId);
                this.ResourceGroupName  = parsedResourceId.ResourceGroupName;
                this.ParentResourceName = parsedResourceId.ParentResource.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Last();
                this.Name = parsedResourceId.ResourceName;
            }

            //// Get the vpngateway object - this will throw not found if the object is not found
            PSVpnGateway parentGateway = this.GetVpnGateway(this.ResourceGroupName, this.ParentResourceName);

            if (parentGateway == null ||
                parentGateway.Connections == null ||
                !parentGateway.Connections.Any(connection => connection.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)))
            {
                throw new PSArgumentException(Properties.Resources.VpnConnectionNotFound);
            }

            var vpnConnectionToModify = parentGateway.Connections.FirstOrDefault(connection => connection.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase));

            if (ParameterSetName.Equals(CortexParameterSetNames.ByVpnConnectionObject, StringComparison.OrdinalIgnoreCase))
            {
                vpnConnectionToModify = this.InputObject;
            }

            if (this.SharedKey != null)
            {
                vpnConnectionToModify.SharedKey = SecureStringExtensions.ConvertToString(this.SharedKey);
            }

            if (this.ConnectionBandwidthInMbps > 0)
            {
                vpnConnectionToModify.ConnectionBandwidth = Convert.ToInt32(this.ConnectionBandwidthInMbps);
            }

            if (this.EnableBgp.HasValue)
            {
                vpnConnectionToModify.EnableBgp = this.EnableBgp.Value;
            }

            if (this.IpSecPolicy != null)
            {
                vpnConnectionToModify.IpsecPolicies = new List <PSIpsecPolicy> {
                    this.IpSecPolicy
                };
            }

            ConfirmAction(
                Properties.Resources.SettingResourceMessage,
                this.Name,
                () =>
            {
                WriteVerbose(String.Format(Properties.Resources.UpdatingLongRunningOperationMessage, this.ResourceGroupName, this.Name));
                this.CreateOrUpdateVpnGateway(this.ResourceGroupName, this.ParentResourceName, parentGateway, parentGateway.Tag);

                var createdOrUpdatedVpnGateway = this.GetVpnGateway(this.ResourceGroupName, this.ParentResourceName);
                WriteObject(createdOrUpdatedVpnGateway.Connections.Where(connection => connection.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault());
            });
        }
Beispiel #6
0
        public override void ExecuteCmdlet()
        {
            if (!this.IsParameterBound(c => c.EndDate))
            {
                WriteVerbose(Resources.Properties.Resources.DefaultEndDateUsed);
                EndDate = StartDate.AddYears(1);
            }

            CreatePSApplicationParameters createParameters = new CreatePSApplicationParameters
            {
                DisplayName             = DisplayName,
                HomePage                = HomePage,
                IdentifierUris          = (IdentifierUri == null) ? new string[] { } : IdentifierUri,
                ReplyUrls               = ReplyUrls,
                AvailableToOtherTenants = AvailableToOtherTenants
            };

            switch (ParameterSetName)
            {
            case ParameterSet.ApplicationWithPasswordPlain:
                string decodedPassword = SecureStringExtensions.ConvertToString(Password);
                createParameters.PasswordCredentials = new PSADPasswordCredential[]
                {
                    new PSADPasswordCredential
                    {
                        StartDate = StartDate,
                        EndDate   = EndDate,
                        KeyId     = Guid.NewGuid(),
                        Password  = decodedPassword
                    }
                };
                break;

            case ParameterSet.ApplicationWithPasswordCredential:
                createParameters.PasswordCredentials = PasswordCredentials;
                break;

            case ParameterSet.ApplicationWithKeyPlain:
                createParameters.KeyCredentials = new PSADKeyCredential[]
                {
                    new PSADKeyCredential
                    {
                        StartDate = StartDate,
                        EndDate   = EndDate,
                        KeyId     = Guid.NewGuid(),
                        CertValue = CertValue
                    }
                };
                break;

            case ParameterSet.ApplicationWithKeyCredential:
                createParameters.KeyCredentials = KeyCredentials;
                break;
            }

            ExecutionBlock(() =>
            {
                if (ShouldProcess(target: createParameters.DisplayName, action: string.Format("Adding a new application with display name '{0}'", createParameters.DisplayName)))
                {
                    WriteObject(ActiveDirectoryClient.CreateApplication(createParameters));
                }
            });
        }
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            CustomerUser    user;
            PasswordProfile profile;

            UserId = (InputObject == null) ? UserId : InputObject.UserId;

            user = Partner.Customers[CustomerId].Users[UserId].GetAsync().GetAwaiter().GetResult();

            if (user.Id == UserId)
            {
                if (UserPrincipalName != null)
                {
                    user.UserPrincipalName = UserPrincipalName;
                }

                if (!string.IsNullOrEmpty(FirstName))
                {
                    user.FirstName = FirstName;
                }

                if (!string.IsNullOrEmpty(LastName))
                {
                    user.LastName = LastName;
                }

                if (!string.IsNullOrEmpty(DisplayName))
                {
                    user.DisplayName = DisplayName;
                }

                if (!string.IsNullOrEmpty(UsageLocation))
                {
                    user.UsageLocation = UsageLocation;
                }

                if (Password != null && Password.Length > 0)
                {
                    string stringPassword = SecureStringExtensions.ConvertToString(Password);

                    profile = new PasswordProfile
                    {
                        Password            = stringPassword,
                        ForceChangePassword = ForceChangePasswordNextLogin.IsPresent
                    };

                    user.PasswordProfile = profile;
                }
                else if (ForceChangePasswordNextLogin.IsPresent)
                {
                    profile = new PasswordProfile
                    {
                        ForceChangePassword = ForceChangePasswordNextLogin.IsPresent
                    };

                    user.PasswordProfile = profile;
                }

                if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerUserWhatIf, UserId)))
                {
                    if (InputObject == null && string.IsNullOrEmpty(UserId))
                    {
                        throw new PSInvalidOperationException(Resources.InvalidSetCustomerUserIdentifierException);
                    }

                    user = Partner.Customers[CustomerId].Users[UserId].PatchAsync(user).GetAwaiter().GetResult();

                    WriteObject(new PSCustomerUser(user), true);
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            this.VM.OSProfile = new OSProfile
            {
                ComputerName  = this.ComputerName,
                AdminUsername = this.Credential.UserName,
                AdminPassword = SecureStringExtensions.ConvertToString(this.Credential.Password),
                CustomData    = string.IsNullOrWhiteSpace(this.CustomData) ? null : Convert.ToBase64String(Encoding.UTF8.GetBytes(this.CustomData)),
            };

            if (this.ParameterSetName == LinuxParamSet)
            {
                if (this.VM.OSProfile.WindowsConfiguration != null)
                {
                    throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified);
                }

                if (this.VM.OSProfile.LinuxConfiguration == null)
                {
                    this.VM.OSProfile.LinuxConfiguration = new LinuxConfiguration();
                }

                this.VM.OSProfile.LinuxConfiguration.DisablePasswordAuthentication =
                    (this.DisablePasswordAuthentication.IsPresent)
                    ? (bool?)true
                    : null;
            }
            else
            {
                if (this.VM.OSProfile.LinuxConfiguration != null)
                {
                    throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified);
                }

                if (this.VM.OSProfile.WindowsConfiguration == null)
                {
                    this.VM.OSProfile.WindowsConfiguration = new WindowsConfiguration();
                    this.VM.OSProfile.WindowsConfiguration.AdditionalUnattendContent = null;
                }

                var listenerList = new List <WinRMListener>();

                if (this.WinRMHttp.IsPresent)
                {
                    listenerList.Add(new WinRMListener
                    {
                        Protocol       = ProtocolTypes.Http,
                        CertificateUrl = null,
                    });
                }

                if (this.WinRMHttps.IsPresent)
                {
                    listenerList.Add(new WinRMListener
                    {
                        Protocol       = ProtocolTypes.Https,
                        CertificateUrl = this.WinRMCertificateUrl.ToString(),
                    });
                }

                // OS Profile
                this.VM.OSProfile.WindowsConfiguration.ProvisionVMAgent =
                    (this.ProvisionVMAgent.IsPresent)
                    ? (bool?)true
                    : null;

                this.VM.OSProfile.WindowsConfiguration.EnableAutomaticUpdates =
                    this.EnableAutoUpdate.IsPresent
                    ? (bool?)true
                    : null;

                this.VM.OSProfile.WindowsConfiguration.TimeZone = this.TimeZone;

                this.VM.OSProfile.WindowsConfiguration.WinRM =
                    !(this.WinRMHttp.IsPresent || this.WinRMHttps.IsPresent)
                    ? null
                    : new WinRMConfiguration
                {
                    Listeners = listenerList,
                };
            }

            WriteObject(this.VM);
        }
        public override void Execute()
        {
            base.Execute();

            PSVpnServerConfiguration vpnServerConfigurationToUpdate = null;

            if (ParameterSetName.Contains(CortexParameterSetNames.ByVpnServerConfigurationObject))
            {
                vpnServerConfigurationToUpdate = this.InputObject;
                this.ResourceGroupName         = this.InputObject.ResourceGroupName;
                this.Name = this.InputObject.Name;
            }
            else
            {
                if (ParameterSetName.Contains(CortexParameterSetNames.ByVpnServerConfigurationResourceId))
                {
                    var parsedResourceId = new ResourceIdentifier(this.ResourceId);
                    this.Name = parsedResourceId.ResourceName;
                    this.ResourceGroupName = parsedResourceId.ResourceGroupName;
                }

                vpnServerConfigurationToUpdate = this.GetVpnServerConfiguration(this.ResourceGroupName, this.Name);
            }

            if (vpnServerConfigurationToUpdate == null)
            {
                throw new PSArgumentException(Properties.Resources.VpnServerConfigurationNotFound);
            }

            if (this.VpnProtocol != null)
            {
                vpnServerConfigurationToUpdate.VpnProtocols = new List <string>(this.VpnProtocol);
            }

            if (this.VpnAuthenticationType != null)
            {
                vpnServerConfigurationToUpdate.VpnAuthenticationTypes = new List <string>(this.VpnAuthenticationType);
            }

            if (this.VpnClientIpsecPolicy != null && VpnClientIpsecPolicy.Length != 0)
            {
                vpnServerConfigurationToUpdate.VpnClientIpsecPolicies = new List <PSIpsecPolicy>(this.VpnClientIpsecPolicy);
            }

            // VpnAuthenticationType = Certificate related validations.
            if (vpnServerConfigurationToUpdate.VpnAuthenticationTypes == null ||
                (vpnServerConfigurationToUpdate.VpnAuthenticationTypes != null && vpnServerConfigurationToUpdate.VpnAuthenticationTypes.Contains(MNM.VpnAuthenticationType.Certificate)))
            {
                // Read the VpnClientRootCertificates if present
                if (this.VpnClientRootCertificateFilesList != null)
                {
                    vpnServerConfigurationToUpdate.VpnClientRootCertificates = new List <PSClientRootCertificate>();

                    foreach (string vpnClientRootCertPath in this.VpnClientRootCertificateFilesList)
                    {
                        X509Certificate2 VpnClientRootCertificate = new X509Certificate2(vpnClientRootCertPath);

                        PSClientRootCertificate vpnClientRootCert = new PSClientRootCertificate()
                        {
                            Name           = Path.GetFileNameWithoutExtension(vpnClientRootCertPath),
                            PublicCertData = Convert.ToBase64String(VpnClientRootCertificate.Export(X509ContentType.Cert))
                        };
                        vpnServerConfigurationToUpdate.VpnClientRootCertificates.Add(vpnClientRootCert);
                    }
                }

                // Read the VpnClientRevokedCertificates if present
                if (this.VpnClientRevokedCertificateFilesList != null)
                {
                    vpnServerConfigurationToUpdate.VpnClientRevokedCertificates = new List <PSClientCertificate>();

                    foreach (string vpnClientRevokedCertPath in this.VpnClientRevokedCertificateFilesList)
                    {
                        X509Certificate2 vpnClientRevokedCertificate = new X509Certificate2(vpnClientRevokedCertPath);

                        PSClientCertificate vpnClientRevokedCert = new PSClientCertificate()
                        {
                            Name       = Path.GetFileNameWithoutExtension(vpnClientRevokedCertPath),
                            Thumbprint = vpnClientRevokedCertificate.Thumbprint
                        };

                        vpnServerConfigurationToUpdate.VpnClientRevokedCertificates.Add(vpnClientRevokedCert);
                    }
                }
            }
            else
            {
                vpnServerConfigurationToUpdate.VpnClientRevokedCertificates = null;
                vpnServerConfigurationToUpdate.VpnClientRootCertificates    = null;
            }

            // VpnAuthenticationType = Radius related validations.
            if (vpnServerConfigurationToUpdate.VpnAuthenticationTypes.Contains(MNM.VpnAuthenticationType.Radius))
            {
                if ((this.RadiusServerList != null && this.RadiusServerList.Count() > 0) && (this.RadiusServerAddress != null || this.RadiusServerSecret != null))
                {
                    throw new ArgumentException("Cannot configure both singular radius server and multiple radius servers at the same time.");
                }

                if (RadiusServerList != null && this.RadiusServerList.Count() > 0)
                {
                    vpnServerConfigurationToUpdate.RadiusServers       = this.RadiusServerList.ToList();
                    vpnServerConfigurationToUpdate.RadiusServerAddress = null;
                    vpnServerConfigurationToUpdate.RadiusServerSecret  = null;
                }
                else
                {
                    if (this.RadiusServerAddress != null)
                    {
                        vpnServerConfigurationToUpdate.RadiusServerAddress = this.RadiusServerAddress;
                    }

                    if (this.RadiusServerSecret != null)
                    {
                        vpnServerConfigurationToUpdate.RadiusServerSecret = SecureStringExtensions.ConvertToString(this.RadiusServerSecret);
                    }

                    vpnServerConfigurationToUpdate.RadiusServers = null;
                }

                // Read the RadiusServerRootCertificates if present
                if (this.RadiusServerRootCertificateFilesList != null)
                {
                    vpnServerConfigurationToUpdate.RadiusServerRootCertificates = new List <PSClientRootCertificate>();

                    foreach (string radiusServerRootCertPath in this.RadiusServerRootCertificateFilesList)
                    {
                        X509Certificate2 RadiusServerRootCertificate = new X509Certificate2(radiusServerRootCertPath);

                        PSClientRootCertificate radiusServerRootCert = new PSClientRootCertificate()
                        {
                            Name           = Path.GetFileNameWithoutExtension(radiusServerRootCertPath),
                            PublicCertData = Convert.ToBase64String(RadiusServerRootCertificate.Export(X509ContentType.Cert))
                        };

                        vpnServerConfigurationToUpdate.RadiusServerRootCertificates.Add(radiusServerRootCert);
                    }
                }

                // Read the RadiusClientRootCertificates if present
                if (this.RadiusClientRootCertificateFilesList != null)
                {
                    vpnServerConfigurationToUpdate.RadiusClientRootCertificates = new List <PSClientCertificate>();

                    foreach (string radiusClientRootCertPath in this.RadiusClientRootCertificateFilesList)
                    {
                        X509Certificate2 radiusClientRootCertificate = new X509Certificate2(radiusClientRootCertPath);

                        PSClientCertificate radiusClientRootCert = new PSClientCertificate()
                        {
                            Name       = Path.GetFileNameWithoutExtension(radiusClientRootCertPath),
                            Thumbprint = radiusClientRootCertificate.Thumbprint
                        };

                        vpnServerConfigurationToUpdate.RadiusClientRootCertificates.Add(radiusClientRootCert);
                    }
                }
            }
            else
            {
                vpnServerConfigurationToUpdate.RadiusServerAddress          = null;
                vpnServerConfigurationToUpdate.RadiusServerSecret           = null;
                vpnServerConfigurationToUpdate.RadiusClientRootCertificates = null;
                vpnServerConfigurationToUpdate.RadiusServerRootCertificates = null;
                vpnServerConfigurationToUpdate.RadiusServers = null;
            }

            // VpnAuthenticationType = AAD related validations.
            if (vpnServerConfigurationToUpdate.VpnAuthenticationTypes.Contains(MNM.VpnAuthenticationType.AAD))
            {
                if (vpnServerConfigurationToUpdate.AadAuthenticationParameters == null)
                {
                    vpnServerConfigurationToUpdate.AadAuthenticationParameters = new PSAadAuthenticationParameters();
                }

                if ((this.AadTenant == null && vpnServerConfigurationToUpdate.AadAuthenticationParameters.AadTenant == null) ||
                    (this.AadAudience == null && vpnServerConfigurationToUpdate.AadAuthenticationParameters.AadAudience == null) ||
                    (this.AadIssuer == null && vpnServerConfigurationToUpdate.AadAuthenticationParameters.AadIssuer == null))
                {
                    throw new ArgumentException("All Aad tenant, Aad audience and Aad issuer must be specified if VpnAuthenticationType is being configured as AAD.");
                }

                if (this.AadTenant != null)
                {
                    vpnServerConfigurationToUpdate.AadAuthenticationParameters.AadTenant = this.AadTenant;
                }
                if (this.AadAudience != null)
                {
                    vpnServerConfigurationToUpdate.AadAuthenticationParameters.AadAudience = this.AadAudience;
                }
                if (this.AadIssuer != null)
                {
                    vpnServerConfigurationToUpdate.AadAuthenticationParameters.AadIssuer = this.AadIssuer;
                }
            }
            else
            {
                vpnServerConfigurationToUpdate.AadAuthenticationParameters.AadTenant   = null;
                vpnServerConfigurationToUpdate.AadAuthenticationParameters.AadIssuer   = null;
                vpnServerConfigurationToUpdate.AadAuthenticationParameters.AadAudience = null;
            }

            ConfirmAction(
                Properties.Resources.SettingResourceMessage,
                this.Name,
                () =>
            {
                WriteVerbose(String.Format(Properties.Resources.UpdatingLongRunningOperationMessage, this.ResourceGroupName, this.Name));
                WriteObject(this.CreateOrUpdateVpnServerConfiguration(this.ResourceGroupName, this.Name, vpnServerConfigurationToUpdate, this.Tag));
            });
        }
Beispiel #10
0
 private static bool ValidatePasswordConfirmation(SecureString password, SecureString passwordConfirmation)
 {
     return(SecureStringExtensions.AreEqual(password, passwordConfirmation));
 }
Beispiel #11
0
 public void VerifyThatConvertToUnsecureStringThrowsArgumentException()
 {
     Assert.Throws <ArgumentNullException>(() => SecureStringExtensions.ConvertToUnsecureString(null));
 }
        private void CreateSimpleServicePrincipal()
        {
            var subscriptionId = DefaultProfile.DefaultContext.Subscription.Id;

            if (!this.IsParameterBound(c => c.Scope))
            {
                Scope = string.Format("/subscriptions/{0}", subscriptionId);
                WriteVerbose(string.Format("No scope provided - using the default scope '{0}'", Scope));
            }

            AuthorizationClient.ValidateScope(Scope, true);

            if (!this.IsParameterBound(c => c.Role))
            {
                Role = "Contributor";
                WriteVerbose(string.Format("No role provided - using the default role '{0}'", Role));
            }

            if (!this.IsParameterBound(c => c.StartDate))
            {
                DateTime currentTime = DateTime.UtcNow;
                StartDate = currentTime;
                WriteVerbose("No start date provided - using the current time as default.");
            }

            if (!this.IsParameterBound(c => c.EndDate))
            {
                EndDate = StartDate.AddYears(1);
                WriteVerbose("No end date provided - using the default value of one year after the start date.");
            }

            if (!this.IsParameterBound(c => c.DisplayName))
            {
                DisplayName = "azure-powershell-" + StartDate.ToString("MM-dd-yyyy-HH-mm-ss");
                WriteVerbose(string.Format("No display name provided - using the default display name of '{0}'", DisplayName));
            }

            var identifierUri = "http://" + DisplayName;

            // Handle credentials
            if (!this.IsParameterBound(c => c.Password))
            {
                // If no credentials provided, set the password to a randomly generated GUID
                Password = Guid.NewGuid().ToString().ConvertToSecureString();
            }

            // Create an application and get the applicationId
            var passwordCredential = new PSADPasswordCredential()
            {
                StartDate = StartDate,
                EndDate   = EndDate,
                KeyId     = Guid.NewGuid(),
                Password  = SecureStringExtensions.ConvertToString(Password)
            };

            if (!this.IsParameterBound(c => c.ApplicationId))
            {
                CreatePSApplicationParameters appParameters = new CreatePSApplicationParameters
                {
                    DisplayName         = DisplayName,
                    IdentifierUris      = new[] { identifierUri },
                    HomePage            = identifierUri,
                    PasswordCredentials = new PSADPasswordCredential[]
                    {
                        passwordCredential
                    }
                };

                if (ShouldProcess(target: appParameters.DisplayName, action: string.Format("Adding a new application for with display name '{0}'", appParameters.DisplayName)))
                {
                    var application = ActiveDirectoryClient.CreateApplication(appParameters);
                    ApplicationId = application.ApplicationId;
                    WriteVerbose(string.Format("No application id provided - created new AD application with application id '{0}'", ApplicationId));
                }
            }

            CreatePSServicePrincipalParameters createParameters = new CreatePSServicePrincipalParameters
            {
                ApplicationId       = ApplicationId,
                AccountEnabled      = true,
                PasswordCredentials = new PSADPasswordCredential[]
                {
                    passwordCredential
                }
            };

            var shouldProcessMessage = SkipRoleAssignment() ?
                                       string.Format("Adding a new service principal to be associated with an application " +
                                                     "having AppId '{0}' with no permissions.", createParameters.ApplicationId) :
                                       string.Format("Adding a new service principal to be associated with an application " +
                                                     "having AppId '{0}' with '{1}' role over scope '{2}'.", createParameters.ApplicationId, this.Role, this.Scope);

            if (ShouldProcess(target: createParameters.ApplicationId.ToString(), action: shouldProcessMessage))
            {
                var servicePrincipal = ActiveDirectoryClient.CreateServicePrincipal(createParameters);
                WriteObject(servicePrincipal);
                if (SkipRoleAssignment())
                {
                    WriteVerbose("Skipping role assignment for the service principal.");
                    return;
                }

                WriteWarning(string.Format("Assigning role '{0}' over scope '{1}' to the new service principal.", this.Role, this.Scope));
                FilterRoleAssignmentsOptions parameters = new FilterRoleAssignmentsOptions()
                {
                    Scope = this.Scope,
                    RoleDefinitionName = this.Role,
                    ADObjectFilter     = new ADObjectFilterOptions
                    {
                        SPN = servicePrincipal.ApplicationId.ToString(),
                        Id  = servicePrincipal.Id.ToString()
                    },
                    ResourceIdentifier = new ResourceIdentifier()
                    {
                        Subscription = subscriptionId
                    },
                    CanDelegate = false
                };

                for (var i = 0; i < 6; i++)
                {
                    try
                    {
                        TestMockSupport.Delay(5000);
                        PoliciesClient.CreateRoleAssignment(parameters);
                        var ra = PoliciesClient.FilterRoleAssignments(parameters, subscriptionId);
                        if (ra != null)
                        {
                            WriteVerbose(string.Format("Role assignment with role '{0}' and scope '{1}' successfully created for the created service principal.", this.Role, this.Scope));
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        // Do nothing
                    }
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                if (this.ParameterSetName == SimpleParameterSet)
                {
                    CreateSimpleServicePrincipal();
                    return;
                }

                if (this.IsParameterBound(c => c.ApplicationObject))
                {
                    ApplicationId = ApplicationObject.ApplicationId;
                    DisplayName   = ApplicationObject.DisplayName;
                }

                if (ApplicationId == Guid.Empty)
                {
                    string uri = "http://" + DisplayName.Trim().Replace(' ', '_');

                    // Create an application and get the applicationId
                    CreatePSApplicationParameters appParameters = new CreatePSApplicationParameters
                    {
                        DisplayName    = DisplayName,
                        IdentifierUris = new[] { uri },
                        HomePage       = uri
                    };

                    if (ShouldProcess(target: appParameters.DisplayName, action: string.Format("Adding a new application for with display name '{0}'", appParameters.DisplayName)))
                    {
                        var application = ActiveDirectoryClient.CreateApplication(appParameters);
                        ApplicationId   = application.ApplicationId;
                    }
                }

                CreatePSServicePrincipalParameters createParameters = new CreatePSServicePrincipalParameters
                {
                    ApplicationId  = ApplicationId,
                    AccountEnabled = true
                };

                if (this.IsParameterBound(c => c.Password))
                {
                    string decodedPassword = SecureStringExtensions.ConvertToString(Password);
                    createParameters.PasswordCredentials = new PSADPasswordCredential[]
                    {
                        new PSADPasswordCredential
                        {
                            StartDate = StartDate,
                            EndDate   = EndDate,
                            KeyId     = Guid.NewGuid(),
                            Password  = decodedPassword
                        }
                    };
                }
                else if (this.IsParameterBound(c => c.PasswordCredential))
                {
                    createParameters.PasswordCredentials = PasswordCredential;
                }
                else if (this.IsParameterBound(c => c.CertValue))
                {
                    createParameters.KeyCredentials = new PSADKeyCredential[]
                    {
                        new PSADKeyCredential
                        {
                            StartDate = StartDate,
                            EndDate   = EndDate,
                            KeyId     = Guid.NewGuid(),
                            CertValue = CertValue
                        }
                    };
                }
                else if (this.IsParameterBound(c => c.KeyCredential))
                {
                    createParameters.KeyCredentials = KeyCredential;
                }

                if (ShouldProcess(target: createParameters.ApplicationId.ToString(), action: string.Format("Adding a new service principal to be associated with an application having AppId '{0}'", createParameters.ApplicationId)))
                {
                    var servicePrincipal = ActiveDirectoryClient.CreateServicePrincipal(createParameters);
                    WriteObject(servicePrincipal);
                }
            });
        }
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            string userId = InputObject == null ? UserId : InputObject.UserId;

            Scheduler.RunTask(async() =>
            {
                if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerUserWhatIf, userId)))
                {
                    IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false);
                    PasswordProfile profile;

                    CustomerUser user = await partner.Customers[CustomerId].Users[userId].GetAsync(CancellationToken).ConfigureAwait(false);

                    if (UserPrincipalName != null)
                    {
                        user.UserPrincipalName = UserPrincipalName;
                    }

                    if (!string.IsNullOrEmpty(FirstName))
                    {
                        user.FirstName = FirstName;
                    }

                    if (!string.IsNullOrEmpty(LastName))
                    {
                        user.LastName = LastName;
                    }

                    if (!string.IsNullOrEmpty(DisplayName))
                    {
                        user.DisplayName = DisplayName;
                    }

                    if (!string.IsNullOrEmpty(UsageLocation))
                    {
                        user.UsageLocation = UsageLocation;
                    }

                    if (Password != null && Password.Length > 0)
                    {
                        string stringPassword = SecureStringExtensions.ConvertToString(Password);

                        profile = new PasswordProfile
                        {
                            Password            = stringPassword,
                            ForceChangePassword = ForceChangePasswordNextLogin.IsPresent
                        };

                        user.PasswordProfile = profile;
                    }
                    else if (ForceChangePasswordNextLogin.IsPresent)
                    {
                        profile = new PasswordProfile
                        {
                            ForceChangePassword = ForceChangePasswordNextLogin.IsPresent
                        };

                        user.PasswordProfile = profile;
                    }

                    user = await partner.Customers[CustomerId].Users[userId].PatchAsync(user, CancellationToken).ConfigureAwait(false);

                    WriteObject(new PSCustomerUser(user), true);
                }
            }, true);
        }
Beispiel #15
0
        public override void Execute()
        {
            base.Execute();

            if (!this.IsVirtualNetworkGatewayPresent(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name))
            {
                throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound, this.VirtualNetworkGateway.Name));
            }

            if (this.VirtualNetworkGateway.VpnClientConfiguration == null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration = new PSVpnClientConfiguration();
            }
            this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace();
            this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool;

            if ((this.RadiusServerAddress != null && this.RadiusServerSecret == null) ||
                (this.RadiusServerAddress == null && this.RadiusServerSecret != null))
            {
                throw new ArgumentException("Both radius server address and secret must be specified if external radius is being configured");
            }

            if (this.RadiusServerAddress != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerAddress = this.RadiusServerAddress;
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerSecret  = SecureStringExtensions.ConvertToString(this.RadiusServerSecret);
            }

            // Map to the sdk object
            var virtualnetGatewayModel = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualNetworkGateway>(this.VirtualNetworkGateway);

            virtualnetGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.VirtualNetworkGateway.Tag, validate: true);

            string shouldProcessMessage = string.Format("Execute AzureRmVirtualNetworkGatewayVpnClientConfig for ResourceGroupName {0} VirtualNetworkGateway {1}", this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name);

            if (ShouldProcess(shouldProcessMessage, VerbsCommon.Set))
            {
                this.VirtualNetworkGatewayClient.CreateOrUpdate(this.VirtualNetworkGateway.ResourceGroupName,
                                                                this.VirtualNetworkGateway.Name, virtualnetGatewayModel);

                var getvirtualnetGateway = this.GetVirtualNetworkGateway(this.VirtualNetworkGateway.ResourceGroupName,
                                                                         this.VirtualNetworkGateway.Name);

                WriteObject(getvirtualnetGateway);
            }
        }
        private PSVirtualNetworkGateway CreateVirtualNetworkGateway()
        {
            var vnetGateway = new PSVirtualNetworkGateway();

            vnetGateway.Name = this.Name;
            vnetGateway.ResourceGroupName = this.ResourceGroupName;
            vnetGateway.Location          = this.Location;

            if (this.GatewaySku != null)
            {
                vnetGateway.Sku      = new PSVirtualNetworkGatewaySku();
                vnetGateway.Sku.Tier = this.GatewaySku;
                vnetGateway.Sku.Name = this.GatewaySku;
            }
            else
            {
                // If gateway sku param value is not passed,  - Let NRP make the decision, just pass it as null here
                vnetGateway.Sku = null;
            }

            if (this.EnableActiveActiveFeature.IsPresent && !this.VpnType.Equals(MNM.VpnType.RouteBased))
            {
                throw new ArgumentException("Virtual Network Gateway VpnType should be " + MNM.VpnType.RouteBased + " when Active-Active feature flag is set to True.");
            }

            if (this.IpConfigurations != null)
            {
                vnetGateway.IpConfigurations = this.IpConfigurations?.ToList();
            }

            if (!string.IsNullOrEmpty(GatewaySku) &&
                GatewaySku.Equals(
                    MNM.VirtualNetworkGatewaySkuTier.UltraPerformance,
                    StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(GatewayType) &&
                !GatewayType.Equals(
                    MNM.VirtualNetworkGatewayType.ExpressRoute.ToString(),
                    StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Virtual Network Gateway Need to be Express Route when the sku is UltraPerformance.");
            }
            vnetGateway.GatewayType            = this.GatewayType;
            vnetGateway.VpnType                = this.VpnType;
            vnetGateway.EnableBgp              = this.EnableBgp;
            vnetGateway.ActiveActive           = this.EnableActiveActiveFeature.IsPresent;
            vnetGateway.EnablePrivateIpAddress = this.EnablePrivateIpAddress.IsPresent;

            if (this.GatewayDefaultSite != null)
            {
                vnetGateway.GatewayDefaultSite    = new PSResourceId();
                vnetGateway.GatewayDefaultSite.Id = this.GatewayDefaultSite.Id;
            }
            else
            {
                vnetGateway.GatewayDefaultSite = null;
            }

            if (this.VpnClientAddressPool != null ||
                this.VpnClientRootCertificates != null ||
                this.VpnClientRevokedCertificates != null ||
                this.RadiusServerAddress != null ||
                (this.VpnClientIpsecPolicy != null && this.VpnClientIpsecPolicy.Length != 0) ||
                this.AadTenantUri != null)
            {
                vnetGateway.VpnClientConfiguration = new PSVpnClientConfiguration();

                if (this.VpnClientAddressPool != null)
                {
                    // Make sure passed Virtual Network gateway type is RouteBased if P2S VpnClientAddressPool is specified.
                    if (this.VpnType == null || !this.VpnType.Equals(MNM.VpnType.RouteBased))
                    {
                        throw new ArgumentException("Virtual Network Gateway VpnType should be :" + MNM.VpnType.RouteBased + " when P2S VpnClientAddressPool is specified.");
                    }

                    vnetGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace();
                    vnetGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool?.ToList();
                }

                if (this.VpnClientProtocol != null)
                {
                    vnetGateway.VpnClientConfiguration.VpnClientProtocols = this.VpnClientProtocol?.ToList();
                }

                if (this.VpnClientRootCertificates != null)
                {
                    vnetGateway.VpnClientConfiguration.VpnClientRootCertificates = this.VpnClientRootCertificates?.ToList();
                }

                if (this.VpnClientRevokedCertificates != null)
                {
                    vnetGateway.VpnClientConfiguration.VpnClientRevokedCertificates = this.VpnClientRevokedCertificates?.ToList();
                }

                if (this.VpnClientIpsecPolicy != null && this.VpnClientIpsecPolicy.Length != 0)
                {
                    vnetGateway.VpnClientConfiguration.VpnClientIpsecPolicies = this.VpnClientIpsecPolicy?.ToList();
                }

                if ((this.RadiusServerAddress != null && this.RadiusServerSecret == null) ||
                    (this.RadiusServerAddress == null && this.RadiusServerSecret != null))
                {
                    throw new ArgumentException("Both radius server address and secret must be specified if external radius is being configured");
                }

                if (this.RadiusServerAddress != null && this.RadiusServerSecret != null)
                {
                    vnetGateway.VpnClientConfiguration.RadiusServerAddress = this.RadiusServerAddress;
                    vnetGateway.VpnClientConfiguration.RadiusServerSecret  = SecureStringExtensions.ConvertToString(this.RadiusServerSecret);
                }

                if (this.RadiusServerList != null && this.RadiusServerList.Any())
                {
                    vnetGateway.VpnClientConfiguration.RadiusServers = this.RadiusServerList?.ToList();
                }

                if (this.AadTenantUri != null)
                {
                    if (this.AadIssuerUri == null || this.AadAudienceId == null)
                    {
                        throw new ArgumentException("AadTenantUri, AadIssuerUri and AadAudienceId must be specified if AAD authentication is being configured for P2S.");
                    }

                    if (vnetGateway.VpnClientConfiguration.VpnClientProtocols.Count() == 1 &&
                        vnetGateway.VpnClientConfiguration.VpnClientProtocols.First().Equals(MNM.VpnClientProtocol.OpenVPN))
                    {
                        vnetGateway.VpnClientConfiguration.AadTenant   = this.AadTenantUri;
                        vnetGateway.VpnClientConfiguration.AadIssuer   = this.AadIssuerUri;
                        vnetGateway.VpnClientConfiguration.AadAudience = this.AadAudienceId;
                    }
                    else
                    {
                        throw new ArgumentException("Virtual Network Gateway VpnClientProtocol should be :" + MNM.VpnClientProtocol.OpenVPN + " when P2S AAD authentication is being configured.");
                    }
                }
            }
            else
            {
                vnetGateway.VpnClientConfiguration = null;
            }

            if (this.Asn > 0 || this.PeerWeight > 0)
            {
                vnetGateway.BgpSettings = new PSBgpSettings();
                vnetGateway.BgpSettings.BgpPeeringAddress = null; // We block modifying the gateway's BgpPeeringAddress (CA)

                if (this.Asn > 0)
                {
                    vnetGateway.BgpSettings.Asn = this.Asn;
                }

                if (this.PeerWeight > 0)
                {
                    vnetGateway.BgpSettings.PeerWeight = this.PeerWeight;
                }
                else if (this.PeerWeight < 0)
                {
                    throw new ArgumentException("PeerWeight must be a positive integer");
                }
            }

            if (this.IpConfigurationBgpPeeringAddresses != null)
            {
                if (vnetGateway.BgpSettings == null)
                {
                    vnetGateway.BgpSettings = new PSBgpSettings();
                }

                vnetGateway.BgpSettings.BgpPeeringAddresses = new List <PSIpConfigurationBgpPeeringAddress>();

                foreach (var address in this.IpConfigurationBgpPeeringAddresses)
                {
                    address.IpconfigurationId = FormatIdBgpPeeringAddresses(address.IpconfigurationId, this.ResourceGroupName, this.Name);
                    vnetGateway.BgpSettings.BgpPeeringAddresses.Add(address);
                }
            }
            else if (vnetGateway.BgpSettings != null)
            {
                vnetGateway.BgpSettings.BgpPeeringAddresses = null;
            }

            if (this.CustomRoute != null && this.CustomRoute.Any())
            {
                vnetGateway.CustomRoutes = new PSAddressSpace();
                vnetGateway.CustomRoutes.AddressPrefixes = this.CustomRoute?.ToList();
            }
            else
            {
                vnetGateway.CustomRoutes = null;
            }

            vnetGateway.VpnGatewayGeneration = MNM.VpnGatewayGeneration.None;
            if (this.VpnGatewayGeneration != null)
            {
                if (GatewayType.Equals(MNM.VirtualNetworkGatewayType.ExpressRoute.ToString(), StringComparison.InvariantCultureIgnoreCase) &&
                    !this.VpnGatewayGeneration.Equals(MNM.VpnGatewayGeneration.None, StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException("Virtual Network Express Route Gateway cannot have any generation other than None.");
                }

                vnetGateway.VpnGatewayGeneration = this.VpnGatewayGeneration;
            }

            // Map to the sdk object
            var vnetGatewayModel = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualNetworkGateway>(vnetGateway);

            vnetGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);

            // Execute the Create VirtualNetwork call
            this.VirtualNetworkGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, vnetGatewayModel);

            var getVirtualNetworkGateway = this.GetVirtualNetworkGateway(this.ResourceGroupName, this.Name);

            return(getVirtualNetworkGateway);
        }
        public override void Execute()
        {
            base.Execute();

            if (!this.IsVirtualNetworkGatewayPresent(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name))
            {
                throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound, this.VirtualNetworkGateway.Name));
            }

            if (this.EnableActiveActiveFeature.IsPresent && this.DisableActiveActiveFeature.IsPresent)
            {
                throw new ArgumentException("Both EnableActiveActiveFeature and DisableActiveActiveFeature Parameters can not be passed.");
            }

            if (this.EnableActiveActiveFeature.IsPresent)
            {
                this.VirtualNetworkGateway.ActiveActive = true;
            }

            if (this.DisableActiveActiveFeature.IsPresent)
            {
                this.VirtualNetworkGateway.ActiveActive = false;
            }

            if (this.EnablePrivateIpAddress.HasValue)
            {
                this.VirtualNetworkGateway.EnablePrivateIpAddress = this.EnablePrivateIpAddress.Value;
            }

            if (!string.IsNullOrEmpty(GatewaySku))
            {
                this.VirtualNetworkGateway.Sku      = new PSVirtualNetworkGatewaySku();
                this.VirtualNetworkGateway.Sku.Tier = this.GatewaySku;
                this.VirtualNetworkGateway.Sku.Name = this.GatewaySku;
            }

            if (this.VirtualNetworkGateway.ActiveActive && !this.VirtualNetworkGateway.VpnType.Equals(MNM.VpnType.RouteBased))
            {
                throw new ArgumentException("Virtual Network Gateway VpnType should be " + MNM.VpnType.RouteBased + " when Active-Active feature flag is set to True.");
            }

            if (this.GatewayDefaultSite != null)
            {
                this.VirtualNetworkGateway.GatewayDefaultSite    = new PSResourceId();
                this.VirtualNetworkGateway.GatewayDefaultSite.Id = this.GatewayDefaultSite.Id;
            }


            if ((this.VpnClientAddressPool != null ||
                 this.VpnClientRootCertificates != null ||
                 this.VpnClientRevokedCertificates != null ||
                 this.RadiusServerAddress != null ||
                 this.RadiusServerSecret != null ||
                 this.RadiusServerList != null ||
                 (this.VpnClientIpsecPolicy != null && this.VpnClientIpsecPolicy.Length != 0) ||
                 this.AadTenantUri != null) &&
                this.VirtualNetworkGateway.VpnClientConfiguration == null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration = new PSVpnClientConfiguration();
            }

            if (this.VpnClientAddressPool != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace();
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool?.ToList();
            }

            if (this.VpnClientProtocol != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientProtocols = this.VpnClientProtocol?.ToList();
            }

            if (this.VpnAuthenticationType != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnAuthenticationTypes = this.VpnAuthenticationType?.ToList();
            }

            if (this.VpnClientRootCertificates != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRootCertificates = this.VpnClientRootCertificates?.ToList();
            }

            if (this.VpnClientRevokedCertificates != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRevokedCertificates = this.VpnClientRevokedCertificates?.ToList();
            }

            if (this.VpnClientIpsecPolicy != null && this.VpnClientIpsecPolicy.Length != 0)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientIpsecPolicies = this.VpnClientIpsecPolicy?.ToList();
            }

            if (!string.IsNullOrEmpty(this.RadiusServerAddress) &&
                (this.RadiusServerList != null && this.RadiusServerList.Any()))
            {
                throw new ArgumentException("Cannot configure both singular radius server and multiple radius servers at the same time.");
            }

            if (!string.IsNullOrEmpty(this.RadiusServerAddress) && this.RadiusServerSecret != null && !string.IsNullOrEmpty(SecureStringExtensions.ConvertToString(this.RadiusServerSecret)))
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerAddress = this.RadiusServerAddress;
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerSecret  = SecureStringExtensions.ConvertToString(this.RadiusServerSecret);
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServers       = null;
            }

            if (this.RadiusServerList != null && this.RadiusServerList.Any())
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServers       = this.RadiusServerList?.ToList();
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerAddress = null;
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerSecret  = null;
            }

            if (this.AadTenantUri != null || this.AadIssuerUri != null || this.AadAudienceId != null)
            {
                if (this.AadTenantUri == null || this.AadIssuerUri == null || this.AadAudienceId == null)
                {
                    throw new ArgumentException("AadTenantUri, AadIssuerUri and AadAudienceId must be specified if AAD authentication is being configured for P2S.");
                }

                if (this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientProtocols.Count() == 1 &&
                    this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientProtocols.First().Equals(MNM.VpnClientProtocol.OpenVPN))
                {
                    this.VirtualNetworkGateway.VpnClientConfiguration.AadTenant   = this.AadTenantUri;
                    this.VirtualNetworkGateway.VpnClientConfiguration.AadIssuer   = this.AadIssuerUri;
                    this.VirtualNetworkGateway.VpnClientConfiguration.AadAudience = this.AadAudienceId;
                }
                else
                {
                    throw new ArgumentException("Virtual Network Gateway VpnClientProtocol should be :" + MNM.VpnClientProtocol.OpenVPN + " when P2S AAD authentication is being configured.");
                }
            }

            if (this.RemoveAadAuthentication.IsPresent)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.AadTenant   = null;
                this.VirtualNetworkGateway.VpnClientConfiguration.AadIssuer   = null;
                this.VirtualNetworkGateway.VpnClientConfiguration.AadAudience = null;
            }

            if (this.VirtualNetworkGateway.VpnClientConfiguration?.VpnAuthenticationTypes != null && this.VirtualNetworkGateway.VpnClientConfiguration.VpnAuthenticationTypes.Count() > 0)
            {
                if (!this.VirtualNetworkGateway.VpnClientConfiguration.VpnAuthenticationTypes.Contains(MNM.VpnAuthenticationType.AAD))
                {
                    this.VirtualNetworkGateway.VpnClientConfiguration.AadTenant   = string.Empty;
                    this.VirtualNetworkGateway.VpnClientConfiguration.AadIssuer   = string.Empty;
                    this.VirtualNetworkGateway.VpnClientConfiguration.AadAudience = string.Empty;
                }

                if (!this.VirtualNetworkGateway.VpnClientConfiguration.VpnAuthenticationTypes.Contains(MNM.VpnAuthenticationType.Radius))
                {
                    this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServers       = new List <PSRadiusServer>();
                    this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerAddress = string.Empty;
                    this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerSecret  = string.Empty;
                }

                if (!this.VirtualNetworkGateway.VpnClientConfiguration.VpnAuthenticationTypes.Contains(MNM.VpnAuthenticationType.Certificate))
                {
                    this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRevokedCertificates = new List <PSVpnClientRevokedCertificate>();
                    this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRootCertificates    = new List <PSVpnClientRootCertificate>();
                }
            }

            if ((this.Asn > 0 || this.PeerWeight > 0) && this.VirtualNetworkGateway.BgpSettings == null)
            {
                this.VirtualNetworkGateway.BgpSettings = new PSBgpSettings();
                this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddress = null; // The gateway's BGP peering address (private IP address assigned within the vnet) can't be changed
            }

            if (this.Asn > 0)
            {
                this.VirtualNetworkGateway.BgpSettings.Asn = this.Asn;
            }

            if (this.PeerWeight > 0)
            {
                this.VirtualNetworkGateway.BgpSettings.PeerWeight = this.PeerWeight;
            }
            else if (this.PeerWeight < 0)
            {
                throw new ArgumentException("PeerWeight must be a positive integer");
            }

            if (this.IpConfigurationBgpPeeringAddresses != null)
            {
                if (this.VirtualNetworkGateway.BgpSettings == null)
                {
                    this.VirtualNetworkGateway.BgpSettings = new PSBgpSettings();
                }

                if (this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddresses == null)
                {
                    this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddresses = new List <PSIpConfigurationBgpPeeringAddress>();

                    foreach (var address in this.IpConfigurationBgpPeeringAddresses)
                    {
                        this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddresses.Add(address);
                    }
                }
                else
                {
                    foreach (var address in this.IpConfigurationBgpPeeringAddresses)
                    {
                        bool isGatewayIpConfigurationExists = this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddresses.Any(
                            ipconfaddress => ipconfaddress.IpconfigurationId.Equals(address.IpconfigurationId, StringComparison.OrdinalIgnoreCase));

                        if (isGatewayIpConfigurationExists)
                        {
                            var bgpPeeringPropertiesInRequest = this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddresses.FirstOrDefault(
                                x => x.IpconfigurationId.Equals(address.IpconfigurationId, StringComparison.OrdinalIgnoreCase));

                            bgpPeeringPropertiesInRequest.CustomBgpIpAddresses = address.CustomBgpIpAddresses;
                        }
                        else
                        {
                            this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddresses.Add(address);
                        }
                    }
                }
            }

            if (this.CustomRoute != null && this.CustomRoute.Any())
            {
                this.VirtualNetworkGateway.CustomRoutes = new PSAddressSpace();
                this.VirtualNetworkGateway.CustomRoutes.AddressPrefixes = this.CustomRoute?.ToList();
            }
            else
            {
                this.VirtualNetworkGateway.CustomRoutes = null;
            }

            if (this.NatRule != null)
            {
                this.VirtualNetworkGateway.NatRules = this.NatRule?.ToList();
            }

            if (this.BgpRouteTranslationForNat.HasValue)
            {
                this.VirtualNetworkGateway.EnableBgpRouteTranslationForNat = this.BgpRouteTranslationForNat.Value;
            }

            // Map to the sdk object
            MNM.VirtualNetworkGateway sdkVirtualNetworkGateway = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualNetworkGateway>(this.VirtualNetworkGateway);
            sdkVirtualNetworkGateway.Tags =
                ParameterSetName.Contains(VirtualNetworkGatewayParameterSets.UpdateResourceWithTags) ?
                TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true) :
                TagsConversionHelper.CreateTagDictionary(this.VirtualNetworkGateway.Tag, validate: true);

            string shouldProcessMessage = string.Format("Execute AzureRmVirtualNetworkGateway for ResourceGroupName {0} VirtualNetworkGateway {1}", this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name);

            if (ShouldProcess(shouldProcessMessage, VerbsCommon.Set))
            {
                this.VirtualNetworkGatewayClient.CreateOrUpdate(this.VirtualNetworkGateway.ResourceGroupName,
                                                                this.VirtualNetworkGateway.Name, sdkVirtualNetworkGateway);

                var getVirtualNetworkGateway =
                    this.GetVirtualNetworkGateway(this.VirtualNetworkGateway.ResourceGroupName,
                                                  this.VirtualNetworkGateway.Name);

                WriteObject(getVirtualNetworkGateway);
            }
        }
Beispiel #18
0
        public override void ExecuteCmdlet()
        {
            Guid   subscriptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscriptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            if (ClientAssertionParameterSet.Equals(ParameterSetName, StringComparison.OrdinalIgnoreCase))
            {
                string suppressWarningOrErrorValue = System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME);
                bool.TryParse(suppressWarningOrErrorValue, out bool suppressWarningOrError);
                if (!suppressWarningOrError)
                {
                    WriteWarning("The feature related to parameter name 'FederatedToken' is under preview.");
                }
            }

            var azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case UserParameterSet:
                azureAccount.Type = AzureAccount.AccountType.User;
                if (!string.IsNullOrEmpty(AccountId))
                {
                    azureAccount.SetProperty("LoginHint", AccountId);
                }
                break;

            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                azureAccount.SetProperty(Constants.MicrosoftGraphAccessToken, MicrosoftGraphAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
            case ServicePrincipalCertificateFileParameterSet:
            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ClientAssertionParameterSet:
                azureAccount.Type = "ClientAssertion";
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                azureAccount.Id   = this.IsBound(nameof(AccountId)) ? AccountId : $"{Constants.DefaultMsiAccountIdPrefix}{DefaultManagedServicePort}";
                break;

            default:
                //Support username + password for both Windows PowerShell and PowerShell 6+
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (UseDeviceAuthentication.IsPresent)
            {
                azureAccount.SetProperty("UseDeviceAuth", "true");
            }

            if (azureAccount.Type == AzureAccount.AccountType.User && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true");
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrWhiteSpace(CertificatePath))
            {
                var resolvedPath = this.SessionState.Path.GetResolvedPSPathFromPSPath(CertificatePath).FirstOrDefault()?.Path;
                if (string.IsNullOrEmpty(resolvedPath))
                {
                    var parametersLog = $"- Invalid certificate path :'{CertificatePath}'.";
                    throw new InvalidOperationException(parametersLog);
                }
                azureAccount.SetProperty(AzureAccount.Property.CertificatePath, resolvedPath);
                if (CertificatePassword != null)
                {
                    azureAccount.SetProperty(AzureAccount.Property.CertificatePassword, CertificatePassword.ConvertToString());
                }
            }

            if ((ParameterSetName == ServicePrincipalCertificateParameterSet || ParameterSetName == ServicePrincipalCertificateFileParameterSet) &&
                SendCertificateChain)
            {
                azureAccount.SetProperty(AzureAccount.Property.SendCertificateChain, SendCertificateChain.ToString());
                bool supressWarningOrError = false;
                try
                {
                    supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME));
                }
                catch
                {
                    //if value of env variable is invalid, use default value of supressWarningOrError
                }
                if (!supressWarningOrError)
                {
                    WriteWarning(Resources.PreviewFunctionMessage);
                }
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant);
            }

            if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory));
                }
            }
            if (azureAccount.Type == "ClientAssertion" && FederatedToken != null)
            {
                password = SecureStringExtensions.ConvertToSecureString(FederatedToken);
                azureAccount.SetProperty("ClientAssertion", FederatedToken);
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ClientAssertionWarning, file, directory));
                }
            }

            var resourceId = PreProcessAuthScope();

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                if (!AzureSession.Instance.TryGetComponent(nameof(CommonUtilities), out CommonUtilities commonUtilities))
                {
                    commonUtilities = new CommonUtilities();
                    AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => commonUtilities);
                }
                if (!commonUtilities.IsDesktopSession() && IsUsingInteractiveAuthentication())
                {
                    WriteWarning(Resources.InteractiveAuthNotSupported);
                    return;
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    bool shouldPopulateContextList = true;
                    if (this.IsParameterBound(c => c.SkipContextPopulation))
                    {
                        shouldPopulateContextList = false;
                    }

                    profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message)));
                    profileClient.DebugLog   = (message) => _tasks.Enqueue(new Task(() => this.WriteDebugWithTimestamp(message)));
                    var task = new Task <AzureRmProfile>(() => profileClient.Login(
                                                             azureAccount,
                                                             _environment,
                                                             Tenant,
                                                             subscriptionId,
                                                             subscriptionName,
                                                             password,
                                                             SkipValidation,
                                                             WriteWarningEvent, //Could not use WriteWarning directly because it may be in worker thread
                                                             name,
                                                             shouldPopulateContextList,
                                                             MaxContextPopulation,
                                                             resourceId));
                    task.Start();
                    while (!task.IsCompleted)
                    {
                        HandleActions();
                        Thread.Yield();
                    }

                    HandleActions();

                    try
                    {
                        //Must not use task.Result as it wraps inner exception into AggregateException
                        var result = (PSAzureProfile)task.GetAwaiter().GetResult();
                        WriteObject(result);
                    }
                    catch (AuthenticationFailedException ex)
                    {
                        if (IsUnableToOpenWebPageError(ex))
                        {
                            WriteWarning(Resources.InteractiveAuthNotSupported);
                            WriteDebug(ex.ToString());
                        }
                        else
                        {
                            if (IsUsingInteractiveAuthentication())
                            {
                                //Display only if user is using Interactive auth
                                WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
                            }
                            WriteDebug(ex.ToString());
                            throw;
                        }
                    }
                });
            }
        }
        private PSVpnConnection CreateVpnConnection()
        {
            base.Execute();
            PSVpnGateway parentVpnGateway = null;

            //// Resolve the VpnGateway
            if (ParameterSetName.Contains(CortexParameterSetNames.ByVpnGatewayObject))
            {
                this.ResourceGroupName  = this.ParentObject.ResourceGroupName;
                this.ParentResourceName = this.ParentObject.Name;
            }
            else if (ParameterSetName.Contains(CortexParameterSetNames.ByVpnGatewayResourceId))
            {
                var parsedResourceId = new ResourceIdentifier(this.ParentResourceId);
                this.ResourceGroupName  = parsedResourceId.ResourceGroupName;
                this.ParentResourceName = parsedResourceId.ResourceName;
            }

            if (string.IsNullOrWhiteSpace(this.ResourceGroupName) || string.IsNullOrWhiteSpace(this.ParentResourceName))
            {
                throw new PSArgumentException(Properties.Resources.VpnGatewayRequiredToCreateVpnConnection);
            }

            if (this.IsVpnConnectionPresent(this.ResourceGroupName, this.ParentResourceName, this.Name))
            {
                throw new PSArgumentException(string.Format(Properties.Resources.ChildResourceAlreadyPresentInResourceGroup, this.Name, this.ResourceGroupName, this.ParentResourceName));
            }

            //// At this point, we should have the resource name and the resource group for the parent VpnGateway resolved.
            //// This will throw not found exception if the VpnGateway does not exist
            parentVpnGateway = this.GetVpnGateway(this.ResourceGroupName, this.ParentResourceName);
            if (parentVpnGateway == null)
            {
                throw new PSArgumentException(Properties.Resources.ParentVpnGatewayNotFound);
            }

            if (parentVpnGateway.Connections == null)
            {
                parentVpnGateway.Connections = new List <PSVpnConnection>();
            }

            PSVpnConnection vpnConnection = new PSVpnConnection
            {
                Name      = this.Name,
                EnableBgp = this.EnableBgp.IsPresent,
                UseLocalAzureIpAddress         = this.UseLocalAzureIpAddress.IsPresent,
                UsePolicyBasedTrafficSelectors = this.UsePolicyBasedTrafficSelectors.IsPresent,
                EnableInternetSecurity         = this.EnableInternetSecurity.IsPresent
            };

            //// Resolve the VpnSite reference
            //// And set it in the VpnConnection object.
            string vpnSiteResolvedId = null;

            if (ParameterSetName.Contains(CortexParameterSetNames.ByVpnSiteObject))
            {
                vpnSiteResolvedId = this.VpnSite.Id;
            }
            else if (ParameterSetName.Contains(CortexParameterSetNames.ByVpnSiteResourceId))
            {
                vpnSiteResolvedId = this.VpnSiteId;
            }

            if (string.IsNullOrWhiteSpace(vpnSiteResolvedId))
            {
                throw new PSArgumentException(Properties.Resources.VpnSiteRequiredForVpnConnection);
            }

            //// Let's not resolve the vpnSite here. If this does not exist, NRP/GWM will fail the call.
            vpnConnection.RemoteVpnSite = new PSResourceId()
            {
                Id = vpnSiteResolvedId
            };

            //// Set the shared key, if specified
            if (this.SharedKey != null)
            {
                vpnConnection.SharedKey = SecureStringExtensions.ConvertToString(this.SharedKey);
            }

            if (!String.IsNullOrEmpty(this.VpnConnectionProtocolType))
            {
                vpnConnection.VpnConnectionProtocolType = this.VpnConnectionProtocolType;
            }

            if (this.IpSecPolicy != null)
            {
                vpnConnection.IpsecPolicies = new List <PSIpsecPolicy> {
                    this.IpSecPolicy
                };
            }

            if (this.VpnSiteLinkConnection != null)
            {
                //// Use only link connection properties instead of vpn connection properties.
                if (this.SharedKey != null || this.ConnectionBandwidthInMbps > 0 || this.EnableBgp.IsPresent || this.UseLocalAzureIpAddress.IsPresent || this.UsePolicyBasedTrafficSelectors.IsPresent || this.IpSecPolicy != null)
                {
                    throw new PSArgumentException(Properties.Resources.VpnConnectionPropertyIsDeprecated);
                }

                vpnConnection.VpnLinkConnections = new List <PSVpnSiteLinkConnection>();
                vpnConnection.VpnLinkConnections.AddRange(this.VpnSiteLinkConnection);
            }
            else
            {
                //// Connection bandwidth
                vpnConnection.ConnectionBandwidth = this.ConnectionBandwidthInMbps > 0 ?
                                                    Convert.ToInt32(this.ConnectionBandwidthInMbps) :
                                                    20;
            }

            parentVpnGateway.Connections.Add(vpnConnection);

            WriteVerbose(string.Format(Properties.Resources.CreatingLongRunningOperationMessage, this.ResourceGroupName, this.Name));

            PSVpnConnection connectionToReturn = null;

            ConfirmAction(
                Properties.Resources.CreatingResourceMessage,
                this.Name,
                () =>
            {
                WriteVerbose(String.Format(Properties.Resources.CreatingLongRunningOperationMessage, this.ResourceGroupName, this.Name));
                this.CreateOrUpdateVpnGateway(this.ResourceGroupName, this.ParentResourceName, parentVpnGateway, parentVpnGateway.Tag);

                var createdOrUpdatedVpnGateway = this.GetVpnGateway(this.ResourceGroupName, this.ParentResourceName);
                connectionToReturn             = createdOrUpdatedVpnGateway.Connections.Where(connection => connection.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            });

            return(connectionToReturn);
        }
        /// <inheritdoc/>
        public override void ShowInView(IHtmlView htmlView, KeyValueList <string, string> variables)
        {
            base.ShowInView(htmlView, variables);
            IStoryBoardService storyBoardService             = Ioc.GetOrCreate <IStoryBoardService>();
            SerializeableCloudStorageCredentials credentials = storyBoardService.ActiveStory.LoadFromSession <SerializeableCloudStorageCredentials>(SynchronizationStorySessionKey.CloudStorageCredentials.ToInt());

            _viewModel = new CloudStorageAccountViewModel(
                Ioc.GetOrCreate <INavigationService>(),
                Ioc.GetOrCreate <ILanguageService>(),
                Ioc.GetOrCreate <ISvgIconService>(),
                Ioc.GetOrCreate <IBaseUrlService>(),
                storyBoardService,
                Ioc.GetOrCreate <IFeedbackService>(),
                Ioc.GetOrCreate <ICloudStorageClientFactory>(),
                credentials);

            Bindings.BindCommand("GoBack", _viewModel.GoBackCommand);
            Bindings.BindCommand("OkCommand", _viewModel.OkCommand);
            Bindings.BindCommand("CancelCommand", _viewModel.CancelCommand);
            Bindings.BindText("Url", null, (v) => _viewModel.Url           = v, null, null, HtmlViewBindingMode.OneWayToViewmodel);
            Bindings.BindText("Username", null, (v) => _viewModel.Username = v, null, null, HtmlViewBindingMode.OneWayToViewmodel);
            Bindings.BindText("Password", () => SecureStringExtensions.SecureStringToString(_viewModel.Password), (v) => _viewModel.Password = SecureStringExtensions.StringToSecureString(v), _viewModel, nameof(_viewModel.Password), HtmlViewBindingMode.TwoWayPlusOneTimeToView);
            Bindings.BindCheckbox("Secure", null, (v) => _viewModel.Secure = v, null, null, HtmlViewBindingMode.OneWayToViewmodel);

            string html = _viewService.GenerateHtml(_viewModel);

            View.LoadHtml(html);
        }