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

Feature/add linux commands to readme file #65

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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/",
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
38 changes: 21 additions & 17 deletions Source/BSN.IpTables.Cli/Generate-PowerShellClient.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,25 @@
$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 {
Write-Host "Nvm is installed, version" $(nvm --version)
}
catch {
Write-Error "Nvm is not installed, install it manually to continue."
}

# 18.18.0 is the latest LTS node version
New-Variable -Name desiredNodeVersion -Value 'v18.18.0' -Option ReadOnly
if ($(nvm current) -ne $desiredNodeVersion) {
nvm install $desiredNodeVersion
nvm use $desiredNodeVersion
}
else {
Write-Host "Node is installed, version" $desiredNodeVersion
}
try {
Write-Host "Nvm is installed, version" $(nvm --version)
}
catch {
Write-Error "Nvm is not installed, install it manually to continue."
}

# # 18.18.0 is the latest LTS node version
# New-Variable -Name desiredNodeVersion -Value 'v18.18.0' -Option ReadOnly
if ($(nvm current) -ne $desiredNodeVersion) {
nvm install $desiredNodeVersion
nvm use $desiredNodeVersion
}
else {
Write-Host "Node is installed, version" $desiredNodeVersion
}

try {
(autorest --version).Split([Environment]::NewLine) | Select -First 1
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
cp custom/* generated/custom

# Build Module
Write-Host "Building generating Cli .." -ForegroundColor Green
.\generated\build-module.ps1
Expand Down
51 changes: 35 additions & 16 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
- NVM (nvm install 8.0) - You need to install Node.js v10.13.0 or greater.
- autorest in linux - npm install -g autorest
- dotnet sdk if not exists - 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
## Sample Commands in Windows
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 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,25 @@ 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

## Sample Commands in Linux
First - autorest ./configuration.yaml in cli directory

Then - pwsh Generate-PowerShellClient.ps1

Finally - pwsh ./generated\run-module.ps1

Next steps are the same as windows
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() { }
}
}
Loading