|
1 | 1 | using System; |
2 | 2 | using System.Collections.Generic; |
| 3 | +using System.Linq; |
3 | 4 | using System.Management.Automation.Runspaces; |
| 5 | +using System.Text; |
4 | 6 | using System.Threading; |
5 | 7 | using System.Threading.Tasks; |
6 | 8 | using SMA = System.Management.Automation; |
@@ -231,6 +233,142 @@ await Task.Run(() => |
231 | 233 | } |
232 | 234 | } |
233 | 235 |
|
| 236 | + /// <summary> |
| 237 | + /// Creates a new Windows Firewall rule with the properties specified in <paramref name="rule"/>. |
| 238 | + /// The rule's <see cref="FirewallRule.Name"/> is prefixed with <see cref="RuleIdentifier"/> so |
| 239 | + /// it is picked up by <see cref="GetRulesAsync"/> on the next refresh. |
| 240 | + /// </summary> |
| 241 | + /// <param name="rule"> |
| 242 | + /// The firewall rule to create. |
| 243 | + /// </param> |
| 244 | + /// <exception cref="Exception"> |
| 245 | + /// Thrown when the PowerShell pipeline reports one or more errors. |
| 246 | + /// </exception> |
| 247 | + public static async Task AddRuleAsync(FirewallRule rule) |
| 248 | + { |
| 249 | + await Lock.WaitAsync(); |
| 250 | + try |
| 251 | + { |
| 252 | + await Task.Run(() => |
| 253 | + { |
| 254 | + using var ps = SMA.PowerShell.Create(); |
| 255 | + ps.Runspace = SharedRunspace; |
| 256 | + |
| 257 | + ps.AddScript(BuildAddScript(rule)); |
| 258 | + ps.Invoke(); |
| 259 | + |
| 260 | + if (ps.Streams.Error.Count > 0) |
| 261 | + throw new Exception(string.Join("; ", ps.Streams.Error)); |
| 262 | + }); |
| 263 | + } |
| 264 | + finally |
| 265 | + { |
| 266 | + Lock.Release(); |
| 267 | + } |
| 268 | + } |
| 269 | + |
| 270 | + /// <summary> |
| 271 | + /// Builds the PowerShell script that calls <c>New-NetFirewallRule</c> with all |
| 272 | + /// properties from <paramref name="rule"/>. |
| 273 | + /// </summary> |
| 274 | + /// <param name="rule"> |
| 275 | + /// The firewall rule whose properties are used to build the script. |
| 276 | + /// </param> |
| 277 | + private static string BuildAddScript(FirewallRule rule) |
| 278 | + { |
| 279 | + var sb = new StringBuilder(); |
| 280 | + sb.AppendLine("$params = @{"); |
| 281 | + sb.AppendLine($" DisplayName = '{RuleIdentifier}{EscapePs(rule.Name)}'"); |
| 282 | + sb.AppendLine($" Enabled = '{(rule.IsEnabled ? "True" : "False")}'"); |
| 283 | + sb.AppendLine($" Direction = '{rule.Direction}'"); |
| 284 | + sb.AppendLine($" Action = '{rule.Action}'"); |
| 285 | + sb.AppendLine($" Protocol = '{GetProtocolString(rule.Protocol)}'"); |
| 286 | + sb.AppendLine($" InterfaceType = '{GetInterfaceTypeString(rule.InterfaceType)}'"); |
| 287 | + sb.AppendLine($" Profile = '{GetProfileString(rule.NetworkProfiles)}'"); |
| 288 | + sb.AppendLine("}"); |
| 289 | + |
| 290 | + if (!string.IsNullOrWhiteSpace(rule.Description)) |
| 291 | + sb.AppendLine($"$params['Description'] = '{EscapePs(rule.Description)}'"); |
| 292 | + |
| 293 | + if (rule.Protocol is FirewallProtocol.TCP or FirewallProtocol.UDP) |
| 294 | + { |
| 295 | + if (rule.LocalPorts.Count > 0) |
| 296 | + sb.AppendLine($"$params['LocalPort'] = '{FirewallRule.PortsToString(rule.LocalPorts, ',', false)}'"); |
| 297 | + |
| 298 | + if (rule.RemotePorts.Count > 0) |
| 299 | + sb.AppendLine($"$params['RemotePort'] = '{FirewallRule.PortsToString(rule.RemotePorts, ',', false)}'"); |
| 300 | + } |
| 301 | + |
| 302 | + if (rule.LocalAddresses.Count > 0) |
| 303 | + sb.AppendLine($"$params['LocalAddress'] = '{string.Join(',', rule.LocalAddresses.Select(EscapePs))}'"); |
| 304 | + |
| 305 | + if (rule.RemoteAddresses.Count > 0) |
| 306 | + sb.AppendLine($"$params['RemoteAddress'] = '{string.Join(',', rule.RemoteAddresses.Select(EscapePs))}'"); |
| 307 | + |
| 308 | + if (rule.Program != null && !string.IsNullOrWhiteSpace(rule.Program.Name)) |
| 309 | + sb.AppendLine($"$params['Program'] = '{EscapePs(rule.Program.Name)}'"); |
| 310 | + |
| 311 | + sb.AppendLine("New-NetFirewallRule @params"); |
| 312 | + |
| 313 | + return sb.ToString(); |
| 314 | + } |
| 315 | + |
| 316 | + /// <summary> |
| 317 | + /// Escapes a string for embedding inside a PowerShell single-quoted string by |
| 318 | + /// doubling any single-quote characters. |
| 319 | + /// </summary> |
| 320 | + /// <param name="value">The raw string value to escape.</param> |
| 321 | + private static string EscapePs(string value) => value.Replace("'", "''"); |
| 322 | + |
| 323 | + /// <summary> |
| 324 | + /// Maps a <see cref="FirewallProtocol"/> value to the string accepted by |
| 325 | + /// <c>New-NetFirewallRule -Protocol</c>. |
| 326 | + /// </summary> |
| 327 | + /// <param name="protocol">The protocol to convert.</param> |
| 328 | + private static string GetProtocolString(FirewallProtocol protocol) => protocol switch |
| 329 | + { |
| 330 | + FirewallProtocol.Any => "Any", |
| 331 | + FirewallProtocol.TCP => "TCP", |
| 332 | + FirewallProtocol.UDP => "UDP", |
| 333 | + FirewallProtocol.ICMPv4 => "ICMPv4", |
| 334 | + FirewallProtocol.ICMPv6 => "ICMPv6", |
| 335 | + FirewallProtocol.GRE => "GRE", |
| 336 | + FirewallProtocol.L2TP => "L2TP", |
| 337 | + _ => ((int)protocol).ToString() |
| 338 | + }; |
| 339 | + |
| 340 | + /// <summary> |
| 341 | + /// Maps a <see cref="FirewallInterfaceType"/> value to the string accepted by |
| 342 | + /// <c>New-NetFirewallRule -InterfaceType</c>. |
| 343 | + /// </summary> |
| 344 | + /// <param name="interfaceType">The interface type to convert.</param> |
| 345 | + private static string GetInterfaceTypeString(FirewallInterfaceType interfaceType) => interfaceType switch |
| 346 | + { |
| 347 | + FirewallInterfaceType.Wired => "Wired", |
| 348 | + FirewallInterfaceType.Wireless => "Wireless", |
| 349 | + FirewallInterfaceType.RemoteAccess => "RemoteAccess", |
| 350 | + _ => "Any" |
| 351 | + }; |
| 352 | + |
| 353 | + /// <summary> |
| 354 | + /// Converts the three-element network-profile boolean array (Domain, Private, Public) |
| 355 | + /// to the comma-separated profile string accepted by <c>New-NetFirewallRule -Profile</c>. |
| 356 | + /// All-false or all-true both map to <c>"Any"</c>. |
| 357 | + /// </summary> |
| 358 | + /// <param name="profiles">Three-element boolean array (Domain=0, Private=1, Public=2).</param> |
| 359 | + private static string GetProfileString(bool[] profiles) |
| 360 | + { |
| 361 | + if (profiles == null || profiles.Length < 3 || profiles.All(p => p) || profiles.All(p => !p)) |
| 362 | + return "Any"; |
| 363 | + |
| 364 | + var parts = new List<string>(3); |
| 365 | + if (profiles[0]) parts.Add("Domain"); |
| 366 | + if (profiles[1]) parts.Add("Private"); |
| 367 | + if (profiles[2]) parts.Add("Public"); |
| 368 | + |
| 369 | + return parts.Count == 0 ? "Any" : string.Join(",", parts); |
| 370 | + } |
| 371 | + |
234 | 372 | /// <summary> |
235 | 373 | /// Parses a PowerShell direction string (e.g. <c>"Outbound"</c>) to a |
236 | 374 | /// <see cref="FirewallRuleDirection"/> value. Defaults to <see cref="FirewallRuleDirection.Inbound"/>. |
|
0 commit comments