diff --git a/Modules/VMware.vSphere.SsoAdmin/Connect.ps1 b/Modules/VMware.vSphere.SsoAdmin/Connect.ps1 new file mode 100644 index 0000000..278a978 --- /dev/null +++ b/Modules/VMware.vSphere.SsoAdmin/Connect.ps1 @@ -0,0 +1,162 @@ +<# +Copyright 2020-2021 VMware, Inc. +SPDX-License-Identifier: BSD-2-Clause +#> + +function Connect-SsoAdminServer { + <# + .NOTES + =========================================================================== + Created on: 9/29/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function establishes a connection to a vSphere SSO Admin server. + + .PARAMETER Server + Specifies the IP address or the DNS name of the vSphere server to which you want to connect. + + .PARAMETER User + Specifies the user name you want to use for authenticating with the server. + + .PARAMETER Password + Specifies the password you want to use for authenticating with the server. + + .PARAMETER SkipCertificateCheck + Specifies whether server Tls certificate validation will be skipped + + .EXAMPLE + Connect-SsoAdminServer -Server my.vc.server -User myAdmin@vsphere.local -Password MyStrongPa$$w0rd + + Connects 'myAdmin@vsphere.local' user to Sso Admin server 'my.vc.server' +#> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'IP address or the DNS name of the vSphere server')] + [string] + $Server, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'User name you want to use for authenticating with the server')] + [string] + $User, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Password you want to use for authenticating with the server')] + [VMware.vSphere.SsoAdmin.Utils.StringToSecureStringArgumentTransformationAttribute()] + [SecureString] + $Password, + + [Parameter( + Mandatory = $false, + HelpMessage = 'Skips server Tls certificate validation')] + [switch] + $SkipCertificateCheck) + + Process { + $certificateValidator = $null + if ($SkipCertificateCheck) { + $certificateValidator = New-Object 'VMware.vSphere.SsoAdmin.Utils.AcceptAllX509CertificateValidator' + } + + $ssoAdminServer = $null + try { + $ssoAdminServer = New-Object ` + 'VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer' ` + -ArgumentList @( + $Server, + $User, + $Password, + $certificateValidator) + } + catch { + Write-Error (FormatError $_.Exception) + } + + if ($ssoAdminServer -ne $null) { + $existingConnectionIndex = $global:DefaultSsoAdminServers.IndexOf($ssoAdminServer) + if ($existingConnectionIndex -ge 0) { + $global:DefaultSsoAdminServers[$existingConnectionIndex].RefCount++ + $ssoAdminServer = $global:DefaultSsoAdminServers[$existingConnectionIndex] + } + else { + # Update $global:DefaultSsoAdminServers varaible + $global:DefaultSsoAdminServers.Add($ssoAdminServer) | Out-Null + } + + # Function Output + Write-Output $ssoAdminServer + } + } +} + +function Disconnect-SsoAdminServer { + <# + .NOTES + =========================================================================== + Created on: 9/29/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function closes the connection to a vSphere SSO Admin server. + + .PARAMETER Server + Specifies the vSphere SSO Admin systems you want to disconnect from + + .EXAMPLE + $mySsoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd' + Disconnect-SsoAdminServer -Server $mySsoAdminConnection + + Disconnect a SSO Admin connection stored in 'mySsoAdminConnection' varaible +#> + [CmdletBinding()] + param( + [Parameter( + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdmin.Utils.StringToSsoAdminServerArgumentTransformationAttribute()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer[]] + $Server + ) + + Process { + if (-not $PSBoundParameters['Server']) { + switch (@($global:DefaultSsoAdminServers).count) { + { $_ -eq 1 } { $server = ($global:DefaultSsoAdminServers).ToArray()[0] ; break } + { $_ -gt 1 } { + Throw 'Connected to more than 1 SSO server, please specify a SSO server via -Server parameter' + break + } + Default { + Throw 'Not connected to SSO server.' + } + } + } + + foreach ($requestedServer in $Server) { + if ($requestedServer.IsConnected) { + $requestedServer.Disconnect() + } + + if ($global:DefaultSsoAdminServers.Contains($requestedServer) -and $requestedServer.RefCount -eq 0) { + $global:DefaultSsoAdminServers.Remove($requestedServer) | Out-Null + } + } + } +} diff --git a/Modules/VMware.vSphere.SsoAdmin/Group.ps1 b/Modules/VMware.vSphere.SsoAdmin/Group.ps1 new file mode 100644 index 0000000..9e0da4f --- /dev/null +++ b/Modules/VMware.vSphere.SsoAdmin/Group.ps1 @@ -0,0 +1,652 @@ +<# +Copyright 2020-2021 VMware, Inc. +SPDX-License-Identifier: BSD-2-Clause +#> + +function New-SsoGroup { + <# + .NOTES + =========================================================================== + Created on: 5/25/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + + .SYNOPSIS + Creates Local Sso Group + + .DESCRIPTION + Creates Local Sso Group + + .PARAMETER Name + Specifies the name of the group. + + .PARAMETER Description + Specifies an optional description of the group. + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + New-SsoGroup -Name 'myGroup' -Description 'My Group Description' + + Creates a local group with name 'myGroup' and description 'My Group Description' + + #> + + [CmdletBinding()] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Specifies the name of the group')] + [string] + $Name, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Specifies the description of the group')] + [string] + $Description, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + # Output is the result of 'CreateLocalGroup' + try { + $connection.Client.CreateLocalGroup( + $Name, + $Description + ) + } + catch { + Write-Error (FormatError $_.Exception) + } + } + } +} + +function Get-SsoGroup { + <# + .NOTES + =========================================================================== + Created on: 9/29/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function gets domain groups. + + .PARAMETER Name + Specifies Name to filter on when searching for groups. + + .PARAMETER Domain + Specifies the Domain in which search will be applied, default is 'localos'. + + .PARAMETER Group + Specifies the group in which search for person user members will be applied. + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + Get-SsoGroup -Name administrators -Domain vsphere.local + + Gets 'adminsitrators' group in 'vsphere.local' domain + #> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Name filter to be applied when searching for group')] + [string] + $Name, + + [Parameter( + ParameterSetName = 'ByNameAndDomain', + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Domain name to search in, default is "localos"')] + [string] + $Domain = 'localos', + + [Parameter( + ParameterSetName = 'ByGroup', + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Searches group members of the specified group')] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $Group, + + [Parameter( + ParameterSetName = 'ByNameAndDomain', + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($null -ne $Server) { + $serversToProcess = $Server + } + + if ($null -eq $Name) { + $Name = [string]::Empty + } + + try { + if ($null -ne $Group) { + + foreach ($g in $Group) { + $ssoAdminClient = $g.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$g' is from disconnected server" + continue + } + + foreach ($resultGroup in $ssoAdminClient.GetGroupsInGroup( + (RemoveWildcardSymbols $Name), + $Group)) { + + if ([string]::IsNullOrEmpty($Name) ) { + Write-Output $resultGroup + } + else { + # Apply Name filtering + if ((HasWildcardSymbols $Name) -and ` + $resultGroup.Name -like $Name) { + Write-Output $resultGroup + } + elseif ($resultGroup.Name -eq $Name) { + # Exactly equal + Write-Output $resultGroup + } + } + } + } + + } else { + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + foreach ($resultGroup in $connection.Client.GetGroups( + (RemoveWildcardSymbols $Name), + $Domain)) { + + + if ([string]::IsNullOrEmpty($Name) ) { + Write-Output $resultGroup + } + else { + # Apply Name filtering + if ((HasWildcardSymbols $Name) -and ` + $resultGroup.Name -like $Name) { + Write-Output $resultGroup + } + elseif ($resultGroup.Name -eq $Name) { + # Exactly equal + Write-Output $resultGroup + } + } + } + } + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Set-SsoGroup { + <# + .NOTES + =========================================================================== + Created on: 5/25/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + + .SYNOPSIS + Updates Local Sso Group + + .DESCRIPTION + Updates Local Sso Group details + + .PARAMETER Group + Specifies the group instace to update. + + .PARAMETER Description + Specifies a description of the group. + + .EXAMPLE + $myGroup = New-SsoGroup -Name 'myGroup' + $myGroup | Set-SsoGroup -Description 'My Group Description' + + Updates local group $myGroup with description 'My Group Description' + + #> + + [CmdletBinding()] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Group instance you want to update')] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $Group, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Specifies the description of the group')] + [string] + $Description) + + Process { + try { + foreach ($g in $Group) { + $ssoAdminClient = $g.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$g' is from disconnected server" + continue + } + + $ssoAdminClient.UpdateLocalGroup($g, $Description) + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Remove-SsoGroup { + <# + .NOTES + =========================================================================== + Created on: 5/25/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + + .DESCRIPTION + This function removes existing local group. + + .PARAMETER Group + Specifies the Group instance to remove. + + .EXAMPLE + $ssoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd' + $myNewGroup = New-SsoGroup -Server $ssoAdminConnection -Name 'myGroup' + Remove-SsoGroup -Group $myNewGroup + + Remove plocal group with name 'myGroup' +#> + [CmdletBinding(ConfirmImpact = 'High')] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Group instance you want to remove')] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $Group) + + Process { + try { + foreach ($g in $Group) { + $ssoAdminClient = $g.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$g' is from disconnected server" + continue + } + + $ssoAdminClient.RemoveLocalGroup($g) + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Add-GroupToSsoGroup { + <# + .NOTES + =========================================================================== + Created on: 5/26/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + + + .SYNOPSIS + Adds a group to another group + + .DESCRIPTION + Adds the specified group on $Group parameter to target group specified on $TargetGroup parameter + + .PARAMETER Group + A Group instance to be added to the $TargetGroup + + .PARAMETER TargetGroup + A target group to which the $Group will be added. + + .EXAMPLE + $administratosGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' + Get-SsoGroup -Name 'TestGroup' -Domain 'MyDomain' | Add-GroupToSsoGroup -TargetGroup $administratosGroup + + Adds 'TestGroup' from 'MyDomain' domain to vsphere.local Administrators group. + #> + [CmdletBinding(ConfirmImpact = 'Medium')] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'SsoGroup instance you want to add to the target group')] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $Group, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Target SsoGroup instance where the $Group wtill be added')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $TargetGroup) + + Process { + try { + foreach ($g in $Group) { + $ssoAdminClient = $g.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$g' is from disconnected server" + continue + } + + if ($g.GetClient().ServiceUri -ne $TargetGroup.GetClient().ServiceUri) { + Write-Error "Group '$g' is not from the same server as the target group" + continue + } + + $result = $ssoAdminClient.AddGroupToGroup($g, $TargetGroup) + if (-not $result) { + Write-Error "Group '$g' was not added to the target group. The Server operation result doesn't indicate success" + continue + } + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Remove-GroupFromSsoGroup { + <# + .NOTES + =========================================================================== + Created on: 5/26/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + + + .SYNOPSIS + Removes a group to another group + + .DESCRIPTION + Removes the specified group on $Group parameter from target group specified on $TargetGroup parameter + + .PARAMETER Group + A Group instance to be removed from the $TargetGroup + + .PARAMETER TargetGroup + A target group from which the $Group will be removed. + + .EXAMPLE + $administratosGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' + Get-SsoGroup -Name 'TestGroup' -Domain 'MyDomain' | Remove-GroupFromSsoGroup -TargetGroup $administratosGroup + + Removes 'TestGroup' from 'MyDomain' domain from vsphere.local Administrators group. + #> + [CmdletBinding(ConfirmImpact = 'Medium')] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'SsoGroup instance you want to remove from the target group')] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $Group, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Target SsoGroup instance from which the $Group wtill be removed')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $TargetGroup) + + Process { + try { + foreach ($g in $Group) { + $ssoAdminClient = $g.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$g' is from disconnected server" + continue + } + + if ($g.GetClient().ServiceUri -ne $TargetGroup.GetClient().ServiceUri) { + Write-Error "Group '$g' is not from the same server as the target group" + continue + } + + $result = $ssoAdminClient.RemoveGroupFromGroup($g, $TargetGroup) + if (-not $result) { + Write-Error "Group '$g' was not removed to the target group. The Server operation result doesn't indicate success" + continue + } + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Add-UserToSsoGroup { + <# + .NOTES + =========================================================================== + Created on: 5/26/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + + + .SYNOPSIS + Adds an user to a group + + .DESCRIPTION + Adds the user on $User parameter to target group specified on $TargetGroup parameter + + .PARAMETER User + A PersonUser instance to be added to the $TargetGroup + + .PARAMETER TargetGroup + A target group to which the $User will be added. + + .EXAMPLE + $administratosGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' + Get-SsoPersonUser -Name 'TestUser' -Domain 'MyDomain' | Add-UserToSsoGroup -TargetGroup $administratosGroup + + Adds 'TestUser' from 'MyDomain' domain to vsphere.local Administrators group. + #> + [CmdletBinding(ConfirmImpact = 'Medium')] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'PersonUser instance you want to add to the target group')] + [VMware.vSphere.SsoAdminClient.DataTypes.PersonUser] + $User, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Target SsoGroup instance where the $Group wtill be added')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $TargetGroup) + + Process { + try { + foreach ($u in $User) { + $ssoAdminClient = $u.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$u' is from disconnected server" + continue + } + + if ($u.GetClient().ServiceUri -ne $TargetGroup.GetClient().ServiceUri) { + Write-Error "User '$u' is not from the same server as the target group" + continue + } + + $result = $ssoAdminClient.AddPersonUserToGroup($u, $TargetGroup) + if (-not $result) { + Write-Error "User '$u' was not added to the target group. The Server operation result doesn't indicate success" + continue + } + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Remove-UserFromSsoGroup { + <# + .NOTES + =========================================================================== + Created on: 5/26/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + + + .SYNOPSIS + Removes a person user from group + + .DESCRIPTION + Removes the specified person user on $User parameter from target group specified on $TargetGroup parameter + + .PARAMETER User + A PersonUser instance to be removed from the $TargetGroup + + .PARAMETER TargetGroup + A target group from which the $User will be removed. + + .EXAMPLE + $administratosGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' + Get-SsoPersonUser -Name 'TestUser' -Domain 'MyDomain' | Remove-UserFromSsoGroup -TargetGroup $administratosGroup + + Removes 'TestUser' from 'MyDomain' domain from vsphere.local Administrators group. + #> + [CmdletBinding(ConfirmImpact = 'Medium')] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'PersonUser instance you want to remove from the target group')] + [VMware.vSphere.SsoAdminClient.DataTypes.PersonUser] + $User, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Target SsoGroup instance from which the $User wtill be removed')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $TargetGroup) + + Process { + try { + foreach ($u in $User) { + $ssoAdminClient = $u.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$u' is from disconnected server" + continue + } + + if ($u.GetClient().ServiceUri -ne $TargetGroup.GetClient().ServiceUri) { + Write-Error "User '$u' is not from the same server as the target group" + continue + } + + $result = $ssoAdminClient.RemovePersonUserFromGroup($u, $TargetGroup) + if (-not $result) { + Write-Error "User '$u' was not removed to the target group. The Server operation result doesn't indicate success" + continue + } + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} diff --git a/Modules/VMware.vSphere.SsoAdmin/IdentitySource.ps1 b/Modules/VMware.vSphere.SsoAdmin/IdentitySource.ps1 new file mode 100644 index 0000000..496ef65 --- /dev/null +++ b/Modules/VMware.vSphere.SsoAdmin/IdentitySource.ps1 @@ -0,0 +1,633 @@ +<# +Copyright 2020-2021 VMware, Inc. +SPDX-License-Identifier: BSD-2-Clause +#> + +function Add-ExternalDomainIdentitySource { + <# + .NOTES + =========================================================================== + Created on: 2/11/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function adds Identity Source of ActiveDirectory, OpenLDAP or NIS type. + + .PARAMETER Name + Name of the identity source + + .PARAMETER DomainName + Domain name + + .PARAMETER DomainAlias + Domain alias + + .PARAMETER PrimaryUrl + Primary Server URL + + .PARAMETER BaseDNUsers + Base distinguished name for users + + .PARAMETER BaseDNGroups + Base distinguished name for groups + + .PARAMETER Username + Domain authentication user name + + .PARAMETER Passowrd + Domain authentication password + + .PARAMETER DomainServerType + Type of the ExternalDomain, one of 'ActiveDirectory','OpenLdap','NIS' + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + Add-ExternalDomainIdentitySource ` + -Name 'sof-powercli' ` + -DomainName 'sof-powercli.vmware.com' ` + -DomainAlias 'sof-powercli' ` + -PrimaryUrl 'ldap://sof-powercli.vmware.com:389' ` + -BaseDNUsers 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' ` + -BaseDNGroups 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' ` + -Username 'sofPowercliAdmin' ` + -Password '$up3R$Tr0Pa$$w0rD' + + Adds External Identity Source + #> + [CmdletBinding()] + [Alias("Add-ActiveDirectoryIdentitySource")] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Friendly name of the identity source')] + [ValidateNotNull()] + [string] + $Name, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [ValidateNotNull()] + [string] + $DomainName, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [string] + $DomainAlias, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [ValidateNotNull()] + [string] + $PrimaryUrl, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Base distinguished name for users')] + [ValidateNotNull()] + [string] + $BaseDNUsers, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Base distinguished name for groups')] + [ValidateNotNull()] + [string] + $BaseDNGroups, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Domain authentication user name')] + [ValidateNotNull()] + [string] + $Username, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Domain authentication password')] + [ValidateNotNull()] + [string] + $Password, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'External domain server type')] + [ValidateSet('ActiveDirectory')] + [string] + $DomainServerType = 'ActiveDirectory', + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + try { + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + $connection.Client.AddActiveDirectoryExternalDomain( + $DomainName, + $DomainAlias, + $Name, + $PrimaryUrl, + $BaseDNUsers, + $BaseDNGroups, + $Username, + $Password, + $DomainServerType); + } + } + catch { + Write-Error (FormatError $_.Exception) + } +} + +function Add-LDAPIdentitySource { + <# + .NOTES + =========================================================================== + Created on: 2/11/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function adds LDAP Identity Source of ActiveDirectory, OpenLDAP or NIS type. + + .PARAMETER Name + Friendly name of the identity source + + .PARAMETER DomainName + Domain name + + .PARAMETER DomainAlias + Domain alias + + .PARAMETER PrimaryUrl + Primary Server URL + + .PARAMETER SecondaryUrl + Secondary Server URL + + .PARAMETER BaseDNUsers + Base distinguished name for users + + .PARAMETER BaseDNGroups + Base distinguished name for groups + + .PARAMETER Username + Domain authentication user name + + .PARAMETER Passowrd + Domain authentication password + + .PARAMETER ServerType + Type of the ExternalDomain, one of 'ActiveDirectory','OpenLdap','NIS' + + .PARAMETER Certificates + List of X509Certicate2 LDAP certificates + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + Adds LDAP Identity Source + + .EXAMPLE + Add-LDAPIdentitySource ` + -Name 'sof-powercli' ` + -DomainName 'sof-powercli.vmware.com' ` + -DomainAlias 'sof-powercli' ` + -PrimaryUrl 'ldap://sof-powercli.vmware.com:389' ` + -BaseDNUsers 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' ` + -BaseDNGroups 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' ` + -Username 'sofPowercliAdmin@sof-powercli.vmware.com' ` + -Password '$up3R$Tr0Pa$$w0rD' ` + -Certificates 'C:\Temp\test.cer' + #> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Friendly name of the identity source')] + [ValidateNotNull()] + [string] + $Name, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [ValidateNotNull()] + [string] + $DomainName, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [string] + $DomainAlias, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [string] + $SecondaryUrl, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [ValidateNotNull()] + [string] + $PrimaryUrl, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Base distinguished name for users')] + [ValidateNotNull()] + [string] + $BaseDNUsers, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Base distinguished name for groups')] + [ValidateNotNull()] + [string] + $BaseDNGroups, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Domain authentication user name')] + [ValidateNotNull()] + [string] + $Username, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Domain authentication password')] + [ValidateNotNull()] + [string] + $Password, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Ldap Certificates')] + [System.Security.Cryptography.X509Certificates.X509Certificate2[]] + $Certificates, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Ldap Server type')] + [ValidateSet('ActiveDirectory')] + [string] + $ServerType = 'ActiveDirectory', + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + try { + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + $connection.Client.AddLdapIdentitySource( + $DomainName, + $DomainAlias, + $Name, + $PrimaryUrl, + $SecondaryUrl, + $BaseDNUsers, + $BaseDNGroups, + $Username, + $Password, + $ServerType, + $Certificates); + } + } + catch { + Write-Error (FormatError $_.Exception) + } +} + +function Set-LDAPIdentitySource { + <# + .NOTES + =========================================================================== + Created on: 2/17/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function adds LDAP Identity Source of ActiveDirectory, OpenLDAP or NIS type. + + .PARAMETER IdentitySource + Identity Source to update + + .PARAMETER Certificates + List of X509Certicate2 LDAP certificates + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + Updates LDAP Identity Source + + .EXAMPLE + + Updates certificate of a LDAP identity source + + Get-IdentitySource -External | ` + Set-LDAPIdentitySource ` + -Certificates 'C:\Temp\test.cer' + #> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Identity source to update')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.ActiveDirectoryIdentitySource] + $IdentitySource, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Ldap Certificates')] + [System.Security.Cryptography.X509Certificates.X509Certificate2[]] + $Certificates, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + try { + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + $connection.Client.UpdateLdapIdentitySource( + $IdentitySource.Name, + $IdentitySource.FriendlyName, + $IdentitySource.PrimaryUrl, + $IdentitySource.FailoverUrl, + $IdentitySource.UserBaseDN, + $IdentitySource.GroupBaseDN, + $Certificates); + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Get-IdentitySource { + <# + .NOTES + =========================================================================== + Created on: 11/26/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function gets Identity Source. + + .PARAMETER Localos + Filter parameter to return only the localos domain identity source + + .PARAMETER System + Filter parameter to return only the system domain identity source + + .PARAMETER External + Filter parameter to return only the external domain identity sources + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + Get-IdentitySource -External + + Gets all external domain identity source + #> + [CmdletBinding()] + param( + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Returns only the localos domain identity source')] + [Switch] + $Localos, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Returns only the system domain identity source')] + [Switch] + $System, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Returns only the external domain identity sources')] + [Switch] + $External, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + $resultIdentitySources = @() + $allIdentitySources = $connection.Client.GetDomains() + + if (-not $Localos -and -not $System -and -not $External) { + $resultIdentitySources = $allIdentitySources + } + + if ($Localos) { + $resultIdentitySources += $allIdentitySources | Where-Object { $_ -is [VMware.vSphere.SsoAdminClient.DataTypes.LocalOSIdentitySource] } + } + + if ($System) { + $resultIdentitySources += $allIdentitySources | Where-Object { $_ -is [VMware.vSphere.SsoAdminClient.DataTypes.SystemIdentitySource] } + } + + if ($External) { + $resultIdentitySources += $allIdentitySources | Where-Object { $_ -is [VMware.vSphere.SsoAdminClient.DataTypes.ActiveDirectoryIdentitySource] } + } + + #Return result + $resultIdentitySources + } +} + +function Remove-IdentitySource { + <# + .NOTES + =========================================================================== + Created on: 03/19/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function removes Identity Source. + + .PARAMETER IdentitySource + The identity source to remove + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + Get-IdentitySource -External | Remove-IdentitySource + + Removes all external domain identity source + #> + [CmdletBinding()] + param( + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Identity source to remove')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.IdentitySource] + $IdentitySource, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + + try { + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + $connection.Client.DeleteDomain($IdentitySource.Name) + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} diff --git a/Modules/VMware.vSphere.SsoAdmin/LockoutPolicy.ps1 b/Modules/VMware.vSphere.SsoAdmin/LockoutPolicy.ps1 new file mode 100644 index 0000000..bfb9665 --- /dev/null +++ b/Modules/VMware.vSphere.SsoAdmin/LockoutPolicy.ps1 @@ -0,0 +1,164 @@ +<# +Copyright 2020-2021 VMware, Inc. +SPDX-License-Identifier: BSD-2-Clause +#> + +function Get-SsoLockoutPolicy { + <# + .NOTES + =========================================================================== + Created on: 9/30/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function gets lockout policy. + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + Get-SsoLockoutPolicy + + Gets lockout policy for the server connections available in $global:defaultSsoAdminServers + #> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + try { + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + $connection.Client.GetLockoutPolicy(); + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Set-SsoLockoutPolicy { + <# + .NOTES + =========================================================================== + Created on: 9/30/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function updates lockout policy settings. + + .PARAMETER LockoutPolicy + Specifies the LockoutPolicy instance which will be used as original policy. If some properties are not specified they will be updated with the properties from this object. + + .PARAMETER Description + + .PARAMETER AutoUnlockIntervalSec + + .PARAMETER FailedAttemptIntervalSec + + .PARAMETER MaxFailedAttempts + + .EXAMPLE + Get-SsoLockoutPolicy | Set-SsoLockoutPolicy -AutoUnlockIntervalSec 15 -MaxFailedAttempts 4 + + Updates lockout policy auto unlock interval seconds and maximum failed attempts + #> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'LockoutPolicy instance you want to update')] + [VMware.vSphere.SsoAdminClient.DataTypes.LockoutPolicy] + $LockoutPolicy, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'LockoutPolicy description')] + [string] + $Description, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int64]] + $AutoUnlockIntervalSec, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int64]] + $FailedAttemptIntervalSec, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $MaxFailedAttempts) + + Process { + try { + foreach ($lp in $LockoutPolicy) { + + $ssoAdminClient = $lp.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$lp' is from disconnected server" + continue + } + + if ([string]::IsNullOrEmpty($Description)) { + $Description = $lp.Description + } + + if ($AutoUnlockIntervalSec -eq $null) { + $AutoUnlockIntervalSec = $lp.AutoUnlockIntervalSec + } + + if ($FailedAttemptIntervalSec -eq $null) { + $FailedAttemptIntervalSec = $lp.FailedAttemptIntervalSec + } + + if ($MaxFailedAttempts -eq $null) { + $MaxFailedAttempts = $lp.MaxFailedAttempts + } + + $ssoAdminClient.SetLockoutPolicy( + $Description, + $AutoUnlockIntervalSec, + $FailedAttemptIntervalSec, + $MaxFailedAttempts); + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} diff --git a/Modules/VMware.vSphere.SsoAdmin/PasswordPolicy.ps1 b/Modules/VMware.vSphere.SsoAdmin/PasswordPolicy.ps1 new file mode 100644 index 0000000..d5f8c46 --- /dev/null +++ b/Modules/VMware.vSphere.SsoAdmin/PasswordPolicy.ps1 @@ -0,0 +1,262 @@ +<# +Copyright 2020-2021 VMware, Inc. +SPDX-License-Identifier: BSD-2-Clause +#> + +function Get-SsoPasswordPolicy { + <# + .NOTES + =========================================================================== + Created on: 9/30/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function gets password policy. + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + Get-SsoPasswordPolicy + + Gets password policy for the server connections available in $global:defaultSsoAdminServers + #> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + try { + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + $connection.Client.GetPasswordPolicy(); + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Set-SsoPasswordPolicy { + <# + .NOTES + =========================================================================== + Created on: 9/30/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function updates password policy settings. + + .PARAMETER PasswordPolicy + Specifies the PasswordPolicy instance which will be used as original policy. If some properties are not specified they will be updated with the properties from this object. + + .PARAMETER Description + + .PARAMETER ProhibitedPreviousPasswordsCount + + .PARAMETER MinLength + + .PARAMETER MaxLength + + .PARAMETER MaxIdenticalAdjacentCharacters + + .PARAMETER MinNumericCount + + .PARAMETER MinSpecialCharCount + + .PARAMETER MinAlphabeticCount + + .PARAMETER MinUppercaseCount + + .PARAMETER MinLowercaseCount + + .PARAMETER PasswordLifetimeDays + + .EXAMPLE + Get-SsoPasswordPolicy | Set-SsoPasswordPolicy -MinLength 10 -PasswordLifetimeDays 45 + + Updates password policy setting minimum password length to 10 symbols and password lifetime to 45 days + #> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'PasswordPolicy instance you want to update')] + [VMware.vSphere.SsoAdminClient.DataTypes.PasswordPolicy] + $PasswordPolicy, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'PasswordPolicy description')] + [string] + $Description, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $ProhibitedPreviousPasswordsCount, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $MinLength, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $MaxLength, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $MaxIdenticalAdjacentCharacters, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $MinNumericCount, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $MinSpecialCharCount, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $MinAlphabeticCount, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $MinUppercaseCount, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $MinLowercaseCount, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int32]] + $PasswordLifetimeDays) + + Process { + + try { + foreach ($pp in $PasswordPolicy) { + + $ssoAdminClient = $pp.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$pp' is from disconnected server" + continue + } + + if ([string]::IsNullOrEmpty($Description)) { + $Description = $pp.Description + } + + if ($ProhibitedPreviousPasswordsCount -eq $null) { + $ProhibitedPreviousPasswordsCount = $pp.ProhibitedPreviousPasswordsCount + } + + if ($MinLength -eq $null) { + $MinLength = $pp.MinLength + } + + if ($MaxLength -eq $null) { + $MaxLength = $pp.MaxLength + } + + if ($MaxIdenticalAdjacentCharacters -eq $null) { + $MaxIdenticalAdjacentCharacters = $pp.MaxIdenticalAdjacentCharacters + } + + if ($MinNumericCount -eq $null) { + $MinNumericCount = $pp.MinNumericCount + } + + if ($MinSpecialCharCount -eq $null) { + $MinSpecialCharCount = $pp.MinSpecialCharCount + } + + if ($MinAlphabeticCount -eq $null) { + $MinAlphabeticCount = $pp.MinAlphabeticCount + } + + if ($MinUppercaseCount -eq $null) { + $MinUppercaseCount = $pp.MinUppercaseCount + } + + if ($MinLowercaseCount -eq $null) { + $MinLowercaseCount = $pp.MinLowercaseCount + } + + if ($PasswordLifetimeDays -eq $null) { + $PasswordLifetimeDays = $pp.PasswordLifetimeDays + } + + $ssoAdminClient.SetPasswordPolicy( + $Description, + $ProhibitedPreviousPasswordsCount, + $MinLength, + $MaxLength, + $MaxIdenticalAdjacentCharacters, + $MinNumericCount, + $MinSpecialCharCount, + $MinAlphabeticCount, + $MinUppercaseCount, + $MinLowercaseCount, + $PasswordLifetimeDays); + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} diff --git a/Modules/VMware.vSphere.SsoAdmin/PersonUser.ps1 b/Modules/VMware.vSphere.SsoAdmin/PersonUser.ps1 new file mode 100644 index 0000000..ffe39cd --- /dev/null +++ b/Modules/VMware.vSphere.SsoAdmin/PersonUser.ps1 @@ -0,0 +1,523 @@ +<# +Copyright 2020-2021 VMware, Inc. +SPDX-License-Identifier: BSD-2-Clause +#> + +function New-SsoPersonUser { + <# + .NOTES + =========================================================================== + Created on: 9/29/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function creates new person user account. + + .PARAMETER UserName + Specifies the UserName of the requested person user account. + + .PARAMETER Password + Specifies the Password of the requested person user account. + + .PARAMETER Description + Specifies the Description of the requested person user account. + + .PARAMETER EmailAddress + Specifies the EmailAddress of the requested person user account. + + .PARAMETER FirstName + Specifies the FirstName of the requested person user account. + + .PARAMETER LastName + Specifies the FirstName of the requested person user account. + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + $ssoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd' + New-SsoPersonUser -Server $ssoAdminConnection -User myAdmin -Password 'MyStrongPa$$w0rd' + + Creates person user account with user name 'myAdmin' and password 'MyStrongPa$$w0rd' + + .EXAMPLE + New-SsoPersonUser -User myAdmin -Password 'MyStrongPa$$w0rd' -EmailAddress 'myAdmin@mydomain.com' -FirstName 'My' -LastName 'Admin' + + Creates person user account with user name 'myAdmin', password 'MyStrongPa$$w0rd', and details against connections available in 'DefaultSsoAdminServers' +#> + [CmdletBinding(ConfirmImpact = 'Low')] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'User name of the new person user account')] + [string] + $UserName, + + [Parameter( + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Password of the new person user account')] + [string] + $Password, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Description of the new person user account')] + [string] + $Description, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'EmailAddress of the new person user account')] + [string] + $EmailAddress, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'FirstName of the new person user account')] + [string] + $FirstName, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'LastName of the new person user account')] + [string] + $LastName, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + # Output is the result of 'CreateLocalUser' + try { + $connection.Client.CreateLocalUser( + $UserName, + $Password, + $Description, + $EmailAddress, + $FirstName, + $LastName + ) + } + catch { + Write-Error (FormatError $_.Exception) + } + } + } +} + +function Get-SsoPersonUser { + <# + .NOTES + =========================================================================== + Created on: 9/29/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function gets person user account. + + .PARAMETER Name + Specifies Name to filter on when searching for person user accounts. + + .PARAMETER Domain + Specifies the Domain in which search will be applied, default is 'localos'. + + .PARAMETER Group + Specifies the group in which search for person user members will be applied. + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + Get-SsoPersonUser -Name admin -Domain vsphere.local + + Gets person user accounts which contain name 'admin' in 'vsphere.local' domain + + .EXAMPLE + Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' | Get-SsoPersonUser + + Gets person user accounts members of 'Administrators' group +#> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Name filter to be applied when searching for person user accounts')] + [string] + $Name, + + [Parameter( + ParameterSetName = 'ByNameAndDomain', + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Domain name to search in, default is "localos"')] + [string] + $Domain = 'localos', + + [Parameter( + ParameterSetName = 'ByGroup', + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Searches members of the specified group')] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $Group, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + if ($Name -eq $null) { + $Name = [string]::Empty + } + + try { + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + $personUsers = $null + + if ($Group -ne $null) { + $personUsers = $connection.Client.GetPersonUsersInGroup( + (RemoveWildcardSymbols $Name), + $Group) + } + else { + $personUsers = $connection.Client.GetLocalUsers( + (RemoveWildcardSymbols $Name), + $Domain) + } + + if ($personUsers -ne $null) { + foreach ($personUser in $personUsers) { + if ([string]::IsNullOrEmpty($Name) ) { + Write-Output $personUser + } + else { + # Apply Name filtering + if ((HasWildcardSymbols $Name) -and ` + $personUser.Name -like $Name) { + Write-Output $personUser + } + elseif ($personUser.Name -eq $Name) { + # Exactly equal + Write-Output $personUser + } + } + } + } + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Set-SsoPersonUser { + <# + .NOTES + =========================================================================== + Created on: 9/29/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + Updates person user account. + + .PARAMETER User + Specifies the PersonUser instance to update. + + .PARAMETER Group + Specifies the Group you want to add or remove PwersonUser from. + + .PARAMETER Add + Specifies user will be added to the spcified group. + + .PARAMETER Remove + Specifies user will be removed from the spcified group. + + .PARAMETER Unlock + Specifies user will be unloacked. + + .PARAMETER NewPassword + Specifies new password for the specified user. + + .EXAMPLE + Set-SsoPersonUser -User $myPersonUser -Group $myExampleGroup -Add -Server $ssoAdminConnection + + Adds $myPersonUser to $myExampleGroup + + .EXAMPLE + Set-SsoPersonUser -User $myPersonUser -Group $myExampleGroup -Remove -Server $ssoAdminConnection + + Removes $myPersonUser from $myExampleGroup + + .EXAMPLE + Set-SsoPersonUser -User $myPersonUser -Unlock -Server $ssoAdminConnection + + Unlocks $myPersonUser + + .EXAMPLE + Set-SsoPersonUser -User $myPersonUser -NewPassword 'MyBrandNewPa$$W0RD' -Server $ssoAdminConnection + + Resets $myPersonUser password +#> + [CmdletBinding(ConfirmImpact = 'Medium')] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Person User instance you want to update')] + [VMware.vSphere.SsoAdminClient.DataTypes.PersonUser] + $User, + + [Parameter( + ParameterSetName = 'AddToGroup', + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Group instance you want user to be added to or removed from')] + [Parameter( + ParameterSetName = 'RemoveFromGroup', + Mandatory = $true, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Group instance you want user to be added to or removed from')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.Group] + $Group, + + [Parameter( + ParameterSetName = 'AddToGroup', + Mandatory = $true)] + [switch] + $Add, + + [Parameter( + ParameterSetName = 'RemoveFromGroup', + Mandatory = $true)] + [switch] + $Remove, + + [Parameter( + ParameterSetName = 'ResetPassword', + Mandatory = $true, + HelpMessage = 'New password for the specified user.')] + [ValidateNotNull()] + [string] + $NewPassword, + + [Parameter( + ParameterSetName = 'UnlockUser', + Mandatory = $true, + HelpMessage = 'Specifies to unlock user account.')] + [switch] + $Unlock) + + Process { + try { + foreach ($u in $User) { + $ssoAdminClient = $u.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$u' is from disconnected server" + continue + } + + if ($Add) { + $result = $ssoAdminClient.AddPersonUserToGroup($u, $Group) + if ($result) { + Write-Output $u + } + } + + if ($Remove) { + $result = $ssoAdminClient.RemovePersonUserFromGroup($u, $Group) + if ($result) { + Write-Output $u + } + } + + if ($Unlock) { + $result = $ssoAdminClient.UnlockPersonUser($u) + if ($result) { + Write-Output $u + } + } + + if ($NewPassword) { + $ssoAdminClient.ResetPersonUserPassword($u, $NewPassword) + Write-Output $u + } + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Set-SsoSelfPersonUserPassword { + <# + .NOTES + =========================================================================== + Created on: 2/19/2021 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + Resets connected person user password. + + + .PARAMETER NewPassword + Specifies new password for the connected person user. + + + .EXAMPLE + Set-SsoSelfPersonUserPassword -Password 'MyBrandNewPa$$W0RD' -Server $ssoAdminConnection + + Resets password +#> + [CmdletBinding(ConfirmImpact = 'High')] + param( + [Parameter( + Mandatory = $true, + HelpMessage = 'New password for the connected user.')] + [ValidateNotNull()] + [SecureString] + $Password, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + try { + $connection.Client.ResetSelfPersonUserPassword($Password) + } + catch { + Write-Error (FormatError $_.Exception) + } + } + } +} + +function Remove-SsoPersonUser { + <# + .NOTES + =========================================================================== + Created on: 9/29/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function removes existing person user account. + + .PARAMETER User + Specifies the PersonUser instance to remove. + + .EXAMPLE + $ssoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd' + $myNewPersonUser = New-SsoPersonUser -Server $ssoAdminConnection -User myAdmin -Password 'MyStrongPa$$w0rd' + Remove-SsoPersonUser -User $myNewPersonUser + + Remove person user account with user name 'myAdmin' +#> + [CmdletBinding(ConfirmImpact = 'High')] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Person User instance you want to remove')] + [VMware.vSphere.SsoAdminClient.DataTypes.PersonUser] + $User) + + Process { + try { + foreach ($u in $User) { + $ssoAdminClient = $u.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$u' is from disconnected server" + continue + } + + $ssoAdminClient.DeleteLocalUser($u) + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} diff --git a/Modules/VMware.vSphere.SsoAdmin/TokenLifetime.ps1 b/Modules/VMware.vSphere.SsoAdmin/TokenLifetime.ps1 new file mode 100644 index 0000000..2e17b03 --- /dev/null +++ b/Modules/VMware.vSphere.SsoAdmin/TokenLifetime.ps1 @@ -0,0 +1,128 @@ +<# +Copyright 2020-2021 VMware, Inc. +SPDX-License-Identifier: BSD-2-Clause +#> +function Get-SsoTokenLifetime { + <# + .NOTES + =========================================================================== + Created on: 9/30/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function gets HoK and Bearer Token lifetime settings. + + .PARAMETER Server + Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. + If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. + + .EXAMPLE + Get-SsoTokenLifetime + + Gets HoK and Bearer Token lifetime settings for the server connections available in $global:defaultSsoAdminServers + #> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'Connected SsoAdminServer object')] + [ValidateNotNull()] + [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] + $Server) + + Process { + $serversToProcess = $global:DefaultSsoAdminServers.ToArray() + if ($Server -ne $null) { + $serversToProcess = $Server + } + + try { + foreach ($connection in $serversToProcess) { + if (-not $connection.IsConnected) { + Write-Error "Server $connection is disconnected" + continue + } + + $connection.Client.GetTokenLifetime(); + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} + +function Set-SsoTokenLifetime { + <# + .NOTES + =========================================================================== + Created on: 9/30/2020 + Created by: Dimitar Milov + Twitter: @dimitar_milov + Github: https://github.com/dmilov + =========================================================================== + .DESCRIPTION + This function updates HoK or Bearer token lifetime settings. + + .PARAMETER TokenLifetime + Specifies the TokenLifetime instance to update. + + .PARAMETER MaxHoKTokenLifetime + + .PARAMETER MaxBearerTokenLifetime + + .EXAMPLE + Get-SsoTokenLifetime | Set-SsoTokenLifetime -MaxHoKTokenLifetime 60 + + Updates HoK token lifetime setting + #> + [CmdletBinding()] + param( + [Parameter( + Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $false, + HelpMessage = 'TokenLifetime instance you want to update')] + [VMware.vSphere.SsoAdminClient.DataTypes.TokenLifetime] + $TokenLifetime, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int64]] + $MaxHoKTokenLifetime, + + [Parameter( + Mandatory = $false, + ValueFromPipeline = $false, + ValueFromPipelineByPropertyName = $false)] + [Nullable[System.Int64]] + $MaxBearerTokenLifetime) + + Process { + + try { + foreach ($tl in $TokenLifetime) { + + $ssoAdminClient = $tl.GetClient() + if ((-not $ssoAdminClient)) { + Write-Error "Object '$tl' is from disconnected server" + continue + } + + $ssoAdminClient.SetTokenLifetime( + $MaxHoKTokenLifetime, + $MaxBearerTokenLifetime + ); + } + } + catch { + Write-Error (FormatError $_.Exception) + } + } +} diff --git a/Modules/VMware.vSphere.SsoAdmin/VMware.vSphere.SsoAdmin.psd1 b/Modules/VMware.vSphere.SsoAdmin/VMware.vSphere.SsoAdmin.psd1 index cd05667..096afa3 100644 --- a/Modules/VMware.vSphere.SsoAdmin/VMware.vSphere.SsoAdmin.psd1 +++ b/Modules/VMware.vSphere.SsoAdmin/VMware.vSphere.SsoAdmin.psd1 @@ -11,7 +11,7 @@ RootModule = 'VMware.vSphere.SsoAdmin.psm1' # Version number of this module. -ModuleVersion = '1.2.3' +ModuleVersion = '1.3.0' # ID used to uniquely identify this module GUID = 'b3e25326-e809-4d68-a252-ca5fcaf1eb8b' @@ -34,7 +34,14 @@ RequiredModules = @( ) # Functions to export from this module -FunctionsToExport = @('Connect-SsoAdminServer', 'Disconnect-SsoAdminServer', 'New-SsoPersonUser', 'Get-SsoPersonUser', 'Set-SsoPersonUser', 'Remove-SsoPersonUser', 'Get-SsoGroup', 'Get-SsoPasswordPolicy', 'Set-SsoPasswordPolicy', 'Get-SsoLockoutPolicy', 'Set-SsoLockoutPolicy', 'Get-SsoTokenLifetime', 'Set-SsoTokenLifetime', 'Get-IdentitySource', 'Remove-IdentitySource', 'Add-ActiveDirectoryIdentitySource', 'Add-LDAPIdentitySource', 'Set-LDAPIdentitySource', 'Set-SsoSelfPersonUserPassword') +FunctionsToExport = @( + 'Connect-SsoAdminServer', 'Disconnect-SsoAdminServer', + 'New-SsoPersonUser', 'Get-SsoPersonUser', 'Set-SsoPersonUser', 'Remove-SsoPersonUser', 'Set-SsoSelfPersonUserPassword' + 'New-SsoGroup', 'Get-SsoGroup', 'Set-SsoGroup', 'Remove-SsoGroup', 'Add-GroupToSsoGroup', 'Remove-GroupFromSsoGroup', 'Add-UserToSsoGroup', 'Remove-UserFromSsoGroup' + 'Get-SsoPasswordPolicy', 'Set-SsoPasswordPolicy', + 'Get-SsoLockoutPolicy', 'Set-SsoLockoutPolicy', + 'Get-SsoTokenLifetime', 'Set-SsoTokenLifetime', + 'Get-IdentitySource', 'Remove-IdentitySource', 'Add-ActiveDirectoryIdentitySource', 'Add-LDAPIdentitySource', 'Set-LDAPIdentitySource') # Cmdlets to export from this module CmdletsToExport = @() diff --git a/Modules/VMware.vSphere.SsoAdmin/VMware.vSphere.SsoAdmin.psm1 b/Modules/VMware.vSphere.SsoAdmin/VMware.vSphere.SsoAdmin.psm1 index fe06936..d7fff6e 100644 --- a/Modules/VMware.vSphere.SsoAdmin/VMware.vSphere.SsoAdmin.psm1 +++ b/Modules/VMware.vSphere.SsoAdmin/VMware.vSphere.SsoAdmin.psm1 @@ -17,10 +17,10 @@ $PSModuleRoot = $PSModule.ModuleBase $subModuleRoot = $PSModuleRoot if (($PSVersionTable.Keys -contains "PSEdition") -and ($PSVersionTable.PSEdition -ne 'Desktop')) { - $subModuleRoot = Join-Path -Path $PSModuleRoot -ChildPath 'netcoreapp3.1' + $subModuleRoot = Join-Path -Path $PSModuleRoot -ChildPath 'netcoreapp3.1' } else { - $subModuleRoot = Join-Path -Path $PSModuleRoot -ChildPath 'net45' + $subModuleRoot = Join-Path -Path $PSModuleRoot -ChildPath 'net45' } $subModulePath = Join-Path -Path $subModuleRoot -ChildPath $moduleFileName @@ -28,1987 +28,60 @@ $subModule = Import-Module -Name $subModulePath -PassThru # When the module is unloaded, remove the nested binary module that was loaded with it $PSModule.OnRemove = { - Remove-Module -ModuleInfo $subModule + Remove-Module -ModuleInfo $subModule } # Internal helper functions function HasWildcardSymbols { -param( - [string] - $stringToVerify -) - (-not [string]::IsNullOrEmpty($stringToVerify) -and ` - ($stringToVerify -match '\*' -or ` - $stringToVerify -match '\?')) + param( + [string] + $stringToVerify + ) + (-not [string]::IsNullOrEmpty($stringToVerify) -and ` + ($stringToVerify -match '\*' -or ` + $stringToVerify -match '\?')) } function RemoveWildcardSymbols { -param( - [string] - $stringToProcess -) - if (-not [string]::IsNullOrEmpty($stringToProcess)) { - $stringToProcess.Replace('*','').Replace('?','') - } else { - [string]::Empty - } + param( + [string] + $stringToProcess + ) + if (-not [string]::IsNullOrEmpty($stringToProcess)) { + $stringToProcess.Replace('*', '').Replace('?', '') + } + else { + [string]::Empty + } } function FormatError { -param( - [System.Exception] - $exception -) - if ($exception -ne $null) { - if ($exception.InnerException -ne $null) { - $exception = $exception.InnerException - } + param( + [System.Exception] + $exception + ) + if ($exception -ne $null) { + if ($exception.InnerException -ne $null) { + $exception = $exception.InnerException + } - # result - $exception.Message - } + # result + $exception.Message + } } # Global variables $global:DefaultSsoAdminServers = New-Object System.Collections.Generic.List[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] -# Module Advanced Functions Implementation +# Import Module Advanced Functions Implementation -#region Connection Management -function Connect-SsoAdminServer { -<# - .NOTES - =========================================================================== - Created on: 9/29/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function establishes a connection to a vSphere SSO Admin server. - - .PARAMETER Server - Specifies the IP address or the DNS name of the vSphere server to which you want to connect. - - .PARAMETER User - Specifies the user name you want to use for authenticating with the server. - - .PARAMETER Password - Specifies the password you want to use for authenticating with the server. - - .PARAMETER SkipCertificateCheck - Specifies whether server Tls certificate validation will be skipped - - .EXAMPLE - Connect-SsoAdminServer -Server my.vc.server -User myAdmin@vsphere.local -Password MyStrongPa$$w0rd - - Connects 'myAdmin@vsphere.local' user to Sso Admin server 'my.vc.server' -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='IP address or the DNS name of the vSphere server')] - [string] - $Server, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='User name you want to use for authenticating with the server')] - [string] - $User, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Password you want to use for authenticating with the server')] - [VMware.vSphere.SsoAdmin.Utils.StringToSecureStringArgumentTransformationAttribute()] - [SecureString] - $Password, - - [Parameter( - Mandatory=$false, - HelpMessage='Skips server Tls certificate validation')] - [switch] - $SkipCertificateCheck) - - Process { - $certificateValidator = $null - if ($SkipCertificateCheck) { - $certificateValidator = New-Object 'VMware.vSphere.SsoAdmin.Utils.AcceptAllX509CertificateValidator' - } - - $ssoAdminServer = $null - try { - $ssoAdminServer = New-Object ` - 'VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer' ` - -ArgumentList @( - $Server, - $User, - $Password, - $certificateValidator) - } catch { - Write-Error (FormatError $_.Exception) - } - - if ($ssoAdminServer -ne $null) { - $existingConnectionIndex = $global:DefaultSsoAdminServers.IndexOf($ssoAdminServer) - if ($existingConnectionIndex -ge 0) { - $global:DefaultSsoAdminServers[$existingConnectionIndex].RefCount++ - $ssoAdminServer = $global:DefaultSsoAdminServers[$existingConnectionIndex] - } else { - # Update $global:DefaultSsoAdminServers varaible - $global:DefaultSsoAdminServers.Add($ssoAdminServer) | Out-Null - } - - # Function Output - Write-Output $ssoAdminServer - } - } +Get-ChildItem -Path $PSScriptRoot -Filter '*.ps1' | ForEach-Object { + Write-Debug "Importing file: $($_.BaseName)" + try { + . $_.FullName + } + catch { + Write-Error -Message "Failed to import functions from $($_.Fullname): $_" + } } - -function Disconnect-SsoAdminServer { - <# - .NOTES - =========================================================================== - Created on: 9/29/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function closes the connection to a vSphere SSO Admin server. - - .PARAMETER Server - Specifies the vSphere SSO Admin systems you want to disconnect from - - .EXAMPLE - $mySsoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd' - Disconnect-SsoAdminServer -Server $mySsoAdminConnection - - Disconnect a SSO Admin connection stored in 'mySsoAdminConnection' varaible -#> - [CmdletBinding()] - param( - [Parameter( - ValueFromPipeline = $true, - ValueFromPipelineByPropertyName = $false, - HelpMessage = 'SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdmin.Utils.StringToSsoAdminServerArgumentTransformationAttribute()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer[]] - $Server - ) - - Process { - if (-not $PSBoundParameters['Server']) { - switch (@($global:DefaultSsoAdminServers).count) { - { $_ -eq 1 } { $server = ($global:DefaultSsoAdminServers).ToArray()[0] ; break } - { $_ -gt 1 } { - Throw 'Connected to more than 1 SSO server, please specify a SSO server via -Server parameter' - break - } - Default { - Throw 'Not connected to SSO server.' - } - } - } - - foreach ($requestedServer in $Server) { - if ($requestedServer.IsConnected) { - $requestedServer.Disconnect() - } - - if ($global:DefaultSsoAdminServers.Contains($requestedServer) -and $requestedServer.RefCount -eq 0) { - $global:DefaultSsoAdminServers.Remove($requestedServer) | Out-Null - } - } - } -} -#endregion - -#region Person User Management -function New-SsoPersonUser { -<# - .NOTES - =========================================================================== - Created on: 9/29/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function creates new person user account. - - .PARAMETER UserName - Specifies the UserName of the requested person user account. - - .PARAMETER Password - Specifies the Password of the requested person user account. - - .PARAMETER Description - Specifies the Description of the requested person user account. - - .PARAMETER EmailAddress - Specifies the EmailAddress of the requested person user account. - - .PARAMETER FirstName - Specifies the FirstName of the requested person user account. - - .PARAMETER LastName - Specifies the FirstName of the requested person user account. - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - .EXAMPLE - $ssoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd' - New-SsoPersonUser -Server $ssoAdminConnection -User myAdmin -Password 'MyStrongPa$$w0rd' - - Creates person user account with user name 'myAdmin' and password 'MyStrongPa$$w0rd' - - .EXAMPLE - New-SsoPersonUser -User myAdmin -Password 'MyStrongPa$$w0rd' -EmailAddress 'myAdmin@mydomain.com' -FirstName 'My' -LastName 'Admin' - - Creates person user account with user name 'myAdmin', password 'MyStrongPa$$w0rd', and details against connections available in 'DefaultSsoAdminServers' -#> -[CmdletBinding(ConfirmImpact='Low')] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='User name of the new person user account')] - [string] - $UserName, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Password of the new person user account')] - [string] - $Password, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Description of the new person user account')] - [string] - $Description, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='EmailAddress of the new person user account')] - [string] - $EmailAddress, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='FirstName of the new person user account')] - [string] - $FirstName, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='LastName of the new person user account')] - [string] - $LastName, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - Process { - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - # Output is the result of 'CreateLocalUser' - try { - $connection.Client.CreateLocalUser( - $UserName, - $Password, - $Description, - $EmailAddress, - $FirstName, - $LastName - ) - } catch { - Write-Error (FormatError $_.Exception) - } - } - } -} - -function Get-SsoPersonUser { -<# - .NOTES - =========================================================================== - Created on: 9/29/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function gets person user account. - - .PARAMETER Name - Specifies Name to filter on when searching for person user accounts. - - .PARAMETER Domain - Specifies the Domain in which search will be applied, default is 'localos'. - - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - .EXAMPLE - Get-SsoPersonUser -Name admin -Domain vsphere.local - - Gets person user accounts which contain name 'admin' in 'vsphere.local' domain - - .EXAMPLE - Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' | Get-SsoPersonUser - - Gets person user accounts members of 'Administrators' group -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Name filter to be applied when searching for person user accounts')] - [string] - $Name, - - [Parameter( - ParameterSetName = 'ByNameAndDomain', - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Domain name to search in, default is "localos"')] - [string] - $Domain = 'localos', - - [Parameter( - ParameterSetName = 'ByGroup', - Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Searches members of the specified group')] - [VMware.vSphere.SsoAdminClient.DataTypes.Group] - $Group, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - Process { - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - if ($Name -eq $null) { - $Name = [string]::Empty - } - - try { - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - $personUsers = $null - - if ($Group -ne $null) { - $personUsers = $connection.Client.GetPersonUsersInGroup( - (RemoveWildcardSymbols $Name), - $Group) - } else { - $personUsers = $connection.Client.GetLocalUsers( - (RemoveWildcardSymbols $Name), - $Domain) - } - - if ($personUsers -ne $null) { - foreach ($personUser in $personUsers) { - if ([string]::IsNullOrEmpty($Name) ) { - Write-Output $personUser - } else { - # Apply Name filtering - if ((HasWildcardSymbols $Name) -and ` - $personUser.Name -like $Name) { - Write-Output $personUser - } elseif ($personUser.Name -eq $Name) { - # Exactly equal - Write-Output $personUser - } - } - } - } - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} - -function Set-SsoPersonUser { -<# - .NOTES - =========================================================================== - Created on: 9/29/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - Updates person user account. - - .PARAMETER User - Specifies the PersonUser instance to update. - - .PARAMETER Group - Specifies the Group you want to add or remove PwersonUser from. - - .PARAMETER Add - Specifies user will be added to the spcified group. - - .PARAMETER Remove - Specifies user will be removed from the spcified group. - - .PARAMETER Unlock - Specifies user will be unloacked. - - .PARAMETER NewPassword - Specifies new password for the specified user. - - .EXAMPLE - Set-SsoPersonUser -User $myPersonUser -Group $myExampleGroup -Add -Server $ssoAdminConnection - - Adds $myPersonUser to $myExampleGroup - - .EXAMPLE - Set-SsoPersonUser -User $myPersonUser -Group $myExampleGroup -Remove -Server $ssoAdminConnection - - Removes $myPersonUser from $myExampleGroup - - .EXAMPLE - Set-SsoPersonUser -User $myPersonUser -Unlock -Server $ssoAdminConnection - - Unlocks $myPersonUser - - .EXAMPLE - Set-SsoPersonUser -User $myPersonUser -NewPassword 'MyBrandNewPa$$W0RD' -Server $ssoAdminConnection - - Resets $myPersonUser password -#> -[CmdletBinding(ConfirmImpact='Medium')] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Person User instance you want to update')] - [VMware.vSphere.SsoAdminClient.DataTypes.PersonUser] - $User, - - [Parameter( - ParameterSetName = 'AddToGroup', - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Group instance you want user to be added to or removed from')] - [Parameter( - ParameterSetName = 'RemoveFromGroup', - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Group instance you want user to be added to or removed from')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.Group] - $Group, - - [Parameter( - ParameterSetName = 'AddToGroup', - Mandatory=$true)] - [switch] - $Add, - - [Parameter( - ParameterSetName = 'RemoveFromGroup', - Mandatory=$true)] - [switch] - $Remove, - - [Parameter( - ParameterSetName = 'ResetPassword', - Mandatory=$true, - HelpMessage='New password for the specified user.')] - [ValidateNotNull()] - [string] - $NewPassword, - - [Parameter( - ParameterSetName = 'UnlockUser', - Mandatory=$true, - HelpMessage='Specifies to unlock user account.')] - [switch] - $Unlock) - - Process { - try { - foreach ($u in $User) { - $ssoAdminClient = $u.GetClient() - if ((-not $ssoAdminClient)) { - Write-Error "Object '$u' is from disconnected server" - continue - } - - if ($Add) { - $result = $ssoAdminClient.AddPersonUserToGroup($u, $Group) - if ($result) { - Write-Output $u - } - } - - if ($Remove) { - $result = $ssoAdminClient.RemovePersonUserFromGroup($u, $Group) - if ($result) { - Write-Output $u - } - } - - if ($Unlock) { - $result = $ssoAdminClient.UnlockPersonUser($u) - if ($result) { - Write-Output $u - } - } - - if ($NewPassword) { - $ssoAdminClient.ResetPersonUserPassword($u, $NewPassword) - Write-Output $u - } - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} - -function Set-SsoSelfPersonUserPassword { -<# - .NOTES - =========================================================================== - Created on: 2/19/2021 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - Resets connected person user password. - - - .PARAMETER NewPassword - Specifies new password for the connected person user. - - - .EXAMPLE - Set-SsoSelfPersonUserPassword -Password 'MyBrandNewPa$$W0RD' -Server $ssoAdminConnection - - Resets password -#> -[CmdletBinding(ConfirmImpact='High')] - param( - [Parameter( - Mandatory=$true, - HelpMessage='New password for the connected user.')] - [ValidateNotNull()] - [SecureString] - $Password, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - Process { - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - try { - $connection.Client.ResetSelfPersonUserPassword($Password) - } catch { - Write-Error (FormatError $_.Exception) - } - } - } -} - -function Remove-SsoPersonUser { -<# - .NOTES - =========================================================================== - Created on: 9/29/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function removes existing person user account. - - .PARAMETER User - Specifies the PersonUser instance to remove. - - .EXAMPLE - $ssoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd' - $myNewPersonUser = New-SsoPersonUser -Server $ssoAdminConnection -User myAdmin -Password 'MyStrongPa$$w0rd' - Remove-SsoPersonUser -User $myNewPersonUser - - Remove person user account with user name 'myAdmin' -#> -[CmdletBinding(ConfirmImpact='High')] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Person User instance you want to remove from specified servers')] - [VMware.vSphere.SsoAdminClient.DataTypes.PersonUser] - $User) - - Process { - try { - foreach ($u in $User) { - $ssoAdminClient = $u.GetClient() - if ((-not $ssoAdminClient)) { - Write-Error "Object '$u' is from disconnected server" - continue - } - - $ssoAdminClient.DeleteLocalUser($u) - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} -#endregion - -#region Group cmdlets -function Get-SsoGroup { -<# - .NOTES - =========================================================================== - Created on: 9/29/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function gets domain groups. - - .PARAMETER Name - Specifies Name to filter on when searching for groups. - - .PARAMETER Domain - Specifies the Domain in which search will be applied, default is 'localos'. - - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - .EXAMPLE - Get-SsoGroup -Name administrators -Domain vsphere.local - - Gets 'adminsitrators' group in 'vsphere.local' domain -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Name filter to be applied when searching for group')] - [string] - $Name, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Domain name to search in, default is "localos"')] - [string] - $Domain = 'localos', - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - Process { - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - if ($Name -eq $null) { - $Name = [string]::Empty - } - - try { - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - foreach ($group in $connection.Client.GetGroups( - (RemoveWildcardSymbols $Name), - $Domain)) { - - - if ([string]::IsNullOrEmpty($Name) ) { - Write-Output $group - } else { - # Apply Name filtering - if ((HasWildcardSymbols $Name) -and ` - $group.Name -like $Name) { - Write-Output $group - } elseif ($group.Name -eq $Name) { - # Exactly equal - Write-Output $group - } - } - } - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} -#endregion - -#region PasswordPolicy cmdlets -function Get-SsoPasswordPolicy { -<# - .NOTES - =========================================================================== - Created on: 9/30/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function gets password policy. - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - .EXAMPLE - Get-SsoPasswordPolicy - - Gets password policy for the server connections available in $global:defaultSsoAdminServers -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - Process { - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - try { - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - $connection.Client.GetPasswordPolicy(); - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} - -function Set-SsoPasswordPolicy { -<# - .NOTES - =========================================================================== - Created on: 9/30/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function updates password policy settings. - - .PARAMETER PasswordPolicy - Specifies the PasswordPolicy instance which will be used as original policy. If some properties are not specified they will be updated with the properties from this object. - - .PARAMETER Description - - .PARAMETER ProhibitedPreviousPasswordsCount - - .PARAMETER MinLength - - .PARAMETER MaxLength - - .PARAMETER MaxIdenticalAdjacentCharacters - - .PARAMETER MinNumericCount - - .PARAMETER MinSpecialCharCount - - .PARAMETER MinAlphabeticCount - - .PARAMETER MinUppercaseCount - - .PARAMETER MinLowercaseCount - - .PARAMETER PasswordLifetimeDays - - .EXAMPLE - Get-SsoPasswordPolicy | Set-SsoPasswordPolicy -MinLength 10 -PasswordLifetimeDays 45 - - Updates password policy setting minimum password length to 10 symbols and password lifetime to 45 days -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$false, - HelpMessage='PasswordPolicy instance you want to update')] - [VMware.vSphere.SsoAdminClient.DataTypes.PasswordPolicy] - $PasswordPolicy, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='PasswordPolicy description')] - [string] - $Description, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $ProhibitedPreviousPasswordsCount, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $MinLength, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $MaxLength, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $MaxIdenticalAdjacentCharacters, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $MinNumericCount, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $MinSpecialCharCount, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $MinAlphabeticCount, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $MinUppercaseCount, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $MinLowercaseCount, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $PasswordLifetimeDays) - - Process { - - try { - foreach ($pp in $PasswordPolicy) { - - $ssoAdminClient = $pp.GetClient() - if ((-not $ssoAdminClient)) { - Write-Error "Object '$pp' is from disconnected server" - continue - } - - if ([string]::IsNullOrEmpty($Description)) { - $Description = $pp.Description - } - - if ($ProhibitedPreviousPasswordsCount -eq $null) { - $ProhibitedPreviousPasswordsCount = $pp.ProhibitedPreviousPasswordsCount - } - - if ($MinLength -eq $null) { - $MinLength = $pp.MinLength - } - - if ($MaxLength -eq $null) { - $MaxLength = $pp.MaxLength - } - - if ($MaxIdenticalAdjacentCharacters -eq $null) { - $MaxIdenticalAdjacentCharacters = $pp.MaxIdenticalAdjacentCharacters - } - - if ($MinNumericCount -eq $null) { - $MinNumericCount = $pp.MinNumericCount - } - - if ($MinSpecialCharCount -eq $null) { - $MinSpecialCharCount = $pp.MinSpecialCharCount - } - - if ($MinAlphabeticCount -eq $null) { - $MinAlphabeticCount = $pp.MinAlphabeticCount - } - - if ($MinUppercaseCount -eq $null) { - $MinUppercaseCount = $pp.MinUppercaseCount - } - - if ($MinLowercaseCount -eq $null) { - $MinLowercaseCount = $pp.MinLowercaseCount - } - - if ($PasswordLifetimeDays -eq $null) { - $PasswordLifetimeDays = $pp.PasswordLifetimeDays - } - - $ssoAdminClient.SetPasswordPolicy( - $Description, - $ProhibitedPreviousPasswordsCount, - $MinLength, - $MaxLength, - $MaxIdenticalAdjacentCharacters, - $MinNumericCount, - $MinSpecialCharCount, - $MinAlphabeticCount, - $MinUppercaseCount, - $MinLowercaseCount, - $PasswordLifetimeDays); - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} -#endregion - -#region LockoutPolicy cmdlets -function Get-SsoLockoutPolicy { -<# - .NOTES - =========================================================================== - Created on: 9/30/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function gets lockout policy. - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - .EXAMPLE - Get-SsoLockoutPolicy - - Gets lockout policy for the server connections available in $global:defaultSsoAdminServers -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - Process { - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - try { - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - $connection.Client.GetLockoutPolicy(); - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} - -function Set-SsoLockoutPolicy { -<# - .NOTES - =========================================================================== - Created on: 9/30/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function updates lockout policy settings. - - .PARAMETER LockoutPolicy - Specifies the LockoutPolicy instance which will be used as original policy. If some properties are not specified they will be updated with the properties from this object. - - .PARAMETER Description - - .PARAMETER AutoUnlockIntervalSec - - .PARAMETER FailedAttemptIntervalSec - - .PARAMETER MaxFailedAttempts - - .EXAMPLE - Get-SsoLockoutPolicy | Set-SsoLockoutPolicy -AutoUnlockIntervalSec 15 -MaxFailedAttempts 4 - - Updates lockout policy auto unlock interval seconds and maximum failed attempts -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$false, - HelpMessage='LockoutPolicy instance you want to update')] - [VMware.vSphere.SsoAdminClient.DataTypes.LockoutPolicy] - $LockoutPolicy, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='LockoutPolicy description')] - [string] - $Description, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int64]] - $AutoUnlockIntervalSec, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int64]] - $FailedAttemptIntervalSec, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int32]] - $MaxFailedAttempts) - - Process { - try { - foreach ($lp in $LockoutPolicy) { - - $ssoAdminClient = $lp.GetClient() - if ((-not $ssoAdminClient)) { - Write-Error "Object '$lp' is from disconnected server" - continue - } - - if ([string]::IsNullOrEmpty($Description)) { - $Description = $lp.Description - } - - if ($AutoUnlockIntervalSec -eq $null) { - $AutoUnlockIntervalSec = $lp.AutoUnlockIntervalSec - } - - if ($FailedAttemptIntervalSec -eq $null) { - $FailedAttemptIntervalSec = $lp.FailedAttemptIntervalSec - } - - if ($MaxFailedAttempts -eq $null) { - $MaxFailedAttempts = $lp.MaxFailedAttempts - } - - $ssoAdminClient.SetLockoutPolicy( - $Description, - $AutoUnlockIntervalSec, - $FailedAttemptIntervalSec, - $MaxFailedAttempts); - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} -#endregion - -#region TokenLifetime cmdlets -function Get-SsoTokenLifetime { -<# - .NOTES - =========================================================================== - Created on: 9/30/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function gets HoK and Bearer Token lifetime settings. - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - .EXAMPLE - Get-SsoTokenLifetime - - Gets HoK and Bearer Token lifetime settings for the server connections available in $global:defaultSsoAdminServers -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - Process { - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - try { - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - $connection.Client.GetTokenLifetime(); - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} - -function Set-SsoTokenLifetime { -<# - .NOTES - =========================================================================== - Created on: 9/30/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function updates HoK or Bearer token lifetime settings. - - .PARAMETER TokenLifetime - Specifies the TokenLifetime instance to update. - - .PARAMETER MaxHoKTokenLifetime - - .PARAMETER MaxBearerTokenLifetime - - .EXAMPLE - Get-SsoTokenLifetime | Set-SsoTokenLifetime -MaxHoKTokenLifetime 60 - - Updates HoK token lifetime setting -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$false, - HelpMessage='TokenLifetime instance you want to update')] - [VMware.vSphere.SsoAdminClient.DataTypes.TokenLifetime] - $TokenLifetime, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int64]] - $MaxHoKTokenLifetime, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [Nullable[System.Int64]] - $MaxBearerTokenLifetime) - - Process { - - try { - foreach ($tl in $TokenLifetime) { - - $ssoAdminClient = $tl.GetClient() - if ((-not $ssoAdminClient)) { - Write-Error "Object '$tl' is from disconnected server" - continue - } - - $ssoAdminClient.SetTokenLifetime( - $MaxHoKTokenLifetime, - $MaxBearerTokenLifetime - ); - } - } catch { - Write-Error (FormatError $_.Exception) - } - } -} -#endregion - -#region IdentitySource -function Add-ExternalDomainIdentitySource { -<# - .NOTES - =========================================================================== - Created on: 2/11/2021 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function adds Identity Source of ActiveDirectory, OpenLDAP or NIS type. - - .PARAMETER Name - Name of the identity source - - .PARAMETER DomainName - Domain name - - .PARAMETER DomainAlias - Domain alias - - .PARAMETER PrimaryUrl - Primary Server URL - - .PARAMETER BaseDNUsers - Base distinguished name for users - - .PARAMETER BaseDNGroups - Base distinguished name for groups - - .PARAMETER Username - Domain authentication user name - - .PARAMETER Passowrd - Domain authentication password - - .PARAMETER DomainServerType - Type of the ExternalDomain, one of 'ActiveDirectory','OpenLdap','NIS' - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - .EXAMPLE - Add-ExternalDomainIdentitySource ` - -Name 'sof-powercli' ` - -DomainName 'sof-powercli.vmware.com' ` - -DomainAlias 'sof-powercli' ` - -PrimaryUrl 'ldap://sof-powercli.vmware.com:389' ` - -BaseDNUsers 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' ` - -BaseDNGroups 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' ` - -Username 'sofPowercliAdmin' ` - -Password '$up3R$Tr0Pa$$w0rD' - - Adds External Identity Source -#> -[CmdletBinding()] -[Alias("Add-ActiveDirectoryIdentitySource")] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Friendly name of the identity source')] - [ValidateNotNull()] - [string] - $Name, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [ValidateNotNull()] - [string] - $DomainName, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [string] - $DomainAlias, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [ValidateNotNull()] - [string] - $PrimaryUrl, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Base distinguished name for users')] - [ValidateNotNull()] - [string] - $BaseDNUsers, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Base distinguished name for groups')] - [ValidateNotNull()] - [string] - $BaseDNGroups, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Domain authentication user name')] - [ValidateNotNull()] - [string] - $Username, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Domain authentication password')] - [ValidateNotNull()] - [string] - $Password, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='External domain server type')] - [ValidateSet('ActiveDirectory')] - [string] - $DomainServerType = 'ActiveDirectory', - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - try { - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - $connection.Client.AddActiveDirectoryExternalDomain( - $DomainName, - $DomainAlias, - $Name, - $PrimaryUrl, - $BaseDNUsers, - $BaseDNGroups, - $Username, - $Password, - $DomainServerType); - } - } catch { - Write-Error (FormatError $_.Exception) - } -} - -function Add-LDAPIdentitySource { -<# - .NOTES - =========================================================================== - Created on: 2/11/2021 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function adds LDAP Identity Source of ActiveDirectory, OpenLDAP or NIS type. - - .PARAMETER Name - Friendly name of the identity source - - .PARAMETER DomainName - Domain name - - .PARAMETER DomainAlias - Domain alias - - .PARAMETER PrimaryUrl - Primary Server URL - - .PARAMETER SecondaryUrl - Secondary Server URL - - .PARAMETER BaseDNUsers - Base distinguished name for users - - .PARAMETER BaseDNGroups - Base distinguished name for groups - - .PARAMETER Username - Domain authentication user name - - .PARAMETER Passowrd - Domain authentication password - - .PARAMETER ServerType - Type of the ExternalDomain, one of 'ActiveDirectory','OpenLdap','NIS' - - .PARAMETER Certificates - List of X509Certicate2 LDAP certificates - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - Adds LDAP Identity Source - - .EXAMPLE - Add-LDAPIdentitySource ` - -Name 'sof-powercli' ` - -DomainName 'sof-powercli.vmware.com' ` - -DomainAlias 'sof-powercli' ` - -PrimaryUrl 'ldap://sof-powercli.vmware.com:389' ` - -BaseDNUsers 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' ` - -BaseDNGroups 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' ` - -Username 'sofPowercliAdmin@sof-powercli.vmware.com' ` - -Password '$up3R$Tr0Pa$$w0rD' ` - -Certificates 'C:\Temp\test.cer' -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Friendly name of the identity source')] - [ValidateNotNull()] - [string] - $Name, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [ValidateNotNull()] - [string] - $DomainName, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [string] - $DomainAlias, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [string] - $SecondaryUrl, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false)] - [ValidateNotNull()] - [string] - $PrimaryUrl, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Base distinguished name for users')] - [ValidateNotNull()] - [string] - $BaseDNUsers, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Base distinguished name for groups')] - [ValidateNotNull()] - [string] - $BaseDNGroups, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Domain authentication user name')] - [ValidateNotNull()] - [string] - $Username, - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Domain authentication password')] - [ValidateNotNull()] - [string] - $Password, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Ldap Certificates')] - [System.Security.Cryptography.X509Certificates.X509Certificate2[]] - $Certificates, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Ldap Server type')] - [ValidateSet('ActiveDirectory')] - [string] - $ServerType = 'ActiveDirectory', - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - try { - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - $connection.Client.AddLdapIdentitySource( - $DomainName, - $DomainAlias, - $Name, - $PrimaryUrl, - $SecondaryUrl, - $BaseDNUsers, - $BaseDNGroups, - $Username, - $Password, - $ServerType, - $Certificates); - } - } catch { - Write-Error (FormatError $_.Exception) - } -} - -function Set-LDAPIdentitySource { -<# - .NOTES - =========================================================================== - Created on: 2/17/2021 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function adds LDAP Identity Source of ActiveDirectory, OpenLDAP or NIS type. - - .PARAMETER IdentitySource - Identity Source to update - - .PARAMETER Certificates - List of X509Certicate2 LDAP certificates - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - Updates LDAP Identity Source - - .EXAMPLE - - Updates certificate of a LDAP identity source - - Get-IdentitySource -External | ` - Set-LDAPIdentitySource ` - -Certificates 'C:\Temp\test.cer' -#> -[CmdletBinding()] - param( - [Parameter( - Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Identity source to update')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.ActiveDirectoryIdentitySource] - $IdentitySource, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Ldap Certificates')] - [System.Security.Cryptography.X509Certificates.X509Certificate2[]] - $Certificates, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - -Process { - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - try { - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - $connection.Client.UpdateLdapIdentitySource( - $IdentitySource.Name, - $IdentitySource.FriendlyName, - $IdentitySource.PrimaryUrl, - $IdentitySource.FailoverUrl, - $IdentitySource.UserBaseDN, - $IdentitySource.GroupBaseDN, - $Certificates); - } - } catch { - Write-Error (FormatError $_.Exception) - } -} -} - -function Get-IdentitySource { -<# - .NOTES - =========================================================================== - Created on: 11/26/2020 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function gets Identity Source. - - .PARAMETER Localos - Filter parameter to return only the localos domain identity source - - .PARAMETER System - Filter parameter to return only the system domain identity source - - .PARAMETER External - Filter parameter to return only the external domain identity sources - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - .EXAMPLE - Get-IdentitySource -External - - Gets all external domain identity source -#> -[CmdletBinding()] - param( - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Returns only the localos domain identity source')] - [Switch] - $Localos, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Returns only the system domain identity source')] - [Switch] - $System, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Returns only the external domain identity sources')] - [Switch] - $External, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - $resultIdentitySources = @() - $allIdentitySources = $connection.Client.GetDomains() - - if (-not $Localos -and -not $System -and -not $External) { - $resultIdentitySources = $allIdentitySources - } - - if ($Localos) { - $resultIdentitySources += $allIdentitySources | Where-Object { $_ -is [VMware.vSphere.SsoAdminClient.DataTypes.LocalOSIdentitySource] } - } - - if ($System) { - $resultIdentitySources += $allIdentitySources | Where-Object { $_ -is [VMware.vSphere.SsoAdminClient.DataTypes.SystemIdentitySource] } - } - - if ($External) { - $resultIdentitySources += $allIdentitySources | Where-Object { $_ -is [VMware.vSphere.SsoAdminClient.DataTypes.ActiveDirectoryIdentitySource] } - } - - #Return result - $resultIdentitySources - } -} - -function Remove-IdentitySource { -<# - .NOTES - =========================================================================== - Created on: 03/19/2021 - Created by: Dimitar Milov - Twitter: @dimitar_milov - Github: https://github.com/dmilov - =========================================================================== - .DESCRIPTION - This function removes Identity Source. - - .PARAMETER IdentitySource - The identity source to remove - - .PARAMETER Server - Specifies the vSphere Sso Admin Server on which you want to run the cmdlet. - If not specified the servers available in $global:DefaultSsoAdminServers variable will be used. - - .EXAMPLE - Get-IdentitySource -External | Remove-IdentitySource - - Removes all external domain identity source -#> -[CmdletBinding()] - param( - - [Parameter( - Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Identity source to remove')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.IdentitySource] - $IdentitySource, - - [Parameter( - Mandatory=$false, - ValueFromPipeline=$false, - ValueFromPipelineByPropertyName=$false, - HelpMessage='Connected SsoAdminServer object')] - [ValidateNotNull()] - [VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer] - $Server) - -Process { - - $serversToProcess = $global:DefaultSsoAdminServers.ToArray() - if ($Server -ne $null) { - $serversToProcess = $Server - } - - - try { - foreach ($connection in $serversToProcess) { - if (-not $connection.IsConnected) { - Write-Error "Server $connection is disconnected" - continue - } - - $connection.Client.DeleteDomain($IdentitySource.Name) - } - } catch { - Write-Error (FormatError $_.Exception) - } -} -} -#endregion \ No newline at end of file diff --git a/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.LsClient.dll b/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.LsClient.dll index e68d484..2f02656 100644 Binary files a/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.LsClient.dll and b/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.LsClient.dll differ diff --git a/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.SsoAdmin.Utils.dll b/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.SsoAdmin.Utils.dll index 74f1c26..596e661 100644 Binary files a/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.SsoAdmin.Utils.dll and b/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.SsoAdmin.Utils.dll differ diff --git a/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.SsoAdminClient.dll b/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.SsoAdminClient.dll index 11a2ca1..e05ae44 100644 Binary files a/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.SsoAdminClient.dll and b/Modules/VMware.vSphere.SsoAdmin/net45/VMware.vSphere.SsoAdminClient.dll differ diff --git a/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.LsClient.dll b/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.LsClient.dll index e0157ac..b83b8cd 100644 Binary files a/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.LsClient.dll and b/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.LsClient.dll differ diff --git a/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.SsoAdmin.Utils.dll b/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.SsoAdmin.Utils.dll index 0f6bdae..ca8d14b 100644 Binary files a/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.SsoAdmin.Utils.dll and b/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.SsoAdmin.Utils.dll differ diff --git a/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.SsoAdminClient.dll b/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.SsoAdminClient.dll index c06dbf2..4f3958c 100644 Binary files a/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.SsoAdminClient.dll and b/Modules/VMware.vSphere.SsoAdmin/netcoreapp3.1/VMware.vSphere.SsoAdminClient.dll differ diff --git a/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient.Tests/IntegrationTests.cs b/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient.Tests/IntegrationTests.cs index 0ed5620..ff6f1d8 100644 --- a/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient.Tests/IntegrationTests.cs +++ b/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient.Tests/IntegrationTests.cs @@ -103,7 +103,7 @@ namespace VMware.vSphere.SsoAdminClient.Tests var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator()); // Act - var actual = ssoAdminClient.GetPersonUsersInGroup("", new Group { + var actual = ssoAdminClient.GetPersonUsersInGroup("", new Group(ssoAdminClient) { Name = "Administrators", Domain = "vsphere.local" }).ToArray(); diff --git a/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient/DataTypes/Group.cs b/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient/DataTypes/Group.cs index c0edc38..9a0d469 100644 --- a/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient/DataTypes/Group.cs +++ b/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient/DataTypes/Group.cs @@ -9,13 +9,26 @@ using System.Threading.Tasks; namespace VMware.vSphere.SsoAdminClient.DataTypes { - public class Group - { - public string Name { get; set; } - public string Domain { get; set; } + public class Group + { + SsoAdminClient _client; + public Group(SsoAdminClient client) + { + _client = client; + } - public override string ToString() { - return $"{Name}@{Domain}"; - } - } + public string Name { get; set; } + public string Domain { get; set; } + public string Description { get; set; } + + public SsoAdminClient GetClient() + { + return _client; + } + + public override string ToString() + { + return $"{Name}@{Domain}"; + } + } } diff --git a/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient/SsoAdminClient.cs b/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient/SsoAdminClient.cs index e23ad13..8f4ccfa 100644 --- a/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient/SsoAdminClient.cs +++ b/Modules/VMware.vSphere.SsoAdmin/src/VMware.vSphere.SsoAdmin.Client/VMware.vSphere.SsoAdminClient/SsoAdminClient.cs @@ -22,871 +22,1187 @@ using VMware.vSphere.SsoAdminClient.SsoAdminServiceReference2; namespace VMware.vSphere.SsoAdminClient { - public class SsoAdminClient - { - private const int WEB_OPERATION_TIMEOUT_SECONDS = 30; + public class SsoAdminClient + { + private const int WEB_OPERATION_TIMEOUT_SECONDS = 30; - private SsoPortTypeClient _ssoAdminBindingClient; - private UserPassSecurityContext _securityContext; + private SsoPortTypeClient _ssoAdminBindingClient; + private UserPassSecurityContext _securityContext; - public SsoAdminClient(string hostname, string user, SecureString password, X509CertificateValidator serverCertificateValidator) { - if (hostname == null) throw new ArgumentNullException(nameof(hostname)); - if (user == null) throw new ArgumentNullException(nameof(user)); - if (password == null) throw new ArgumentNullException(nameof(password)); + public SsoAdminClient(string hostname, string user, SecureString password, X509CertificateValidator serverCertificateValidator) + { + if (hostname == null) throw new ArgumentNullException(nameof(hostname)); + if (user == null) throw new ArgumentNullException(nameof(user)); + if (password == null) throw new ArgumentNullException(nameof(password)); - var lsClient = new LookupServiceClient(hostname, serverCertificateValidator); + var lsClient = new LookupServiceClient(hostname, serverCertificateValidator); - // Create STS Client - var stsUri = lsClient.GetStsEndpointUri(); - _securityContext = new UserPassSecurityContext(user, password, stsUri, serverCertificateValidator); - // Initialize security context with Saml token by username and password - _securityContext.GetToken(); + // Create STS Client + var stsUri = lsClient.GetStsEndpointUri(); + _securityContext = new UserPassSecurityContext(user, password, stsUri, serverCertificateValidator); + // Initialize security context with Saml token by username and password + _securityContext.GetToken(); - // Create SSO Admin Binding Client - var ssoAdminUri = lsClient.GetSsoAdminEndpointUri(); - ServiceUri = ssoAdminUri; - User = user; - _ssoAdminBindingClient = new SsoPortTypeClient(GetBinding(), new EndpointAddress(ssoAdminUri)); - _ssoAdminBindingClient.ChannelFactory.Endpoint.EndpointBehaviors.Add(new WsTrustBehavior()); + // Create SSO Admin Binding Client + var ssoAdminUri = lsClient.GetSsoAdminEndpointUri(); + ServiceUri = ssoAdminUri; + User = user; + _ssoAdminBindingClient = new SsoPortTypeClient(GetBinding(), new EndpointAddress(ssoAdminUri)); + _ssoAdminBindingClient.ChannelFactory.Endpoint.EndpointBehaviors.Add(new WsTrustBehavior()); - var serverAuthentication = GetServerAuthentication(serverCertificateValidator); + var serverAuthentication = GetServerAuthentication(serverCertificateValidator); - if (serverAuthentication != null) { - _ssoAdminBindingClient - .ChannelFactory - .Credentials - .ServiceCertificate - .SslCertificateAuthentication = serverAuthentication; - } - } + if (serverAuthentication != null) + { + _ssoAdminBindingClient + .ChannelFactory + .Credentials + .ServiceCertificate + .SslCertificateAuthentication = serverAuthentication; + } + } - #region Private Helpers - private X509ServiceCertificateAuthentication GetServerAuthentication(X509CertificateValidator serverCertificateValidator) { - if (serverCertificateValidator != null) { - return new X509ServiceCertificateAuthentication { - CertificateValidationMode = X509CertificateValidationMode.Custom, - CustomCertificateValidator = serverCertificateValidator + #region Private Helpers + private X509ServiceCertificateAuthentication GetServerAuthentication(X509CertificateValidator serverCertificateValidator) + { + if (serverCertificateValidator != null) + { + return new X509ServiceCertificateAuthentication + { + CertificateValidationMode = X509CertificateValidationMode.Custom, + CustomCertificateValidator = serverCertificateValidator + }; + } + + // Default .NET behavior for TLS certificate validation + return null; + } + + private static MessageEncodingBindingElement GetWcfEncoding() + { + // VMware STS requires SOAP version 1.1 + return new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8); + } + + private static HttpsTransportBindingElement GetWcfTransport(bool useSystemProxy) + { + // Communication with the STS is over https + HttpsTransportBindingElement transport = new HttpsTransportBindingElement + { + RequireClientCertificate = false }; - } - // Default .NET behavior for TLS certificate validation - return null; - } + transport.UseDefaultWebProxy = useSystemProxy; + transport.MaxBufferSize = 2147483647; + transport.MaxReceivedMessageSize = 2147483647; - private static MessageEncodingBindingElement GetWcfEncoding() { - // VMware STS requires SOAP version 1.1 - return new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8); - } + return transport; + } - private static HttpsTransportBindingElement GetWcfTransport(bool useSystemProxy) { - // Communication with the STS is over https - HttpsTransportBindingElement transport = new HttpsTransportBindingElement { - RequireClientCertificate = false - }; + private static CustomBinding GetBinding() + { - transport.UseDefaultWebProxy = useSystemProxy; - transport.MaxBufferSize = 2147483647; - transport.MaxReceivedMessageSize = 2147483647; + // There is no build-in WCF binding capable of communicating + // with VMware STS, so we create a plain custom one. + // This binding does not provide support for WS-Trust, + // that support is currently implemented as a WCF endpoint behaviour. + var binding = new CustomBinding(GetWcfEncoding(), GetWcfTransport(true)); - return transport; - } + var timeout = TimeSpan.FromSeconds(WEB_OPERATION_TIMEOUT_SECONDS); + binding.CloseTimeout = timeout; + binding.OpenTimeout = timeout; + binding.ReceiveTimeout = timeout; + binding.SendTimeout = timeout; - private static CustomBinding GetBinding() { + return binding; + } - // There is no build-in WCF binding capable of communicating - // with VMware STS, so we create a plain custom one. - // This binding does not provide support for WS-Trust, - // that support is currently implemented as a WCF endpoint behaviour. - var binding = new CustomBinding(GetWcfEncoding(), GetWcfTransport(true)); + private WsSecurityContext CreateAuthorizedInvocationContext() + { + // Issue Bearer token to authorize create solution user to SSO Admin service + var bearerToken = _securityContext.GetToken(); - var timeout = TimeSpan.FromSeconds(WEB_OPERATION_TIMEOUT_SECONDS); - binding.CloseTimeout = timeout; - binding.OpenTimeout = timeout; - binding.ReceiveTimeout = timeout; - binding.SendTimeout = timeout; - - return binding; - } - - private WsSecurityContext CreateAuthorizedInvocationContext() { - // Issue Bearer token to authorize create solution user to SSO Admin service - var bearerToken = _securityContext.GetToken(); - - // Set WS Trust Header Serialization with issued bearer SAML token - var securityContext = new WsSecurityContext { - ClientChannel = _ssoAdminBindingClient.InnerChannel, - Properties = { + // Set WS Trust Header Serialization with issued bearer SAML token + var securityContext = new WsSecurityContext + { + ClientChannel = _ssoAdminBindingClient.InnerChannel, + Properties = { Credentials = { BearerToken = bearerToken } } - }; - return securityContext; - } - - String SecureStringToString(SecureString value) { - IntPtr valuePtr = IntPtr.Zero; - try { - valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value); - return Marshal.PtrToStringUni(valuePtr); - } finally { - Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); - } - } - #endregion - - #region Public interface - - public Uri ServiceUri { get; } - public string User { get; } - - public PersonUser CreateLocalUser( - string userName, - string password, - string description = null, - string emailAddress = null, - string firstName = null, - string lastName = null) { - - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin CreateLocalSolutionUser operation - var ssoPrincipalId = authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.CreateLocalPersonUserAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalManagementService", - Value = "principalManagementService" - }, - userName, - new SsoAdminPersonDetails { - description = description, - emailAddress = emailAddress, - firstName = firstName, - lastName = lastName - }, - password)).Result; - - return GetLocalUsers(ssoPrincipalId.name, ssoPrincipalId.domain, authorizedInvocationContext); - } - - private PersonUser GetLocalUsers(string userName, string domain, WsSecurityContext wsSecurityContext) { - // Invoke SSO Admin FindPersonUserAsync operation - var personUser = wsSecurityContext. - InvokeOperation(() => - _ssoAdminBindingClient.FindPersonUserAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalDiscoveryService", - Value = "principalDiscoveryService" - }, - new SsoPrincipalId { - name = userName, - domain = domain - })).Result; - return new PersonUser(this) { - Name = personUser.id.name, - Domain = personUser.id.domain, - Description = personUser.details.description, - FirstName = personUser.details.firstName, - LastName = personUser.details.lastName, - EmailAddress = personUser.details.emailAddress, - Locked = personUser.locked, - Disabled = personUser.disabled - }; - } - - public IEnumerable GetLocalUsers(string searchString, string domain) { - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin FindPersonUsersAsync operation - var personUsers = authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.FindPersonUsersAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalDiscoveryService", - Value = "principalDiscoveryService" - }, - new SsoAdminPrincipalDiscoveryServiceSearchCriteria { - searchString = searchString, - domain = domain - }, - int.MaxValue)).Result.returnval; - - if (personUsers != null) { - foreach (var personUser in personUsers) { - yield return new PersonUser(this) { - Name = personUser.id.name, - Domain = personUser.id.domain, - Description = personUser.details.description, - FirstName = personUser.details.firstName, - LastName = personUser.details.lastName, - EmailAddress = personUser.details.emailAddress, - Locked = personUser.locked, - Disabled = personUser.disabled - }; - } - } - - } - - public IEnumerable GetPersonUsersInGroup(string searchString, DataTypes.Group group) { - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin FindPersonUsersAsync operation - var personUsers = authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.FindPersonUsersInGroupAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalDiscoveryService", - Value = "principalDiscoveryService" - }, - new SsoPrincipalId { - name = group.Name, - domain = group.Domain - }, - searchString, - int.MaxValue)).Result.returnval; - - if (personUsers != null) { - foreach (var personUser in personUsers) { - yield return new PersonUser(this) { - Name = personUser.id.name, - Domain = personUser.id.domain, - Description = personUser.details.description, - FirstName = personUser.details.firstName, - LastName = personUser.details.lastName, - EmailAddress = personUser.details.emailAddress, - Locked = personUser.locked, - Disabled = personUser.disabled - }; - } - } - } - - public void DeleteLocalUser( - PersonUser principal) { - - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin DeleteLocalPrincipal operation - authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.DeleteLocalPrincipalAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalManagementService", - Value = "principalManagementService" - }, - principal.Name)); - } - - public IEnumerable GetGroups(string searchString, string domain) { - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin FindGroupsAsync operation - var ssoAdminGroups = authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.FindGroupsAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalDiscoveryService", - Value = "principalDiscoveryService" - }, - new SsoAdminPrincipalDiscoveryServiceSearchCriteria { - searchString = searchString, - domain = domain - }, - int.MaxValue)).Result.returnval; - - if (ssoAdminGroups != null) { - foreach (var group in ssoAdminGroups) { - yield return new DataTypes.Group { - Name = group.id.name, - Domain = group.id.domain - }; - } - } - } - - public bool AddPersonUserToGroup(PersonUser user, DataTypes.Group group) { - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin AddUserToLocalGroupAsync operation - return authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.AddUserToLocalGroupAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalManagementService", - Value = "principalManagementService" - }, - new SsoPrincipalId { - name = user.Name, - domain = user.Domain - }, - group.Name)).Result; - } - - public bool RemovePersonUserFromGroup(PersonUser user, DataTypes.Group group) { - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin RemoveFromLocalGroupAsync operation - return authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.RemoveFromLocalGroupAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalManagementService", - Value = "principalManagementService" - }, - new SsoPrincipalId { - name = user.Name, - domain = user.Domain - }, - group.Name)).Result; - } - - public void ResetPersonUserPassword(PersonUser user, string newPassword) { - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin ResetLocalPersonUserPasswordAsync operation - authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.ResetLocalPersonUserPasswordAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalManagementService", - Value = "principalManagementService" - }, - user.Name, - newPassword)).Wait(); - } - - public void ResetSelfPersonUserPassword(SecureString newPassword) { - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin ResetLocalPersonUserPasswordAsync operation - authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.ResetSelfLocalPersonUserPasswordAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalManagementService", - Value = "principalManagementService" - }, - SecureStringToString(newPassword))).Wait(); - } - - public bool UnlockPersonUser(PersonUser user) { - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin UnlockUserAccountAsync operation - return authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.UnlockUserAccountAsync( - new ManagedObjectReference { - type = "SsoAdminPrincipalManagementService", - Value = "principalManagementService" - }, - new SsoPrincipalId { - name = user.Name, - domain = user.Domain - })).Result; - } - - public PasswordPolicy GetPasswordPolicy() { - PasswordPolicy result = null; - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin GetLocalPasswordPolicyAsync operation - var ssoAdminPasswordPolicy = authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.GetLocalPasswordPolicyAsync( - new ManagedObjectReference { - type = "SsoAdminPasswordPolicyService", - Value = "passwordPolicyService" - })).Result; - - if (ssoAdminPasswordPolicy != null) { - result = new PasswordPolicy(this) { - Description = ssoAdminPasswordPolicy.description, - ProhibitedPreviousPasswordsCount = ssoAdminPasswordPolicy.prohibitedPreviousPasswordsCount, - MinLength = ssoAdminPasswordPolicy.passwordFormat.lengthRestriction.minLength, - MaxLength = ssoAdminPasswordPolicy.passwordFormat.lengthRestriction.maxLength, - MaxIdenticalAdjacentCharacters = ssoAdminPasswordPolicy.passwordFormat.maxIdenticalAdjacentCharacters, - MinNumericCount = ssoAdminPasswordPolicy.passwordFormat.minNumericCount, - MinSpecialCharCount = ssoAdminPasswordPolicy.passwordFormat.minSpecialCharCount, - MinAlphabeticCount = ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minAlphabeticCount, - MinUppercaseCount = ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minUppercaseCount, - MinLowercaseCount = ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minLowercaseCount, - PasswordLifetimeDays = ssoAdminPasswordPolicy.passwordLifetimeDays }; - } + return securityContext; + } - return result; - } + String SecureStringToString(SecureString value) + { + IntPtr valuePtr = IntPtr.Zero; + try + { + valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value); + return Marshal.PtrToStringUni(valuePtr); + } + finally + { + Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); + } + } + #endregion - public PasswordPolicy SetPasswordPolicy( + #region Public interface + + public Uri ServiceUri { get; } + public string User { get; } + + public PersonUser CreateLocalUser( + string userName, + string password, string description = null, - int? prohibitedPreviousPasswordsCount = null, - int? minLength = null, - int? maxLength = null, - int? maxIdenticalAdjacentCharacters = null, - int? minNumericCount = null, - int? minSpecialCharCount = null, - int? minAlphabeticCount = null, - int? minUppercaseCount = null, - int? minLowercaseCount = null, - int? passwordLifetimeDays = null) { + string emailAddress = null, + string firstName = null, + string lastName = null) + { - if (description != null || - prohibitedPreviousPasswordsCount != null || - minLength != null || - maxLength != null || - maxIdenticalAdjacentCharacters != null || - minNumericCount != null || - minSpecialCharCount != null || - minAlphabeticCount != null || - minUppercaseCount != null || - minLowercaseCount != null || - passwordLifetimeDays != null) { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); - var ssoAdminPasswordPolicy = new SsoAdminPasswordPolicy(); - ssoAdminPasswordPolicy.description = description; + // Invoke SSO Admin CreateLocalSolutionUser operation + var ssoPrincipalId = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.CreateLocalPersonUserAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + userName, + new SsoAdminPersonDetails + { + description = description, + emailAddress = emailAddress, + firstName = firstName, + lastName = lastName + }, + password)).Result; - if (passwordLifetimeDays != null) { - ssoAdminPasswordPolicy.passwordLifetimeDays = passwordLifetimeDays.Value; - ssoAdminPasswordPolicy.passwordLifetimeDaysSpecified = true; + return GetLocalUsers(ssoPrincipalId.name, ssoPrincipalId.domain, authorizedInvocationContext); + } + + private PersonUser GetLocalUsers(string userName, string domain, WsSecurityContext wsSecurityContext) + { + // Invoke SSO Admin FindPersonUserAsync operation + var personUser = wsSecurityContext. + InvokeOperation(() => + _ssoAdminBindingClient.FindPersonUserAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalDiscoveryService", + Value = "principalDiscoveryService" + }, + new SsoPrincipalId + { + name = userName, + domain = domain + })).Result; + return new PersonUser(this) + { + Name = personUser.id.name, + Domain = personUser.id.domain, + Description = personUser.details.description, + FirstName = personUser.details.firstName, + LastName = personUser.details.lastName, + EmailAddress = personUser.details.emailAddress, + Locked = personUser.locked, + Disabled = personUser.disabled + }; + } + + public IEnumerable GetLocalUsers(string searchString, string domain) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin FindPersonUsersAsync operation + var personUsers = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.FindPersonUsersAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalDiscoveryService", + Value = "principalDiscoveryService" + }, + new SsoAdminPrincipalDiscoveryServiceSearchCriteria + { + searchString = searchString, + domain = domain + }, + int.MaxValue)).Result.returnval; + + if (personUsers != null) + { + foreach (var personUser in personUsers) + { + yield return new PersonUser(this) + { + Name = personUser.id.name, + Domain = personUser.id.domain, + Description = personUser.details.description, + FirstName = personUser.details.firstName, + LastName = personUser.details.lastName, + EmailAddress = personUser.details.emailAddress, + Locked = personUser.locked, + Disabled = personUser.disabled + }; + } } - if (prohibitedPreviousPasswordsCount != null) { - ssoAdminPasswordPolicy.prohibitedPreviousPasswordsCount = prohibitedPreviousPasswordsCount.Value; + } + + public IEnumerable GetPersonUsersInGroup(string searchString, DataTypes.Group group) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin FindPersonUsersAsync operation + var personUsers = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.FindPersonUsersInGroupAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalDiscoveryService", + Value = "principalDiscoveryService" + }, + new SsoPrincipalId + { + name = group.Name, + domain = group.Domain + }, + searchString, + int.MaxValue)).Result.returnval; + + if (personUsers != null) + { + foreach (var personUser in personUsers) + { + yield return new PersonUser(this) + { + Name = personUser.id.name, + Domain = personUser.id.domain, + Description = personUser.details.description, + FirstName = personUser.details.firstName, + LastName = personUser.details.lastName, + EmailAddress = personUser.details.emailAddress, + Locked = personUser.locked, + Disabled = personUser.disabled + }; + } + } + } + + public void DeleteLocalUser( + PersonUser principal) + { + + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin DeleteLocalPrincipal operation + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.DeleteLocalPrincipalAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + principal.Name)); + } + + private DataTypes.Group FindGroup(string name, string domain, WsSecurityContext wsSecurityContext) + { + // Invoke SSO Admin FindGroupAsync operation + var group = wsSecurityContext. + InvokeOperation(() => + _ssoAdminBindingClient.FindGroupAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalDiscoveryService", + Value = "principalDiscoveryService" + }, + new SsoPrincipalId + { + name = name, + domain = domain + })).Result; + + return new DataTypes.Group(this) + { + Name = group.id.name, + Domain = group.id.domain, + Description = group.details.description + }; + } + + public IEnumerable GetGroupsInGroup(string searchString, DataTypes.Group group) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin FindGroupsInGroupResponse operation + var groups = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.FindGroupsInGroupAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalDiscoveryService", + Value = "principalDiscoveryService" + }, + new SsoPrincipalId + { + name = group.Name, + domain = group.Domain + }, + searchString, + int.MaxValue)).Result.returnval; + + if (groups != null) + { + foreach (var g in groups) + { + yield return new DataTypes.Group(this) + { + Name = g.id.name, + Domain = g.id.domain, + Description = g.details.description + }; + } + } + } + + public DataTypes.Group CreateLocalGroup(string name, string description) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin FindGroupsAsync operation + var ssoAdminGroup = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.CreateLocalGroupAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + name, + new SsoAdminGroupDetails + { + description = description + })).Result; + + if (ssoAdminGroup != null) + { + return FindGroup(ssoAdminGroup.name, ssoAdminGroup.domain, authorizedInvocationContext); + } + else + { + return null; + } + } + + public DataTypes.Group UpdateLocalGroup(DataTypes.Group group, string description) + { + if (description == null) { + description = string.Empty; } - // Update SsoAdminPasswordFormat if needed - if (minLength != null || + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin DeleteLocalPrincipal operation + var updatedGroup = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.UpdateLocalGroupDetailsAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + group.Name, + new SsoAdminGroupDetails + { + description = description + })).Result; + + if (updatedGroup != null) + { + return FindGroup(updatedGroup.name, updatedGroup.domain, authorizedInvocationContext); + } + else + { + return null; + } + } + + + public void RemoveLocalGroup(DataTypes.Group group) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin DeleteLocalPrincipal operation + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.DeleteLocalPrincipalAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + group.Name)); + } + + public IEnumerable GetGroups(string searchString, string domain) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin FindGroupsAsync operation + var ssoAdminGroups = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.FindGroupsAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalDiscoveryService", + Value = "principalDiscoveryService" + }, + new SsoAdminPrincipalDiscoveryServiceSearchCriteria + { + searchString = searchString, + domain = domain + }, + int.MaxValue)).Result.returnval; + + if (ssoAdminGroups != null) + { + foreach (var group in ssoAdminGroups) + { + yield return FindGroup(group.id.name, group.id.domain, authorizedInvocationContext); + } + } + } + + public bool AddPersonUserToGroup(PersonUser user, DataTypes.Group group) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin AddUserToLocalGroupAsync operation + return authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.AddUserToLocalGroupAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + new SsoPrincipalId + { + name = user.Name, + domain = user.Domain + }, + group.Name)).Result; + } + + public bool AddGroupToGroup(DataTypes.Group groupToAdd, DataTypes.Group destinationGroup) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin AddGroupToLocalGroupAsync operation + return authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.AddGroupToLocalGroupAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + new SsoPrincipalId + { + name = groupToAdd.Name, + domain = groupToAdd.Domain + }, + destinationGroup.Name)).Result; + } + + public bool RemovePersonUserFromGroup(PersonUser user, DataTypes.Group group) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin RemoveFromLocalGroupAsync operation + return authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.RemoveFromLocalGroupAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + new SsoPrincipalId + { + name = user.Name, + domain = user.Domain + }, + group.Name)).Result; + } + + public bool RemoveGroupFromGroup(DataTypes.Group groupToRemove, DataTypes.Group group) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin RemoveFromLocalGroupAsync operation + return authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.RemoveFromLocalGroupAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + new SsoPrincipalId + { + name = groupToRemove.Name, + domain = groupToRemove.Domain + }, + group.Name)).Result; + } + + public void ResetPersonUserPassword(PersonUser user, string newPassword) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin ResetLocalPersonUserPasswordAsync operation + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.ResetLocalPersonUserPasswordAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + user.Name, + newPassword)).Wait(); + } + + public void ResetSelfPersonUserPassword(SecureString newPassword) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin ResetLocalPersonUserPasswordAsync operation + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.ResetSelfLocalPersonUserPasswordAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + SecureStringToString(newPassword))).Wait(); + } + + public bool UnlockPersonUser(PersonUser user) + { + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin UnlockUserAccountAsync operation + return authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.UnlockUserAccountAsync( + new ManagedObjectReference + { + type = "SsoAdminPrincipalManagementService", + Value = "principalManagementService" + }, + new SsoPrincipalId + { + name = user.Name, + domain = user.Domain + })).Result; + } + + public PasswordPolicy GetPasswordPolicy() + { + PasswordPolicy result = null; + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin GetLocalPasswordPolicyAsync operation + var ssoAdminPasswordPolicy = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.GetLocalPasswordPolicyAsync( + new ManagedObjectReference + { + type = "SsoAdminPasswordPolicyService", + Value = "passwordPolicyService" + })).Result; + + if (ssoAdminPasswordPolicy != null) + { + result = new PasswordPolicy(this) + { + Description = ssoAdminPasswordPolicy.description, + ProhibitedPreviousPasswordsCount = ssoAdminPasswordPolicy.prohibitedPreviousPasswordsCount, + MinLength = ssoAdminPasswordPolicy.passwordFormat.lengthRestriction.minLength, + MaxLength = ssoAdminPasswordPolicy.passwordFormat.lengthRestriction.maxLength, + MaxIdenticalAdjacentCharacters = ssoAdminPasswordPolicy.passwordFormat.maxIdenticalAdjacentCharacters, + MinNumericCount = ssoAdminPasswordPolicy.passwordFormat.minNumericCount, + MinSpecialCharCount = ssoAdminPasswordPolicy.passwordFormat.minSpecialCharCount, + MinAlphabeticCount = ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minAlphabeticCount, + MinUppercaseCount = ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minUppercaseCount, + MinLowercaseCount = ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minLowercaseCount, + PasswordLifetimeDays = ssoAdminPasswordPolicy.passwordLifetimeDays + }; + } + + return result; + } + + public PasswordPolicy SetPasswordPolicy( + string description = null, + int? prohibitedPreviousPasswordsCount = null, + int? minLength = null, + int? maxLength = null, + int? maxIdenticalAdjacentCharacters = null, + int? minNumericCount = null, + int? minSpecialCharCount = null, + int? minAlphabeticCount = null, + int? minUppercaseCount = null, + int? minLowercaseCount = null, + int? passwordLifetimeDays = null) + { + + if (description != null || + prohibitedPreviousPasswordsCount != null || + minLength != null || maxLength != null || maxIdenticalAdjacentCharacters != null || minNumericCount != null || minSpecialCharCount != null || minAlphabeticCount != null || minUppercaseCount != null || - minLowercaseCount != null) { + minLowercaseCount != null || + passwordLifetimeDays != null) + { - ssoAdminPasswordPolicy.passwordFormat = new SsoAdminPasswordFormat(); + var ssoAdminPasswordPolicy = new SsoAdminPasswordPolicy(); + ssoAdminPasswordPolicy.description = description; - if (maxIdenticalAdjacentCharacters != null) { - ssoAdminPasswordPolicy.passwordFormat.maxIdenticalAdjacentCharacters = maxIdenticalAdjacentCharacters.Value; - } + if (passwordLifetimeDays != null) + { + ssoAdminPasswordPolicy.passwordLifetimeDays = passwordLifetimeDays.Value; + ssoAdminPasswordPolicy.passwordLifetimeDaysSpecified = true; + } - if (minNumericCount != null) { - ssoAdminPasswordPolicy.passwordFormat.minNumericCount = minNumericCount.Value; - } + if (prohibitedPreviousPasswordsCount != null) + { + ssoAdminPasswordPolicy.prohibitedPreviousPasswordsCount = prohibitedPreviousPasswordsCount.Value; + } - if (minSpecialCharCount != null) { - ssoAdminPasswordPolicy.passwordFormat.minSpecialCharCount = minSpecialCharCount.Value; - } + // Update SsoAdminPasswordFormat if needed + if (minLength != null || + maxLength != null || + maxIdenticalAdjacentCharacters != null || + minNumericCount != null || + minSpecialCharCount != null || + minAlphabeticCount != null || + minUppercaseCount != null || + minLowercaseCount != null) + { - // Update LengthRestriction if needed - if (minLength != null || - maxLength != null) { - ssoAdminPasswordPolicy.passwordFormat.lengthRestriction = new SsoAdminPasswordFormatLengthRestriction(); - if (maxLength != null) { - ssoAdminPasswordPolicy.passwordFormat.lengthRestriction.maxLength = maxLength.Value; - } - if (minLength != null) { - ssoAdminPasswordPolicy.passwordFormat.lengthRestriction.minLength = minLength.Value; - } - } + ssoAdminPasswordPolicy.passwordFormat = new SsoAdminPasswordFormat(); - // Update AlphabeticRestriction if needed - if (minAlphabeticCount != null || - minUppercaseCount != null || - minLowercaseCount != null) { - ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction = new SsoAdminPasswordFormatAlphabeticRestriction(); + if (maxIdenticalAdjacentCharacters != null) + { + ssoAdminPasswordPolicy.passwordFormat.maxIdenticalAdjacentCharacters = maxIdenticalAdjacentCharacters.Value; + } - if (minAlphabeticCount != null) { - ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minAlphabeticCount = minAlphabeticCount.Value; - } + if (minNumericCount != null) + { + ssoAdminPasswordPolicy.passwordFormat.minNumericCount = minNumericCount.Value; + } - if (minUppercaseCount != null) { - ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minUppercaseCount = minUppercaseCount.Value; - } + if (minSpecialCharCount != null) + { + ssoAdminPasswordPolicy.passwordFormat.minSpecialCharCount = minSpecialCharCount.Value; + } - if (minLowercaseCount != null) { - ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minLowercaseCount = minLowercaseCount.Value; - } - } + // Update LengthRestriction if needed + if (minLength != null || + maxLength != null) + { + ssoAdminPasswordPolicy.passwordFormat.lengthRestriction = new SsoAdminPasswordFormatLengthRestriction(); + if (maxLength != null) + { + ssoAdminPasswordPolicy.passwordFormat.lengthRestriction.maxLength = maxLength.Value; + } + if (minLength != null) + { + ssoAdminPasswordPolicy.passwordFormat.lengthRestriction.minLength = minLength.Value; + } + } + + // Update AlphabeticRestriction if needed + if (minAlphabeticCount != null || + minUppercaseCount != null || + minLowercaseCount != null) + { + ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction = new SsoAdminPasswordFormatAlphabeticRestriction(); + + if (minAlphabeticCount != null) + { + ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minAlphabeticCount = minAlphabeticCount.Value; + } + + if (minUppercaseCount != null) + { + ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minUppercaseCount = minUppercaseCount.Value; + } + + if (minLowercaseCount != null) + { + ssoAdminPasswordPolicy.passwordFormat.alphabeticRestriction.minLowercaseCount = minLowercaseCount.Value; + } + } + } + + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin UpdateLocalPasswordPolicyAsync operation + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.UpdateLocalPasswordPolicyAsync( + new ManagedObjectReference + { + type = "SsoAdminPasswordPolicyService", + Value = "passwordPolicyService" + }, + ssoAdminPasswordPolicy)).Wait(); } - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin UpdateLocalPasswordPolicyAsync operation - authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.UpdateLocalPasswordPolicyAsync( - new ManagedObjectReference { - type = "SsoAdminPasswordPolicyService", - Value = "passwordPolicyService" - }, - ssoAdminPasswordPolicy)).Wait(); - } - - return GetPasswordPolicy(); - } - - public LockoutPolicy GetLockoutPolicy() { - LockoutPolicy result = null; - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - // Invoke SSO Admin GetLockoutPolicyAsync operation - var ssoAdminLockoutPolicy = authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.GetLockoutPolicyAsync( - new ManagedObjectReference { - type = "SsoAdminLockoutPolicyService", - Value = "lockoutPolicyService" - })).Result; - - if (ssoAdminLockoutPolicy != null) { - result = new LockoutPolicy(this) { - Description = ssoAdminLockoutPolicy.description, - AutoUnlockIntervalSec = ssoAdminLockoutPolicy.autoUnlockIntervalSec, - FailedAttemptIntervalSec = ssoAdminLockoutPolicy.failedAttemptIntervalSec, - MaxFailedAttempts = ssoAdminLockoutPolicy.maxFailedAttempts - }; - } - - return result; - } - - public LockoutPolicy SetLockoutPolicy( - string description, - long? autoUnlockIntervalSec, - long? failedAttemptIntervalSec, - int? maxFailedAttempts) { - - if (description != null || - autoUnlockIntervalSec != null || - failedAttemptIntervalSec != null || - maxFailedAttempts != null) { - - var ssoAdminLockoutPolicy = new SsoAdminLockoutPolicy(); - - ssoAdminLockoutPolicy.description = description; - - if (autoUnlockIntervalSec != null) { - ssoAdminLockoutPolicy.autoUnlockIntervalSec = autoUnlockIntervalSec.Value; - } - - if (failedAttemptIntervalSec != null) { - ssoAdminLockoutPolicy.failedAttemptIntervalSec = failedAttemptIntervalSec.Value; - } - - if (maxFailedAttempts != null) { - ssoAdminLockoutPolicy.maxFailedAttempts = maxFailedAttempts.Value; - } + return GetPasswordPolicy(); + } + public LockoutPolicy GetLockoutPolicy() + { + LockoutPolicy result = null; // Create Authorization Invocation Context var authorizedInvocationContext = CreateAuthorizedInvocationContext(); // Invoke SSO Admin GetLockoutPolicyAsync operation - authorizedInvocationContext. + var ssoAdminLockoutPolicy = authorizedInvocationContext. InvokeOperation(() => - _ssoAdminBindingClient.UpdateLockoutPolicyAsync( - new ManagedObjectReference { - type = "SsoAdminLockoutPolicyService", - Value = "lockoutPolicyService" - }, - ssoAdminLockoutPolicy)).Wait(); + _ssoAdminBindingClient.GetLockoutPolicyAsync( + new ManagedObjectReference + { + type = "SsoAdminLockoutPolicyService", + Value = "lockoutPolicyService" + })).Result; - } - - return GetLockoutPolicy(); - } - - public TokenLifetime GetTokenLifetime() { - - // Create Authorization Invocation Context - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - var maxHoKTokenLifetime = authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.GetMaximumHoKTokenLifetimeAsync( - new ManagedObjectReference { - type = "SsoAdminConfigurationManagementService", - Value = "configurationManagementService" - })).Result; - - var maxBearerTokenLifetime = authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.GetMaximumBearerTokenLifetimeAsync( - new ManagedObjectReference { - type = "SsoAdminConfigurationManagementService", - Value = "configurationManagementService" - })).Result; - - return new TokenLifetime(this) { - MaxHoKTokenLifetime = maxHoKTokenLifetime, - MaxBearerTokenLifetime = maxBearerTokenLifetime - }; - } - - public TokenLifetime SetTokenLifetime( - long? maxHoKTokenLifetime, - long? maxBearerTokenLifetime) { - - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - if (maxHoKTokenLifetime != null) { - authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.SetMaximumHoKTokenLifetimeAsync( - new ManagedObjectReference { - type = "SsoAdminConfigurationManagementService", - Value = "configurationManagementService" - }, - maxHoKTokenLifetime.Value)).Wait(); - } - - if (maxBearerTokenLifetime != null) { - authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.SetMaximumBearerTokenLifetimeAsync( - new ManagedObjectReference { - type = "SsoAdminConfigurationManagementService", - Value = "configurationManagementService" - }, - maxBearerTokenLifetime.Value)).Wait(); - } - - - return GetTokenLifetime(); - } - - public void AddActiveDirectoryExternalDomain( - string domainName, - string domainAlias, - string friendlyName, - string primaryUrl, - string baseDNUsers, - string baseDNGroups, - string authenticationUserName, - string authenticationPassword, - string serverType) { - - string authenticationType = "password"; - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.AddExternalDomainAsync( - new ManagedObjectReference { - type = "SsoAdminDomainManagementService", - Value = "domainManagementService" - }, - serverType, - domainName, - domainAlias, - new SsoAdminExternalDomainDetails { - friendlyName = friendlyName, - primaryUrl = primaryUrl, - userBaseDn = baseDNUsers, - groupBaseDn = baseDNGroups - }, - authenticationType, - new SsoAdminDomainManagementServiceAuthenticationCredentails { - username = authenticationUserName, - password = authenticationPassword - })).Wait(); - } - - public void AddLdapIdentitySource( - string domainName, - string domainAlias, - string friendlyName, - string primaryUrl, - string failoverUrl, - string baseDNUsers, - string baseDNGroups, - string authenticationUserName, - string authenticationPassword, - string serverType, - X509Certificate2[] ldapCertificates) { - - string authenticationType = "password"; - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); - - var adminLdapIdentitySourceDetails = new SsoAdminLdapIdentitySourceDetails { - friendlyName = friendlyName, - primaryUrl = primaryUrl, - failoverUrl = failoverUrl, - userBaseDn = baseDNUsers, - groupBaseDn = baseDNGroups - }; - - if (ldapCertificates != null && ldapCertificates.Length > 0) { - var certificates = new List(); - foreach (var ldapCert in ldapCertificates) { - certificates.Add(Convert.ToBase64String(ldapCert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)); + if (ssoAdminLockoutPolicy != null) + { + result = new LockoutPolicy(this) + { + Description = ssoAdminLockoutPolicy.description, + AutoUnlockIntervalSec = ssoAdminLockoutPolicy.autoUnlockIntervalSec, + FailedAttemptIntervalSec = ssoAdminLockoutPolicy.failedAttemptIntervalSec, + MaxFailedAttempts = ssoAdminLockoutPolicy.maxFailedAttempts + }; } - if (certificates.Count > 0) { - adminLdapIdentitySourceDetails.certificates = certificates.ToArray(); - } - } + return result; + } + + public LockoutPolicy SetLockoutPolicy( + string description, + long? autoUnlockIntervalSec, + long? failedAttemptIntervalSec, + int? maxFailedAttempts) + { + + if (description != null || + autoUnlockIntervalSec != null || + failedAttemptIntervalSec != null || + maxFailedAttempts != null) + { + + var ssoAdminLockoutPolicy = new SsoAdminLockoutPolicy(); + + ssoAdminLockoutPolicy.description = description; + + if (autoUnlockIntervalSec != null) + { + ssoAdminLockoutPolicy.autoUnlockIntervalSec = autoUnlockIntervalSec.Value; + } + + if (failedAttemptIntervalSec != null) + { + ssoAdminLockoutPolicy.failedAttemptIntervalSec = failedAttemptIntervalSec.Value; + } + + if (maxFailedAttempts != null) + { + ssoAdminLockoutPolicy.maxFailedAttempts = maxFailedAttempts.Value; + } + + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + // Invoke SSO Admin GetLockoutPolicyAsync operation + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.UpdateLockoutPolicyAsync( + new ManagedObjectReference + { + type = "SsoAdminLockoutPolicyService", + Value = "lockoutPolicyService" + }, + ssoAdminLockoutPolicy)).Wait(); + + } + + return GetLockoutPolicy(); + } + + public TokenLifetime GetTokenLifetime() + { + + // Create Authorization Invocation Context + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + var maxHoKTokenLifetime = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.GetMaximumHoKTokenLifetimeAsync( + new ManagedObjectReference + { + type = "SsoAdminConfigurationManagementService", + Value = "configurationManagementService" + })).Result; + + var maxBearerTokenLifetime = authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.GetMaximumBearerTokenLifetimeAsync( + new ManagedObjectReference + { + type = "SsoAdminConfigurationManagementService", + Value = "configurationManagementService" + })).Result; + + return new TokenLifetime(this) + { + MaxHoKTokenLifetime = maxHoKTokenLifetime, + MaxBearerTokenLifetime = maxBearerTokenLifetime + }; + } + + public TokenLifetime SetTokenLifetime( + long? maxHoKTokenLifetime, + long? maxBearerTokenLifetime) + { + + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + if (maxHoKTokenLifetime != null) + { + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.SetMaximumHoKTokenLifetimeAsync( + new ManagedObjectReference + { + type = "SsoAdminConfigurationManagementService", + Value = "configurationManagementService" + }, + maxHoKTokenLifetime.Value)).Wait(); + } + + if (maxBearerTokenLifetime != null) + { + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.SetMaximumBearerTokenLifetimeAsync( + new ManagedObjectReference + { + type = "SsoAdminConfigurationManagementService", + Value = "configurationManagementService" + }, + maxBearerTokenLifetime.Value)).Wait(); + } + + + return GetTokenLifetime(); + } + + public void AddActiveDirectoryExternalDomain( + string domainName, + string domainAlias, + string friendlyName, + string primaryUrl, + string baseDNUsers, + string baseDNGroups, + string authenticationUserName, + string authenticationPassword, + string serverType) + { + + string authenticationType = "password"; + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); - try { authorizedInvocationContext. InvokeOperation(() => - _ssoAdminBindingClient.RegisterLdapAsync( - new ManagedObjectReference { - type = "SsoAdminIdentitySourceManagementService", - Value = "identitySourceManagementService" + _ssoAdminBindingClient.AddExternalDomainAsync( + new ManagedObjectReference + { + type = "SsoAdminDomainManagementService", + Value = "domainManagementService" }, serverType, domainName, domainAlias, - adminLdapIdentitySourceDetails, + new SsoAdminExternalDomainDetails + { + friendlyName = friendlyName, + primaryUrl = primaryUrl, + userBaseDn = baseDNUsers, + groupBaseDn = baseDNGroups + }, authenticationType, - new SsoAdminIdentitySourceManagementServiceAuthenticationCredentials { - username = authenticationUserName, - password = authenticationPassword + new SsoAdminDomainManagementServiceAuthenticationCredentails + { + username = authenticationUserName, + password = authenticationPassword })).Wait(); - } catch (AggregateException e) { - throw e.InnerException; - } - } + } - public void UpdateLdapIdentitySource( - string name, - string friendlyName, - string primaryUrl, - string failoverUrl, - string baseDNUsers, - string baseDNGroups, - X509Certificate2[] ldapCertificates) { - - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); + public void AddLdapIdentitySource( + string domainName, + string domainAlias, + string friendlyName, + string primaryUrl, + string failoverUrl, + string baseDNUsers, + string baseDNGroups, + string authenticationUserName, + string authenticationPassword, + string serverType, + X509Certificate2[] ldapCertificates) + { - var adminLdapIdentitySourceDetails = new SsoAdminLdapIdentitySourceDetails { - friendlyName = friendlyName, - primaryUrl = primaryUrl, - failoverUrl = failoverUrl, - userBaseDn = baseDNUsers, - groupBaseDn = baseDNGroups - }; + string authenticationType = "password"; + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); - if (ldapCertificates != null && ldapCertificates.Length > 0) { - var certificates = new List(); - foreach (var ldapCert in ldapCertificates) { - certificates.Add(Convert.ToBase64String(ldapCert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)); + var adminLdapIdentitySourceDetails = new SsoAdminLdapIdentitySourceDetails + { + friendlyName = friendlyName, + primaryUrl = primaryUrl, + failoverUrl = failoverUrl, + userBaseDn = baseDNUsers, + groupBaseDn = baseDNGroups + }; + + if (ldapCertificates != null && ldapCertificates.Length > 0) + { + var certificates = new List(); + foreach (var ldapCert in ldapCertificates) + { + certificates.Add(Convert.ToBase64String(ldapCert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)); + } + + if (certificates.Count > 0) + { + adminLdapIdentitySourceDetails.certificates = certificates.ToArray(); + } } - if (certificates.Count > 0) { - adminLdapIdentitySourceDetails.certificates = certificates.ToArray(); + try + { + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.RegisterLdapAsync( + new ManagedObjectReference + { + type = "SsoAdminIdentitySourceManagementService", + Value = "identitySourceManagementService" + }, + serverType, + domainName, + domainAlias, + adminLdapIdentitySourceDetails, + authenticationType, + new SsoAdminIdentitySourceManagementServiceAuthenticationCredentials + { + username = authenticationUserName, + password = authenticationPassword + })).Wait(); } - } + catch (AggregateException e) + { + throw e.InnerException; + } + } - try { - authorizedInvocationContext. + public void UpdateLdapIdentitySource( + string name, + string friendlyName, + string primaryUrl, + string failoverUrl, + string baseDNUsers, + string baseDNGroups, + X509Certificate2[] ldapCertificates) + { + + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + var adminLdapIdentitySourceDetails = new SsoAdminLdapIdentitySourceDetails + { + friendlyName = friendlyName, + primaryUrl = primaryUrl, + failoverUrl = failoverUrl, + userBaseDn = baseDNUsers, + groupBaseDn = baseDNGroups + }; + + if (ldapCertificates != null && ldapCertificates.Length > 0) + { + var certificates = new List(); + foreach (var ldapCert in ldapCertificates) + { + certificates.Add(Convert.ToBase64String(ldapCert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)); + } + + if (certificates.Count > 0) + { + adminLdapIdentitySourceDetails.certificates = certificates.ToArray(); + } + } + + try + { + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.UpdateLdapAsync( + new ManagedObjectReference + { + type = "SsoAdminIdentitySourceManagementService", + Value = "identitySourceManagementService" + }, + name, + adminLdapIdentitySourceDetails)).Wait(); + } + catch (AggregateException e) + { + throw e.InnerException; + } + } + + public IEnumerable GetDomains() + { + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); + + var domains = authorizedInvocationContext. InvokeOperation(() => - _ssoAdminBindingClient.UpdateLdapAsync( - new ManagedObjectReference { - type = "SsoAdminIdentitySourceManagementService", - Value = "identitySourceManagementService" - }, - name, - adminLdapIdentitySourceDetails)).Wait(); - } catch (AggregateException e) { - throw e.InnerException; - } - } + _ssoAdminBindingClient.GetDomainsAsync( + new ManagedObjectReference + { + type = "SsoAdminDomainManagementService", + Value = "domainManagementService" + })).Result; - public IEnumerable GetDomains() { - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); + if (domains != null) + { + var localos = new LocalOSIdentitySource(); + localos.Name = domains.localOSDomainName; + yield return localos; - var domains = authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.GetDomainsAsync( - new ManagedObjectReference { - type = "SsoAdminDomainManagementService", - Value = "domainManagementService" - })).Result; + var system = new SystemIdentitySource(); + system.Name = domains.systemDomainName; + yield return system; - if (domains != null) { - var localos = new LocalOSIdentitySource(); - localos.Name = domains.localOSDomainName; - yield return localos; - - var system = new SystemIdentitySource(); - system.Name = domains.systemDomainName; - yield return system; - - if (domains.externalDomains != null && domains.externalDomains.Length > 0) { - foreach (var externalDomain in domains.externalDomains) { - var extIdentitySource = new ActiveDirectoryIdentitySource(); - extIdentitySource.Name = externalDomain.name; - extIdentitySource.Alias = externalDomain.alias; - extIdentitySource.Type = externalDomain.type; - extIdentitySource.AuthenticationType = externalDomain.authenticationDetails?.authenticationType; - extIdentitySource.AuthenticationUsername = externalDomain.authenticationDetails?.username; - extIdentitySource.FriendlyName = externalDomain.details?.friendlyName; - extIdentitySource.PrimaryUrl = externalDomain.details?.primaryUrl; - extIdentitySource.FailoverUrl = externalDomain.details?.failoverUrl; - extIdentitySource.GroupBaseDN = externalDomain.details?.groupBaseDn; - extIdentitySource.UserBaseDN = externalDomain.details?.userBaseDn; - yield return extIdentitySource; - } + if (domains.externalDomains != null && domains.externalDomains.Length > 0) + { + foreach (var externalDomain in domains.externalDomains) + { + var extIdentitySource = new ActiveDirectoryIdentitySource(); + extIdentitySource.Name = externalDomain.name; + extIdentitySource.Alias = externalDomain.alias; + extIdentitySource.Type = externalDomain.type; + extIdentitySource.AuthenticationType = externalDomain.authenticationDetails?.authenticationType; + extIdentitySource.AuthenticationUsername = externalDomain.authenticationDetails?.username; + extIdentitySource.FriendlyName = externalDomain.details?.friendlyName; + extIdentitySource.PrimaryUrl = externalDomain.details?.primaryUrl; + extIdentitySource.FailoverUrl = externalDomain.details?.failoverUrl; + extIdentitySource.GroupBaseDN = externalDomain.details?.groupBaseDn; + extIdentitySource.UserBaseDN = externalDomain.details?.userBaseDn; + yield return extIdentitySource; + } + } } - } - } + } - public void DeleteDomain(string name) { + public void DeleteDomain(string name) + { - var authorizedInvocationContext = - CreateAuthorizedInvocationContext(); + var authorizedInvocationContext = + CreateAuthorizedInvocationContext(); - try { - authorizedInvocationContext. - InvokeOperation(() => - _ssoAdminBindingClient.DeleteAsync( - new ManagedObjectReference { - type = "SsoAdminIdentitySourceManagementService", - Value = "identitySourceManagementService" - }, - name)).Wait(); - } catch (AggregateException e) { - throw e.InnerException; - } - } - #endregion - } + try + { + authorizedInvocationContext. + InvokeOperation(() => + _ssoAdminBindingClient.DeleteAsync( + new ManagedObjectReference + { + type = "SsoAdminIdentitySourceManagementService", + Value = "identitySourceManagementService" + }, + name)).Wait(); + } + catch (AggregateException e) + { + throw e.InnerException; + } + } + #endregion + } } diff --git a/Modules/VMware.vSphere.SsoAdmin/src/test/ConnectDisconnect.Tests.ps1 b/Modules/VMware.vSphere.SsoAdmin/src/test/ConnectDisconnect.Tests.ps1 index 7a69809..222c610 100644 --- a/Modules/VMware.vSphere.SsoAdmin/src/test/ConnectDisconnect.Tests.ps1 +++ b/Modules/VMware.vSphere.SsoAdmin/src/test/ConnectDisconnect.Tests.ps1 @@ -65,7 +65,7 @@ Describe "Connect-SsoAdminServer and Disconnect-SsoAdminServer Tests" { -User $User ` -Password $Password ` -ErrorAction Stop } | ` - Should -Throw "The SSL connection could not be established, see inner exception." + Should -Throw "*The SSL connection could not be established, see inner exception.*" } } diff --git a/Modules/VMware.vSphere.SsoAdmin/src/test/Group.Tests.ps1 b/Modules/VMware.vSphere.SsoAdmin/src/test/Group.Tests.ps1 index 7eda354..311673a 100644 --- a/Modules/VMware.vSphere.SsoAdmin/src/test/Group.Tests.ps1 +++ b/Modules/VMware.vSphere.SsoAdmin/src/test/Group.Tests.ps1 @@ -20,57 +20,203 @@ param( $modulePath = Join-Path (Split-Path $PSScriptRoot | Split-Path) "VMware.vSphere.SsoAdmin.psd1" Import-Module $modulePath -Describe "Get-SsoGroup Tests" { - BeforeEach { - Connect-SsoAdminServer ` - -Server $VcAddress ` - -User $User ` - -Password $Password ` - -SkipCertificateCheck - } +Describe "SsoGroup Tests" { + BeforeEach { + Connect-SsoAdminServer ` + -Server $VcAddress ` + -User $User ` + -Password $Password ` + -SkipCertificateCheck - AfterEach { - $connectionsToCleanup = $global:DefaultSsoAdminServers.ToArray() - foreach ($connection in $connectionsToCleanup) { - Disconnect-SsoAdminServer -Server $connection - } - } + $script:testGroupsToDelete = @() + $script:testUsersToDelete = @() + } - Context "Get-SsoGroup" { - It 'Gets groups without filters' { - # Act - $actual = Get-SsoGroup + AfterEach { - # Assert - $actual | Should -Not -Be $null - $actual.Count | Should -BeGreaterThan 0 - $actual[0].Name | Should -Not -Be $null - $actual[0].Domain | Should -Be 'localos' - } + foreach ($group in $script:testGroupsToDelete) { + Remove-SsoGroup -Group $group + } - It 'Gets groups for default domain' { - # Arrange - $newUserName = "NewUser1" - $password = '$tr0NG_TestPa$$w0rd' + foreach ($user in $script:testUsersToDelete) { + Remove-SsoPersonUser -User $user + } - ## Create Person User to determine default domain name - ## Person Users are created in the default domain - $newPersonUser = New-SsoPersonUser ` - -UserName $newUserName ` - -Password $password + $connectionsToCleanup = $global:DefaultSsoAdminServers.ToArray() + foreach ($connection in $connectionsToCleanup) { + Disconnect-SsoAdminServer -Server $connection + } + } - # Act - $actual = Get-SsoGroup ` - -Domain $newPersonUser.Domain + Context "Get-SsoGroup" { + It 'Gets groups without filters' { + # Act + $actual = Get-SsoGroup - # Assert - $actual | Should -Not -Be $null - $actual.Count | Should -BeGreaterThan 0 - $actual[0].Name | Should -Not -Be $null - $actual[0].Domain | Should -Be $newPersonUser.Domain + # Assert + $actual | Should -Not -Be $null + $actual.Count | Should -BeGreaterThan 0 + $actual[0].Name | Should -Not -Be $null + $actual[0].Domain | Should -Be 'localos' + } - # Cleanup - Remove-SsoPersonUser -User $newPersonUser - } - } + It 'Gets groups for default domain' { + # Arrange + $newUserName = "NewUser1" + $password = '$tr0NG_TestPa$$w0rd' + + ## Create Person User to determine default domain name + ## Person Users are created in the default domain + $newPersonUser = New-SsoPersonUser ` + -UserName $newUserName ` + -Password $password + + # Act + $actual = Get-SsoGroup ` + -Domain $newPersonUser.Domain + + # Assert + $actual | Should -Not -Be $null + $actual.Count | Should -BeGreaterThan 0 + $actual[0].Name | Should -Not -Be $null + $actual[0].Domain | Should -Be $newPersonUser.Domain + + # Cleanup + Remove-SsoPersonUser -User $newPersonUser + } + } + + Context "New-SsoGroup" { + It 'Should create SsoGroup specifying only the name of the group' { + # Arrange + $expectedName = 'TestGroup1' + + # Act + $actual = New-SsoGroup -Name $expectedName + + # Assert + $actual | Should -Not -Be $null + $script:testGroupsToDelete += $actual + $actual.Name | Should -Be $expectedName + $actual.Domain | Should -Be 'vsphere.local' + $actual.Description | Should -Be ([string]::Empty) + } + + It 'Should create SsoGroup specifying name and description' { + # Arrange + $expectedName = 'TestGroup2' + $expectedDescription = 'Test Description 2' + + # Act + $actual = New-SsoGroup -Name $expectedName -Description $expectedDescription + + # Assert + $actual | Should -Not -Be $null + $script:testGroupsToDelete += $actual + $actual.Name | Should -Be $expectedName + $actual.Domain | Should -Be 'vsphere.local' + $actual.Description | Should -Be $expectedDescription + } + } + + Context "Remove-SsoGroup" { + It 'Should remove SsoGroup' { + # Arrange + $groupName = 'TestGroup3' + $groupToRemove = New-SsoGroup -Name $groupName + + # Act + $groupToRemove | Remove-SsoGroup + + # Assert + Get-SsoGroup -Name $groupName -Domain 'vsphere.local' | Should -Be $null + } + } + + Context "Set-SsoGroup" { + It 'Should update a SsoGroup with new description' { + # Arrange + $groupName = 'TestGroup4' + $expectedDescription = 'Test Description 4' + $groupToUpdate = New-SsoGroup -Name $groupName + + # Act + $actual = $groupToUpdate | Set-SsoGroup -Description $expectedDescription + + # Assert + $actual | Should -Not -Be $null + $script:testGroupsToDelete += $actual + $actual.Description | Should -Be $expectedDescription + } + } + + Context "Add-GroupToSsoGroup" { + It 'Should add a newly created SsoGroup to another SsoGroup' { + # Arrange + $expectedGroup = New-SsoGroup -Name 'TestGroup5' + $script:testGroupsToDelete += $expectedGroup + + $targetGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' + + # Act + $expectedGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup + + # Assert + $actualGroups = $targetGroup | Get-SsoGroup + $actualGroups | Where-Object { $_.Name -eq $expectedGroup.Name} | Should -Not -Be $null + } + } + + Context "Remove-GroupFromSsoGroup" { + It 'Should remove a SsoGroup from another SsoGroup' { + # Arrange + $expectedGroup = New-SsoGroup -Name 'TestGroup6' + $script:testGroupsToDelete += $expectedGroup + + $targetGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' + $expectedGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup + + # Act + $expectedGroup | Remove-GroupFromSsoGroup -TargetGroup $targetGroup + + # Assert + $actualGroups = $targetGroup | Get-SsoGroup + $actualGroups | Where-Object { $_.Name -eq $expectedGroup.Name} | Should -Be $null + } + } + + Context "Add-UserToSsoGroup" { + It 'Should add a newly created PersonUser to SsoGroup' { + # Arrange + $expectedUser = New-SsoPersonUser -User 'GroupTestUser1' -Password 'MyStrongPa$$w0rd' + $script:testUsersToDelete += $expectedUser + + $targetGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' + + # Act + $expectedUser | Add-UserToSsoGroup -TargetGroup $targetGroup + + # Assert + $actualUsers = $targetGroup | Get-SsoPersonUser + $actualUsers | Where-Object { $_.Name -eq $expectedUser.Name} | Should -Not -Be $null + } + } + + Context "Remove-GroupFromSsoGroup" { + It 'Should remove a SsoGroup from another SsoGroup' { + # Arrange + $expectedUser = New-SsoPersonUser -User 'GroupTestUser2' -Password 'MyStrongPa$$w0rd' + $script:testUsersToDelete += $expectedUser + + $targetGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' + $expectedUser | Add-UserToSsoGroup -TargetGroup $targetGroup + + # Act + $expectedUser | Remove-UserFromSsoGroup -TargetGroup $targetGroup + + # Assert + $actualUsers = $targetGroup | Get-SsoPersonUser + $actualUsers | Where-Object { $_.Name -eq $expectedUser.Name} | Should -Be $null + } + } } \ No newline at end of file