what is the equivalent "az ad sp create-for-rbac" in powershell az - azure-powershell

What is the equivalent of az command in powershell
az ad sp create-for-rbac --query "{ client_id: appId, client_secret: password, tenant_id: tenant }"
What extra parameters should I add to New-AzADServicePrincipal
az ad sp create-for-rbac Create a service principal and configure its
access to Azure resources.
I would like to do the same with powershell az command

If you want to create an Azure AD service principle by command : New-AzADServicePrincipal and get its client id, client secret and tenant id as cli command replies , try command below :
$sp = New-AzADServicePrincipal
$clientsec = [System.Net.NetworkCredential]::new("", $sp.Secret).Password
$tenantID = (get-aztenant).Id
$jsonresp =
#{client_id=$sp.ApplicationId
client_secret=$clientsec
tenant_id=$tenantID}
$jsonresp | ConvertTo-Json
Result :

The New-AzADSecurityPrincipal cmdlet has changed. Here's an updated version of the previous answer:
$sp = New-AzADServicePrincipal
$json = #{
client_id = $sp.AppId
client_secret = $sp.PasswordCredentials.SecretText
tenant_id = (Get-AzTenant).Id
} | ConvertTo-Json

Related

HashiCorp Vault AppRole based authentication Unwrap secret_id got permission denied

I am using this code as an example to use AppRole based authentification to Vault. For the secret_id I wanna use an wrapped token to be more secure
import unittest
from hvac import Client
URL = "https://p.vault.myfine-company.de"
JENKINS_TOKEN = "mylovelytoken"
def test_ci_startup(self):
# Jenkins authentifies with token as secure instance
jenkins_client = Client(url=URL, token=JENKINS_TOKEN)
# fetch the role_id and stores this somewhere in the image of the app
resp = jenkins_client.auth.approle.read_role_id(role_name='workshop')
role_id = resp["data"]["role_id"]
# get a wrapped secret_id and passes this to the starting app
result = jenkins_client.write(path='auth/approle/role/workshop/secret-id',wrap_ttl="2s")
unwrap_token = result['wrap_info']['token']
# No the app comes in place
app_client = Client(url=URL) # , token=JENKINS_TOKEN)
# unwrap the secret_id
unwrap_response = app_client.sys.unwrap(unwrap_token) # !!! Here I get permission denied
secret_id = unwrap_response['data']['secret_id']
# use role_id and secret_id to login
login_result = app_client.auth.approle.login(role_id=role_id, secret_id=secret_id)
client_token = login_result['auth']['client_token']
# Read the database credential
read_response = app_client.secrets.kv.v2.read_secret_version(path='test/webapp')
self.assertEqual("users", read_response['data']['data']['db_name'])
return
Unfortunatly when try to unwrap the secret_id with app_client.sys.unwrap(unwrap_token) there is an 403 "permission denied" When I use the app_client-Connection with app_client = Client(url=URL), token=JENKINS_TOKEN) everything works fine. But this of course this not the way the AppRole based authentication should be used. All this is bases on the following Tutorials and Best Practices :
https://developer.hashicorp.com/vault/tutorials/recommended-patterns/pattern-approle
https://developer.hashicorp.com/vault/tutorials/auth-methods/approle?in=vault%2Fauth-methods
I think is somewhat related to policies. But I did not find the solution yet.
Bash window 1:
$ export VAULT_ADDR="https://p.vault.myfine-company.de"
$ export VAULT_TOKEN="my-fine-token"
$ # This creates a secret
$ vault kv put secret/mysql/webapp db_name="users" username="admin" password="passw0rd"
$ # this writes the policy to access the secret
$ vault policy write jenkins -<<EOF\n# Read-only permission on secrets stored at 'secret/data/mysql/webapp'\npath "secret/data/mysql/webapp" {\n capabilities = [ "read" ]\n}\nEOF\n
$ # This creates an approle jenkins
$ vault write auth/approle/role/jenkins token_policies="jenkins" \\n token_ttl=1h token_max_ttl=4h\n
$ # this reads the role-id
$ vault read auth/approle/role/jenkins/role-id
Key Value
--- -----
role_id fcff5e13-wonderfull-my-fine-role-id
$ This creates a wrapping token with TTL 120s
$ vault write -wrap-ttl=120s -force auth/approle/role/jenkins/secret-id
Key Value
--- -----
wrapping_token: hvs.wonderfull-msgiIp9nu91c1fLrcwGh4KHGh2cy5HMmw4bkh2-my-fine-wrapping-token
wrapping_accessor: ddXZLPFmy-fine-accessor
wrapping_token_ttl: 2m
wrapping_token_creation_time: 2022-11-23 12:19:46.958503493 +0000 UTC
wrapping_token_creation_path: auth/approle/role/jenkins/secret-id
wrapped_accessor: 5superp-6-my-fine-wrapped-accessor
role_id and wrapping_token is now used in bash window 2:
$ # unwrap token to obtain the secret-id
$ VAULT_TOKEN=hvs.wonderfull-msgiIp9nu91c1fLrcwGh4KHGh2cy5HMmw4bkh2-my-fine-wrapping-token vault unwrap
Key Value
--- -----
secret_id ac8b3594-my-wundervolles-secret-id
secret_id_accessor 485423my-wundervolles-secret-accessor
secret_id_ttl 0s
$ # login to vault and get a APP_TOKEN to be used to read secrets
$ vault write auth/approle/login role_id=fcff5e13-wonderfull-my-fine-role-id secret_id=ac8b3594-my-wundervolles-secret-id
Key Value
--- -----
token hvs.CAESIEW-so-a-nice-token-lEgXb9ZIf-my-wonderfull-token
token_accessor MehfK-my-wonderfull-accessor
token_duration 1h
token_renewable true
token_policies ["default" "jenkins"]
identity_policies []
policies ["default" "jenkins"]
token_meta_role_name jenkins
$ export APP_TOKEN=hvs.CAESIEW-so-a-nice-token-lEgXb9ZIf-my-wonderfull-token
$ # Read a secret
$ VAULT_TOKEN=$APP_TOKEN vault kv get secret/mysql/webapp
====== Secret Path ======
secret/data/mysql/webapp
======= Metadata =======
Key Value
--- -----
created_time 2022-11-23T09:44:24.429733013Z
custom_metadata <nil>
deletion_time n/a
destroyed false
version 1
====== Data ======
Key Value
--- -----
db_name users
password passw0rd
username admin
The advantage with this wrapped_token is that the CI Pipeline passes this short lived token to the app. The app uses this token to retrieve the secret-id (by unwrapping it) and performs the login together with the role-idto obtain the access token to read the database secret.
Solution :
The Problem is solved by providing the unwrap_token to app_client = Client(url=URL) token=unwrap_token as mentioned in a still open pull-request to hvac (as of 2022-11-30) :
import hvac
client = hvac.Client(url='https://127.0.0.1:8200')
client.token = "hvs.wonderfull-msgiIp9nu91c1fLrcwGh4KHGh2cy5HMmw4bkh2-my-fine-wrapping-token"
# When authenticating with just the wrapping token, should not pass token into unwrap call
unwrap_response = client.sys.unwrap()
print('Unwrapped approle role token secret id accessor: "%s"' % unwrap_response['data']['secret_id_accessor'])

Failed to setup Custom Domain for APIM using PowerShell script

I am trying to setup custom domain for my APIM instance using below script
[CmdletBinding()]
param (
[String]
$ResourceGroupName,
[String]
$Hostname,
[String]
$ApimServiceName,
[string]
$KeyVaultId
)
$ProxyHostnameConf = New-AzApiManagementCustomHostnameConfiguration -Hostname $Hostname -HostnameType "Proxy" -KeyVaultId $KeyVaultId -DefaultSslBinding
$apim = Get-AzApiManagement -ResourceGroupName $ResourceGroupName -Name $ApimServiceName
$apim.ProxyCustomHostnameConfiguration = $ProxyHostnameConf
Set-AzApiManagement -InputObject $apim
But the script is failing with below error
Line |
15 | Set-AzApiManagement -InputObject $apim
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| 'SubnetResourceId' does not match expected pattern
| '^/subscriptions/[^/]*/resourceGroups/[^/]*/providers/Microsoft.(ClassicNetwork|Network)/virtualNetworks/[^/]*/subnets/[^/]*$'.
I am getting this error both in my local machine as well as from the devops Microsoft hosted agent
I was able to fix this using azure cli command mentioned in the below ink
Azure CLI - Bash script to set up API Management custom domain
[CmdletBinding()]
param (
[String]
$ResourceGroupName,
[String]
$HostName,
[String]
$KeyVaultId,
[String]
$ApimServiceName
)
$config ='[{\"hostName\":\"'+$HostName+'\",\"type\":\"Proxy\",\"keyVaultId\":\"'+$KeyVaultId+'\",\"defaultSslBinding\":true,\"negotiateClientCertificate\":false}]'
Write-Host $config
az apim update --resource-group $ResourceGroupName --name $ApimServiceName --set hostnameConfigurations=$config

Az PowerShell CmdLet Get-AzDataLakeGen2ChildItem Proxy Authentication Error

I am running simple ps cmdlets to connect to azure datalake gen2 storage, some of the cmdlets are working and authenticating through corporate proxy (powershell is configured to use proxy on my machine). however some commands are failing with "Proxy Authentication is required".
Can someone share ideas or reason or fix ?
$subscription = "subscription"
$storageAccount = "storage"
$filesystem = "rawdata"
Connect-AzAccount -Subscription $subscription | Out-Null
$context = New-AzStorageContext -StorageAccountName $storageAccount -UseConnectedAccount
Below commands are throwing an error
Get-AzDataLakeGen2Item -Context $ctx -FileSystem $fileSystem
Get-AzDataLakeGen2ChildItem -Context $context -FileSystem $fileSystem
Get-AzDataLakeGen2ChildItem : Proxy Authentication Required At line:1
char:1
Get-AzDataLakeGen2ChildItem -Context $ctx
+ CategoryInfo : CloseError: (:) [Get-AzDataLakeGen2ChildItem], RequestFailedException
+ FullyQualifiedErrorId : RequestFailedException,Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet.GetAzDataLakeGen2ChildItemCommand
But this command is working fine.
Get-AzDatalakeGen2FileSystem -Context $ctx
One of the workaround for connecting to the Azure Data Lake Gen2 Storage account using PowerShell through Proxy by using following Code:
$browser = New-Object System.Net.WebClient
$browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials
Run this Code before connecting to the Azure Account.
I have executed this code to list the files available in the directory of my container in Azure Data Lake Gen2 Storage locally (Windows PowerShell ISE)
Windows PowerShell ISE:
Reference: Access web using PowerShell and Proxy

Automate Powershell Script to connect to MSOnline while MFA is applied

Thanks in advance.
Quick brief, I work in a team managing multiple Microsoft CSPs (Partner Centers), every now and then somebody asks us to run a script that does specific activities or grab specific info from all 30 CSPs we manage and all customers under them.
Previously we used to keep all usernames, passwords, TenantIDs, WebApp IDs in a CSV file and we create a script that runs on every raw to get the required info for each CSP Automatically without prompting credentials using below command:
$credential = (New-Object –TypeName System.Management.Automation.PSCredential –argumentlist $AdminName ,(ConvertTo-SecureString $AdminPassword –AsPlainText –Force))
And then call it in all modules like the below:
#MSonline
Connect-Msolservice –Credential $Credential
#ExchangeOnline
$session = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri https://outlook.office365.com/powershell-liveid?DelegatedOrg=$Customerdomain –Credential $credential –Authentication Basic –AllowRedirection
Import-PSSession $Session
#Partner Center
Add-PCAuthentication -cspappID $NAtive_clientid -cspDomain $domain -credential $credentials
Connect-MsolService -Credential $credentials
Then MFA was applied on all CSPs, though secure, it presented a problem with automating our scripts. Every time we're asked to run a script we would have to login manually at least 1 time to enter our MFA credentials to be able to run the script on each CSP individually.
The Modules we usually connect to are:
PartnerCenter
MSOnline
CsOnline
AzureRM
AzureAD
Microsoft provided steps to work around this by using secure API Modules: https://learn.microsoft.com/en-us/powershell/partnercenter/secure-app-model?view=partnercenterps-1.5
I've created New APPs with new secrets and call backs , managed to get refresh token and integrated it in PartnerCenter module successfully as follows:
Connect-PartnerCenter -ApplicationId $NAtive_clientid -RefreshToken $refresh_token
Now I'm tying to do the same for the other Modules I'm addressing, as per the above document I could do the same for MS Online and for Azure AD simply by getting 3 other tokens (Graph Token , Azure AD token and Azure token)
$credential = Get-Credential
$refreshToken = 'Your-Refresh-Token-Value'
$azureToken = New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://management.azure.com/ -Credential $credential -TenantId '<Your Tenant Id>'
$graphToken = New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://graph.microsoft.com -Credential $credential -TenantId '<Your Tenant Id>'
$aadGraphToken = New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://graph.windows.net -Credential $credential -TenantId '<Your Tenant Id>'
#MS Module
Connect-MsolService -AdGraphAccessToken $aadGraphToken.AccessToken -MsGraphAccessToken $graphToken.AccessToken
# Az Module
Connect-AzAccount -AccessToken $azureToken.AccessToken -GraphAccessToken $graphToken.AccessToken -TenantId '<TenantId>'
# AzureRM Module
Connect-AzureRmAccount -AccessToken $azureToken.AccessToken -GraphAccessToken $graphToken.AccessToken -TenantId '<TenantId>'
When Applying this and running the below command I get an error:
New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://management.azure.com/ -Credential $credential -TenantId '<Your Tenant Id>'
New-PartnerAccessToken : Cannot validate argument on parameter 'RefreshToken'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:1 char:38
+ New-PartnerAccessToken -RefreshToken $refreshToken -Resource https:// ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-PartnerAccessToken], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Store.PartnerCenter.PowerShell.Commands.NewPartnerAccessT
oken
After some investigation I found that the parameter "-resource" no longer exists as per the documentation: https://learn.microsoft.com/en-us/powershell/module/partnercenter/new-partneraccesstoken?view=partnercenterps-3.0
Yet as per the documentation related to MSOnline, it shows I should be able to use it : https://learn.microsoft.com/en-us/powershell/module/msonline/connect-msolservice?view=azureadps-1.0
Now I'm stuck without the resource parameter I can't get the tokens required to use the 3 modules.
My question, is there another way to use App ID, refresh token, secret, Tenant ID to authenticate using powershell without human interference , if not how can I make the above method work for other modules the same way I did with the partner center.
According to my research. if the version of your PartnerCenter module is larger than 2.0.1909.1, it has rplaced the Resource parameter with the Scopes parameter for the Connect-PartnerCenter and New-PartnerAccessToken cmdlets. So please use the following script to get access token
New-PartnerAccessToken -ApplicationId 'xxxx-xxxx-xxxx-xxxx' -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant 'xxxx-xxxx-xxxx-xxxx'

LDAP implementation

I want to implementation centralize auth using AWS Simple AD (samba). The client machine is linux based (ubuntu and amazon linux). Ony my ldap, i just creat one user (cn=test) under dc=ldap,dc=test,dc=io.
I am using sssd as the auth client from my linux machine. And here my /etc/sssd/sssd.conf :
[sssd]
config_file_version = 2
services = nss, pam
domains = LDAP
[nss]
[pam]
[domain/LDAP]
id_provider = ldap
auth_provider = ldap
ldap_schema = rfc2307
ldap_uri = ldap://ldap.test.io
ldap_default_bind_dn = dc=ldap,dc=test,dc=io
ldap_default_authtok = password01
ldap_default_authtok_type = password
ldap_search_base = dc=ldap,dc=test,dc=io
ldap_user_search_base = dc=ldap,dc=test,dc=io
ldap_group_search_base = odc=ldap,dc=test,dc=io
ldap_user_object_class = inetOrgPerson
ldap_user_gecos = cn
override_shell = /bin/bash
cache_credentials = true
enumerate = true
But, it looks like not working from the client, i didn't get the ldap user from my client (i execute this getent passwd).
And i got this error:
nss_ldap: reconnecting to LDAP server...
nss_ldap: reconnecting to LDAP server (sleeping 1 seconds)...
nss_ldap: could not search LDAP server - Server is unavailable
No passwd entry for user 'test'
Here is my reference to configure the sssd client enter link description here
Any suggestion for this case ?
Thanks
The error message you are getting is from nss_ldap, not from nss_sss. So I assume in /etc/nsswitch.conf, you configured the ldap module either on its own or before sss. If the user information is to be returned by sssd then use the sss nsswich module.
I would also recommend to not use enumerate=true unless your directory is quite small.
In /etc/nsswitch.conf be sure to have:
passwd: files sss
shadow: files sss
groups: files sss
And of course in the stack of the /etc/pam.d/system-auth-ac and /etc/pam.d/password-auth-ac you have to use the pam_sss.so library.