-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateNPSClientV3.ps1
328 lines (257 loc) · 12.3 KB
/
createNPSClientV3.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
param(
[string]$CsvFilePath,
[Parameter(Mandatory = $false)]
[string]$IPAddress,
[Parameter(Mandatory = $false)]
[string]$ClientName,
[Parameter(Mandatory = $false)]
[string]$SharedSecret,
[Parameter(Mandatory = $false)]
[string]$Projectname,
[Parameter(Mandatory = $false)]
[string]$Regex
)
# Start Transcript
$transcriptPath = "C:\buildLog\createnpsclient_Transcript_Log_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt"
Start-Transcript -Path $transcriptPath -Append
# Get the script file name without extension
$scriptName = [System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Path)
# Define the log file path using the script file name and current date/time
$logFilePath = "C:\buildLog\$scriptName.log"
function Write-Log {
param(
[string]$Message,
[string]$Level = ""
)
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$logMessage = "$timestamp - [$Level] $Message"
if (-not (Test-Path $logFilePath)) {
New-Item -ItemType File -Path $logFilePath -Force | Out-Null
}
$logMessage | Out-File -FilePath $logFilePath -Append
}
function Backup-NPSFile {
param (
[string]$FilePath
)
# Check if the file exists
if (-not (Test-Path -Path $FilePath -PathType Leaf)) {
Write-Host "Error: File '$FilePath' not found."
return
}
# Generate a timestamp to append to the backup file name
$timestamp = Get-Date -Format "yyyy-MM-dd-HHmm"
# Extract filename and extension from the source file path
$fileName = [System.IO.Path]::GetFileNameWithoutExtension($FilePath)
$fileExtension = [System.IO.Path]::GetExtension($FilePath)
# Construct the backup file name with timestamp
$backupFileName = "${fileName}_Backup_$timestamp$fileExtension"
# Construct the full path for the backup file in the same directory as the source file
$backupFilePath = Join-Path -Path (Split-Path -Path $FilePath -Parent) -ChildPath $backupFileName
# Copy the source file to the backup location
Copy-Item -Path $FilePath -Destination $backupFilePath -Force
# Output the success message
Write-Host "Backup of NPS configuration '$FilePath' created at '$backupFilePath' `n" -ForegroundColor Yellow
Write-Log "Backup of NPS configuration '$FilePath' created at '$backupFilePath" -Level "SUCCESS"
}
function Add-ConnectionRequestPolicy {
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]$IPAddress,
[Parameter(Mandatory = $false)]
[string]$ClientName,
[Parameter(Mandatory = $false)]
[string]$Projectname,
[Parameter(Mandatory = $false)]
[string]$Regex
)
# Determine the value for conditiondata based on the regex parameter
$conditiondata = if ($Regex) { $Regex } else { $IPAddress }
# Get the current Policy Number
$IASConfig = [XML](Get-Content -Path C:\Windows\System32\ias\ias.xml)
[int]$CurrentProcessingOrder = $IASConfig.root.children.Microsoft_Internet_Authentication_Service.children.Proxy_Policies.Children.LastChild.Properties.msNPSequence.'#text'
$NextProcessOrder = $CurrentProcessingOrder + 1
$logMessage = "Adding Connection Request Policy with name: $Projectname_$ClientName with IP: $IPAddress"
Write-Host $logMessage -ForegroundColor Green
write-Log -message $logMessage -Level "INFO"
$arguments = @(
"name = `"$Projectname`_$ClientName`"",
"conditionid = `"0x100c`"",
"conditiondata = `"$conditiondata`"",
"processingorder = $NextProcessOrder",
"policysource = '0'",
"profileid = '0x1025'",
"profiledata = '0x1'"
)
try {
$command = "netsh nps add crp " + ($arguments -join ' ')
$output = Invoke-Expression $command
if ($output -eq 'Ok.' ) {
Write-Log -message "Command executed successfully." -Level "INFO"
Write-Host "Connection request policy With Name $Projectname_$ClientName with $IPAddress has been created successfully `n" -ForegroundColor Green
Write-Log -Message "Connection request policy With Name $Projectname_$ClientName with $IPAddress has been created successfully" -Level "SUCCESS"
}
else {
Write-Log -message "Command failed with output: $output" -level "WARNING"
Write-Host "Command failed with output: $output `n"
}
}
catch {
write-log -message "Failed to execute command: $_" -level "ERROR"
Write-Host "Failed to execute command: $_ `n"
}
}
function Add-NpsNetworkPolicy {
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]$IPAddress,
[Parameter(Mandatory = $false)]
[string]$ClientName,
[Parameter(Mandatory = $false)]
[string]$Projectname,
[Parameter(Mandatory = $false)]
[string]$Regex
)
# Determine the value for conditiondata based on the regex parameter
$conditiondata = if ($Regex) { $Regex } else { $IPAddress }
# Get the current Policy Number
$IASConfig = [XML](Get-Content -Path C:\Windows\System32\ias\ias.xml)
[int]$CurrentProcessingOrder = $IASConfig.root.children.Microsoft_Internet_Authentication_Service.children.NetworkPolicy.children.LastChild.Properties.msNPSequence.'#text'
$NextProcessOrder = $CurrentProcessingOrder + 1
$logMessage = "Adding Network Policy with name: $ProjectName_$ClientName and IPAddress: $ip"
Write-Log -message $logMessage -level "INFO"
Write-Host $logMessage -ForegroundColor Green
$arguments = @(
"name = `"$Projectname`_$ClientName`"",
"conditionid = '0x100c'",
"conditiondata = `"$conditiondata`"",
"policysource = '0'",
"processingorder = `"$NextProcessOrder`"",
"profileid = '0x1009'",
"profiledata = '0x1'",
"profiledata = '0x2'",
"profiledata = '0x3'",
"profiledata = '0x9'",
"profiledata = '0x4'",
"profiledata = '0xa'",
"profiledata = '0x7'",
"profileid = '0x1005'",
"profiledata = 'TRUE'",
"profileid = '0x100f'",
"profiledata = 'TRUE'",
"profileid = '0x7'",
"profiledata = '0x1'",
"profileid = '0x6'",
"profiledata = '0x2'",
"profileid = '0x1b'",
"profiledata = '0x1a4'"
)
try {
$command = "netsh nps add np " + ($arguments -join ' ')
$output = Invoke-Expression $command
if ($output -eq "Ok.") {
Write-Log -message "Command executed successfully." -Level "INFO"
Write-Host "Network policy With Name $Projectname`_$ClientName with $IPAddress has been created successfully `n" -ForegroundColor Green
Write-Log -Message "Network policy With Name $Projectname`_$ClientName with $IPAddress has been created successfully" -Level "SUCCESS"
}
else {
Write-Log -message "Command failed with output: $output" -level "ERROR"
Write-Host "Command failed with output: $output `n" -ForegroundColor Yellow
}
}
catch {
Write-Log -message "Failed to execute command: $_" -level "ERROR"
Write-Host "$_ `n" -ForegroundColor Yellow
}
}
$StartTime = (Get-Date)
Write-Log "Script Started at: $(Get-date -format 'dd/MM/yyy hh:mm:ss tt')" -Level "INFO"
Write-Host "############ Script Started at: $(Get-date -format 'dd/MM/yyy hh:mm:ss tt')############## `n" -ForegroundColor Yellow
#################################################
# Main Script
#############################################3
#Backup NPS Configuration File
Backup-NPSFile -FilePath "C:\Windows\System32\ias\ias.xml"
# Creatin New NPS Clients and its corresponding Conection Request Policies and Network Policies.
# Check if CSV file path is provided
if ($CsvFilePath) {
# Check if CSV file exists
if (-not (Test-Path $CsvFilePath -PathType Leaf)) {
Write-Host "CSV file not found at the specified path."
exit
}
# Read CSV file
$CsvData = Import-Csv -Path $CsvFilePath
# Iterate through each entry in the CSV file
foreach ($Entry in $CsvData) {
$IPAddress = $Entry.IPAddress
$ClientName = $Entry.ClientName
$SharedSecret = $Entry.SharedSecret
$Projectname = $Entry.Projectname
$Regex = $Entry.Regex
# Create NPS client
try {
$NpsClient = New-NpsRadiusClient -Name $ClientName -Address $IPAddress -SharedSecret $SharedSecret -VendorName "RADIUS Standard"
if ($null -ne $NpsClient) {
Write-Log -Message "NPS client '$ClientName' with IP address '$IPAddress' has been created successfully." -Level "SUCCESS"
Write-Host "NPS client '$ClientName' with IP address '$IPAddress' has been created successfully . `n"
Add-ConnectionRequestPolicy -IPAddress $IPAddress -ClientName $ClientName -Projectname $Projectname -Regex $Regex
Add-NpsNetworkPolicy -IPAddress $IPAddress -ClientName $ClientName -Projectname $Projectname -Regex $Regex
Get-NpsRadiusClient | Where-Object { $_.name -eq "$ClientName" }
& netsh nps show cp | select-string "$ClientName" -Context 2, 13 | Out-Host
& netsh nps show np | select-string "$ClientName" -Context 2, 22 | Out-Host
}
else {
throw "An error occurred while adding NPS client '$ClientName'. The client object is null."
Write-Log -message "An error occurred while adding NPS client $ClientName." -level "ERROR"
Write-Host "Failed to create NPS client for '$ClientName' with IP address '$IPAddress'. `n"
}
}
catch {
Write-Host "An error occurred while adding NPS client '$ClientName': $_.Exception.Message `n"
Write-Log -message "An error occurred while adding NPS client '$ClientName': $_.Exception.Message" -level "ERROR"
}
}
}
elseif ($IPAddress -and $ClientName -and $SharedSecret) {
# Check if NPS role is installed
if (-not (Get-WindowsFeature -Name NPAS)) {
Write-Host "NPS role is not installed. Please install the NPS role first."
exit
}
# Create NPS client
try {
$NpsClient = New-NpsRadiusClient -Name $ClientName -Address $IPAddress -SharedSecret $SharedSecret -VendorName "RADIUS Standard"
if ($null -ne $NpsClient) {
Write-Log -Message "NPS client '$ClientName' with IP address '$IPAddress' has been created successfully." -Level "SUCCESS"
Write-Host "NPS client '$ClientName' with IP address '$IPAddress' has been created successfully.`n"
Add-ConnectionRequestPolicy -IPAddress $IPAddress -ClientName $ClientName -Projectname $Projectname -Regex $Regex
Add-NpsNetworkPolicy -IPAddress $IPAddress -ClientName $ClientName -Projectname $Projectname -Regex $Regex
Get-NpsRadiusClient | Where-Object { $_.name -eq "$ClientName" }
& netsh nps show cp | select-string "$ClientName" -Context 2, 13 | Out-Host
& netsh nps show np | select-string "$ClientName" -Context 2, 22 | Out-Host
}
else {
throw "An error occurred while adding NPS client '$ClientName'. The client object is null."
Write-Log -message "An error occurred while adding NPS client $ClientName." -level "ERROR"
Write-Host "Failed to create NPS client for '$ClientName' with IP address '$IPAddress'.`n"
}
}
catch {
Write-Host "An error occurred while adding NPS client '$ClientName': $_.Exception.Message `n"
Write-Log -message "An error occurred while adding NPS client '$ClientName': $_.Exception.Message" -level "ERROR"
}
}
$EndTime = (Get-Date)
Write-Log "Script Ended at: $(Get-date -format 'dd/MM/yyy hh:mm:ss tt')" -Level "INFO"
Write-Host "############Script Ended at: $(Get-date -format 'dd/MM/yyy hh:mm:ss tt')############ `n" -ForegroundColor Green
# Get Elapsed Time
$ElapsedTime = ($EndTime - $StartTime).Seconds
Write-Log "Script Execution Time: $ElapsedTime Seconds" -Level "INFO"
Write-Host " Script Execution Time: $ElapsedTime Seconds `n" -ForegroundColor Green
Write-Host "You can check the script logs at $logFilePath "
# Stop transcript logging
Stop-Transcript
##End of script.