# Mg Module

### Mg Module

* The **MSGraph PowerShell module (Mg module)** is an API wrapper for the **MSGraph API**.
* It allows management of **Entra ID** and various **Microsoft 365 services** like **SharePoint**, **OneDrive**, **Exchange**, **Teams**, and **Outlook**.
* The commands in the Mg module are **autogenerated** from the Graph API.
* The Mg module serves as a replacement for the older **Azure AD** and **MSOnline** modules.

```powershell
Install-Module Microsoft.Graph
```

> *Note: Try to use `AADGraph` used by Azure AD module for enumeration as long as it is available. Since the new security features like graph activity logs aren’t updated here. It can also be used to enumerate* Conditional Access Policy *as regular user.*

> For `MgGraph` Module requests are sent to `graph.microsoft.com` i.e MS Graph API. When using `AADGraph` Module requests are sent to `aad.windows.net` i.e AAD Graph API.

1. Connecting to the MG Graph Powershell Module

```powershell
Connect-MgGraph
```

or using Az Powershell Module if we have a set of cleartext credentials.

```powershell
$passwd = ConvertTo-SecureString "V3ryH4rdt0Cr4ckN0OneCanGu3ssP@ssw0rd" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential("test@defcorphq.onmicrosoft.com",$passwd)
Connect-AzAccount -Credential $creds

$Token = (Get-AzAccessToken -ResourceTypeName MSGraph).Token
Connect-MgGraph -AccessToken ($Token|ConvertTo-SecureString -AsPlainText -Force)
```

Get Current Session State

```powershell
Get-MgContext
```

Get details of the current tenant

```powershell
Get-MgOrganization | fl *
```

### Users

Enumerate all users

```powershell
Get-MgUser -All
```

Enumerate a specific user

```powershell
Get-MgUser -UserId test@defcorphq.onmicrosoft.com
```

Search for a user based on string in first characters of DisplayName or userPrincipalName (wildcard not supported)

```powershell
Get-MgUser -Filter "startsWith(DisplayName, 'a')" -ConsistencyLevel eventual 
```

Search for users who contain the word "admin" in their Display name:

```powershell
Get-MgUser -All |?{$_.Displayname -match "admin"}

Get-MgUser -Search '"DisplayName:admin"' -ConsistencyLevel eventual
```

List all the attributes for a user

```powershell
Get-MgUser -UserId test@defcorphq.onmicrosoft.com | fl * 

Get-MgUser -UserId test@defcorphq.onmicrosoft.com | %{$_.PSObject.Properties.Name}
```

Search attributes for all users that contain the string "password":

```powershell
Get-MgUser -All |%{$Properties = $_;$Properties.PSObject.Properties.Name | % {if ($Properties.$_ -match 'password') {"$($Properties.UserPrincipalName) - $_ - $($Properties.$_)"}}}
```

All users who are synced from on-prem

```powershell
Get-MgUser -All | ?{$_.OnPremisesSecurityIdentifier -ne $null}
```

All users who are from Entra ID

```powershell
Get-MgUser -All | ?{$_.OnPremisesSecurityIdentifier -eq $null}
```

Objects created by any user (use -ObjectId for a specific user)

```powershell
Get-MgUserCreatedObject -UserId test@defcorphq.onmicrosoft.com | fl *
```

Objects owned by a specific user

```powershell
Get-MgUserOwnedObject -UserId test@defcorphq.onmicrosoft.com | fl *
```

### Groups

List all Groups

```powershell
Get-MgGroup -All
```

Enumerate a specific group

```powershell
Get-MgGroup -GroupId 783a312d-0de2-4490-92e4-539b0e4ee03e
```

Search for a group based on string in first characters of DisplayName (wildcard not supported)

```powershell
Get-MgGroup -ConsistencyLevel eventual -Search '"DisplayName:A"'
```

To search for groups which contain the word "admin" in their name:

```powershell
Get-MgGroup -ConsistencyLevel eventual -Search '"DisplayName:Admin"'
```

Get Groups that allow Dynamic membership

```powershell
Get-MgGroup | ?{$_.GroupTypes -eq 'DynamicMembership'} 
```

All groups that are synced from on-prem (note that security groups are not synced)

```powershell
Get-MgGroup -All| ?{$_.OnPremisesSecurityIdentifier -ne $null}
```

All groups that are from Entra ID

```powershell
Get-MgGroup -All | ?{$_.OnPremisesSecurityIdentifier -eq $null}
```

Get members of a group

```powershell
Get-MgGroupMember -GroupId 783a312d-0de2-4490-92e4-539b0e4ee03e
(Get-MgGroupMember -GroupId 783a312d-0de2-4490-92e4-539b0e4ee03e).AdditionalProperties
```

Get groups and roles where the specified user is a member

```powershell
(Get-MgUserMemberOf -UserId test@defcorphq.onmicrosoft.com).AdditionalProperties
```

### Roles

Get all available role templates

```powershell
Get-MgDirectoryRoleTemplate
Get-MgDirectoryRoleTemplate | fl *
```

Get all enabled roles (a built-in role must be enabled before usage)

```powershell
Get-MgDirectoryRole
Get-MgDirectoryRole | fl *
```

Enumerate users to whom roles are assigned

```powershell
$RoleId = (Get-MgDirectoryRole -Filter "DisplayName eq 'Global Administrator'").Id
(Get-MgDirectoryRoleMember -DirectoryRoleId $RoleId).AdditionalProperties
```

List Custom Roles

```powershell
Get-MgRoleManagementDirectoryRoleDefinition | Where-Object { $_.IsBuiltIn -eq $false } | Select-Object Id, DisplayName, Description, Permissions
```

> Microsoft recommends one Global Admins and rest of the admin accounts should be PIM i.e, sudo to GA.

#### Devices

* Get all Azure joined and registered devices

```powershell
Get-MgDevice –All | fl *
```

* List all the active devices (and not the stale devices)

```powershell
Get-MgDevice –All | ?{$_.ApproximateLastSignInDateTime -ne $null}
```

* List Registered owners of all the devices

```powershell
$Ids = (Get-MgDevice –All).Id; foreach($i in $Ids){ (Get-MgDeviceRegisteredOwner -DeviceId $i).AdditionalProperties}
$Ids = (Get-MgDevice –All).Id; foreach($i in $Ids){ (Get-MgDeviceRegisteredOwner -DeviceId $i).AdditionalProperties.userPrincipalName}
```

* List Registered users of all the devices

```powershell
$Ids = (Get-MgDevice –All).Id; foreach($i in $Ids){ (Get-MgDeviceRegisteredUser -DeviceId $i).AdditionalProperties}
$Ids = (Get-MgDevice –All).Id; foreach($i in $Ids){ (Get-MgDeviceRegisteredUser -DeviceId $i).AdditionalProperties.userPrincipalName}
```

* List devices owned by a user

```powershell
(Get-MgUserOwnedDevice -userId michaelmbarron@defcorphq.onmicrosoft.com).AdditionalProperties
```

* List devices registered by a user

```powershell
(Get-MgUserRegisteredDevice -userId michaelmbarron@defcorphq.onmicrosoft.com).AdditionalProperties
```

* List devices managed using Intune

```powershell
Get-MgDevice -All| ?{$_.IsCompliant -eq "True"} | fl *
```

#### Apps

> App Registration(Apps) is Configuration whereas Enterprise Application(Service Principal) is an Instance of the Application. Enterprise Applications can also have roles assigned to it. These applications are used if we want to use Entra ID authentication in front of the application.

* Get all the application objects registered with the current tenant (visible in App Registrations in Azure portal). An application object is the global representation of an app.

```powershell
Get-MgApplication -All
```

* Get all details about an application

```powershell
Get-MgApplicationByAppId -AppId f072c4a6-b440-40de-983fa7f3bd317d8f | fl *
```

* Get an application based on the display name

```powershell
Get-MgApplication -All | ?{$_.DisplayName -match "app"}
```

* The `Get-MgApplication` will show all the applications details including password but password value is not shown. List all the apps with an application password.

```powershell
Get-MgApplication -All| ?{$_.PasswordCredentials -ne $null}
```

* Get owner of an application

```powershell
(Get-MgApplicationOwner -ApplicationId 35589758-714e-43a9-be9e94d22fdd34f6).AdditionalProperties.userPrincipalName
```

* Get Apps where a User has a role (exact role is not shown)

```powershell
Get-MgUserAppRoleAssignment -UserId roygcain@defcorphq.onmicrosoft.com | fl *
```

* Get Apps where a Group has a role (exact role is not shown)

```powershell
Get-MgGroupAppRoleAssignment -GroupId 57ada729-a581-4d6f-9f16-3fe0961ada82 | fl *
```

> Adding credentials to an application is verbosely logged hence add creds to an application already having credentials.

#### Service Principals

* Enumerate Service Principals (visible as Enterprise Applications in Azure Portal). Service principal is local representation for an app in a specific tenant and it is the security object that has privileges. This is the 'service account'!
* Service Principals can be assigned Azure roles.
* Get all service principals

```powershell
Get-MgServicePrincipal -All
```

* Get all details about a service principal

```powershell
Get-MgServicePrincipal -ServicePrincipalId 09655102-7c74-43d7-bda3-238d5394b0ae| fl *
```

* Get an service principal based on the display name

```powershell
Get-MgServicePrincipal –All | ?{$_.DisplayName -match "app"}
```

* List all the service principals with an application password

```powershell
Get-MgServicePrincipal –All | ?{$_.KeyCredentials -ne $null}
```

* Get owner of a service principal

```powershell
(Get-MgServicePrincipalOwner -ServicePrincipalId fd518680-b290-4db2-b92a-5dbd025c6791).AdditionalProperties.userPrincipalName
```

* Get objects owned by a service principal

```powershell
Get-MgServicePrincipalOwnedObject -ServicePrincipalId fd518680-b290-4db2-b92a-5dbd025c6791
```

* Get objects created by a service principal

```powershell
Get-MgServicePrincipalCreatedObject -ServicePrincipalId fd518680-b290-4db2-b92a-5dbd025c6791
```

* Get group and role memberships of a service principal

```powershell
Get-MgServicePrincipalMemberOf -ServicePrincipalId fd518680-b290-4db2-b92a-5dbd025c6791 | fl *
```
