Skip to content

Commit

Permalink
Add connect method to set destination server. (#56)
Browse files Browse the repository at this point in the history
Add connect method to set destination server.

---------

Co-authored-by: Amirhossein <Amirhossein@DESKTOP-RGEIFHK>
Co-authored-by: Seyed Mehran Siadati <[email protected]>
Co-authored-by: Sayed Mehran Siadati <[email protected]>
  • Loading branch information
4 people authored Jan 29, 2024
1 parent 61143bc commit 06ebb8d
Show file tree
Hide file tree
Showing 6 changed files with 173 additions and 34 deletions.
11 changes: 2 additions & 9 deletions Source/BSN.IpTables.Api/ConfigureSwaggerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,8 @@ public void Configure(SwaggerGenOptions options)
{
// Add host to generated swagger file (swagger.json)
options.AddServer(new OpenApiServer {
Url = "http://{serverAddress}",
Description = "IpTables Test Server",
Variables = new Dictionary<string, OpenApiServerVariable>
{
{ "serverAddress", new OpenApiServerVariable {
Default = "192.168.21.56:8080",
Description = "Target Server Address" }
}
}
Url = "http://iptable.bsn.local",
Description = "IpTables Test Server"
});

// add swagger document for every API version discovered
Expand Down
10 changes: 2 additions & 8 deletions Source/BSN.IpTables.Api/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,8 @@
},
"servers": [
{
"url": "http://{serverAddress}",
"description": "IpTables Test Server",
"variables": {
"serverAddress": {
"default": "192.168.21.56:8080",
"description": "Target Server Address"
}
}
"url": "http://iptable.bsn.local",
"description": "IpTables Test Server"
}
],
"paths": {
Expand Down
8 changes: 6 additions & 2 deletions Source/BSN.IpTables.Cli/Generate-PowerShellClient.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
$ErrorActionPreference = 'Stop'

if ($PSEdition -ne 'Core') {
Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.'
Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.'
}

try {
Expand All @@ -30,7 +30,7 @@ else {
}

try {
(autorest --version).Split([Environment]::NewLine) | Select -First 1
(autorest --version).Split([Environment]::NewLine) | Select-Object -First 1
}
catch {
Write-Host "autorest is not installed, installing .." -ForegroundColor Yellow
Expand All @@ -43,6 +43,10 @@ catch {
Write-Host "Generating Cli .." -ForegroundColor Green
autorest configuration.yaml --verbose

# Copy custom files
Write-Host "Copy custom files .." -ForegroundColor Green
Copy-Item "custom\*" -Destination "generated\custom"

# Build Module
Write-Host "Building generating Cli .." -ForegroundColor Green
.\generated\build-module.ps1
Expand Down
55 changes: 40 additions & 15 deletions Source/BSN.IpTables.Cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ This module was primarily generated via [AutoRest](https://github.com/Azure/auto

## Module Requirements

- None
- Node.js v18.18.0. It could be installed by NVM
- Autorest node package
- dotnet sdk if not exists (in linux run: sudo snap install dotnet-sdk)

---

Expand All @@ -50,7 +52,8 @@ All Cli commands are encapsulated in `BsnIPTablesCli` module. To show all comman
Sample output:

CommandType Name Version Source
----------- ---- ------- ------
----------- ----
Function Connect-BsnIPTablesCli 1.2.0 BsnIPTablesCli
Function Add-BsnIPTablesCli 1.2.0 BsnIPTablesCli
Function Get-BsnIPTablesCli 1.2.0 BsnIPTablesCli
Function Remove-BsnIPTablesCli 1.2.0 BsnIPTablesCli
Expand All @@ -61,18 +64,25 @@ To see a command input parameters run:

Sample output:

Add-BsnIPTablesCli -ServerAddress <string> [-Chain <string>] [-RuleDestinationIP <string>] [-RuleDestinationPort <string>] [-RuleInterfaceName <string>] [-RuleJump <string>] [-RuleProtocol <string>] [-RuleSourceIP <string>] [-RuleSourcePort <string>] [-Break] [-HttpPipelineAppend <SendAsyncStep[]>] [-HttpPipelinePrepend <SendAsyncStep[]>] [-Proxy <uri>] [-ProxyCredential <pscredential>] [-ProxyUseDefaultCredentials] [-WhatIf] [-Confirm] [<CommonParameters>]
Add-BsnIPTablesCli [-Chain <string>] [-RuleDestinationIP <string>] [-RuleDestinationPort <string>] [-RuleInterfaceName <string>] [-RuleJump <string>] [-RuleProtocol <string>] [-RuleSourceIP <string>] [-RuleSourcePort <string>] [-Break] [-HttpPipelineAppend <SendAsyncStep[]>] [-HttpPipelinePrepend <SendAsyncStep[]>] [-Proxy <uri>] [-ProxyCredential <pscredential>] [-ProxyUseDefaultCredentials] [-WhatIf] [-Confirm] [<CommonParameters>]


To see full help for a command run:

Get-Help Add-BsnIPTablesCli -Full

## Sample Commands
First run .\Generate-PowerShellClient.ps1 in cli directory

1. List all existing IpTable rules.
Then .\generated\run-module.ps1

Get-BsnIPTablesCli -serverAddress 192.168.21.56:8080
1. Connect to the main server.

Connect-BsnIPTablesCli -serverAddress 192.168.21.56:8080

2. List all existing IpTable rules.

Get-BsnIPTablesCli

Sample output:

Expand All @@ -91,20 +101,20 @@ Sample output:

Which means only one rule exists. The rule casues to drop incoming tcp packets from `1.2.3.4` IPv4 address.

2. Drop all incoming ICMP packets from any source, on all interfaces:
3. Drop all incoming ICMP packets from any source, on all interfaces:

Add-BsnIPTablesCli -serverAddress 192.168.21.56:8080 -Chain INPUT -RuleJump DROP -RuleProtocol icmp
Add-BsnIPTablesCli -Chain INPUT -RuleJump DROP -RuleProtocol icmp

3. Remove the previous rule:
4. Remove the previous rule:

Remove-BsnIPTablesCli -serverAddress 192.168.21.56:8080 -Chain INPUT -RuleJump DROP -RuleProtocol icmp
Remove-BsnIPTablesCli -Chain INPUT -RuleJump DROP -RuleProtocol icmp

## Verification

Each CLI command is equivalent to an `iptables` command. Valid execution of CLI commands could be verified by checking existing rules in the destination server.
Another way to verify a successful operation is to check rule enforcement in a traffic flow. Below are some scenarios to test IpTables by these two methods.

Scenario 1: Add a rule with `iptables`, then list existing rules with CLI and check its existence.
Scenario 1: Connect to server, then add a rule with `iptables`, then list existing rules with CLI and check its existence.

First flush rules:

Expand All @@ -116,7 +126,7 @@ Then add a rule to drop tcp packets from specific IP adddress and port:

List rules with CLI:

Get-BsnIPTablesCli -serverAddress 192.168.21.56:8080
Get-BsnIPTablesCli

Check and find added rule in output:

Expand All @@ -132,11 +142,11 @@ Check and find added rule in output:
"target": "DROP"
}

Scenario 2: Add a rule with CLI, then list existing rules with `iptables` and check its existence:
Scenario 2: Connect to server, then add a rule with CLI, then list existing rules with `iptables` and check its existence:

Add a rule to drop tcp packets to specific IP adddress range on specific interface:

Add-BsnIPTablesCli -serverAddress 192.168.21.56:8080 -Chain OUTPUT -RuleInterfaceName ens160 -RuleProtocol tcp -RuleDestinationIP 69.171.224.0/19 -RuleJump DROP
Add-BsnIPTablesCli -Chain OUTPUT -RuleInterfaceName ens160 -RuleProtocol tcp -RuleDestinationIP 69.171.224.0/19 -RuleJump DROP

List output rules with `iptables`:

Expand All @@ -148,16 +158,31 @@ Check and find added rule in output:
num target prot opt source destination
1 DROP tcp -- 0.0.0.0/0 69.171.224.0/19

Scenario 3: Add a rule with CLI, then check its effect in traffic:
Scenario 3: Connect to server, then add a rule with CLI, then check its effect in traffic:

Check ping to the server:

ping 192.168.21.56

Add a rule to drop incoming icmp packets:

Add-BsnIPTablesCli -serverAddress 192.168.21.56:8080 -Chain INPUT -RuleJump DROP -RuleProtocol icmp
Add-BsnIPTablesCli -Chain INPUT -RuleJump DROP -RuleProtocol icmp

Check ping to the server, it should not be available:

ping 192.168.21.56

## Running in Linux
First install dotnet sdk and powershell:

sudo snap install dotnet-sdk pwsh

Then:

pwsh Generate-PowerShellClient.ps1

Finally:

pwsh ./generated/run-module.ps1

Next steps are the same as windows.
55 changes: 55 additions & 0 deletions Source/BSN.IpTables.Cli/custom/Connect-BsnIPTablesCli.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<#
.SYNOPSIS
This cmdlet establishes a connection to the BSN IP Tables with the specified server address.
.DESCRIPTION
The Connect-BsnIPTablesCli cmdlet connects to the BSN IP Tables using the provided server address.
It is a mandatory parameter, and the connection is established in the begin block.
.PARAMETER ServerAddress
Specifies the target server address for the connection. This is a mandatory parameter.
.EXAMPLE
Connect-BsnIPTablesCli -ServerAddress "http://iptable.bsn.local"
Establishes a connection to the BSN IP Tables with the server address "http://iptable.bsn.local".
.NOTES
File Name : Connect-BsnIPTablesCli.ps1
Prerequisite : PowerShell V5
Copyright 2019 - The BSN Team
#>

function Connect-BsnIPTablesCli {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[BSN.IpTables.V1.Category('Uri')]
[System.String]
# Target Server Address
${ServerAddress}
)

begin {
# Check if $ServerAddress is null
if ($null -eq $ServerAddress) {
Write-Error "ServerAddress is mandatory. Please provide a valid value."
return
}
# Check if the ServerAddress environment variable exists
$previousValue = $env:ServerAddress
$envExists = [System.Environment]::GetEnvironmentVariable('ServerAddress', [System.EnvironmentVariableTarget]::Process) -ne $null

if ($envExists) {
Write-Output "Last ServerAddress was: $previousValue and now is changed to: $ServerAddress"
}
else {
Write-Output "Connected to: $ServerAddress"
}

# Save the ServerAddress in a session variable
$env:ServerAddress = $ServerAddress
}

end {
}
}
68 changes: 68 additions & 0 deletions Source/BSN.IpTables.Cli/custom/Module.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
* The partial class Module is used to extend or modify the behavior of the AutoRest-generated classes and methods.
* Here we are trying to get the environmental variable server address and set to request of all URLs in SendAsync method.
*/

using System;
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BSN.IpTables.V1
{
public partial class Module
{
/**
* Pipeline Modification: The Module class contains methods (AfterCreatePipeline and BeforeCreatePipeline) that are
* involved in the creation of an HTTP pipeline (HttpPipeline).
* This pipeline is used for handling HTTP requests and responses.
*/
partial void AfterCreatePipeline(
global::System.Management.Automation.InvocationInfo invocationInfo,
ref BSN.IpTables.V1.Runtime.HttpPipeline pipeline
)
{
if (pipeline == null)
throw new NullReferenceException("Pipeline is null!");
pipeline.Append(SendAsync);
}

partial void BeforeCreatePipeline(
global::System.Management.Automation.InvocationInfo invocationInfo,
ref BSN.IpTables.V1.Runtime.HttpPipeline pipeline
) { }

/**
* The SendAsync method is involved in processing HTTP requests. It uses the
* GetIptableServerAddressAsync method to obtain a server address, modifies the request URI accordingly,
* and then delegates to the next step in the pipeline.
*/
public async System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(
System.Net.Http.HttpRequestMessage request,
BSN.IpTables.V1.Runtime.IEventListener callback,
BSN.IpTables.V1.Runtime.ISendAsync next
)
{
string serverAddress = Environment.GetEnvironmentVariable("ServerAddress").ToString();
if (serverAddress == null)
{
throw new ArgumentNullException(
nameof(serverAddress),
"ServerAddress variable is not set."
);
}
string requestUriString = request.RequestUri.ToString();
Uri newUri = new Uri(requestUriString);
string host = newUri.Host;
string finalUrl = requestUriString.Replace(host, serverAddress);
request.RequestUri = new Uri(finalUrl);
if (next == null)
throw new NullReferenceException("Next is null!");

return await next.SendAsync(request, callback);
}

partial void CustomInit() { }
}
}

0 comments on commit 06ebb8d

Please sign in to comment.