Win Server ADGroup Security Access Control - remote-access

I would like to create a user on Win Server 2022, without admin rights, who can modify the content of administrator groups.
I have added this user a full control over these groups with a PS script, but after a while, Windows automatically removes my user from there.
Is threre a way to stay there permanently?
$PWord = ConvertTo-SecureString -String "# ... #" -AsPlainText -Force
New-ADUser -Name "creator" -SamAccountName "creator" -UserPrincipalName "creator" -DisplayName "creator" -Enabled $true -AccountPassword $PWord -ChangePasswordAtLogon $false -PasswordNeverExpires $true
Add-AdGroupMember -Identity "S-1-5-32-548" -Members "creator"
Add-AdGroupMember -Identity "S-1-5-32-580" -Members "creator"
New-ADOrganizationalUnit -Name "MyDomain"
enable-psremoting -Force
$sid = (Get-ADDomain -Server 127.0.0.1 | Select DomainSID | ft -HideTableHeaders | out-string).Trim()
$groups = #("S-1-5-32-544",$($sid+"-512"),$($sid+"-518"),$($sid+"-519"),$($sid+"-520"))
$colRights = [System.DirectoryServices.ActiveDirectoryRights]"GenericAll"
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objUser = New-Object System.Security.Principal.NTAccount("creator")
$objACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule ($objUser, $colRights, $objType)
foreach($group in $groups)
{
$objACL=Get-ACL "AD:$((get-adgroup $group).DistinguishedName)"
$objACL.AddAccessRule($objACE)
Set-ACL "AD:$((get-adgroup $group).DistinguishedName)" $objACL
}
$OU = (Get-ADOrganizationalUnit -Filter {Name -eq 'MyDomain'}).DistinguishedName
$ouACL=Get-ACL "AD:$OU"
$ouACL.AddAccessRule($objACE)
Set-ACL "AD:$OU" $ouACL

Related

PowerShell - How do I bulk upload Certificates to an Azure App Registration Certificate store?

As you can see from the code below I can upload on certificate at a time, but the problem is it wipes out all of the existing certificates when doing so.
$Tenant_ID = '00000000-0000-0000-0000-000000000000'
$Subscription_ID = '00000000-0000-0000-0000-000000000000'
$Azure_PassWord = (Get-StoredCredential -Target 'Domain' -Type Generic -AsCredentialObject).Password
$UserName = "$($env:USERNAME)#Google.com"
$EncryptedPassword = ConvertTo-SecureString $Azure_PassWord -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PsCredential($UserName,$EncryptedPassword)
$AzureConnection = (Connect-AzAccount -Credential $Credential -Tenant $Tenant_ID -Subscription $Subscription_ID -WarningAction 'Ignore').context
$AzureContext = (Set-AzContext -SubscriptionName $Subscription_ID -DefaultProfile $AzureConnection)
$Application_ID = '00000000-0000-0000-0000-000000000000'
$PFX_FileName = "Azure_Dev_V2"
$Cert_Password = "123456"
$Cert_Password = ConvertTo-SecureString -String $Cert_Password -Force -AsPlainText
$CurrentDate = Get-Date
$EndDate = $CurrentDate.AddYears(10)
$certificatePath = "C:\FilePath\Certificates\Certs\$($PFX_FileName).pfx" # OR Get-ChildItem -Path cert:\localmachine\my\$($Certificate_Thumbprint)
$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2($certificatePath, $Cert_Password)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
$Azure_App_Registration = Get-AzADApplication -ApplicationId $Application_ID -DefaultProfile $AzureContext
New-AzADAppCredential -ApplicationObject $Azure_App_Registration -CertValue $keyValue -EndDate $EndDate -StartDate $CurrentDate
Connect-AzAccount -Subscription $Subscription_ID -ApplicationId $Azure_App_Registration.AppId -Tenant $Tenant_ID -CertificateThumbprint $cert.Thumbprint | Out-Null
Get-AzADAppCredential -ApplicationId $Azure_App_Registration.AppId | Where-Object {$_.DisplayName -match "CN=Azure_Dev_V2"}
In the Azure portal multiple certificates can be uploaded manually, and they will not delete the existing certificates.
EDIT: If bulk upload is not possible then how would I go about making sure the existing certificates that are in the Azure AD App Registration cert store do not get deleted ?
Thanks in Advance.

How to activate Privileged Access Groups using Powershell?

I am trying to activate my privileged access groups using powershell however so far unable to do so. All the examples either in MS Docs site or google search only have examples regarding instruction to activate roles using powershell for PIM.
Has anyone been successful or have an idea how to get privileged access groups activated using powershell?
Here is what i tried:
#variables
$upn = ""
$tenantId = ""
$reason = "Test"
$groupId = "" #privileged access groups Id retrieved from Azure Portal > Groups > <group which has roles>
#MFA setup
if(!(Get-Module | Where-Object {$_.Name -eq 'PowerShellGet' -and $_.Version -ge '2.2.4.1'})) { Install-Module PowerShellGet -Force }
if(!(Get-Package msal.ps)) { Install-Package msal.ps }
# Get token for MS Graph by prompting for MFA
$MsResponse = Get-MSALToken -Scopes #("https://graph.microsoft.com/.default") -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Authority "https://login.microsoftonline.com/common" -Interactive -ExtraQueryParameters #{claims='{"access_token" : {"amr": { "values": ["mfa"] }}}'}
# Get token for AAD Graph
$AadResponse = Get-MSALToken -Scopes #("https://graph.windows.net/.default") -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Authority "https://login.microsoftonline.com/common"
Connect-AzureAD -AadAccessToken $AadResponse.AccessToken -MsAccessToken $MsResponse.AccessToken -AccountId: $upn -tenantId: $tenantId
$roleDefinitionCollection = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId $resource.Id -Filter "subjectId eq '$grouipId'"
#set schedule
$schedule = New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule
$schedule.Type = "Once"
$schedule.StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$schedule.endDateTime = (Get-Date).AddHours($activateTime).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$subject = Get-AzureADUser -Filter "userPrincipalName eq '$upn'"
foreach ($roleDefinition in $roleDefinitionCollection) {
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRoles -Schedule $schedule -ResourceId $resource.Id -RoleDefinitionId $roleDefinition.RoleDefinitionId -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason $reason
}
This returns error message:
Open-AzureADMSPrivilegedRoleAssignmentRequest : Error occurred while executing OpenAzureADMSPrivilegedRoleAssignmentRequest
Code: RoleAssignmentDoesNotExist
Message: The Role assignment does not exist.
InnerError:
RequestId: b6e750c4-acf4-4032-84ea-29d74fbc53ac
DateTimeStamp: Fri, 25 Mar 2022 19:00:10 GMT
HttpStatusCode: NotFound
HttpStatusDescription: Not Found
HttpResponseStatus: Completed
At line:2 char:5
+ Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRole ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Open-AzureADMSP...signmentRequest], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.MSGraphBeta.Client.ApiException,Microsoft.Open.MSGraphBeta.PowerShell.OpenAzureADMSPrivilegedRoleAssignmentRequest
These were some of the sites that i referred: (all only have example to activate the role)
http://www.anujchaudhary.com/2020/02/connect-to-azure-ad-powershell-with-mfa.html
https://learn.microsoft.com/en-us/azure/active-directory/privileged-identity-management/powershell-for-azure-ad-roles#activate-a-role-assignment
https://www.youtube.com/watch?v=OVfwO8_eDjs
Edit: Sorry I misread some part of your question actually.
In fact, you should adapt the provider id to "aadGroups" in order to use the group features.
This should help you to be on track depending on your environment:
$groupId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$upn="myyupn#domain.com"
Connect-AzureAD
$resource = Get-AzureADMSPrivilegedResource -ProviderId aadGroups
$subject = Get-AzureADUser -Filter "userPrincipalName eq '$upn'"
# here you will require some additionnal filtering depending on your environment
$roleDefinitionCollection = Get-AzureADMSPrivilegedRoleDefinition -ProviderId "aadGroups" -ResourceId $groupId
#this works only when pimed in my case:
#$roleDefinitionCollection = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadGroups" -ResourceId $resource.id -Filter "ResourceId eq '$groupId' and AssignmentState eq 'Eligible'"
$reason = "test"
foreach ($roleDefinition in $roleDefinitionCollection) {
$schedule = New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule
$schedule.Type = "Once"
$schedule.Duration="PT1H"
$schedule.StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId "aadGroups" -Schedule $schedule -ResourceId $groupId -RoleDefinitionId $roleDefinition.id -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason $reason
}
When you try to assign the Role, it will be
You Can't be assigned for a duration of less than five minutes.
You Can't be removed within five minutes of it being assigned
Here is your script, you need to wait for 5 minutes for every iteration to create a Group Role Assignment
foreach ($roleDefinition in $roleDefinitionCollection) {
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRoles -Schedule $schedule -ResourceId $resource.Id -RoleDefinitionId $roleDefinition.RoleDefinitionId -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason $reason
# wait for 5 minutes
Start-Sleep -s 300
}
Refer here for more information

Exporting Group Types from Azure AD Powershell

I am trying to export all Azure AD groups, their owners, description, email and its group type. Such as Office 365, Security or Distrubution. I have managed to export everything correctly into a .csv except the group type. Get-AzureADGroup will return only "Group" and I can't get any results from get-msolgroup -grouptype.
Script I have been using:
$array = #()
$Properties=#{}
$Properties.add("GroupDisplayName","1")
$Properties.add("OwnerObjectId","2")
$Properties.add("OwnerObjectType","3")
$Properties.add("OwnerUserType","4")
$Properties.add("OwnerUserPrincipalName","5")
$Properties.add("GroupDescription","6")
$Properties.add("Email","7")
$Properties.add("GroupTypes","8")
$groups = Get-AzureADGroup -All $true
$GroupType = Get-MsolGroup -Grouptype
Foreach($group in $groups){
$Owners = Get-AzureADGroupOwner -ObjectId $group.ObjectId -All $true
$Properties.GroupDisplayName=$group.DisplayName
$Properties.GroupDescription=$group.description
$Properties.Email=$group.mail
$Properties.GroupTypes=$group.GroupType
if($Owners -ne $null){
# group has owner
Foreach($Owner in $Owners){
$Properties.OwnerObjectId=$Owner.ObjectId
$Properties.OwnerObjectType=$Owner.ObjectType
$Properties.OwnerUserType=$Owner.UserType
$Properties.OwnerUserPrincipalName=$Owner.UserPrincipalName
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
else{
#group has no owner
$Properties.OwnerObjectId=$null
$Properties.OwnerObjectType=$null
$Properties.OwnerUserType=$null
$Properties.OwnerUserPrincipalName=$null
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
$array | export-csv -Path C:\scripts\Owners13.csv -NoTypeInformation -Encoding UTF8
According to my research, the command Get-MsolGroup is a command of Azure AD V1 module : MSOnline. But the other commands you use are the command of Azure AD V2 module: AzureAD. They are in different modules. So if you want to use the command Get-MsolGroup, you need to run the command Connect-MsolService at frist.
For example:
Connect-MsolService
Get-MsolGroup -all | Select-Object DisplayName, GroupType
Besides, if you just want to use AzureAD module to get group type, we can use the command Get-AzureADMSGroup to get it. But if we use the command, we need to make some judgments by the response's properties. For more details, please refer to the document
For example
Connect-AzureAD
Get-AzureADMSGroup -All $true | Select-Object DisplayName, GroupTypes,MailEnabled, SecurityEnabled
Update
You can use the following script to implement your need.
connect-AzureAD
$array = #()
$Properties=#{}
$Properties.add("GroupDisplayName","1")
$Properties.add("OwnerObjectId","2")
$Properties.add("OwnerObjectType","3")
$Properties.add("OwnerUserType","4")
$Properties.add("OwnerUserPrincipalName","5")
$Properties.add("GroupDescription","6")
$Properties.add("Email","7")
$Properties.add("GroupTypes","8")
$groups = Get-AzureADGroup -All $true
Foreach($group in $groups){
$Owners = Get-AzureADGroupOwner -ObjectId $group.ObjectId -All $true
$Properties.GroupDisplayName=$group.DisplayName
$Properties.GroupDescription=$group.description
$Properties.Email=$group.mail
$result=Get-AzureADMSGroup -Id $group.ObjectId | Select-Object GroupTypes,MailEnabled, SecurityEnabled, DisplayName
If($result.GroupTypes -contains "Unified"){
$Properties.GroupTypes="O365"
}
elseif($result.SecurityEnabled ){
$Properties.GroupTypes="Security"
}
else{
$Properties.GroupTypes="Distrubution"
}
if($Owners -ne $null){
# group has owner
Foreach($Owner in $Owners){
$Properties.OwnerObjectId=$Owner.ObjectId
$Properties.OwnerObjectType=$Owner.ObjectType
$Properties.OwnerUserType=$Owner.UserType
$Properties.OwnerUserPrincipalName=$Owner.UserPrincipalName
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
else{
#group has no owner
$Properties.OwnerObjectId=$null
$Properties.OwnerObjectType=$null
$Properties.OwnerUserType=$null
$Properties.OwnerUserPrincipalName=$null
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
$array | export-csv -Path E:\test.csv -Encoding UTF8 -NoTypeInformation

Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials

While logging into the Azure account through powershell, I am getting the error -
Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials.
I need to understand when this error comes?
[string]$TenantID,
[string]$ApplicationID,
[string]$SecretKey,
[string]$ProcessInstanceID,
[string]$Endpoint
)
$securePassword = ConvertTo-SecureString -String $SecretKey -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($ApplicationID, $securePassword)
$profilePath = "D:\" + $ProcessInstanceID + "_azureProfile.json"
Clear-AzureRmContext -Scope Process
$azureok = $null
while ($azureok -eq $null) {
if($Endpoint -match "china"){
Connect-AzureRmAccount -ServicePrincipal -TenantId $TenantID -Credential $cred -Environment AzureChinaCloud -ea silentlycontinue -wa silentlycontinue -ev errorvar | out-null
}
else{
Connect-AzureRmAccount -ServicePrincipal -TenantId $TenantID -Credential $cred -ea silentlycontinue -wa silentlycontinue -ev errorvar | out-null
}
if ($errorvar.exception -ne $null) {
if ($errorvar.exception.message -eq "An error occurred while sending the request.") {
Start-sleep -s 10
$error.clear()
} else {
break
}
} else {
$azureok = $true
}
}
Save-AzureRmContext -Path $profilePath ````
Error message -
Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials.

How to deny Windows Credential Password Prompt everytime when operate remote windows service in powershell?

Below is my code:
$s = Get-WmiObject -computer 10.10.zz.zz Win32_Service -Filter "Name='XXX'" -credential (Get-Credential XXXXXX\fanwx)
$s.stopservice()
copy-item D:\.....\aaa.exe -destination \\10.10.zz.zz\c$\vvv\
copy-item D:\.....\aaa.pdb -destination \\10.10.zz.zz\c$\vvv\
$s.startservice()
everytime executed, will be prompted enter the password of the remote server. Is there a way allowed me only enter once in powershell OR read the credential in Credential Manager?
Thanks.
Just start by
$cred = Get-Credential "XXXXXX\fanwx"
and after :
$s = Get-WmiObject -computer 10.10.zz.zz Win32_Service -Filter "Name='XXX'" -credential $cred
You can put the password on the disk :
PS > $cred.Password | ConvertFrom-SecureString | Set-Content c:\temp\password.txt
And retreive it with :
$password = Get-Content c:\temp\password.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PsCredential "UserName",$password

Resources