-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathUpdate-NamedLocationsFromHelseCert.ps1
More file actions
193 lines (150 loc) · 10.1 KB
/
Copy pathUpdate-NamedLocationsFromHelseCert.ps1
File metadata and controls
193 lines (150 loc) · 10.1 KB
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
<#
.SYNOPSIS
Script for automatisk nedhenting av blockliste og oppdatering av Named Locations i Conditional Access
.DESCRIPTION
Laster ned blockliste fra Helse- og KommuneCERT
Kobler til Microsoft Graph
Oppdaterer (overskriver) Named Location i Conditional Access
Sender e-post hvis egen public ip-adresser er inkludert i blocklista
Scriptet er laga for å kjøres som oppgave i Windows Task Scheduler
Scriptet krever ein app registrert i Azure AD med følgende API tilganger:
- Policy.Read.All
- Policy.ReadWrite.ConditionalAccess
Scriptet krever ein SMTP server for å sende epost
Scriptet anbefales kjørt en gang i timen.
.NOTES
Version: 0.6
Author: Sopra Steria, SysIKT KO
Updated date: 2025-11-06
Takk til Alexander Filipin for utgangspunktet til scriptet:
https://github.com/AlexFilipin/ConditionalAccess/blob/master/Deploy-NamedLocations.ps1
NB! NB! NB!
Om ein er ukjent med CA, så lag først ein break-glas konto så ein ikkje stenger seg sjølv ute frå tenanten ved ein feil!
https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/security-emergency-access
Denne versjonen av scriptet er tilpassa for å kunne brukes av medlemmer av Nasjonalt beskyttelsesprogram (NBP),
men har blitt utvikla for å passe inn i SysIKT KO sitt driftsmiljø, og ein må rekne med å måtte gjere lokale tilpassingar.
Helse- og KommuneCERT mottar gjerne oppdaterte versjoner av scriptet frå andre medlemmer som vil bidra til å forbedre det.
Variablane må settes i fila config.txt før kjøring av scriptet. Denne er referert til i linje 79 i koden.
Det anbefales å kjøre scriptet manuelt første gang for å sjekke at det fungerer som forventa.
Scriptet krever at det blir oppretta ein applikasjon i Entra med riktige rettigheter, samt eit sertifikat som blir brukt til autentisering.
https://www.alitajran.com/connect-to-microsoft-graph-powershell/#h-method-2-how-to-connect-to-microsoft-graph-with-certificate-based-authentication-cba
Det anbefales å først kjøre scriptet manuelt for å sjekke at det fungerer slik det skal,
når det er gjort setter man opp ein Scheduled task på ein server:
https://lazyadmin.nl/powershell/how-to-create-a-powershell-scheduled-task/
Obs! Brukaren som kjører scriptet må ha sertifikatet oppretta i førre steg i sin personlige sert-store.
Det må lages ein "tom" Named Location og opprettes ein eigen Condtional Access policy som hindrer all pålogging frå IPane i den Named Location.
ID'en til Named Location finner man ved å kjøre: Get-MgIdentityConditionalAccessNamedLocation -All
https://newhelptech.wordpress.com/2022/03/01/step-by-step-how-to-configuring-conditional-access-policy-to-restrict-access-from-specific-location-in-office-365/ (berre ikkje velg land!)
Potensielle forbedringer:
- Logging
- Epost utsending via Microsoft Graph / andre varslingsmetoder som td. Teams eller API
- Kjøre scriptet som en Azure Automation istadenfor i Task Scheduler
- Fjerne klartekst brukarnavn og passord
- Array av public ip-adresser/ipnett mot blocklista og varsling på dette, for virksomheter som har fleire public ip-adresser i bruk.
- Støtte bruk av proxy for nedlasting av blokkeringslister
Mtp. bruk av proxy kan kode som dette kan benyttes:
$ProxyServer = 'http://proxy.virksomhet.local:3128'
#ved autentisert proxy, og spesifikt brukernavn og passord for proxy, bruk -ProxyCredential parameteret (med credential som argument) til Invoke-WebRequest linja.
#ved autentisert proxy, og credential til bruker som kjører scriptet også brukes for proxy, bruk -UseDefaultCredentials som parameter (uten argument) til Invoke-Webrequest linja.
if ($proxyserver) {
Invoke-WebRequest -Uri $blocklisturl -Credential $credential -Proxy $ProxyServer | Select-Object -ExpandProperty Content | Out-File $NamedLocations
}
else {
Invoke-WebRequest -Uri $blocklisturl -Credential $credential | Select-Object -ExpandProperty Content | Out-File $NamedLocations
}
#>
############################################################################################################
# Variabel som kan endrast
############################################################################################################
# lokasjon for konfigurasjon for scriptet
$configfil = "C:\Scripts\_Task scheduler\config.txt"
############################################################################################################
# Slutt: Variabel som kan endrast
############################################################################################################
# Henter inn configdata fra filen config.txt
Get-Content $configfil | ForEach-Object {
$key, $val = $_ -split '='
if($val -ne $null) {
$key = $key.Trim()
$val = $val.Trim()
if ($key -eq '$TenantId') { $TenantId=$val }
elseif ($key -eq '$AppId') { $AppId=$val }
elseif ($key -eq '$CertificateThumbprint') { $CertificateThumbprint=$val }
elseif ($key -eq '$NBPpass') { $NBPpass=$val }
elseif ($key -eq '$smtpserver') { $smtpserver=$val }
elseif ($key -eq '$smtpto') { $smtpto=$val }
elseif ($key -eq '$smtpfrom') { $smtpfrom=$val }
elseif ($key -eq '$NamedLocations') { $NamedLocations=$val }
elseif ($key -eq '$blocklistdomain') { $blocklistdomain=$val }
elseif ($key -eq '$NamedLocationId') { $NamedLocationId=$val }
}
}
# Sjekker om variabler er endret før kjøring
if($NBPpass -eq 'DittNbpBlocklistPassord') {write-error 'Variabel $NBPpass ikke endret fra defaultverdi. Gjør dette før kjøring'; Exit}
if($smtpserver -eq "X.X.X.X") {write-error 'Variabel $smtpserver ikke endret fra defaultverdi. Gjør dette før kjøring'; Exit}
foreach($smtptoemail in $smtpto){if($smtptoemail.contains("virksomhet.local")) {write-error 'Variabel $NBPsmtptouser ikke endret fra defaultverdi. Gjør dette før kjøring'; Exit}}
if($smtpfrom -eq "noreply@virksomhet.local") {write-error 'Variabel $smtpfrom ikke endret fra defaultverdi. Gjør dette før kjøring'; Exit}
if($TenantId -eq "12345678-abcd-1234-abcd-0123456789abcd") {write-error 'Variabel $TenantId ikke endret fra defaultverdi. Gjør dette før kjøring'; Exit}
if($AppId -eq "12345678-1234-abcd-1234-0123456789abcd") {write-error 'Variabel $AppId ikke endret fra defaultverdi. Gjør dette før kjøring'; Exit}
if($CertificateThumbprint -eq "AA123456ABC12345ABC41B4F20E4B2D1") {write-error 'Variabel $CertificateThumbprint ikke endret fra defaultverdi. Gjør dette før kjøring'; Exit}
if($blocklistdomain -eq "blocklistdomain.local") {write-error 'Variabel $blocklistdomain ikke endret fra defaultverdi. Gjør dette før kjøring'; Exit}
if($NamedLocationId -eq "1234abcd-1234-abcd-1324-abcdf12345") {write-error 'Variabel $blocklistdomain ikke endret fra defaultverdi. Gjør dette før kjøring'; Exit}
# Sett parameter for nedlasting av blocklist fra Helse og KommuneCERT
$blocklisturl = "https://$blocklistdomain/v3?apikey="+ $NBPpass +"&format=list_cidr&type=ipv4&type=ipv4_cidr&type=ipv6&type=ipv6_cidr&list_name=auth&list_name=default"
# Sjekker om fila NamedLocations finnes fra før, vis ikkje opprette den
if(!(Test-Path $NamedLocations)) {New-Item -Path $NamedLocations -ItemType File -Force}
#Requires -Modules Microsoft.Graph.Authentication, Microsoft.Graph.Identity.SignIns
#region connect
Import-Module -Name Microsoft.Graph.Authentication
Import-Module -Name Microsoft.Graph.Identity.SignIns
try { Disconnect-MgGraph -ErrorAction SilentlyContinue }catch {}
Connect-MgGraph -TenantId $TenantId -AppId $AppId -CertificateThumbprint $CertificateThumbprint -ErrorAction Stop
#endregion
$NBPsecpasswd = ConvertTo-SecureString $NBPpass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($NBPuser, $NBPsecpasswd)
# Last ned nyeste blocklist fra Helse- og KommuneCERT
Write-Host "Laster ned blocklist frå Helse- og KommuneCERT" -ForegroundColor Green
Invoke-WebRequest -Uri $blocklisturl -Credential $credential | Select-Object -ExpandProperty Content | Out-File $NamedLocations
# Sjekk om filen er lastet ned og ikkje tom. Dette gjøres for å unngå at scriptet overskriver Named Locations med ei tom fil.
if ((Test-Path $NamedLocations) -and (Get-Content $NamedLocations | Measure-Object -Line).Lines -gt 0) {
# Importer csv fil
$Locations = Import-Csv -Path $NamedLocations -Delimiter "`t" -Header "cidrAddress"
# Fjerner duplikater
$Locations = $Locations | Group-Object -Property cidrAddress | ForEach-Object { $_.Group[0] }
# Bygge opp body
$params = @{
"@odata.type" = "#microsoft.graph.ipNamedLocation"
DisplayName = "HelseCertBlockList"
isTrusted = $false
}
$params.Add("IpRanges",@())
# Loop gjennom alle ipane i csv filen
foreach ($Location in $Locations) {
$IpRanges = @{}
if ($Location.cidrAddress -match ":") {
write-host "Legger til IPv6:" $Location.cidrAddress -ForegroundColor Yellow
# Finner IPv6 (inneholder kolon)
$IpRanges.add("@odata.type", "#microsoft.graph.iPv6CidrRange")
}
else {
write-host "Legger til IPv4:" $Location.cidrAddress -ForegroundColor Yellow
$IpRanges.add("@odata.type", "#microsoft.graph.iPv4CidrRange")
}
$IpRanges.add("CidrAddress", $Location.cidrAddress)
$params.IpRanges += $IpRanges
}
$params | ConvertTo-Json -Depth 4
# Oppdater Named Location
write-host "Oppdaterer Named Locations" -ForegroundColor Green
Update-MgIdentityConditionalAccessNamedLocation -NamedLocationId $NamedLocationId -BodyParameter $params
}
else {
Write-Host "Nedlasting feilet! Avslutter scriptet." -ForegroundColor Red
Send-MailMessage -SmtpServer $smtpserver -To $smtpto -From $smtpfrom -Subject "Nedlasting av blokkliste fra Helse- og KommuneCERT feilet!” -Body "Scriptet Update-NamedLocationsFromHelseCert.ps1 feila ved nedlasting av ny blockliste fil!" -Encoding UTF8
}
#region disconnect
try {
write-host "Kobler fra MgGraph" -ForegroundColor Green
Disconnect-MgGraph -ErrorAction SilentlyContinue
}catch {}
#endregion