예제 #1
0
        /// <summary>
        /// Ensures the service principal.
        /// </summary>
        /// <returns>PSADServicePrincipal.</returns>
        public PSADServicePrincipal EnsureServicePrincipal()
        {
            string applicationId = CurrentApplicationId.ToString();
            string appObjectId   = ActiveDirectoryClient.GetServicePrincipalsIdByAppId(CurrentApplicationId);
            PSADServicePrincipal servicePrincipal = ActiveDirectoryClient.GetServicePrincipalByObjectId(appObjectId);

            if (servicePrincipal == null)
            {
                VerboseLogger.Invoke(StorageSyncResources.CreateServicePrincipalMessage);
                // Create an application and get the applicationId
                var passwordCredential = new PSADPasswordCredential()
                {
                    StartDate = DateTime.Now,
                    EndDate   = DateTime.Now.AddYears(1),
                    KeyId     = Guid.NewGuid(),
                    Password  = SecureStringExtensions.ConvertToString(Guid.NewGuid().ToString().ConvertToSecureString())
                };

                var createParameters = new CreatePSServicePrincipalParameters
                {
                    ApplicationId       = CurrentApplicationId,
                    AccountEnabled      = bool.TrueString,
                    PasswordCredentials = new PSADPasswordCredential[]
                    {
                        passwordCredential
                    }
                };

                servicePrincipal = ActiveDirectoryClient.CreateServicePrincipal(createParameters);
            }

            return(servicePrincipal);
        }
예제 #2
0
        /// <summary>
        /// Ensures the service principal.
        /// </summary>
        /// <returns>PSADServicePrincipal.</returns>
        public PSADServicePrincipal EnsureServicePrincipal()
        {
            string applicationId     = KailaniAppId.ToString();
            var    servicePrincipals = ActiveDirectoryClient.FilterServicePrincipals(new ODataQuery <ServicePrincipal>(s => s.AppId == applicationId));
            PSADServicePrincipal servicePrincipal = servicePrincipals.FirstOrDefault();

            if (servicePrincipal == null)
            {
                VerboseLogger.Invoke(StorageSyncResources.CreateServicePrincipalMessage);
                // Create an application and get the applicationId
                var passwordCredential = new PSADPasswordCredential()
                {
                    StartDate = DateTime.Now,
                    EndDate   = DateTime.Now.AddYears(1),
                    KeyId     = Guid.NewGuid(),
                    Password  = SecureStringExtensions.ConvertToString(Guid.NewGuid().ToString().ConvertToSecureString())
                };

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

                servicePrincipal = ActiveDirectoryClient.CreateServicePrincipal(createParameters);
            }

            return(servicePrincipal);
        }
        public override void ExecuteCmdlet()
        {
            string decodedPassword      = SecureStringExtensions.ConvertToString(Password);
            var    userCreateparameters = new UserCreateParameters
            {
                AccountEnabled  = true,
                DisplayName     = DisplayName,
                MailNickname    = MailNickname,
                PasswordProfile = new PasswordProfile
                {
                    Password = decodedPassword,
                    ForceChangePasswordNextLogin = ForceChangePasswordNextLogin.IsPresent ? true : false
                },
                UserPrincipalName = UserPrincipalName
            };

            if (this.IsParameterBound(c => c.ImmutableId))
            {
                userCreateparameters.ImmutableId = ImmutableId;
            }

            ExecutionBlock(() =>
            {
                if (ShouldProcess(target: UserPrincipalName, action: string.Format("Adding a new user with UPN '{0}'", UserPrincipalName)))
                {
                    WriteObject(ActiveDirectoryClient.CreateUser(userCreateparameters));
                }
            });
        }
예제 #4
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.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
                {
                    throw new InvalidOperationException("No valid keyCredential or passwordCredential to update!!");
                }
            });
        }
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            CustomerUser newUser;
            string       country;

            CustomerId.AssertNotEmpty(nameof(CustomerId));

            if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewPartnerCustomerUserWhatIf, UserPrincipalName)))
            {
                country = (string.IsNullOrEmpty(UsageLocation)) ? PartnerSession.Instance.Context.CountryCode : UsageLocation;
                string stringPassword = SecureStringExtensions.ConvertToString(Password);

                newUser = new CustomerUser
                {
                    PasswordProfile = new PasswordProfile()
                    {
                        ForceChangePassword = ForceChangePassword.IsPresent,
                        Password            = stringPassword
                    },
                    DisplayName       = DisplayName,
                    FirstName         = FirstName,
                    LastName          = LastName,
                    UsageLocation     = country,
                    UserPrincipalName = UserPrincipalName
                };
                CustomerUser createdUser = Partner.Customers[CustomerId].Users.CreateAsync(newUser).GetAwaiter().GetResult();
                WriteObject(new PSCustomerUser(createdUser));
            }
        }
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            Scheduler.RunTask(async() =>
            {
                if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewPartnerCustomerUserWhatIf, UserPrincipalName)))
                {
                    IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false);
                    CustomerUser newUser;
                    string country;

                    country = (string.IsNullOrEmpty(UsageLocation)) ? PartnerSession.Instance.Context.CountryCode : UsageLocation;
                    string stringPassword = SecureStringExtensions.ConvertToString(Password);

                    newUser = new CustomerUser
                    {
                        PasswordProfile = new PasswordProfile()
                        {
                            ForceChangePassword = ForceChangePassword.IsPresent,
                            Password            = stringPassword
                        },
                        DisplayName       = DisplayName,
                        FirstName         = FirstName,
                        LastName          = LastName,
                        UsageLocation     = country,
                        UserPrincipalName = UserPrincipalName
                    };
                    CustomerUser createdUser = await partner.Customers[CustomerId].Users.CreateAsync(newUser, CancellationToken).ConfigureAwait(false);
                    WriteObject(new PSCustomerUser(createdUser));
                }
            }, true);
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            if (ShouldProcess(VirtualMachineADDomainExtensionContext.ExtensionDefaultName, VerbsCommon.Set))
            {
                ExecuteClientAction(() =>
                {
                    Hashtable publicSettings = new Hashtable();
                    publicSettings.Add(nameKey, this.DomainName);

                    if (this.OUPath != null)
                    {
                        publicSettings.Add(ouPathKey, this.OUPath);
                    }

                    if (this.JoinOption != null)
                    {
                        publicSettings.Add(optionKey, this.JoinOption);
                    }

                    publicSettings.Add(restartKey, Restart.IsPresent);

                    Hashtable privateSettings = new Hashtable();
                    if (Credential != null)
                    {
                        publicSettings.Add(userKey, Credential.UserName);
                        privateSettings.Add(passwordKey, SecureStringExtensions.ConvertToString(this.Credential.Password));
                    }

                    if (string.IsNullOrEmpty(this.Location))
                    {
                        this.Location = GetLocationFromVm(this.ResourceGroupName, this.VMName);
                    }

                    var parameters = new VirtualMachineExtension
                    {
                        Location  = this.Location,
                        Publisher = VirtualMachineADDomainExtensionContext.ExtensionDefaultPublisher,
                        VirtualMachineExtensionType = VirtualMachineADDomainExtensionContext.ExtensionDefaultName,
                        TypeHandlerVersion          = this.TypeHandlerVersion ?? VirtualMachineADDomainExtensionContext.ExtensionDefaultVersion,
                        AutoUpgradeMinorVersion     = !this.DisableAutoUpgradeMinorVersion.IsPresent,
                        ForceUpdateTag    = this.ForceRerun,
                        Settings          = publicSettings,
                        ProtectedSettings = privateSettings
                    };

                    var op = this.VirtualMachineExtensionClient.CreateOrUpdateWithHttpMessagesAsync(
                        this.ResourceGroupName,
                        this.VMName,
                        this.Name ?? VirtualMachineADDomainExtensionContext.ExtensionDefaultName,
                        parameters).GetAwaiter().GetResult();

                    var result = Mapper.Map <PSAzureOperationResponse>(op);
                    WriteObject(result);
                });
            }
        }
        public override void ExecuteCmdlet()
        {
            CreatePSApplicationParameters createParameters = new CreatePSApplicationParameters
            {
                DisplayName             = DisplayName,
                HomePage                = HomePage,
                IdentifierUris          = IdentifierUris,
                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));
                }
            });
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                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     = Guid.NewGuid().ToString(),
                        Value     = decodedPassword
                    };
                    if (ShouldProcess(target: ObjectId.ToString(), action: string.Format("Adding a new password to application with objectId {0}", ObjectId)))
                    {
                        WriteObject(ActiveDirectoryClient.CreateAppPasswordCredential(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 certificate to application with objectId {0}", ObjectId)))
                    {
                        WriteObject(ActiveDirectoryClient.CreateAppKeyCredential(ObjectId, keyCredential));
                    }
                }
                else
                {
                    throw new InvalidOperationException("No valid keyCredential or passowrdCredential to update!!");
                }
            });
        }
예제 #10
0
        public override void Execute()
        {
            base.Execute();
            var radiusServer = new PSRadiusServer();

            radiusServer.RadiusServerAddress = this.RadiusServerAddress;
            radiusServer.RadiusServerSecret  = SecureStringExtensions.ConvertToString(this.RadiusServerSecret);

            // default score value
            radiusServer.RadiusServerScore = (!this.MyInvocation.BoundParameters.ContainsKey("RadiusServerScore")) ? 30 : this.RadiusServerScore;

            WriteObject(radiusServer);
        }
        public override void ExecuteCmdlet()
        {
            PasswordProfile profile = null;

            if (Password != null && Password.Length > 0)
            {
                string decodedPassword = SecureStringExtensions.ConvertToString(Password);
                profile = new PasswordProfile
                {
                    Password = decodedPassword,
                    ForceChangePasswordNextLogin = ForceChangePasswordNextLogin.IsPresent ? true : false
                };
            }

            var userUpdateParameters = new UserUpdateParameters
            {
                AccountEnabled  = EnableAccount,
                DisplayName     = DisplayName,
                PasswordProfile = profile
            };

            ExecutionBlock(() =>
            {
                if (this.IsParameterBound(c => c.InputObject))
                {
                    UPNOrObjectId = !string.IsNullOrEmpty(InputObject.UserPrincipalName) ?
                                    InputObject.UserPrincipalName :
                                    InputObject.Id.ToString();
                }
                else if (this.IsParameterBound(c => c.UserPrincipalName))
                {
                    UPNOrObjectId = UserPrincipalName;
                }
                else if (this.IsParameterBound(c => c.ObjectId))
                {
                    UPNOrObjectId = ObjectId;
                }

                if (ShouldProcess(target: UPNOrObjectId, action: string.Format("Updating properties for user with upn or object id '{0}'", UPNOrObjectId)))
                {
                    WriteObject(ActiveDirectoryClient.UpdateUser(UPNOrObjectId, userUpdateParameters));
                }
            });
        }
예제 #12
0
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            CustomerUser newUser;
            string       country;

            CustomerId.AssertNotEmpty(nameof(CustomerId));

            try
            {
                if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewPartnerCustomerUserWhatIf, UserPrincipalName)))
                {
                    country = (string.IsNullOrEmpty(UsageLocation)) ? PartnerProfile.Instance.Context.CountryCode : UsageLocation;
                    string stringPassword = SecureStringExtensions.ConvertToString(Password);

                    newUser = new CustomerUser
                    {
                        PasswordProfile = new PasswordProfile()
                        {
                            ForceChangePassword = ForceChangePassword.IsPresent,
                            Password            = stringPassword
                        },
                        DisplayName       = DisplayName,
                        FirstName         = FirstName,
                        LastName          = LastName,
                        UsageLocation     = country,
                        UserPrincipalName = UserPrincipalName
                    };
                    CustomerUser createdUser = Partner.Customers[CustomerId].Users.Create(newUser);
                    WriteObject(new PSCustomerUser(createdUser));
                }
            }
            catch (PSPartnerException ex)
            {
                throw new PSPartnerException("Error creating user:" + UserPrincipalName, ex);
            }
            finally
            {
                newUser = null;
                country = null;
            }
        }
예제 #13
0
        public override void Execute()
        {
            base.Execute();

            var vpnSiteLinkConnection = new PSVpnSiteLinkConnection
            {
                Name      = this.Name,
                EnableBgp = this.EnableBgp.IsPresent,
                UseLocalAzureIpAddress         = this.UseLocalAzureIpAddress.IsPresent,
                UsePolicyBasedTrafficSelectors = this.UsePolicyBasedTrafficSelectors.IsPresent,
                RoutingWeight         = Convert.ToInt32(this.RoutingWeight),
                IngressNatRules       = IngressNatRule?.ToList(),
                EgressNatRules        = EgressNatRule?.ToList(),
                VpnLinkConnectionMode = this.VpnLinkConnectionMode
            };

            if (this.VpnSiteLink == null)
            {
                throw new PSArgumentException(Properties.Resources.VpnSiteLinkRequiredForVpnSiteLinkConnection);
            }

            vpnSiteLinkConnection.VpnSiteLink = this.VpnSiteLink;

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

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

            //// Connection bandwidth
            vpnSiteLinkConnection.ConnectionBandwidth = this.ConnectionBandwidth > 0 ?
                                                        Convert.ToInt32(this.ConnectionBandwidth) :
                                                        20;

            WriteObject(vpnSiteLinkConnection);
        }
예제 #14
0
        public override void ExecuteCmdlet()
        {
            PasswordProfile profile = null;

            if (Password != null && Password.Length > 0)
            {
                string decodedPassword = SecureStringExtensions.ConvertToString(Password);
                profile = new PasswordProfile
                {
                    Password = decodedPassword,
                    ForceChangePasswordNextLogin = ForceChangePasswordNextLogin.IsPresent ? true : false
                };
            }

            var userUpdateParameters = new UserUpdateParameters(EnableAccount, DisplayName, profile);

            ExecutionBlock(() =>
            {
                if (ShouldProcess(target: UPNOrObjectId, action: string.Format("Updating properties for user with upn or object id '{0}'", UPNOrObjectId)))
                {
                    WriteObject(ActiveDirectoryClient.UpdateUser(UPNOrObjectId, userUpdateParameters));
                }
            });
        }
예제 #15
0
        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
            };

            //// 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;
            }

            //// Connection bandwidth
            vpnConnection.ConnectionBandwidth = this.ConnectionBandwidthInMbps > 0 ?
                                                Convert.ToInt32(this.ConnectionBandwidthInMbps) :
                                                20;

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

            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);
        }
예제 #16
0
        /// <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();

            try
            {
                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);
                    }
                }
            }
            catch (PartnerCenter.Exceptions.PartnerException ex)
            {
                throw new PSPartnerException("An error was encountered when communicating with Partner Center.", ex);
            }
        }
        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());
            });
        }
        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.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.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 (ParameterSetName.Contains(VirtualNetworkGatewayParameterSets.RadiusServerConfiguration))
            {
                if (this.RadiusServerSecret == null || this.RadiusServerAddress == null)
                {
                    throw new ArgumentException("Both radius server address and secret must be specified if external radius is being configured");
                }

                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerAddress = this.RadiusServerAddress;
                this.VirtualNetworkGateway.VpnClientConfiguration.RadiusServerSecret  = SecureStringExtensions.ConvertToString(this.RadiusServerSecret);
            }

            if (ParameterSetName.Contains(VirtualNetworkGatewayParameterSets.AadAuthenticationConfiguration))
            {
                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.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.CustomRoute != null && this.CustomRoute.Any())
            {
                this.VirtualNetworkGateway.CustomRoutes = new PSAddressSpace();
                this.VirtualNetworkGateway.CustomRoutes.AddressPrefixes = this.CustomRoute?.ToList();
            }
            else
            {
                this.VirtualNetworkGateway.CustomRoutes = null;
            }

            // 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);
            }
        }
예제 #19
0
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            CustomerUser user;

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

            // Get the current user information
            user = GetUserById(CustomerId, UserId);

            try
            {
                if (user.Id == UserId)
                {
                    // see what has changed for this user
                    if (UserPrincipalName != null)
                    {
                        user.UserPrincipalName = UserPrincipalName;
                    }

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

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

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

                    PasswordProfile profile = null;
                    if (Password != null && Password.Length > 0)
                    {
                        string stringPassword = SecureStringExtensions.ConvertToString(Password);
                        profile = new PasswordProfile
                        {
                            Password            = stringPassword,
                            ForceChangePassword = ForceChangePasswordNextLogin.IsPresent ? true : false
                        };
                        user.PasswordProfile = profile;
                    }
                    else if (ForceChangePasswordNextLogin.IsPresent)
                    {
                        profile = new PasswordProfile
                        {
                            ForceChangePassword = ForceChangePasswordNextLogin.IsPresent ? true : false
                        };
                        user.PasswordProfile = profile;
                    }

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

                        CustomerUser result = Partner.Customers[CustomerId].Users[UserId].Patch(user);
                        WriteObject(new PSCustomerUser(user), true);
                    }
                }
            }
            catch (PartnerException ex)
            {
                throw new PSPartnerException("An error was encountered when communicating with Partner Center.", ex);
            }
            finally
            {
                user = null;
            }
        }
예제 #20
0
        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);
            }

            // Modify the vpnServerConfigurationPolicyGroups
            if (this.ConfigurationPolicyGroup != null)
            {
                vpnServerConfigurationToUpdate.ConfigurationPolicyGroups = new List <PSVpnServerConfigurationPolicyGroup>();
                vpnServerConfigurationToUpdate.ConfigurationPolicyGroups.AddRange(this.ConfigurationPolicyGroup);
            }

            // 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;
            }

            if (vpnServerConfigurationToUpdate.VpnAuthenticationTypes != null)
            {
                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 (this.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;
                }

                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 = 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));
            });
        }
예제 #21
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 PSVpnServerConfiguration CreateVpnServerConfigurationObject(
            PSVpnServerConfiguration vpnServerConfiguration,
            string[] vpnProtocol,
            string[] vpnAuthenticationType,
            string[] vpnClientRootCertificateFilesList,
            string[] vpnClientRevokedCertificateFilesList,
            string radiusServerAddress,
            SecureString radiusServerSecret,
            string[] radiusServerRootCertificateFilesList,
            string[] radiusClientRootCertificateFilesList,
            string aadTenant,
            string aadAudience,
            string aadIssuer,
            PSIpsecPolicy[] vpnClientIpsecPolicy)
        {
            if (vpnProtocol != null)
            {
                vpnServerConfiguration.VpnProtocols = new List <string>(vpnProtocol);
            }

            if (vpnAuthenticationType != null)
            {
                vpnServerConfiguration.VpnAuthenticationTypes = new List <string>(vpnAuthenticationType);
            }

            if (vpnClientIpsecPolicy != null && vpnClientIpsecPolicy.Length != 0)
            {
                vpnServerConfiguration.VpnClientIpsecPolicies = new List <PSIpsecPolicy>(vpnClientIpsecPolicy);
            }

            // VpnAuthenticationType = Certificate related validations.
            if (vpnAuthenticationType == null ||
                (vpnAuthenticationType != null && vpnAuthenticationType.Contains(MNM.VpnAuthenticationType.Certificate)))

            {
                // Read the VpnClientRootCertificates if present
                if (vpnClientRootCertificateFilesList != null)
                {
                    vpnServerConfiguration.VpnClientRootCertificates = new List <PSClientRootCertificate>();

                    foreach (string vpnClientRootCertPath in vpnClientRootCertificateFilesList)
                    {
                        X509Certificate2 VpnClientRootCertificate = new X509Certificate2(vpnClientRootCertPath);

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

                        vpnServerConfiguration.VpnClientRootCertificates.Add(vpnClientRootCert);
                    }
                }

                // Read the VpnClientRevokedCertificates if present
                if (vpnClientRevokedCertificateFilesList != null)
                {
                    vpnServerConfiguration.VpnClientRevokedCertificates = new List <PSClientCertificate>();

                    foreach (string vpnClientRevokedCertPath in vpnClientRevokedCertificateFilesList)
                    {
                        X509Certificate2 vpnClientRevokedCertificate = new X509Certificate2(vpnClientRevokedCertPath);

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

                        vpnServerConfiguration.VpnClientRevokedCertificates.Add(vpnClientRevokedCert);
                    }
                }
            }
            // VpnAuthenticationType = Radius related validations.
            else if (vpnAuthenticationType.Contains(MNM.VpnAuthenticationType.Radius))
            {
                if (radiusServerAddress == null || radiusServerSecret == null)
                {
                    throw new ArgumentException("Both radius server address and secret must be specified if VpnAuthenticationType is being configured as Radius.");
                }

                vpnServerConfiguration.RadiusServerAddress = radiusServerAddress;
                vpnServerConfiguration.RadiusServerSecret  = SecureStringExtensions.ConvertToString(radiusServerSecret);

                // Read the RadiusServerRootCertificates if present
                if (radiusServerRootCertificateFilesList != null)
                {
                    vpnServerConfiguration.RadiusServerRootCertificates = new List <PSClientRootCertificate>();

                    foreach (string radiusServerRootCertPath in radiusServerRootCertificateFilesList)
                    {
                        X509Certificate2 RadiusServerRootCertificate = new X509Certificate2(radiusServerRootCertPath);

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

                        vpnServerConfiguration.RadiusServerRootCertificates.Add(radiusServerRootCert);
                    }
                }

                // Read the RadiusClientRootCertificates if present
                if (radiusClientRootCertificateFilesList != null)
                {
                    vpnServerConfiguration.RadiusClientRootCertificates = new List <PSClientCertificate>();

                    foreach (string radiusClientRootCertPath in radiusClientRootCertificateFilesList)
                    {
                        X509Certificate2 radiusClientRootCertificate = new X509Certificate2(radiusClientRootCertPath);

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

                        vpnServerConfiguration.RadiusClientRootCertificates.Add(radiusClientRootCert);
                    }
                }
            }
            // VpnAuthenticationType = AAD related validations.
            else if (vpnAuthenticationType.Contains(MNM.VpnAuthenticationType.AAD))
            {
                if (aadTenant == null || aadAudience == null || aadIssuer == null)
                {
                    throw new ArgumentException("All Aad tenant, Aad audience and Aad issuer must be specified if VpnAuthenticationType is being configured as AAD.");
                }

                vpnServerConfiguration.AadAuthenticationParameters = new PSAadAuthenticationParameters()
                {
                    AadTenant   = aadTenant,
                    AadAudience = aadAudience,
                    AadIssuer   = aadIssuer
                };
            }

            return(vpnServerConfiguration);
        }
예제 #23
0
        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.DisableIPsecProtection = this.DisableIPsecProtection;
            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.VpnAuthenticationType != null)
                {
                    vnetGateway.VpnClientConfiguration.VpnAuthenticationTypes = this.VpnAuthenticationType?.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;
            }

            if (this.NatRule != null && this.NatRule.Any())
            {
                vnetGateway.NatRules = this.NatRule?.ToList();
            }

            // Set the EnableBgpRouteTranslationForNat, if it is specified by customer.
            vnetGateway.EnableBgpRouteTranslationForNat = EnableBgpRouteTranslationForNat.IsPresent;

            // 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);
        }
예제 #24
0
        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
                }
            };

            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);
                if (this.IsParameterBound(c => c.SkipAssignment))
                {
                    WriteVerbose("Skipping role assignment for the service principal.");
                    return;
                }

                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
                    }
                }
            }
        }
        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;

            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))
            {
                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)
                {
                    vnetGateway.VpnClientConfiguration.RadiusServerAddress = this.RadiusServerAddress;
                    vnetGateway.VpnClientConfiguration.RadiusServerSecret  = SecureStringExtensions.ConvertToString(this.RadiusServerSecret);
                }
            }
            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.CustomRoute != null && this.CustomRoute.Any())
            {
                vnetGateway.CustomRoutes = new PSAddressSpace();
                vnetGateway.CustomRoutes.AddressPrefixes = this.CustomRoute?.ToList();
            }
            else
            {
                vnetGateway.CustomRoutes = null;
            }

            // 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(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound);
            }

            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 = 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);
            }
        }
예제 #27
0
        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);
                }
            });
        }
        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.AdditionalUnattendContents = 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,
                    });
                }

                // 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.WinRMConfiguration =
                    !(this.WinRMHttp.IsPresent || this.WinRMHttps.IsPresent)
                    ? null
                    : new WinRMConfiguration
                {
                    Listeners = listenerList,
                };
            }

            WriteObject(this.VM);
        }
        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 (this.IsParameterBound(c => c.CertValue))
                {
                    // 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"
                    };

                    if (ShouldProcess(target: ObjectId, 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
                    var Password = Guid.NewGuid().ToString().ConvertToSecureString();

                    string decodedPassword = SecureStringExtensions.ConvertToString(Password);

                    var passwordCredential = new PasswordCredential()
                    {
                        EndDate   = EndDate,
                        StartDate = StartDate,
                        KeyId     = KeyId == default(Guid) ? Guid.NewGuid().ToString() : KeyId.ToString(),
                        Value     = decodedPassword
                    };
                    if (ShouldProcess(target: ObjectId, 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);
                    }
                }
            });
        }
예제 #30
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.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.VirtualNetworkGateway.ActiveActive && this.VirtualNetworkGateway.IpConfigurations.Count != 2)
            {
                throw new ArgumentException("Virtual Network Gateway should have 2 Gateway IpConfigurations specified when Active-Active feature flag is True.");
            }

            if (!this.VirtualNetworkGateway.ActiveActive && this.VirtualNetworkGateway.IpConfigurations.Count == 2)
            {
                throw new ArgumentException("Virtual Network Gateway should have Active-Active feature flag set to True as there are 2 Gateway IpConfigurations specified. OR there should be only one Gateway IpConfiguration specified.");
            }

            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.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.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);
            }
        }