Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add connect method to set destination server. #56

Merged
merged 26 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
8e2fd4e
change uri with serverAddress substring
Dec 16, 2023
661ac42
Modify serverAddress location to env
Dec 21, 2023
9e4defd
pre-autorest deleted and powershellcliend modified
Dec 26, 2023
a8d698a
Connect moved to custom
Dec 26, 2023
355644c
Connect modified
Dec 26, 2023
956afe1
Connect modified
Dec 26, 2023
6e0e9c9
Connect modified
Dec 26, 2023
eae25ad
Connect modified
Dec 26, 2023
1d46b74
Fix connect error in build
siadatism Dec 27, 2023
b7879d2
Fix uri path error
siadatism Dec 28, 2023
7e77036
Fix uri path error
siadatism Dec 28, 2023
9ece3c5
Cli readme file updated
Dec 29, 2023
ec1cf77
Reuest url modification simplified in module.cs
Dec 29, 2023
beb81c2
Fix code review points.
Dec 30, 2023
328fee8
Connect method modified for 2023-12-31 comments
Jan 1, 2024
207844e
Merge branch 'feature/add-connect-method-with-file' of https://github…
Jan 1, 2024
79d98ad
cli readme file modified for win and linux
Jan 16, 2024
95c6e17
Update README.md
amirhosseinmirmohammad Jan 16, 2024
c90f67b
Update README.md
amirhosseinmirmohammad Jan 16, 2024
093379e
Update README.md
amirhosseinmirmohammad Jan 16, 2024
a755dee
uncomment nvm installation in pwsh
Jan 20, 2024
23581f8
ConfigureSwaggerOptions url changed
Jan 20, 2024
3d16f94
connect-method-change-address-text-modified-andcreated-new-exception-…
Jan 20, 2024
c71b3fe
connect-method-change-address-text-modified-andcreated-new-exception-…
Jan 20, 2024
1f7ede1
Modify module.cs comments format
Jan 24, 2024
a17520b
Some comment improvements.
Jan 26, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@
"isRoot": true,
"tools": {
"cake.tool": {
"version": "3.1.0",
"version": "3.2.0",
"commands": [
"dotnet-cake"
]
},
"csharpier": {
"version": "0.26.7",
"commands": [
"dotnet-csharpier"
]
}
}
}
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://resaa.net/",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resaa.net?!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Passive aggressive comment :D

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please resolve Url value

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
6 changes: 5 additions & 1 deletion 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 Down Expand Up @@ -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
cp custom/* generated/custom

# Build Module
Write-Host "Building generating Cli .." -ForegroundColor Green
.\generated\build-module.ps1
Expand Down
33 changes: 19 additions & 14 deletions Source/BSN.IpTables.Cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,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,7 +62,7 @@ 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:
Expand All @@ -70,9 +71,13 @@ To see full help for a command run:

## Sample Commands

1. List all existing IpTable rules.
1. Connect to main server.

Get-BsnIPTablesCli -serverAddress 192.168.21.56:8080
Connect-BsnIPTablesCli -serverAddress 192.168.21.56:8080

2. List all existing IpTable rules.

Get-BsnIPTablesCli

Sample output:

Expand All @@ -91,20 +96,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 +121,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 +137,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,15 +153,15 @@ 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:

Expand Down
48 changes: 48 additions & 0 deletions Source/BSN.IpTables.Cli/custom/Connect-BsnIPTablesCli.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<#
.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://example.com"
Establishes a connection to the BSN IP Tables with the server address "http://example.com".

.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
}
# Save the ServerAddress in a session variable
$env:ServerAddress = $ServerAddress
}

process {
Write-Output "Connected to: $ServerAddress"
}

end {
}
}
56 changes: 56 additions & 0 deletions Source/BSN.IpTables.Cli/custom/Module.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//The partial class Module appears to be a part of an application that utilizes AutoRest-generated code. AutoRest is a tool used for generating client libraries for accessing RESTful web services. In this context, the Module partial class is likely used to extend or modify the behavior of the AutoRest-generated classes and methods.
//Here we are trying to get enviromental variable mean server address and set to requst of all urls in SendAsync method
//Also we have AfterCreatePipeline,BeforeCreatePipeline and CustomInit that are called at the required places to do somethings
//Pipeline Modification: The Module class contains methods (AfterCreatePipeline and BeforeCreatePipeline) that seem to be involved in the creation of an HTTP pipeline (HttpPipeline). This pipeline is likely used for handling HTTP requests and responses.
//SendAsync Method: The SendAsync method is asynchronous and is involved in processing HTTP requests. It uses the GetIptabaleServerAddressAsync method to obtain a server address, modifies the request URI accordingly, and then delegates to the next step in the pipeline.

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
{
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
) { }

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)
{
Console.WriteLine("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() { }
}
}