Identity.SignIns.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
using namespace Microsoft.Graph.PowerShell.Models
#MicrosoftGraphInvitation object is in Microsoft.Graph.Identity.SignIns.private.dll
function New-GraphInvitation   {
    <#
        .synopsis
            Invites an external user to become a guest in Azure AD
    #>

    [cmdletbinding(SupportsShouldProcess=$true)]
    param   (
        #The email address of the user being invited.
        #The characters #~ ! $ % ^ & * ( [ { < > } ] ) + = \ / | ; : " " ? , are not permitted
        #A . or - is permitted except at the beginning or end of the name. A _ is permitted anywhere.
        [Parameter(Position=0,ValueFromPipeline=$true)]
        [string]$EmailAddress,
        #The display name of the user being invited.
        [string]$DisplayName,
        #The userType of the user being invited. By default, this is Guest. You can invite as Member if you are a company administrator.'
        [string]$UserType,
        #The URL the user should be redirected to once the invitation is redeemed. Required.
        [string]$RedirectUrl  = 'https://mysignins.microsoft.com/',
        #Indicates whether an email should be sent to the user being invited or not.
        [switch]$SendInvitationMessage
    )

    ContextHas -WorkOrSchoolAccount -BreakIfNot
    $settings = @{
        'invitedUserEmailAddress'    = $EmailAddress
        'sendInvitationMessage'      = $SendInvitationMessage -as [bool]
        'inviteRedirectUrl'          = $RedirectUrl
    }
    if ($DisplayName) {$settings['invitedUserDisplayName']  = $DisplayName}
    if ($UserType)    {$settings['invitedUserType']         = $UserType}

    $webparams = @{
        'Method'            = 'POST'
        'Uri'               = "$GraphUri/invitations"
        'Contenttype'       = 'application/json'
        'Body'              = (ConvertTo-Json $settings -Depth 5)
        'AsType'            = [MicrosoftGraphInvitation]
        'ExcludeProperty'   = '@odata.context'
    }
    Write-Debug $webparams.Body
    if ($force -or $pscmdlet.ShouldProcess($EmailAddress, 'Invite User')){
        try {
            $u = Invoke-GraphRequest @webparams
            if ($Passthru ) {return $u }
        }
        catch {
        # xxxx Todo figure out what errors need to be handled (illegal name, duplicate user)
        $_
        }
    }
}

function Get-GraphNamedLocation {
    <#
    .synopsis
        Returns named locations used in conditional access
    #>

    param   (
        #The ID or start of the display-name of a Location
        [Parameter(ValueFromPipeline=$true,Position=0)]
        $Location = ""
    )
    process {
        $uri = "$GraphUri/identity/conditionalAccess/namedlocations"
        foreach ($l in $Location) {
            if ($l -match $GUIDRegex) {
                $response = Invoke-GraphRequest "$uri/$l" -PropertyNotMatch '@odata'
            }
            elseif ($l) {
                $response = Invoke-GraphRequest  -ValueOnly  ($uri + "?`$filter=startswith(toLower(displayName),'{0}')" -f $l.ToLower())
            }
            else{
                $response = Invoke-GraphRequest -ValueOnly $uri
            }
            foreach ($r in $response) {
                if ($r.isTrusted -is [bool]) {
                    $trusted = $r.isTrusted
                    $null = $r.Remove('isTrusted')
                }
                else {$trusted = $null}
                if ($r.ipRanges) {
                    $ipranges =   $(foreach ($ipRange in $r.ipRanges) {$ipRange.cidrAddress}) -join ";"
                    $null = $r.Remove('ipranges')
                }
                else {$ipranges = $null}
                if ($r.countriesAndRegions) {
                    $countries =   $r.countriesAndRegions -join ";"
                    $null = $r.Remove('countriesAndRegions')
                }
                else {$countries = $null}
                if ($r.includeUnknownCountriesAndRegions -is [bool]) {
                    $includeUnknown =   $r.includeUnknownCountriesAndRegions
                    $null = $r.Remove('includeUnknownCountriesAndRegions')
                }
                else {$includeUnknown = $null }

                $null = $r.remove('@odata.type')
                New-object -TypeName  Microsoft.Graph.PowerShell.Models.MicrosoftGraphNamedLocation -Property $r  |
                        Add-Member -PassThru -NotePropertyName IsTrusted            -NotePropertyValue $trusted   |
                        Add-Member -PassThru -NotePropertyName IpRanges             -NotePropertyValue $ipranges  |
                        Add-Member -PassThru -NotePropertyName CountriesAndRegions  -NotePropertyValue $countries |
                        Add-Member -PassThru -NotePropertyName IncludeUnknownCountriesAndRegions  -NotePropertyValue $includeUnknown
            }
        }
    }
}

function Get-GraphConditionalAccessPolicy {
    param   (
        #The ID or start of the display-name of a Policy
        [Parameter(ValueFromPipeline=$true,Position=0)]
        $Policy = ""
    )
    process {
        #needs beta to work when conditions.devices is set (which is marked as preview in the GUI)
        $uri = "beta/identity/conditionalAccess/policies"
        foreach ($p in $Policy) {
            if ($p -match $GUIDRegex) {
                    Invoke-GraphRequest "$uri/$p" -AsType ([MicrosoftGraphConditionalAccessPolicy]) -PropertyNotMatch '@odata'
            }
            elseif ($P) {
                   $uri += ("?`$filter=startswith(toLower(displayName),'{0}')" -f $p.ToLower())
                  Invoke-GraphRequest -ValueOnly $uri            -AsType ([MicrosoftGraphConditionalAccessPolicy])
            }
            else{ Invoke-GraphRequest -ValueOnly $uri -AllValues -AsType ([MicrosoftGraphConditionalAccessPolicy]) }
        }
    }
}

function Expand-GraphConditionalAccessPolicy {
    param (
        #The ID or start of the display-name of a Policy
        [Parameter(ValueFromPipeline=$true,Position=0)]
        $Policy = ""
    )
    begin {
        $locations          = @{}
        Invoke-GraphRequest "$GraphUri/identity/conditionalAccess/namedlocations" -ValueOnly -AllValues |
            ForEach-Object {$locations[$_.id]         = $_.DisplayName}
        $dirRoleTemplates   = @{} ;
        Invoke-GraphRequest  -Uri "$GraphUri/directoryroletemplates/" -ValueOnly -AllValues  |
            ForEach-Object {$dirRoleTemplates[$_.id]  = $_.DisplayName}
        $servicePrincipals  = @{}
        Invoke-GraphRequest  -Uri "$GraphUri/servicePrincipals/" -ValueOnly -AllValues  |
            ForEach-Object {$servicePrincipals[$_.id] = $_.Displayname}

        $dirobjs            = @{}
        $result             = @()
        function resolveDirObj {
            param (
                [Parameter(ValueFromPipeline=$true)] $D
            )
            process {
                if ($D -notmatch $GUIDRegex ) {return $d}
                elseif (-not $dirobjs.ContainsKey($D)) {
                    $dirobjs[$d] = (Invoke-GraphRequest "$GraphUri/directoryObjects/$d").displayname
                }
                $dirobjs[$d]
            }
        }
        function tranlasteGUID {
            param (
                [Parameter(ValueFromPipeline=$true)]$G,
                [Parameter(Position=0)]$hash
            )
            process {if ($g -notmatch $GUIDRegex ) {return $g} else {$hash[$g]}}
        }
    }
    process {
        Get-GraphConditionalAccessPolicy @PSBoundParameters |
            Select-Object -Property DisplayName , Description, State,
                @{n='IncludeUsers';             e={($_.Conditions.Users.IncludeUsers                | resolveDirObj ) -join '; '}},
                @{n='ExcludeUsers';             e={($_.Conditions.Users.ExcludeUsers                | resolveDirObj ) -join '; '}},
                @{n='IncludeGroups';            e={($_.Conditions.Users.IncludeGroups               | resolveDirObj ) -join '; '}},
                @{n='ExcludeGroups';            e={($_.Conditions.Users.ExcludeGroups               | resolveDirObj ) -join '; '}},
                @{n='IncludeRoles';             e={($_.Conditions.Users.IncludeRoles                | tranlasteGUID $dirRoleTemplates)  -join '; '}},
                @{n='ExcludeRoles';             e={($_.Conditions.Users.ExcludeRoles                | tranlasteGUID $dirRoleTemplates)  -join '; '}},
                @{n='IncludeLocations';         e={($_.Conditions.Locations.IncludeLocations        | translateGuid $locations)         -join '; '}},
                @{n='ExcludeLocations';         e={($_.Conditions.Locations.ExcludeLocations        | translateGuid $locations)         -join "; "}},
                @{n='IncludeApplications';      e={($_.Conditions.Applications.IncludeApplications  | tranlasteGUID $servicePrincipals) -join '; '}},
                @{n='ExcludeApplications';      e={($_.Conditions.Applications.ExcludeApplications  | tranlasteGUID $servicePrincipals) -join '; '}},
                @{n='IncludeUserActions';       e={ $_.Conditions.Applications.IncludeUserActions     -join '; '}},
                @{n='IncludeDevices';           e={ $_.Conditions.Devices.IncludeDevices              -join '; '}},
                @{n='ExcludeDevices';           e={ $_.Conditions.Devices.ExcludeDevices              -join '; '}},
                @{n='ClientAppTypes';           e={ $_.Conditions.ClientAppTypes                      -join '; '}},
                @{n='IncludePlatforms';         e={ $_.Conditions.Platforms.IncludePlatforms          -join '; '}},
                @{n='ExcludePlatforms';         e={ $_.Conditions.Platforms.EccludePlatforms          -join '; '}},
                @{n='AppEnforcedRestrictions';  e={ $_.SessionControls.ApplicationEnforcedRestrictions.IsEnabled}},
                @{n='PersistentBrowser'; e={
                                              if   ($_.SessionControls.PersistentBrowser.isenabled) {
                                                    $_.SessionControls.PersistentBrowser.Mode}
                                              else {$null}}},
                @{n='CloudAppSecurity';  e={
                                              if   ($_.SessionControls.CloudAppSecurity.isenabled)  {
                                                    $_.SessionControls.CloudAppSecurity.CloudAppSecurityType}
                                              else {$null}}} ,
                @{n='SignInFrequency';   e={
                                              if   ($_.SessionControls.SignInFrequency.isenabled)  {
                                                    $_.SessionControls.SignInFrequency.Value + " " +
                                                    $_.SessionControls.SignInFrequency.Type }
                                            else {$null}}}
    }
}