Azure Activity Log - azure

I want to monitor who made a change in rbac assignment, I created powershell script for collection data from Azure Activity Log. I used below piece of code. Using this solution I am able to get items like:
caller - user who made a role assignment change,
timestamp,
Resource name - on this resource assignment change has been provided,
action type - write or delete
In Activity Log panel in Azure portal, in Summary portal (Message: shared with "user info"), I can see name of a user who has been granted permissions/assignment to the resource, but using my powershell script I am not able to catch this information, is there any method to get this info?
Get-AzureRmLog -StartTime (Get-Date).AddDays(-7) |
Where-Object {$_.Authorization.Action -like
'Microsoft.Authorization/roleAssignments/*'} |
Select-Object #{N="Caller";E={$_.Caller}},
#{N="Resource";E={$_.Authorization.Scope}},
#{N="Action";E={Split-Path $_.Authorization.action -leaf}},
EventTimestamp
script output:
Caller : username#xxx.com
Resource :/subscriptions/xxxx/resourceGroups/Powershell/providers/Microsoft.Compute/virtualMachines/xx/providers/Microsoft.Authorization/roleAssignments/xxxx
Action : write
EventTimestamp : 8/29/2019 10:12:31 AM

Your requirement of fetching the user name to whom the RBAC role is assigned is currently not supported using Az PowerShell cmdlet Get-AzLog or Get-AzureRmLog.
However, we can accomplish your requirement by leveraging Azure REST API for Activity Logs - List and Az PowerShell cmdlet Get-AzureADUser.
In this way as we are depending on Azure REST API for Activity Logs - List (but looks like you want PowerShell way of accomplishing the requirement) so call the REST API in PowerShell as something shown below.
$request = "https://management.azure.com/subscriptions/{subscriptionId}/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&`$filter={$filter}"
$auth = "eyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$authHeader = #{
'Content-Type'='application/json'
'Accept'='application/json'
'Authorization'= "Bearer $auth"
}
$Output = Invoke-RestMethod -Uri $request -Headers $authHeader -Method GET -Body $Body
$ActivityLogsFinalOutput = $Output.Value
Develop your PowerShell code to get "PrincipalId" (which is under "properties") from the output of your Azure REST API for Activity Logs - List call. The fetched "PrincipalId" is the ObjectID of the user whom you want to get ultimately.
Now leverage Az PowerShell cmdlet Get-AzureADUser and have your command something like shown below.
(Get-AzureADUser -ObjectID "<PrincipalID>").DisplayName
Hope this helps!! Cheers!!
UPDATE:
Please find PowerShell way of fetching auth token (i.e., $auth) that needs to be used in above REST API call.
$ClientID = "<ClientID>" #ApplicationID
$ClientSecret = "<ClientSecret>" #key from Application
$tennantid = "<TennantID>"
$TokenEndpoint = {https://login.windows.net/{0}/oauth2/token} -f $tennantid
$ARMResource = "https://management.core.windows.net/";
$Body1 = #{
'resource'= $ARMResource
'client_id' = $ClientID
'grant_type' = 'client_credentials'
'client_secret' = $ClientSecret
}
$params = #{
ContentType = 'application/x-www-form-urlencoded'
Headers = #{'accept'='application/json'}
Body = $Body1
Method = 'Post'
URI = $TokenEndpoint
}
$token = Invoke-RestMethod #params
$token | select access_token, #{L='Expires';E={[timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.expires_on))}} | fl *
I see this new way as well but I didn't get chance to test this out. If interested, you may alternatively try this or go with above approach.
UPDATE2:
$ActivityLogsFinalOutput| %{
if(($_.properties.responseBody) -like "*principalId*"){
$SplittedPrincipalID = $_.properties.responseBody -split "PrincipalID"
$SplittedComma = $SplittedPrincipalID[1] -split ","
$SplittedDoubleQuote = $SplittedComma[0] -split "`""
$PrincipalID = $SplittedDoubleQuote[2]
#Continue code for getting Azure AD User using above fetched $PrincipalID
#...
#...
}
}

Does this work for you?
Get-AzureRmLog -StartTime (Get-Date).AddDays(-7) |
Where-Object {$_.Authorization.Action -like 'Microsoft.Authorization/roleAssignments/*'} |
Select-Object #{N="Caller";E={$_.Caller}},
#{N="Resource";E={$_.Authorization.Scope}},
#{N="Action";E={Split-Path $_.Authorization.action -leaf}},
#{N="Name";E={$_.Claims.Content.name}},
EventTimestamp
My output:
Caller : username#domain.com
Resource : /subscriptions/xxxx/resourceGroups/xxxx/providers/Microsoft.Authorization/roleAssignments/xxxx
Action : write
Name : John Doe
EventTimestamp : 30.08.2019 12.05.52
NB: I used Get-AzLog. Not sure if there is any difference between Get-AzLog and Get-AzureRmLog.

Fairly certain this wouldn't be exposed with this cmdlet. I dont even see this information in the Role Assignments. So not sure what do you mean exactly.

Related

Can we add label to tiles on Azure Dashboard [duplicate]

Is it possible to show custom information in azure dashboards?
I was searching on how to add custom content in azure dashboards but did not find anything. The only thing close was the markdown tile which allows html to be displayed.
With this in mind and after a lot of digging I found a solution:
Basically we needed a custom tile that displays data retrieved from our REST api.
1. Create a new, empty 'Markdown' tile on a new or existing dashboard, give it a 'Title'
2. Share the dashboard
3. Navigate to All services, Filter by 'dashboards' in the ResourceGroup filter
- Click on the dashboard which contains the 'Markdown' tile
- Take a note of the 'RESOURCE ID'
In our scenario, we used Azure Automation Runbooks. In this scenario we utilized the Azure Resource Manager REST api.
4. Create a new RunBook [Powershell Runbook]
The following steps concern the following:
- Login to the ResourceManagerAPI
- Get Azure Resource by ID [The Resource ID above]
- Update Azure Resource by ID [The Resource ID above]
Before we continue, we need to get our client credentials. To do so:
- Click on Cloud Shell in the Portal Menu bar
- Type 'az'
- Type 'az ad sp create-for-rpac -n "runbooks"' //runbooks is just a name, feel free to input a different string
- The above command should list out the credentials needed. If an error occurs, kindly contact your Azure admin and run it from their account.
5. In your empty powershell runbook, add the following 2 variables:
$ExpectedTileName = "Extension/HubsExtension/PartType/MarkdownPart"
$MarkdownTileTitle = "<The Markdown title you've set in the first step>"
6. Getting the Access_Token [The variables <> represent the values retrieved from the previous step]
#Get Bearer Token
$TenantId = '<Your tenantID>'
$LoginUri = "https://login.microsoftonline.com/"+$TenantId+"/oauth2/token"
$params = #{
"grant_type"="client_credentials";
"client_id"="<appId>";
"client_secret"="<password>";
"resource"="https://management.azure.com";
}
$LoginResponse = Invoke-RestMethod -Uri $LoginUri -Method Post -Body $params
$Access_Token = $LoginResponse.access_token;
$Access_TokenString = "Bearer " + $Access_Token
7. Getting the DashboardResource by ResourceID:
#Get Resource
$RMUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$DashboardResource = (Invoke-RestMethod -Uri $RMUri -Method Get -Headers #{'Authorization'=$Access_TokenString}) | ConvertTo-Json -Depth 100 | ConvertFrom-Json
8. Looping through all tiles within the dashboard. Please note that tiles are not contained within an array, thus you may need to increase/decrease the length of the for loop.
#Loop through all tiles within the dashboard
$Parts = $DashboardResource.properties.lenses.0.0.parts
For ($i=0; $i -lt 200; $i++)
{
$Part = $Parts | Select-Object -Property $i.toString()
if($Part.$i)
{
if($Part.$i.metadata.type -eq $ExpectedTileName -And $Part.$i.metadata.settings.content.settings.title -eq $MarkdownTileTitle)
{
$Part.$i.metadata.settings.content.settings.content = <CustomValue ex: invoke a get request to your api>
}
}
else
{
break
}
}
9. Finally we need to update the dashboard resource
#Update Resource
$UpdateUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$JsonValue = $DashboardResource | ConvertTo-Json -Depth 100
Invoke-RestMethod -Uri $UpdateUri -Method Put -Headers #{'Authorization'=$Access_TokenString; 'Content-type'='application/json'} -Body $JsonValue
To sum it up:
$ExpectedTileName = "Extension/HubsExtension/PartType/MarkdownPart"
$MarkdownTileTitle = "<The Markdown title you've set in the first step>"
#Get Bearer Token
$TenantId = '<Your subscriptionID>'
$LoginUri = "https://login.microsoftonline.com/"+$TenantId+"/oauth2/token"
$params = #{
"grant_type"="client_credentials";
"client_id"="<appId>";
"client_secret"="<password>";
"resource"="https://management.azure.com";
}
$LoginResponse = Invoke-RestMethod -Uri $LoginUri -Method Post -Body $params
$Access_Token = $LoginResponse.access_token;
$Access_TokenString = "Bearer " + $Access_Token
#Get Resource
$RMUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$DashboardResource = (Invoke-RestMethod -Uri $RMUri -Method Get -Headers #{'Authorization'=$Access_TokenString}) | ConvertTo-Json -Depth 100 | ConvertFrom-Json
#Loop through all tiles within the dashboard
$Parts = $DashboardResource.properties.lenses.0.0.parts
For ($i=0; $i -lt 200; $i++)
{
$Part = $Parts | Select-Object -Property $i.toString()
if($Part.$i)
{
if($Part.$i.metadata.type -eq $ExpectedTileName -And $Part.$i.metadata.settings.content.settings.title -eq $MarkdownTileTitle)
{
$Part.$i.metadata.settings.content.settings.content = <CustomValue ex: invoke a get request to your api>
}
}
else
{
break
}
}
#Update Resource
$UpdateUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$JsonValue = $DashboardResource | ConvertTo-Json -Depth 100
Invoke-RestMethod -Uri $UpdateUri -Method Put -Headers #{'Authorization'=$Access_TokenString; 'Content-type'='application/json'} -Body $JsonValue
Conclusion
With this newly created runbook we can now schedule it to run every 1 hour. In our case, 1 hour was too much. The following article shows how we can schedule the runbook to run every 1 minute.
https://blogs.technet.microsoft.com/stefan_stranger/2017/06/21/azure-scheduler-schedule-your-runbooks-more-often-than-every-hour/

How to check which Azure Active Directory Groups I am currently in?

It is possible to return a list that shows all the Azure AD groups the current account is belonging to?
Both using Azure portal web UI and PowerShell are appreciated!
Here's a few different ways other than using the Portal
Azure AD PowerShell Module
Get-AzureADUserMembership
$user = "user#domain.com"
Connect-AzureAD
Get-AzureADUserMembership -ObjectId $user | Select DisplayName, ObjectId
Microsoft Graph PowerShell Module
Get-MgUserMemberOf
$user = "user#domain.com"
Connect-MgGraph
(Get-MgUserMemberOf -UserId $user).AdditionalProperties | Where-Object {$_."#odata.type" -ne "#microsoft.graph.directoryRole"} | ForEach-Object {$_.displayName}
Microsoft Graph API HTTP Request through PowerShell
List memberOf
$user = "user#domain.com"
$params = #{
Headers = #{ Authorization = "Bearer $access_token" }
Uri = "https://graph.microsoft.com/v1.0/users/$user/memberOf"
Method = "GET"
}
$result = Invoke-RestMethod #params
$result.Value | Where-Object {$_."#odata.type" -ne "#microsoft.graph.directoryRole"} | Select DisplayName, Id
Microsoft Graph Explorer
GET https://graph.microsoft.com/v1.0/users/user#domain.com/memberOf
For Portal, simply click on the user for which you want to find this detail and then click on "Groups" button.
If you want to use PowerShell, the Cmdlet you would want to use is Get-AzureADUserMembership.

Azure Data factory pipeline and dependent triggers

I am trying to list all of my ADF pipelines and their dependent triggers.
As per this article https://learn.microsoft.com/en-us/rest/api/datafactory/triggers/get there is a simple GET method which will list all the triggers with their associated pipelines.
This is working fine when I use a web activity with GET method in ADF pipeline.
I am trying to do the same using powershell. The pipeline name which is visible in ADF output is no longer visible when running via powershell.
Can someone please help me with the code below to identify what needs to be added to fetch the dependent pipeline name for a trigger when this GET method is executed. Any other approach will also be highly appreciated.
Connect-AzAccount -Identity
$azContext = Get-AzContext
$azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile)
$token = $profileClient.AcquireAccessToken($azContext.Subscription.TenantId)
$authHeader = #{
'Content-Type'='application/json'
'Authorization'='Bearer ' + $token.AccessToken
}
$restUri = 'https://management.azure.com/subscriptions/1111111-1111-1111-11111-1111111/resourceGroups/resourceGroupName/providers/Microsoft.DataFactory/factories/DataFactoryName/triggers?api-version=2018-06-01'
$response = Invoke-RestMethod -Method GET -Header $authHeader -URI $restUri
$response | ConvertTo-Json
Powershell Output - Using powershell 5.1 via Azure runbook
"value": [
{
"id": "/subscriptions/1234-1234-1234-1234/resourceGroups/ResourceGroupName/providers/Microsoft.DataFactory/factories/DataFactoryName/triggers/eventbasedtrigger",
"name": "eventbasedtrigger",
"type": "Microsoft.DataFactory/factories/triggers",
"properties": "#{description=Tets Trigger; annotations=System.Object[]; runtimeState=Stopped; pipelines=System.Object[]; type=BlobEventsTrigger; typeProperties=}",
"etag": "000000-0000-0d00-0000-0000000"
},
Cheers
Powershell command Get-AzDataFactoryV2Trigger will provide you the list of triggers for an ADF pipeline / data factory
To get information about all the triggers in ADF:
Get-AzDataFactoryV2Trigger -ResourceGroupName "<RG_NAME>"
-DataFactoryName "<ADF_NAME>"
Get information about a specific trigger
Get-AzDataFactoryV2Trigger -ResourceGroupName "<RG_NAME>" -DataFactoryName "<ADF_NAME>" -TriggerName "<TRIGGER_NAME>"

Using PowerShell, How to get list of all Azure subscriptions having Azure Data factory Resource in it?

I want to retrieve the list of subscriptions having Azure Data Factory resource in it. I want to use PowerShell and get the subscription list and ADF list.
I have tried Get-AzSubscription, but it does not contain filter for resource type i.e. Microsoft.DataFactory/factories. This filter can be added to only Get-AzResource.
Get-AzSubscription Module
Get-AzResource Module
Ok here you are:
$resType = "Microsoft.DataFactory/factories"
$resTypeName = "DataFactory"
Get-AzSubscription | ForEach-Object {
$subscriptionName = $_.Name
$tenantId = $_.TenantId
Set-AzContext -SubscriptionId $_.SubscriptionId -TenantId $_.TenantId
(Get-AzResource -ResourceType $ResType) | ForEach-Object {
[PSCustomObject] #{
true_sub = $subscriptionName
}
} | get-unique
} | Select-String 'true_sub' | ForEach-Object{ "Found_" + "$resTypeName" + "_In_Subscription= $($subscriptionName)"}
EDIT: Added variables to make it easily reusable for any resource type.
I used the code available here and here to create a custom one based on the requirements. Tested in my environment - it seems to work as expected.
I should disclose that I'm not an advanced PowerShell user, so the code I'm providing could really be sub-optimal.

Access Azure PIM api in azure pipelines via service principal

I'm trying to call the azure privileged identity management api (https://api.azrbac.mspim.azure.com/api/v2/privilegedAccess) in an azure pipeline. I have the following code to call the register method, but it is not working, but I can't figure out what is wrong. Let me show the code first:
install-module azureadpreview -Force
import-module azureadpreview
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
$graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
$pimToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "<what do i enter here?>").AccessToken
$aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken
Write-Output "Create PIM role"
$Group = New-AzureADMSGroup -DisplayName "TestPIMGroup" -Description "TestForPim" -MailEnabled $false -SecurityEnabled $true -MailNickName "NOTUSED" -IsAssignableToRole $true
Write-Output "Test api call"
$Headers = #{
"Accept" = "*/*"
"Accept-Language" = "en"
"Authorization" = "Bearer {0}" -f $pimToken
"Content-Type" = "application/json"
}
$Body = #{
externalId = $Group.Id
} | ConvertTo-Json
$URL = 'https://api.azrbac.mspim.azure.com/api/v2/privilegedAccess/aadGroups/resources/register'
Write-Output "Body: $Body"
$HeaderJson = $Headers | ConvertTo-Json
Write-Output "Headers: $HeaderJson"
try {
$QueryResponse = Invoke-RestMethod -Uri $URL -Headers $Headers -Method POST -Body $Body
}
catch {
$_.Exception.Response
$result = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($result)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
$responseBody
exit 1
}
$QueryResponse.value
So what I'm trying to accomplish, it to create a PIM group, and enable privileged access on it. The azureadpreview module has functionality to create a PIM group, so I use that. This works perfectly. The method of getting the token for the service principal I got from this post.
Now to enable privileged access on it, I need to directly call the API, because there doesn't seem to be any powershell command for it. This where things get tricky. The API call returns a 500 internal server error, with the only error in the body being an error has occurred. So that doesn't really tell me anything. So I started investigating:
When I don't pass a token, I get an unauthorized exception
When I pass nonsense as a token, I get an internal server error. So this pointed me in the direction that something is wrong with the token. I think there is something wrong with the audience tag in the token.
I tried all kinds of URL's in the token, which all show me a 500 as response.
I recorded the api call the browser did in azure portal when doing the same call. I read the token from this request, and it got me some guid as aud. When I use this guid, it given me a Unauthorized response
Can anyone help me with my situation?
answer restriction:
I need to be able to access the pim api by reusing the service principal I'm already using in my azure pipeline via my service connection. So I'm not looking for answers about creating certificates in azure an authenticating using it.
Edit:
Some background info:
https://feedback.azure.com/forums/169401-azure-active-directory/suggestions/42203638-allow-privileged-access-for-groups-to-be-enabled-f
https://feedback.azure.com/forums/34192--general-feedback/suggestions/42644962-possibility-for-azure-ad-privileged-access-groups
https://github.com/MicrosoftDocs/azure-docs/issues/70296#issuecomment-776069283
The guid you get from token in browser in azure portal should be correct.
But this API endpoint looks like to be not exposed for external usage.
We can not generate an application token for this resource currently.
As you see there are several user voice posts are requiring this feature.
Keep voting up the posts will be helpful.

Resources