.
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: all clean proxy agent
2 |
3 | ifndef TOKEN
4 | CONN_STRING ?=
5 | else
6 | CONN_STRING = -X 'main.ConnString=$(TOKEN)'
7 | endif
8 |
9 | all: clean proxy agent
10 |
11 | proxy:
12 | go build -ldflags="-s -w" -trimpath -o proxy cmd/proxy/main.go
13 |
14 | agent:
15 | go build -ldflags="-s -w $(CONN_STRING)" -trimpath -o agent cmd/agent/main.go
16 |
17 | clean:
18 | rm -f proxy agent
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ProxyBlob
2 |
3 |
4 |
5 |
6 | SOCKS proxy over Azure Storage Blob service
7 |
8 | ## Overview
9 |
10 | ProxyBlob is a tool designed to create SOCKS proxy tunnels through Azure Blob Storage service. This is particularly useful in environments where direct network connectivity is restricted but `*.blob.core.windows.net` is accessible.
11 |
12 | The system consists of two components:
13 |
14 | 1. **Proxy Server**: Runs on your local machine and provides a SOCKS interface for your applications
15 | 2. **Agent**: Runs inside the target network and communicates with the proxy through Azure Blob Storage
16 |
17 | ## Features
18 |
19 | - SOCKS5 protocol (CONNECT and UDP ASSOCIATE)
20 | - Communication through Azure Blob Storage
21 | - Interactive CLI with auto-completion
22 | - Multiple agent management
23 | - Local proxy server
24 |
25 | ## Prerequisites
26 |
27 | - Go 1.23 or higher
28 | - An Azure Storage Account
29 |
30 | ### Storage Account
31 |
32 | #### Azure
33 |
34 | In order to use ProxyBlob, you will need an Azure Subscription to create an Azure Storage Account. Once you have a subscription, you can create a storage account in the Azure Portal or using the Azure CLI.
35 |
36 | Here are the steps to create a storage account using the Azure Portal:
37 |
38 | 1. Go to [https://portal.azure.com](https://portal.azure.com)
39 | 2. Login with your Azure account
40 | 3. In the top Search bar, type "Storage accounts"
41 | 4. Click on "+ Create"
42 | 5. Fill in the required fields
43 | 6. Click on "Review + create"
44 | 7. Click on "Create"
45 |
46 | Storage account settings:
47 |
48 | - **Subscription**: Select your Azure subscription
49 | - **Resource Group**: Create new Resource Group or select existing
50 | - **Storage account name**: Choose a name for your storage account
51 | - **Location**: Select a location near you
52 | - **Performance**: Premium ⚠️ we will require low latency and high throughput
53 | - **Premium account type**: Block blobs (high transaction rates)
54 | - **Redundancy**: Locally-redundant Storage (LRS)
55 |
56 |
57 |
58 |
59 |
60 |
61 | Once the deployment is complete, you will see the newly created storage account in the list.
62 |
63 |
64 |
65 |
66 |
67 | Finally, click on "Security + networking" and then "Access keys" to get the storage account key.
68 |
69 |
70 |
71 |
72 |
73 | Here are the steps to create a storage account using the Azure CLI:
74 |
75 | ```bash
76 | # Login to Azure
77 | az login
78 |
79 | # Create a resource group
80 | az group create --name "proxyblob-resource-group" --location "Central US"
81 |
82 | # Create a storage account
83 | az storage account create --name "myproxyblob" --resource-group "proxyblob-resource-group" --location "Central US" --sku "Premium_LRS" --kind BlockBlobStorage
84 |
85 | # Get the storage account key
86 | az storage account keys list --account-name "myproxyblob" --output table
87 | ```
88 |
89 | You should see displayed the storage account keys.
90 |
91 | #### Azurite
92 |
93 | If you want to test the tool, you can also use [Azurite](https://github.com/Azure/Azurite), a lightweight server clone of Azure Storage that can be run locally. To install Azurite, I recommend using either [Visual Studio Code extension](https://marketplace.visualstudio.com/items?itemName=Azurite.azurite) or [Docker](https://hub.docker.com/r/microsoft/azure-storage-azurite).
94 |
95 | For the extension, installation is straightforward:
96 |
97 | 1. Go to the Extensions tab
98 | 2. Search for `Azurite.azurite`
99 | 3. Click "Install"
100 |
101 | You should see down right of your editor 3 buttons like this:
102 |
103 | ```
104 | [Azurite Table Service] [Azurie Queue Service] [Azurite Blob Service]
105 | ```
106 |
107 | Press on the `[Azurite Blob Service]` and the service should be running.
108 |
109 | For Docker, you will have to pull the image and run it:
110 |
111 | ```
112 | docker pull mcr.microsoft.com/azure-storage/azurite
113 | docker run -p 10000:10000 mcr.microsoft.com/azure-storage/azurite
114 | ```
115 |
116 | The default storage account name is `devstoreaccount1` and the account key is `Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==`.
117 |
118 | ## Installation
119 |
120 | ```bash
121 | # Clone the repository
122 | git clone https://github.com/quarkslab/proxyblob
123 | cd proxyblob
124 |
125 | # Build both components
126 | make
127 | ```
128 |
129 | This will produce the following binaries:
130 |
131 | - `proxy` - the proxy server running on your machine
132 | - `agent` - the agent running on the target
133 |
134 | ## Configuration
135 |
136 | Create a `config.json` file based on the [example](example_config.json) with your Azure Storage credentials:
137 |
138 | ```json
139 | {
140 | "storage_url": "http://localhost:10000/", // omit if using Azure
141 | "storage_account_name": "your-storage-account-name",
142 | "storage_account_key": "your-storage-account-key"
143 | }
144 | ```
145 |
146 | ## Usage
147 |
148 | ### Starting the Proxy Server
149 |
150 | ```bash
151 | ./proxy -c my-config.json # if omitted, config.json is used by default
152 | ```
153 |
154 | This will start an interactive CLI with the following commands:
155 |
156 | ```
157 | Commands:
158 | clear clear the screen
159 | create, new create a new agent container and generate its connection string
160 | delete, rm delete an existing agent container
161 | exit exit the shell
162 | help use 'help [command]' for command help
163 | list, ls list all existing agent containers
164 | select, use select an agent for subsequent commands
165 | start, proxy start SOCKS proxy server
166 | stop stop running proxy for the selected agent
167 | ```
168 |
169 | Once the proxy server is running, you can create a new agent container by using the `create` command.
170 |
171 | ```
172 | proxyblob » create
173 | 16:28:37 INF Agent container created successfully container_id=5f5250e9-5518-4682-90ea-f61abf797654
174 | 16:28:37 INF Connection string generated connection_string=aHR0cDovL2xvY2FsaG9zdDoxMDAwMC9kZXZzdG9yZWFjY291bnQxLzVmNTI1MGU5LTU1MTgtNDY4Mi05MGVhLWY2MWFiZjc5NzY1ND9zZT0yMDI1LTA0LTI0VDE0JTNBMjglM0EzN1omc2lnPXpjNUNVYVZKJTJGS1duY3RtbnlNZ0clMkZZNkNrRzZHYXJzMXRFTXkxR0ZiTVVZJTNEJnNwPXJ3JnNwcj1odHRwcyUyQ2h0dHAmc3I9YyZzdD0yMDI1LTA0LTE3VDE0JTNBMjMlM0EzN1omc3Y9MjAyMC0xMC0wMg
175 | ```
176 |
177 | Use the connection string generated with the agent (see below [Starting the Agent](#starting-the-agent)). If the agent connects successfully, you should see the “Agent Info” column filled in when you list the agents with the `list` command.
178 |
179 | ```
180 | proxyblob » list
181 | ╭──────────────────────────────────────┬────────────┬────────────┬─────────────────────┬─────────────────────╮
182 | │ CONTAINER ID │ AGENT INFO │ PROXY PORT │ FIRST SEEN │ LAST SEEN │
183 | ├──────────────────────────────────────┼────────────┼────────────┼─────────────────────┼─────────────────────┤
184 | │ 5f5250e9-5518-4682-90ea-f61abf797654 │ atsika@qb │ │ 2025-04-17 14:28:37 │ 2025-04-17 14:28:37 │
185 | ╰──────────────────────────────────────┴────────────┴────────────┴─────────────────────┴─────────────────────╯
186 | ```
187 |
188 | Select the agent using `select ` and start the proxy listener (by default it listens on localhost:1080) by using the `start` command.
189 |
190 | ```
191 | atsika@qb » select 5f5250e9-5518-4682-90ea-f61abf797654
192 | 17:17:51 INF Agent selected agent=atsika@qb
193 | atsika@qb » start
194 | 17:17:58 INF Proxy started successfully agent=atsika@qb port=1080
195 | ```
196 |
197 | You can now use for example [proxychains](https://github.com/rofl0r/proxychains-ng) to tunnel the traffic through the SOCKS proxy.
198 |
199 | ```bash
200 | proxychains xfreerdp /v:dc01.domain.local /u:Administrator
201 | ```
202 |
203 | ### Starting the Agent
204 |
205 | In order to run, the agent requires a connection string that can be generated using the proxy. You can pass it as an argument or directly embed it at compile-time.
206 |
207 | ```bash
208 | # Via argument
209 | ./agent -c
210 |
211 | # Build the agent with embedded connection string
212 | make agent TOKEN=
213 | ./agent
214 | ```
215 |
216 | ## Architecture
217 |
218 | The communication flow works like this:
219 |
220 | 1. The agent periodically polls an Azure Blob container for encoded packets in a request blob
221 | 2. The proxy writes encoded packets to the Azure Blob container in a request blob
222 | 3. When the agent finds a packet, it processes it and writes the response back to a response blob
223 | 4. The proxy reads the response and maintains the SOCKS connection with client applications
224 |
225 | The global flow is the following:
226 |
227 | ```mermaid
228 | graph TB
229 | %% Client applications
230 | Client1[Client Application] -->|SOCKS5 Request| SocksServer
231 | Client2[Web Browser] -->|SOCKS5 Request| SocksServer
232 |
233 | %% Proxy Server Components
234 | subgraph "Proxy Server (Local Machine)"
235 | SocksServer[SOCKS5 Server]
236 | CLI[Interactive CLI]
237 | ProxyHandler[Proxy Handler]
238 | TransportP[Blob Transport]
239 | end
240 |
241 | %% Connection between components
242 | CLI -->|Commands| SocksServer
243 | SocksServer -->|Process Request| ProxyHandler
244 | ProxyHandler -->|Encode Packets| TransportP
245 | TransportP -->|Receive Responses| ProxyHandler
246 | ProxyHandler -->|Return Data| SocksServer
247 |
248 | %% Azure Blob Storage
249 | subgraph "Azure Blob Storage"
250 | RequestBlob[Request Blob]
251 | ResponseBlob[Response Blob]
252 | end
253 |
254 | %% Connection to Azure
255 | TransportP -->|Write| RequestBlob
256 | ResponseBlob -->|Read| TransportP
257 |
258 | %% Agent Components
259 | subgraph "Agent (Target Network)"
260 | AgentPoller[Polling Component]
261 | TransportA[Blob Transport]
262 | SocksHandler[SOCKS Handler]
263 | CommandProcessor[Command Processor]
264 | end
265 |
266 | %% Agent connections
267 | RequestBlob -->|Poll| AgentPoller
268 | AgentPoller -->|Process| TransportA
269 | TransportA -->|Decode Packets| SocksHandler
270 | SocksHandler -->|Process Commands| CommandProcessor
271 |
272 | %% Command Processing - Fixed syntax
273 | subgraph "Command Processing"
274 | Connect["CONNECT"]
275 | Bind["TODO: BIND"]
276 | UDP["UDP ASSOCIATE"]
277 | end
278 |
279 | CommandProcessor -->|Route| Connect
280 | CommandProcessor -->|Route| Bind
281 | CommandProcessor -->|Route| UDP
282 |
283 | %% Target Connections
284 | Connect -->|TCP Connection| TargetServer1[Target Server]
285 | UDP -->|UDP Connection| TargetServer2[Target Server]
286 |
287 | %% Return path
288 | TargetServer1 -->|Response Data| SocksHandler
289 | TargetServer2 -->|UDP Data| SocksHandler
290 | SocksHandler -->|Encode Response| TransportA
291 | TransportA -->|Write| ResponseBlob
292 | ```
293 |
294 | An example of a CONNECT operation is the following:
295 |
296 | ```mermaid
297 | sequenceDiagram
298 | participant Client as Client Application
299 | participant Proxy as Proxy Server
300 | participant AzureStor as Azure Blob Storage
301 | participant Agent as Agent
302 | participant Target as Target Server
303 |
304 | Note over Client,Target: SOCKS5 Protocol Flow
305 |
306 | %% Proxy Server and Agent Initialization
307 | Proxy->>AzureStor: Initialize connection
308 | Agent->>AzureStor: Start polling for requests
309 |
310 | %% Client Connection and Authentication
311 | Client->>Proxy: TCP Connection
312 | Proxy->>Client: Auth methods (NoAuth supported)
313 | Client->>Proxy: Select Auth method
314 |
315 | %% Command Processing
316 | Client->>Proxy: CONNECT command + target address
317 | Proxy->>AzureStor: Write CONNECT request packet to Request Blob
318 | Agent->>AzureStor: Poll and retrieve CONNECT request
319 |
320 | %% Target Connection
321 | Agent->>Target: Establish TCP connection
322 | Target->>Agent: Connection established
323 | Agent->>AzureStor: Write connection success to Response Blob
324 | Proxy->>AzureStor: Poll and retrieve response
325 | Proxy->>Client: CONNECT success response
326 |
327 | %% Data Transfer (Bidirectional)
328 | Client->>Proxy: Send data
329 | Proxy->>AzureStor: Write data packet to Request Blob
330 | Agent->>AzureStor: Poll and retrieve data packet
331 | Agent->>Target: Forward data
332 |
333 | Target->>Agent: Response data
334 | Agent->>AzureStor: Write response data to Response Blob
335 | Proxy->>AzureStor: Poll and retrieve response data
336 | Proxy->>Client: Forward response data
337 | ```
338 |
339 | ## Troubleshooting
340 |
341 | **Why does my agent immediately stop running ?**
342 |
343 | There might be several reasons why your agent stops immediately after you run it. Check its exit code:
344 | ```sh
345 | # Bash
346 | echo $?
347 | ```
348 | ```cmd
349 | REM CMD
350 | echo %ERRORLEVEL%
351 | ```
352 | ```pwsh
353 | # PowerShell
354 | echo $LastExitCode
355 | ```
356 |
357 | Each exit code describes why the agent stopped running:
358 |
359 | | Exit code | Reason |
360 | | --------- | ------------------------------------------- |
361 | | 0 | No error |
362 | | 1 | The context has been canceled |
363 | | 2 | The connection string is missing |
364 | | 3 | The connection string is invalid or expired |
365 | | 4 | The agent failed to write its metadata |
366 | | 5 | The agent container is not found |
367 |
368 | If you encounter issues:
369 |
370 | 1. Check Azure credentials and permissions
371 | 2. Verify connectivity to Azure Blob Storage
372 | 3. Check for any firewall rules blocking outbound connections
373 | 4. Ensure the agent is running and properly connected
374 |
375 | ## TODO
376 |
377 | - BIND command implementation (currently not working)
378 | - Enhanced error handling and recovery
379 | - Improve proxy speed
380 |
381 | ## License
382 |
383 | [GNU GPLv3 License](LICENSE)
--------------------------------------------------------------------------------
/cmd/agent/main.go:
--------------------------------------------------------------------------------
1 | // Package main implements the SOCKS proxy agent.
2 | package main
3 |
4 | import (
5 | "bytes"
6 | "context"
7 | "encoding/base64"
8 | "errors"
9 | "flag"
10 | "fmt"
11 | "net/url"
12 | "os"
13 | "os/signal"
14 | "os/user"
15 | "strings"
16 | "syscall"
17 | "time"
18 |
19 | "github.com/Azure/azure-storage-blob-go/azblob"
20 | "github.com/rs/zerolog"
21 | "github.com/rs/zerolog/log"
22 |
23 | "proxyblob/pkg/protocol"
24 | proxy "proxyblob/pkg/proxy/socks"
25 | "proxyblob/pkg/transport"
26 | )
27 |
28 | // Exit codes.
29 | const (
30 | Success = 0 // success
31 | ErrContextCanceled = 1 // context canceled
32 | ErrNoConnectionString = 2 // missing connection string
33 | ErrConnectionStringError = 3 // invalid connection string
34 | ErrInfoBlobError = 4 // info blob write failed
35 | ErrContainerNotFound = 5 // container not found
36 | )
37 |
38 | // ConnString holds the Azure connection string.
39 | // Can be set at compile time or via command line flag.
40 | var ConnString string
41 |
42 | // Blob names for proxy-agent communication.
43 | const (
44 | InfoBlobName = "info" // agent metadata
45 | RequestBlobName = "request" // proxy-to-agent traffic
46 | ResponseBlobName = "response" // agent-to-proxy traffic
47 | )
48 |
49 | // InfoKey defines the XOR encryption key for agent information
50 | // Security Note: Changing this key requires synchronized updates on both proxy and agent
51 | var (
52 | InfoKey = []byte{0xDE, 0xAD, 0xB1, 0x0B}
53 | )
54 |
55 | // Agent manages proxy operations and blob storage communication.
56 | type Agent struct {
57 | ContainerURL azblob.ContainerURL // Azure container access
58 | Handler *proxy.SocksHandler // SOCKS handler
59 | }
60 |
61 | // NewAgent creates an agent from a connection string.
62 | func NewAgent(ctx context.Context, connString string) (*Agent, int) {
63 | storageURL, containerID, sasToken, errCode := ParseConnectionString(connString)
64 | if errCode != Success {
65 | return nil, errCode
66 | }
67 |
68 | pipeline := azblob.NewPipeline(
69 | azblob.NewAnonymousCredential(),
70 | azblob.PipelineOptions{},
71 | )
72 |
73 | fullURL := fmt.Sprintf("%s/%s?%s", storageURL, containerID, sasToken)
74 | containerURL, err := url.Parse(fullURL)
75 | if err != nil {
76 | return nil, ErrConnectionStringError
77 | }
78 |
79 | container := azblob.NewContainerURL(*containerURL, pipeline)
80 | blobTransport := transport.NewBlobTransport(
81 | container.NewBlockBlobURL(RequestBlobName), // read
82 | container.NewBlockBlobURL(ResponseBlobName), // write
83 | )
84 | handler := proxy.NewSocksHandler(ctx, blobTransport)
85 |
86 | agent := &Agent{
87 | ContainerURL: container,
88 | Handler: handler,
89 | }
90 |
91 | return agent, Success
92 | }
93 |
94 | // Start begins processing proxy requests.
95 | func (a *Agent) Start(ctx context.Context) int {
96 | // Push agent information to blob storage
97 | if err := a.WriteInfoBlob(ctx); err != Success {
98 | a.Stop()
99 | return ErrContainerNotFound
100 | }
101 |
102 | // Start the container monitoring goroutine
103 | go a.healthCheck(ctx)
104 |
105 | // Start the handler
106 | a.Handler.Start("")
107 |
108 | // Wait for handler context to be done
109 | <-a.Handler.Ctx.Done()
110 |
111 | // Check if context was canceled externally
112 | if errors.Is(ctx.Err(), context.Canceled) {
113 | return ErrContextCanceled
114 | }
115 |
116 | return Success
117 | }
118 |
119 | // Stop terminates agent operations.
120 | func (a *Agent) Stop() {
121 | a.Handler.Stop()
122 | }
123 |
124 | // healthCheck verifies container existence every 30s and stops the agent if it's unavailable.
125 | func (a *Agent) healthCheck(ctx context.Context) {
126 | ticker := time.NewTicker(30 * time.Second)
127 | defer ticker.Stop()
128 |
129 | for {
130 | select {
131 | case <-ctx.Done():
132 | return
133 | case <-ticker.C:
134 | blobURL := a.ContainerURL.NewBlockBlobURL(InfoBlobName)
135 | _, err := blobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
136 | if err != nil {
137 | if storageErr, ok := err.(azblob.StorageError); ok {
138 | if storageErr.ServiceCode() == azblob.ServiceCodeContainerNotFound ||
139 | storageErr.ServiceCode() == azblob.ServiceCodeContainerBeingDeleted {
140 | a.Stop()
141 | return
142 | }
143 | }
144 | }
145 | }
146 | }
147 | }
148 |
149 | // WriteInfoBlob updates agent metadata.
150 | func (a *Agent) WriteInfoBlob(ctx context.Context) int {
151 | info := GetCurrentInfo()
152 | encryptedInfo := protocol.Xor([]byte(info), InfoKey)
153 |
154 | blobURL := a.ContainerURL.NewBlockBlobURL(InfoBlobName)
155 | _, err := blobURL.Upload(
156 | ctx,
157 | bytes.NewReader(encryptedInfo),
158 | azblob.BlobHTTPHeaders{ContentType: "text/plain"},
159 | azblob.Metadata{},
160 | azblob.BlobAccessConditions{},
161 | azblob.DefaultAccessTier,
162 | nil,
163 | azblob.ClientProvidedKeyOptions{},
164 | azblob.ImmutabilityPolicyOptions{},
165 | )
166 |
167 | if err != nil {
168 | // Check for context cancellation first
169 | if errors.Is(ctx.Err(), context.Canceled) {
170 | return ErrContextCanceled
171 | }
172 |
173 | // Check for container deletion
174 | if storageErr, ok := err.(azblob.StorageError); ok {
175 | if storageErr.ServiceCode() == azblob.ServiceCodeContainerNotFound ||
176 | storageErr.ServiceCode() == azblob.ServiceCodeContainerBeingDeleted {
177 | return ErrContainerNotFound
178 | }
179 | // Other storage errors
180 | return ErrInfoBlobError
181 | }
182 |
183 | return ErrInfoBlobError
184 | }
185 |
186 | return Success
187 | }
188 |
189 | // ParseConnectionString extracts storage URL, container ID and SAS token from a connection string.
190 | func ParseConnectionString(connString string) (string, string, string, int) {
191 | // Check for empty string first
192 | if connString == "" {
193 | return "", "", "", ErrNoConnectionString
194 | }
195 |
196 | // Try to decode the base64 encoded string
197 | decoded, err := base64.RawStdEncoding.DecodeString(connString)
198 | if err != nil {
199 | return "", "", "", ErrConnectionStringError
200 | }
201 |
202 | // Parse the URL and extract components
203 | u, err := url.Parse(string(decoded))
204 | if err != nil {
205 | return "", "", "", ErrConnectionStringError
206 | }
207 |
208 | // Extract path components and query string
209 | path := strings.TrimPrefix(u.Path, "/")
210 | if path == "" {
211 | return "", "", "", ErrConnectionStringError
212 | }
213 |
214 | if u.RawQuery == "" {
215 | return "", "", "", ErrConnectionStringError
216 | }
217 |
218 | // Return the storage URL, container ID and SAS token
219 | storageURL := fmt.Sprintf("%s://%s", u.Scheme, u.Host)
220 | return storageURL, path, u.RawQuery, Success
221 | }
222 |
223 | // GetCurrentInfo returns username@hostname.
224 | func GetCurrentInfo() string {
225 | hostname, err := os.Hostname()
226 | if err != nil {
227 | hostname = "unknown"
228 | }
229 |
230 | currentUser, err := user.Current()
231 | if err != nil {
232 | currentUser = &user.User{
233 | Username: "unknown",
234 | }
235 | }
236 |
237 | return fmt.Sprintf("%s@%s", currentUser.Username, hostname)
238 | }
239 |
240 | // init configures logging with zerolog
241 | // Sets up console output and INFO level logging
242 | func init() {
243 | // Configure logging
244 | zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
245 | zerolog.SetGlobalLevel(zerolog.InfoLevel)
246 |
247 | // Use a more human-friendly output for console
248 | log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
249 | }
250 |
251 | // main is the entry point for the agent process
252 | // Handles command-line flags, signal management, and agent lifecycle
253 | func main() {
254 | // Parse command line flags
255 | flag.StringVar(&ConnString, "c", ConnString, "Connection string")
256 | flag.Parse()
257 |
258 | if ConnString == "" {
259 | os.Exit(ErrNoConnectionString)
260 | }
261 |
262 | // Create context that can be cancelled with CTRL+C
263 | ctx, cancel := context.WithCancel(context.Background())
264 | defer cancel()
265 |
266 | // Handle SIGINT (CTRL+C) and SIGTERM
267 | sig := make(chan os.Signal, 1)
268 | signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
269 | go func() {
270 | <-sig
271 | cancel()
272 | }()
273 |
274 | // Create the agent
275 | agent, err := NewAgent(ctx, ConnString)
276 | if err != Success {
277 | os.Exit(err)
278 | }
279 |
280 | // Start the agent
281 | ErrCode := agent.Start(ctx)
282 | os.Exit(ErrCode)
283 | }
284 |
--------------------------------------------------------------------------------
/cmd/proxy/main.go:
--------------------------------------------------------------------------------
1 | // Package main implements the SOCKS proxy server.
2 | package main
3 |
4 | import (
5 | "context"
6 | "encoding/base64"
7 | "encoding/json"
8 | "fmt"
9 | "io"
10 | "net"
11 | "net/url"
12 | "os"
13 | "path/filepath"
14 | "strings"
15 | "sync"
16 | "time"
17 |
18 | "github.com/Azure/azure-storage-blob-go/azblob"
19 | "github.com/desertbit/grumble"
20 | "github.com/google/uuid"
21 | "github.com/jedib0t/go-pretty/table"
22 | "github.com/rs/zerolog"
23 | "github.com/rs/zerolog/log"
24 |
25 | "proxyblob/pkg/protocol"
26 | proxy "proxyblob/pkg/proxy/server"
27 | "proxyblob/pkg/transport"
28 | )
29 |
30 | // CLI banner with version.
31 | const banner = `
32 | ____ ____ _ _
33 | | _ \ _ __ _____ ___ _| __ )| | ___ | |__
34 | | |_) | '__/ _ \ \/ / | | | _ \| |/ _ \| '_ \
35 | | __/| | | (_) > <| |_| | |_) | | (_) | |_) |
36 | |_| |_| \___/_/\_\\__, |____/|_|\___/|_.__/
37 | |___/
38 |
39 | SOCKS Proxy over Azure Blob Storage (v1.0)
40 | ------------------------------------------
41 |
42 | `
43 |
44 | // Blob names for proxy-agent communication.
45 | const (
46 | InfoBlobName = "info" // agent metadata
47 | RequestBlobName = "request" // proxy-to-agent traffic
48 | ResponseBlobName = "response" // agent-to-proxy traffic
49 | )
50 |
51 | // InfoKey defines the XOR encryption key for agent information
52 | // Security Note: Changing this key requires synchronized updates on both proxy and agent
53 | var (
54 | InfoKey = []byte{0xDE, 0xAD, 0xB1, 0x0B}
55 | )
56 |
57 | // Config holds Azure Storage credentials.
58 | type Config struct {
59 | StorageAccountName string `json:"storage_account_name"` // account ID
60 | StorageAccountKey string `json:"storage_account_key"` // access key
61 | StorageURL string `json:"storage_url,omitempty"` // custom endpoint (for development purposes)
62 | }
63 |
64 | // StorageManager handles Azure Storage operations.
65 | type StorageManager struct {
66 | ServiceURL *azblob.ServiceURL // storage endpoint
67 | SharedKeyCredential *azblob.SharedKeyCredential // auth credentials
68 | }
69 |
70 | // ContainerInfo tracks proxy agent metadata.
71 | type ContainerInfo struct {
72 | ID string // container ID
73 | AgentInfo string // username@hostname
74 | ProxyPort string // SOCKS port
75 | CreatedAt time.Time // creation time
76 | LastActivity time.Time // last operation
77 | }
78 |
79 | // Global state.
80 | var (
81 | config *Config // app config
82 | storageManager *StorageManager // storage access
83 | selectedAgent string // current agent
84 | runningProxies sync.Map // active proxies
85 | )
86 |
87 | // LoadConfig reads and parses config file.
88 | func LoadConfig(configPath string) (*Config, error) {
89 | // Use default config path (./config.json) if none provided
90 | if configPath == "" {
91 | configPath = "./config.json"
92 | }
93 |
94 | // Get absolute path for clearer error messages
95 | absPath, err := filepath.Abs(configPath)
96 | if err != nil {
97 | return nil, fmt.Errorf("failed to resolve config path: %v", err)
98 | }
99 |
100 | // Check if config file exists
101 | if _, err := os.Stat(absPath); os.IsNotExist(err) {
102 | return nil, fmt.Errorf("configuration file not found at %s", absPath)
103 | }
104 |
105 | // Read and parse the configuration file
106 | data, err := os.ReadFile(absPath)
107 | if err != nil {
108 | return nil, fmt.Errorf("failed to read config file %s: %v", absPath, err)
109 | }
110 |
111 | config := new(Config)
112 | if err := json.Unmarshal(data, config); err != nil {
113 | return nil, fmt.Errorf("failed to parse config file %s: %v", absPath, err)
114 | }
115 |
116 | // Validate configuration
117 | if err := config.Validate(); err != nil {
118 | return nil, err
119 | }
120 |
121 | return config, nil
122 | }
123 |
124 | // Validate checks required config fields.
125 | func (config *Config) Validate() error {
126 | if config.StorageAccountName == "" {
127 | return fmt.Errorf("storage_account_name is required")
128 | }
129 | if config.StorageAccountKey == "" {
130 | return fmt.Errorf("storage_account_key is required")
131 | }
132 | return nil
133 | }
134 |
135 | // NewStorageManager creates Azure Storage client.
136 | func NewStorageManager(config *Config) (*StorageManager, error) {
137 | // Create credentials using the storage account name and key
138 | credential, err := azblob.NewSharedKeyCredential(
139 | config.StorageAccountName,
140 | config.StorageAccountKey,
141 | )
142 | if err != nil {
143 | return nil, fmt.Errorf("failed to create storage credentials: %v", err)
144 | }
145 |
146 | // Create a pipeline for storage operations
147 | pipeline := azblob.NewPipeline(
148 | credential,
149 | azblob.PipelineOptions{},
150 | )
151 |
152 | // Build the service URL for the storage account
153 | var serviceURL *url.URL
154 | if config.StorageURL != "" {
155 | // Use the custom storage URL provided in the config (for Azurite support)
156 | serviceURL, err = url.Parse(config.StorageURL)
157 | if err != nil {
158 | return nil, fmt.Errorf("failed to parse storage URL: %v", err)
159 | }
160 | serviceURL = serviceURL.JoinPath(config.StorageAccountName)
161 | } else {
162 | // Use the default Azure Storage URL format
163 | serviceURL, err = url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/", config.StorageAccountName))
164 | if err != nil {
165 | return nil, fmt.Errorf("failed to parse service URL: %v", err)
166 | }
167 | }
168 |
169 | service := azblob.NewServiceURL(*serviceURL, pipeline)
170 |
171 | return &StorageManager{
172 | ServiceURL: &service,
173 | SharedKeyCredential: credential,
174 | }, nil
175 | }
176 |
177 | // CreateAgentContainer creates a new container for agent communication.
178 | // Returns the container ID and connection string that should be provided to the agent.
179 | func (sm *StorageManager) CreateAgentContainer(expiry time.Duration) (string, string, error) {
180 | // Generate a unique ID for the container
181 | containerID := uuid.New().String()
182 | containerURL := sm.ServiceURL.NewContainerURL(containerID)
183 |
184 | ctx := context.Background()
185 |
186 | // Create the container with private access level
187 | _, err := containerURL.Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
188 | if err != nil {
189 | return "", "", fmt.Errorf("failed to create container: %v", err)
190 | }
191 |
192 | // Initialize the required blobs
193 | blobNames := []string{InfoBlobName, RequestBlobName, ResponseBlobName}
194 | for _, blobName := range blobNames {
195 | blobURL := containerURL.NewBlockBlobURL(blobName)
196 |
197 | // Create an empty blob - it will be populated later by the agent or proxy
198 | _, err := blobURL.Upload(
199 | ctx,
200 | strings.NewReader(""), // Empty content initially
201 | azblob.BlobHTTPHeaders{
202 | ContentType: "application/octet-stream",
203 | },
204 | azblob.Metadata{
205 | "created": time.Now().UTC().Format(time.RFC3339),
206 | },
207 | azblob.BlobAccessConditions{},
208 | azblob.DefaultAccessTier,
209 | azblob.BlobTagsMap{}, // No initial tags
210 | azblob.ClientProvidedKeyOptions{}, // No client-provided encryption
211 | azblob.ImmutabilityPolicyOptions{}, // No immutability policy
212 | )
213 |
214 | if err != nil {
215 | // If blob creation fails, attempt to clean up the container
216 | if _, delErr := containerURL.Delete(ctx, azblob.ContainerAccessConditions{}); delErr != nil {
217 | return "", "", fmt.Errorf("failed to delete container after blob creation failed: %v", delErr)
218 | }
219 | return "", "", fmt.Errorf("failed to create %s blob: %v", blobName, err)
220 | }
221 | }
222 |
223 | // Generate a SAS token for the container
224 | sasToken, err := sm.GenerateSASToken(containerID, expiry)
225 | if err != nil {
226 | // If SAS token generation fails, clean up the container
227 | if _, delErr := containerURL.Delete(ctx, azblob.ContainerAccessConditions{}); delErr != nil {
228 | return "", "", fmt.Errorf("failed to delete container after SAS token generation failed")
229 | }
230 | return "", "", fmt.Errorf("failed to generate SAS token")
231 | }
232 |
233 | connectionString, _ := url.Parse(storageManager.ServiceURL.String())
234 | connectionString = connectionString.JoinPath(containerID)
235 | connString := connectionString.String() + "?" + sasToken
236 |
237 | return containerID, connString, nil
238 | }
239 |
240 | // GenerateSASToken creates a Shared Access Signature token for container access.
241 | // The token provides limited-time read/write access to specific container resources.
242 | func (sm *StorageManager) GenerateSASToken(containerName string, expiry time.Duration) (string, error) {
243 | // Start time is 5 minutes before now to avoid clock skew issues
244 | startTime := time.Now().UTC().Add(-5 * time.Minute)
245 |
246 | // Set expiry time (default 7 days)
247 | expiryTime := time.Now().UTC().Add(expiry)
248 |
249 | // Define the permissions for the SAS token
250 | permissions := azblob.ContainerSASPermissions{
251 | Read: true,
252 | Write: true,
253 | }
254 |
255 | // Generate the SAS signature
256 | sasQueryParams, err := azblob.BlobSASSignatureValues{
257 | Protocol: azblob.SASProtocolHTTPSandHTTP,
258 | StartTime: startTime,
259 | ExpiryTime: expiryTime,
260 | ContainerName: containerName,
261 | Permissions: permissions.String(),
262 | }.NewSASQueryParameters(sm.SharedKeyCredential)
263 |
264 | if err != nil {
265 | return "", fmt.Errorf("failed to create SAS query parameters: %v", err)
266 | }
267 |
268 | // Convert the SAS query parameters to a string
269 | sasToken := sasQueryParams.Encode()
270 | return sasToken, nil
271 | }
272 |
273 | // ListAgentContainers retrieves information about all agent containers.
274 | // It fetches container metadata and agent information, sorted by creation time.
275 | func (sm *StorageManager) ListAgentContainers(ctx context.Context) ([]ContainerInfo, error) {
276 | var containers []ContainerInfo
277 |
278 | // List all containers in the storage account
279 | for marker := (azblob.Marker{}); marker.NotDone(); {
280 | // Get a segment of containers (up to 100 at a time)
281 | listResponse, err := sm.ServiceURL.ListContainersSegment(ctx, marker, azblob.ListContainersSegmentOptions{
282 | Prefix: "",
283 | MaxResults: 0,
284 | })
285 |
286 | if err != nil {
287 | return nil, fmt.Errorf("failed to list containers: %v", err)
288 | }
289 |
290 | // Update marker for next iteration
291 | marker = listResponse.NextMarker
292 |
293 | // Process each container
294 | for _, containerItem := range listResponse.ContainerItems {
295 | // Create container URL for accessing blobs
296 | containerURL := sm.ServiceURL.NewContainerURL(containerItem.Name)
297 |
298 | // Try to get the info blob
299 | blobURL := containerURL.NewBlockBlobURL(InfoBlobName)
300 | downloadResponse, err := blobURL.Download(ctx, 0, azblob.CountToEnd, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
301 |
302 | // Skip containers that don't have our expected structure
303 | if err != nil {
304 | continue
305 | }
306 |
307 | // Read the info blob content
308 | bodyReader := downloadResponse.Body(azblob.RetryReaderOptions{MaxRetryRequests: 3})
309 | agentInfo, err := io.ReadAll(bodyReader)
310 | bodyReader.Close()
311 | if err != nil {
312 | log.Warn().Err(err).Str("container", containerItem.Name).Msg("Failed to read info blob")
313 | continue
314 | }
315 | agentInfo = protocol.Xor(agentInfo, InfoKey)
316 |
317 | // Get last activity from response blob
318 | responseBlob := containerURL.NewBlockBlobURL(ResponseBlobName)
319 | responseProps, err := responseBlob.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
320 |
321 | // Get the last modified time, defaulting to container creation time if not available
322 | var lastActivity time.Time
323 | if err != nil {
324 | lastActivity = containerItem.Properties.LastModified
325 | } else {
326 | lastActivity = responseProps.LastModified()
327 | }
328 |
329 | // Check if the container has an active proxy
330 | var proxyPort string
331 | if value, running := runningProxies.Load(containerItem.Name); running {
332 | // Try to get the port from the server object
333 | if server, ok := value.(*proxy.ProxyServer); ok && server.Listener != nil {
334 | _, portStr, err := net.SplitHostPort(server.Listener.Addr().String())
335 | if err == nil {
336 | proxyPort = portStr
337 | }
338 | }
339 | }
340 |
341 | // Add the container to our list
342 | containers = append(containers, ContainerInfo{
343 | ID: containerItem.Name,
344 | AgentInfo: string(agentInfo),
345 | ProxyPort: proxyPort,
346 | CreatedAt: containerItem.Properties.LastModified,
347 | LastActivity: lastActivity,
348 | })
349 | }
350 | }
351 |
352 | return containers, nil
353 | }
354 |
355 | // RenderAgentTable formats container information into a human-readable table.
356 | // The table includes container ID, agent info, proxy port, and timing information.
357 | func RenderAgentTable(containers []ContainerInfo) string {
358 | t := table.NewWriter()
359 | t.SetStyle(table.StyleRounded)
360 |
361 | // Set up headers
362 | t.AppendHeader(table.Row{
363 | "Container ID",
364 | "Agent info",
365 | "Proxy port",
366 | "First seen",
367 | "Last seen",
368 | })
369 |
370 | // Add rows for each container
371 | for _, c := range containers {
372 | // Add the container information as a row
373 | t.AppendRow(table.Row{
374 | c.ID,
375 | c.AgentInfo,
376 | c.ProxyPort,
377 | c.CreatedAt.Format("2006-01-02 15:04:05"),
378 | c.LastActivity.Format("2006-01-02 15:04:05"),
379 | })
380 | }
381 |
382 | // Configure column options for better readability
383 | t.SetColumnConfigs([]table.ColumnConfig{
384 | {Number: 1}, // Container ID
385 | {Number: 2}, // Agent Info
386 | {Number: 3}, // Proxy port
387 | {Number: 4}, // Created At
388 | {Number: 5}, // Last Activity
389 | })
390 |
391 | return t.Render()
392 | }
393 |
394 | // DeleteAgentContainer removes a container and its associated blobs.
395 | // This terminates the connection with the remote agent.
396 | func (sm *StorageManager) DeleteAgentContainer(ctx context.Context, containerID string) error {
397 |
398 | // Stop any running proxy for this container
399 | if server, running := runningProxies.Load(containerID); running {
400 | if proxyServer, ok := server.(*proxy.ProxyServer); ok {
401 | proxyServer.Stop()
402 | }
403 | runningProxies.Delete(containerID)
404 | }
405 |
406 | // Create URL for the container we want to delete
407 | containerURL := sm.ServiceURL.NewContainerURL(containerID)
408 |
409 | // Delete the container and all its contents
410 | _, err := containerURL.Delete(ctx, azblob.ContainerAccessConditions{})
411 | if err != nil {
412 | return fmt.Errorf("failed to delete container")
413 | }
414 |
415 | return nil
416 | }
417 |
418 | // ValidateAgent checks if an agent container exists and is properly configured.
419 | // Returns error if the container is missing.
420 | func (sm *StorageManager) ValidateAgent(ctx context.Context, containerID string) error {
421 | containerURL := sm.ServiceURL.NewContainerURL(containerID)
422 | blobURL := containerURL.NewBlockBlobURL(InfoBlobName)
423 |
424 | // Try to get the info blob to verify this is a valid agent container
425 | _, err := blobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
426 | if err != nil {
427 | if serr, ok := err.(azblob.StorageError); ok {
428 | if serr.ServiceCode() == azblob.ServiceCodeContainerNotFound {
429 | return fmt.Errorf("agent container %s does not exist", containerID)
430 | }
431 | }
432 | return fmt.Errorf("invalid agent container %s: %v", containerID, err)
433 | }
434 |
435 | return nil
436 | }
437 |
438 | // GetSelectedAgentInfo retrieves the metadata for the currently selected agent.
439 | // Returns error if no agent is selected or the agent information is unavailable.
440 | func (sm *StorageManager) GetSelectedAgentInfo(ctx context.Context) (string, error) {
441 | if selectedAgent == "" {
442 | return "", fmt.Errorf("no agent selected. Use 'agent use ' first")
443 | }
444 |
445 | containerURL := sm.ServiceURL.NewContainerURL(selectedAgent)
446 | blobURL := containerURL.NewBlockBlobURL(InfoBlobName)
447 |
448 | // Download the info blob
449 | response, err := blobURL.Download(ctx, 0, azblob.CountToEnd, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
450 | if err != nil {
451 | return "", fmt.Errorf("failed to get agent info: %v", err)
452 | }
453 |
454 | // Read the agent info
455 | agentInfo, err := io.ReadAll(response.Body(azblob.RetryReaderOptions{MaxRetryRequests: 3}))
456 | if err != nil {
457 | return "", fmt.Errorf("failed to read agent info: %v", err)
458 | }
459 | agentInfo = protocol.Xor(agentInfo, InfoKey)
460 |
461 | return string(agentInfo), nil
462 | }
463 |
464 | // AddCommands registers all CLI commands with the application.
465 | // This includes commands for agent management, proxy control, and configuration.
466 | func AddCommands(app *grumble.App) {
467 | // Command to create a new agent
468 | app.AddCommand(&grumble.Command{
469 | Name: "create",
470 | Aliases: []string{"new"},
471 | Help: "create a new agent container and generate its connection string",
472 | Flags: func(f *grumble.Flags) {
473 | f.Duration("d", "duration", 7*24*time.Hour, "duration for the SAS token. by default the token will be valid for 7 days")
474 | },
475 | Run: func(c *grumble.Context) error {
476 | expiry := c.Flags.Duration("duration")
477 | containerID, connString, err := storageManager.CreateAgentContainer(expiry)
478 | if err != nil {
479 | log.Error().Err(err).Msg("Failed to create agent container")
480 | return nil
481 | }
482 | log.Info().Str("container_id", containerID).Msg("Agent container created successfully")
483 | log.Info().Str("connection_string", base64.RawStdEncoding.EncodeToString([]byte(connString))).Msg("Connection string generated")
484 | return nil
485 | },
486 | })
487 | // Command to list existing agents
488 | app.AddCommand(&grumble.Command{
489 | Name: "list",
490 | Aliases: []string{"ls"},
491 | Help: "list all existing agent containers",
492 | Run: func(c *grumble.Context) error {
493 | ctx := context.Background()
494 |
495 | // Retrieve all containers
496 | containers, err := storageManager.ListAgentContainers(ctx)
497 | if err != nil {
498 | log.Error().Err(err).Msg("Failed to list containers")
499 | return nil
500 | }
501 |
502 | // Display message if no containers found
503 | if len(containers) == 0 {
504 | log.Info().Msg("No agent containers found")
505 | return nil
506 | }
507 |
508 | // Display the container table
509 | c.App.Println(RenderAgentTable(containers))
510 | return nil
511 | },
512 | })
513 | // Command to delete an agent
514 | app.AddCommand(&grumble.Command{
515 | Name: "delete",
516 | Aliases: []string{"rm"},
517 | Help: "delete an existing agent container",
518 | Args: func(a *grumble.Args) {
519 | a.StringList("containers-id", "ID of the containers to delete")
520 | },
521 | Completer: CompleteAgents,
522 | Run: func(c *grumble.Context) error {
523 | containerIDs := c.Args.StringList("containers-id")
524 | if len(containerIDs) == 0 {
525 | containerIDs = append(containerIDs, selectedAgent)
526 | }
527 |
528 | for _, containerID := range containerIDs {
529 | // Ask for confirmation before deletion
530 | log.Info().Str("container_id", containerID).Msg("Are you sure you want to delete container? [y/N]")
531 | var response string
532 | fmt.Scanln(&response)
533 |
534 | if strings.ToLower(response) != "y" {
535 | log.Info().Msg("Deletion cancelled")
536 | return nil
537 | }
538 |
539 | // Proceed with deletion
540 | ctx := context.Background()
541 | if err := storageManager.DeleteAgentContainer(ctx, containerID); err != nil {
542 | log.Error().Err(err).Str("container_id", containerID).Msg("Failed to delete container")
543 | return nil
544 | }
545 |
546 | if selectedAgent == containerID {
547 | selectedAgent = ""
548 | c.App.SetPrompt("proxyblob » ")
549 | }
550 |
551 | log.Info().Str("container_id", containerID).Msg("Container deleted successfully")
552 | }
553 | return nil
554 | },
555 | })
556 | // Command to select an agent
557 | app.AddCommand(&grumble.Command{
558 | Name: "select",
559 | Aliases: []string{"use"},
560 | Help: "select an agent for subsequent commands",
561 | Args: func(a *grumble.Args) {
562 | a.String("container-id", "ID of the container to select")
563 | },
564 | Completer: CompleteAgents,
565 | Run: func(c *grumble.Context) error {
566 | ctx := context.Background()
567 | containerID := c.Args.String("container-id")
568 |
569 | // Validate the agent exists
570 | if err := storageManager.ValidateAgent(ctx, containerID); err != nil {
571 | log.Error().Err(err).Msg("Failed to validate agent")
572 | return nil
573 | }
574 |
575 | // Store the selected agent
576 | selectedAgent = containerID
577 |
578 | // Get and display agent info
579 | agentInfo, err := storageManager.GetSelectedAgentInfo(ctx)
580 | if err != nil {
581 | log.Error().Err(err).Msg("Failed to get agent info")
582 | return nil
583 | }
584 | if agentInfo == "" {
585 | agentInfo = "unknown@host"
586 | }
587 |
588 | log.Info().Str("agent", agentInfo).Msg("Agent selected")
589 | c.App.SetPrompt(agentInfo + " » ")
590 |
591 | return nil
592 | },
593 | })
594 | // Command to start the proxy server over the current selected agent
595 | app.AddCommand(&grumble.Command{
596 | Name: "start",
597 | Aliases: []string{"proxy"},
598 | Help: "start SOCKS proxy server",
599 | Flags: func(f *grumble.Flags) {
600 | f.String("l", "listen", "127.0.0.1:1080", "listen address for SOCKS server")
601 | },
602 | Run: func(c *grumble.Context) error {
603 | if selectedAgent == "" {
604 | log.Warn().Msg("No agent selected. Use 'select ' first")
605 | return nil
606 | }
607 |
608 | if _, exists := runningProxies.Load(selectedAgent); exists {
609 | log.Warn().Msg("Proxy already running for this agent")
610 | return nil
611 | }
612 |
613 | // Verify the container still exists before starting a proxy
614 | ctx := context.Background()
615 |
616 | // Check if the container exists
617 | if err := storageManager.ValidateAgent(ctx, selectedAgent); err != nil {
618 | log.Error().Err(err).Msg("Cannot start proxy")
619 | return nil
620 | }
621 |
622 | containerURL := storageManager.ServiceURL.NewContainerURL(selectedAgent)
623 | transport := transport.NewBlobTransport(
624 | containerURL.NewBlockBlobURL(ResponseBlobName),
625 | containerURL.NewBlockBlobURL(RequestBlobName),
626 | )
627 |
628 | server := proxy.NewProxyServer(ctx, transport)
629 | listenAddr := c.Flags.String("listen")
630 |
631 | runningProxies.Store(selectedAgent, server)
632 | server.Start(listenAddr)
633 |
634 | // Log the port info for user feedback
635 | if server.Listener != nil {
636 | _, portStr, _ := net.SplitHostPort(server.Listener.Addr().String())
637 | // Get agent info for notification
638 | agentInfo, err := storageManager.GetSelectedAgentInfo(context.Background())
639 | if err != nil || agentInfo == "" {
640 | agentInfo = selectedAgent // Fallback to container ID if we can't get agent info
641 | }
642 |
643 | log.Info().Str("agent", agentInfo).Str("port", portStr).Msg("Proxy started successfully")
644 | }
645 |
646 | return nil
647 | },
648 | })
649 | // Command to stop the proxy server running the current selected agent
650 | app.AddCommand(&grumble.Command{
651 | Name: "stop",
652 | Help: "stop running proxy for the selected agent",
653 | Run: func(c *grumble.Context) error {
654 | if selectedAgent == "" {
655 | log.Warn().Msg("No agent selected. Use 'select ' first")
656 | return nil
657 | }
658 |
659 | // Retrieve and remove the value from the map in one atomic operation
660 | value, exists := runningProxies.LoadAndDelete(selectedAgent)
661 | if !exists {
662 | log.Warn().Msg("No proxy running for this agent")
663 | return nil
664 | }
665 |
666 | // Try to stop the proxy gracefully
667 | server, _ := value.(*proxy.ProxyServer)
668 | server.Stop()
669 |
670 | // Get agent info for notification
671 | agentInfo, err := storageManager.GetSelectedAgentInfo(context.Background())
672 | if err != nil || agentInfo == "" {
673 | agentInfo = selectedAgent // Fallback to container ID if we can't get agent info
674 | }
675 |
676 | log.Info().Str("agent", agentInfo).Msg("Proxy stopped")
677 |
678 | return nil
679 | },
680 | })
681 | }
682 |
683 | // CompleteAgents provides tab completion for agent IDs.
684 | // Returns a list of available agent container IDs.
685 | func CompleteAgents(_ string, _ []string) []string {
686 | containers, err := storageManager.ListAgentContainers(context.Background())
687 | if err != nil {
688 | return []string{} // Return empty slice on error
689 | }
690 |
691 | var completions []string
692 | for _, container := range containers {
693 | completions = append(completions, container.ID)
694 | }
695 | return completions
696 | }
697 |
698 | // -----------------------------------------------------------------------------
699 | // Main Application Entry
700 | // -----------------------------------------------------------------------------
701 |
702 | // main is the entry point for the application.
703 | // It sets up the CLI, configuration, and command handlers.
704 | func main() {
705 | // Set up logging
706 | configureLogging()
707 |
708 | // Configure and create the CLI app
709 | app := setupCLI()
710 |
711 | // Add all command handlers
712 | AddCommands(app)
713 |
714 | // Run the application and handle any errors
715 | if err := app.Run(); err != nil {
716 | log.Fatal().Msg(err.Error())
717 | }
718 | }
719 |
720 | // configureLogging sets up zerolog with appropriate formatting and level.
721 | func configureLogging() {
722 | // Configure zerolog with a pretty console writer for interactive use
723 | log.Logger = log.Output(zerolog.ConsoleWriter{
724 | Out: os.Stdout,
725 | TimeFormat: "15:04:05",
726 | })
727 |
728 | // Set reasonable default log level
729 | zerolog.SetGlobalLevel(zerolog.InfoLevel)
730 | }
731 |
732 | // setupCLI initializes the command-line interface with basic configuration.
733 | // Returns a configured grumble App instance.
734 | func setupCLI() *grumble.App {
735 | // Determine history file location
736 | var histFile string
737 | home, err := os.UserHomeDir()
738 | if err != nil {
739 | histFile = ".proxyblob" // current working directory
740 | } else {
741 | histFile = filepath.Join(home, ".proxyblob") // home directory
742 | }
743 |
744 | // Create and configure the CLI app
745 | app := grumble.New(&grumble.Config{
746 | Name: "proxyblob",
747 | HistoryFile: histFile,
748 | Flags: func(f *grumble.Flags) {
749 | f.String("c", "config", "config.json", "path to configuration file")
750 | },
751 | })
752 |
753 | // Set up our ASCII art banner
754 | app.SetPrintASCIILogo(func(a *grumble.App) {
755 | fmt.Print(banner)
756 | })
757 |
758 | // Initialize configuration when the app starts
759 | app.OnInit(func(a *grumble.App, flags grumble.FlagMap) error {
760 | // Load configuration from file
761 | var err error
762 | config, err = LoadConfig(flags.String("config"))
763 | if err != nil {
764 | return fmt.Errorf("failed to load configuration: %v", err)
765 | }
766 |
767 | // Validate the configuration
768 | if err := config.Validate(); err != nil {
769 | return fmt.Errorf("invalid configuration: %v", err)
770 | }
771 |
772 | // Initialize the storage manager
773 | storageManager, err = NewStorageManager(config)
774 | if err != nil {
775 | return fmt.Errorf("failed to initialize storage manager: %v", err)
776 | }
777 |
778 | return nil
779 | })
780 |
781 | return app
782 | }
783 |
--------------------------------------------------------------------------------
/docs/access-keys.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/quarkslab/proxyblob/d148bc3198fc01b405bc4aa7e0dc7b78ffccbdfe/docs/access-keys.png
--------------------------------------------------------------------------------
/docs/create-storage-account.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/quarkslab/proxyblob/d148bc3198fc01b405bc4aa7e0dc7b78ffccbdfe/docs/create-storage-account.png
--------------------------------------------------------------------------------
/docs/list-storage-accounts.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/quarkslab/proxyblob/d148bc3198fc01b405bc4aa7e0dc7b78ffccbdfe/docs/list-storage-accounts.png
--------------------------------------------------------------------------------
/docs/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/quarkslab/proxyblob/d148bc3198fc01b405bc4aa7e0dc7b78ffccbdfe/docs/logo.png
--------------------------------------------------------------------------------
/example_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "storage_account_name": "storage-name",
3 | "storage_account_key": "storage-access-key"
4 | }
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module proxyblob
2 |
3 | go 1.23.4
4 |
5 | require (
6 | github.com/desertbit/grumble v1.1.3
7 | github.com/google/uuid v1.6.0
8 | golang.org/x/crypto v0.33.0
9 | )
10 |
11 | require (
12 | github.com/Azure/azure-pipeline-go v0.2.3 // indirect
13 | github.com/Azure/go-autorest/autorest/adal v0.9.24 // indirect
14 | github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
15 | github.com/go-openapi/errors v0.22.0 // indirect
16 | github.com/go-openapi/strfmt v0.23.0 // indirect
17 | github.com/golang-jwt/jwt/v4 v4.5.1 // indirect
18 | github.com/mattn/go-ieproxy v0.0.12 // indirect
19 | github.com/mattn/go-runewidth v0.0.16 // indirect
20 | github.com/mitchellh/mapstructure v1.5.0 // indirect
21 | github.com/oklog/ulid v1.3.1 // indirect
22 | github.com/rivo/uniseg v0.4.7 // indirect
23 | go.mongodb.org/mongo-driver v1.17.3 // indirect
24 | golang.org/x/net v0.35.0 // indirect
25 | golang.org/x/text v0.22.0 // indirect
26 | )
27 |
28 | require (
29 | github.com/Azure/azure-storage-blob-go v0.15.0
30 | github.com/desertbit/closer/v3 v3.7.5 // indirect
31 | github.com/desertbit/columnize v2.1.0+incompatible // indirect
32 | github.com/desertbit/go-shlex v0.1.1 // indirect
33 | github.com/desertbit/readline v1.5.1 // indirect
34 | github.com/fatih/color v1.18.0 // indirect
35 | github.com/jedib0t/go-pretty v4.3.0+incompatible
36 | github.com/mattn/go-colorable v0.1.14 // indirect
37 | github.com/mattn/go-isatty v0.0.20 // indirect
38 | github.com/rs/zerolog v1.33.0
39 | golang.org/x/sys v0.30.0 // indirect
40 | )
41 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/Azure/azure-pipeline-go v0.2.3 h1:7U9HBg1JFK3jHl5qmo4CTZKFTVgMwdFHMVtCdfBE21U=
2 | github.com/Azure/azure-pipeline-go v0.2.3/go.mod h1:x841ezTBIMG6O3lAcl8ATHnsOPVl2bqk7S3ta6S6u4k=
3 | github.com/Azure/azure-storage-blob-go v0.15.0 h1:rXtgp8tN1p29GvpGgfJetavIG0V7OgcSXPpwp3tx6qk=
4 | github.com/Azure/azure-storage-blob-go v0.15.0/go.mod h1:vbjsVbX0dlxnRc4FFMPsS9BsJWPcne7GB7onqlPvz58=
5 | github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs=
6 | github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24=
7 | github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M=
8 | github.com/Azure/go-autorest/autorest/adal v0.9.24 h1:BHZfgGsGwdkHDyZdtQRQk1WeUdW0m2WPAwuHZwUi5i4=
9 | github.com/Azure/go-autorest/autorest/adal v0.9.24/go.mod h1:7T1+g0PYFmACYW5LlG2fcoPiPlFHjClyRGL7dRlP5c8=
10 | github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw=
11 | github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74=
12 | github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k=
13 | github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+ZtXWSmf4Tg=
14 | github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8=
15 | github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo=
16 | github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
17 | github.com/Netflix/go-expect v0.0.0-20180615182759-c93bf25de8e8/go.mod h1:oX5x61PbNXchhh0oikYAH+4Pcfw5LKv21+Jnpr6r6Pc=
18 | github.com/Netflix/go-expect v0.0.0-20190729225929-0e00d9168667/go.mod h1:oX5x61PbNXchhh0oikYAH+4Pcfw5LKv21+Jnpr6r6Pc=
19 | github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
20 | github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
21 | github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=
22 | github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
23 | github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=
24 | github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
25 | github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
26 | github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
27 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
28 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
29 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
30 | github.com/desertbit/closer/v3 v3.1.2/go.mod h1:AAC4KRd8DC40nwvV967J/kDFhujMEiuwIKQfN0IDxXw=
31 | github.com/desertbit/closer/v3 v3.7.5 h1:tJ3BXDeflcWjGSacIQFiFOZf3ep7kit9HMxM87qXVLc=
32 | github.com/desertbit/closer/v3 v3.7.5/go.mod h1:wxbB5mDxqhQC8CjI8ApBhj9aHHSLjdok5WFkJj4Bq7M=
33 | github.com/desertbit/columnize v2.1.0+incompatible h1:h55rYmdrWoTj7w9aAnCkxzM3C2Eb8zuFa2W41t0o5j0=
34 | github.com/desertbit/columnize v2.1.0+incompatible/go.mod h1:5kPrzQwKbQ8E5D28nvTVPqIBJyj+8jvJzwt6HXZvXgI=
35 | github.com/desertbit/go-shlex v0.1.1 h1:c65HnbgX1QyC6kPL1dMzUpZ4puNUE6ai/eVucWNLNsk=
36 | github.com/desertbit/go-shlex v0.1.1/go.mod h1:Qbb+mJNud5AypgHZ81EL8syOGaWlwvAOTqS7XmWI4pQ=
37 | github.com/desertbit/grumble v1.1.3 h1:gbdgVGWsHmNraJ7Gn6Q4TiUEIHU/UHfbc1KUSbBlgYU=
38 | github.com/desertbit/grumble v1.1.3/go.mod h1:r7j3ShNy5EmOsegRD2DzTutIaGiLiA3M5yBTXXeLwcs=
39 | github.com/desertbit/readline v1.5.1 h1:/wOIZkWYl1s+IvJm/5bOknfUgs6MhS9svRNZpFM53Os=
40 | github.com/desertbit/readline v1.5.1/go.mod h1:pHQgTsCFs9Cpfh5mlSUFi9Xa5kkL4d8L1Jo4UVWzPw0=
41 | github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
42 | github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
43 | github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
44 | github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
45 | github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
46 | github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k=
47 | github.com/go-openapi/errors v0.22.0 h1:c4xY/OLxUBSTiepAg3j/MHuAv5mJhnf53LLMWFB+u/w=
48 | github.com/go-openapi/errors v0.22.0/go.mod h1:J3DmZScxCDufmIMsdOuDHxJbdOGC0xtUynjIx092vXE=
49 | github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c=
50 | github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4=
51 | github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
52 | github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
53 | github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo=
54 | github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
55 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
56 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
57 | github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
58 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
59 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
60 | github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
61 | github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
62 | github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
63 | github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
64 | github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174/go.mod h1:DqJ97dSdRW1W22yXSB90986pcOyQ7r45iio1KN2ez1A=
65 | github.com/hinshun/vt10x v0.0.0-20180809195222-d55458df857c/go.mod h1:DqJ97dSdRW1W22yXSB90986pcOyQ7r45iio1KN2ez1A=
66 | github.com/jedib0t/go-pretty v4.3.0+incompatible h1:CGs8AVhEKg/n9YbUenWmNStRW2PHJzaeDodcfvRAbIo=
67 | github.com/jedib0t/go-pretty v4.3.0+incompatible/go.mod h1:XemHduiw8R651AF9Pt4FwCTKeG3oo7hrHJAoznj9nag=
68 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
69 | github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
70 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
71 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
72 | github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
73 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
74 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
75 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
76 | github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
77 | github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
78 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
79 | github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
80 | github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
81 | github.com/mattn/go-ieproxy v0.0.1/go.mod h1:pYabZ6IHcRpFh7vIaLfK7rdcWgFEb3SFJ6/gNWuh88E=
82 | github.com/mattn/go-ieproxy v0.0.12 h1:OZkUFJC3ESNZPQ+6LzC3VJIFSnreeFLQyqvBWtvfL2M=
83 | github.com/mattn/go-ieproxy v0.0.12/go.mod h1:Vn+N61199DAnVeTgaF8eoB9PvLO8P3OBnG95ENh7B7c=
84 | github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
85 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
86 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
87 | github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
88 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
89 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
90 | github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
91 | github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
92 | github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
93 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
94 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
95 | github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d/go.mod h1:o96djdrsSGy3AWPyBgZMAGfxZNfgntdJG+11KU4QvbU=
96 | github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4=
97 | github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
98 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
99 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
100 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
101 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
102 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
103 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
104 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
105 | github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
106 | github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
107 | github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
108 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
109 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
110 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
111 | github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
112 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
113 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
114 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
115 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
116 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
117 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
118 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
119 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
120 | go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ=
121 | go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
122 | golang.org/x/crypto v0.0.0-20190123085648-057139ce5d2b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
123 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
124 | golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
125 | golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
126 | golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
127 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
128 | golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
129 | golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
130 | golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
131 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
132 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
133 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
134 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
135 | golang.org/x/net v0.0.0-20191112182307-2180aed22343/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
136 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
137 | golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
138 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
139 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
140 | golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
141 | golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
142 | golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
143 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
144 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
145 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
146 | golang.org/x/sys v0.0.0-20180606202747-9527bec2660b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
147 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
148 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
149 | golang.org/x/sys v0.0.0-20191112214154-59a1497f0cea/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
150 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
151 | golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
152 | golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
153 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
154 | golang.org/x/sys v0.0.0-20201214210602-f9fddec55a1e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
155 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
156 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
157 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
158 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
159 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
160 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
161 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
162 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
163 | golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
164 | golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
165 | golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
166 | golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
167 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
168 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
169 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
170 | golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
171 | golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
172 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
173 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
174 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
175 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
176 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
177 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
178 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
179 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
180 | golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
181 | golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
182 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
183 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
184 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
185 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
186 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
187 | gopkg.in/AlecAivazis/survey.v1 v1.8.5/go.mod h1:iBNOmqKz/NUbZx3bA+4hAGLRC7fSK7tgtVDT4tB22XA=
188 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
189 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
190 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
191 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
192 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
193 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
194 |
--------------------------------------------------------------------------------
/pkg/protocol/base.go:
--------------------------------------------------------------------------------
1 | package protocol
2 |
3 | import (
4 | "context"
5 | "sync"
6 | "time"
7 |
8 | "proxyblob/pkg/transport"
9 |
10 | "github.com/google/uuid"
11 | )
12 |
13 | // PacketHandler processes protocol packets and manages connection lifecycle.
14 | // Implementations must be safe for concurrent use by multiple goroutines.
15 | type PacketHandler interface {
16 | // Start begins packet processing and listens on the specified address (listen only on proxy side)
17 | Start(string)
18 |
19 | // Stop gracefully terminates all connections and processing
20 | Stop()
21 |
22 | // ReceiveLoop processes incoming packets until stopped
23 | ReceiveLoop()
24 |
25 | // OnNew handles connection establishment request
26 | OnNew(uuid.UUID, []byte) byte
27 |
28 | // OnAck handles connection establishment acknowledgment
29 | OnAck(uuid.UUID, []byte) byte
30 |
31 | // OnData handles payload transfer for established connection
32 | OnData(uuid.UUID, []byte) byte
33 |
34 | // OnClose handles connection termination request
35 | OnClose(uuid.UUID, byte) byte
36 | }
37 |
38 | // BaseHandler implements common protocol functionality for proxy and agent.
39 | // It provides connection management, packet routing, and error handling.
40 | type BaseHandler struct {
41 | // transport handles underlying packet transmission
42 | transport transport.Transport
43 |
44 | // Connections maps UUIDs to active Connection objects
45 | Connections sync.Map
46 |
47 | // Ctx controls handler lifecycle
48 | Ctx context.Context
49 |
50 | // Cancel terminates handler context
51 | Cancel context.CancelFunc
52 |
53 | // PacketHandler routes packets to specific handlers
54 | PacketHandler
55 | }
56 |
57 | // NewBaseHandler creates a handler with specified context and transport.
58 | // Uses background context if parent context is nil.
59 | func NewBaseHandler(parentCtx context.Context, transport transport.Transport) *BaseHandler {
60 | if parentCtx == nil {
61 | parentCtx = context.Background()
62 | }
63 | ctx, cancel := context.WithCancel(parentCtx)
64 | return &BaseHandler{
65 | transport: transport,
66 | Ctx: ctx,
67 | Cancel: cancel,
68 | }
69 | }
70 |
71 | // ReceiveLoop processes incoming packets until context cancellation.
72 | // Implements exponential backoff for consecutive errors.
73 | func (h *BaseHandler) ReceiveLoop() {
74 | consecutiveErrors := 0
75 | maxConsecutiveErrors := 5
76 |
77 | for {
78 | select {
79 | case <-h.Ctx.Done():
80 | return
81 | default:
82 | data, errCode := h.transport.Receive(h.Ctx)
83 | if errCode != ErrNone {
84 | if h.transport.IsClosed(errCode) {
85 | h.Stop()
86 | return
87 | }
88 |
89 | if h.Ctx.Err() == nil && errCode != ErrTransportError {
90 | consecutiveErrors++
91 | if consecutiveErrors == maxConsecutiveErrors {
92 | return // Too many errors, just exit
93 | }
94 | time.Sleep(time.Duration(consecutiveErrors*50) * time.Millisecond)
95 | }
96 | continue
97 | }
98 |
99 | consecutiveErrors = 0
100 |
101 | if len(data) == 0 {
102 | continue
103 | }
104 |
105 | packet := Decode(data)
106 | if packet == nil {
107 | continue
108 | }
109 |
110 | errCode = h.handlePacket(packet)
111 | if errCode != ErrNone {
112 | if h.Ctx.Err() != nil && errCode == ErrConnectionClosed {
113 | continue
114 | }
115 | h.SendClose(packet.ConnectionID, errCode)
116 | }
117 | }
118 | }
119 | }
120 |
121 | // handlePacket routes packet to appropriate handler based on command.
122 | // Returns error code indicating success or specific failure.
123 | func (h *BaseHandler) handlePacket(packet *Packet) byte {
124 | switch packet.Command {
125 | case CmdNew:
126 | return h.PacketHandler.OnNew(packet.ConnectionID, packet.Data)
127 | case CmdAck:
128 | return h.PacketHandler.OnAck(packet.ConnectionID, packet.Data)
129 | case CmdData:
130 | return h.PacketHandler.OnData(packet.ConnectionID, packet.Data)
131 | case CmdClose:
132 | return h.PacketHandler.OnClose(packet.ConnectionID, packet.Data[0])
133 | default:
134 | return ErrInvalidCommand
135 | }
136 | }
137 |
138 | // SendNewConnection initiates key exchange for new connection.
139 | // Returns error code indicating success or specific failure.
140 | func (h *BaseHandler) SendNewConnection(connectionID uuid.UUID) byte {
141 | privateKey, publicKey := GenerateKeyPair()
142 | nonce := GenerateNonce()
143 |
144 | connObj, exists := h.Connections.Load(connectionID)
145 | if !exists {
146 | return ErrConnectionNotFound
147 | }
148 | conn := connObj.(*Connection)
149 |
150 | // Store nonce and private key for key derivation during ACK
151 | tempData := make([]byte, len(nonce)+len(privateKey))
152 | copy(tempData[:len(nonce)], nonce)
153 | copy(tempData[len(nonce):], privateKey)
154 | conn.SecretKey = tempData
155 |
156 | // Send nonce and public key to peer
157 | data := make([]byte, len(nonce)+len(publicKey))
158 | copy(data[:len(nonce)], nonce)
159 | copy(data[len(nonce):], publicKey)
160 |
161 | return h.sendPacket(CmdNew, connectionID, data)
162 | }
163 |
164 | // SendConnAck completes key exchange by deriving shared key.
165 | // Returns error code indicating success or specific failure.
166 | func (h *BaseHandler) SendConnAck(connectionID uuid.UUID) byte {
167 | connObj, exists := h.Connections.Load(connectionID)
168 | if !exists {
169 | return ErrConnectionNotFound
170 | }
171 | conn := connObj.(*Connection)
172 |
173 | privateKey, publicKey := GenerateKeyPair()
174 |
175 | // The first 24 bytes of SecretKey should be the nonce,
176 | // and the server's public key should be in the data field from OnNew
177 | serverData := conn.SecretKey
178 | nonce := serverData[:24]
179 | serverPublicKey := serverData[24:]
180 |
181 | symmetricKey, errCode := DeriveKey(privateKey, serverPublicKey, nonce)
182 | if errCode != ErrNone {
183 | return errCode
184 | }
185 |
186 | conn.SecretKey = symmetricKey
187 |
188 | // Send public key in CmdAck
189 | return h.sendPacket(CmdAck, connectionID, publicKey)
190 | }
191 |
192 | func (h *BaseHandler) SendData(connectionID uuid.UUID, data []byte) byte {
193 | // Get connection
194 | connObj, exists := h.Connections.Load(connectionID)
195 | if !exists {
196 | return ErrConnectionNotFound
197 | }
198 | conn := connObj.(*Connection)
199 |
200 | encrypted, errCode := Encrypt(conn.SecretKey, data)
201 | if errCode != ErrNone {
202 | return errCode
203 | }
204 | data = encrypted
205 |
206 | return h.sendPacket(CmdData, connectionID, data)
207 | }
208 |
209 | // SendClose sends a connection termination packet with an error code.
210 | func (h *BaseHandler) SendClose(connectionID uuid.UUID, errCode byte) byte {
211 | connObj, exists := h.Connections.Load(connectionID)
212 | if !exists {
213 | return ErrConnectionNotFound
214 | }
215 | conn := connObj.(*Connection)
216 |
217 | conn.Close()
218 | return h.sendPacket(CmdClose, connectionID, []byte{errCode})
219 | }
220 |
221 | // sendPacket is the internal method that encodes and sends all packet types.
222 | // It handles error checking and context checking.
223 | func (h *BaseHandler) sendPacket(cmd byte, connectionID uuid.UUID, data []byte) byte {
224 | if h.Ctx.Err() != nil {
225 | return ErrHandlerStopped
226 | }
227 |
228 | packet := NewPacket(cmd, connectionID, data)
229 | if packet == nil {
230 | return ErrInvalidPacket
231 | }
232 |
233 | encoded := packet.Encode()
234 | if encoded == nil {
235 | return ErrInvalidPacket
236 | }
237 |
238 | errCode := h.transport.Send(h.Ctx, encoded)
239 | if errCode != ErrNone {
240 | // Check if this is a transport closure
241 | if h.transport.IsClosed(errCode) {
242 | return ErrTransportClosed
243 | }
244 | return ErrPacketSendFailed
245 | }
246 |
247 | return ErrNone
248 | }
249 |
250 | func (h *BaseHandler) CloseAllConnections() {
251 | h.Connections.Range(func(key, value interface{}) bool {
252 | conn := value.(*Connection)
253 |
254 | // Only notify if not already closed
255 | select {
256 | case <-conn.Closed:
257 | // Already closed
258 | default:
259 | conn.Close()
260 | }
261 |
262 | return true
263 | })
264 | }
265 |
--------------------------------------------------------------------------------
/pkg/protocol/connection.go:
--------------------------------------------------------------------------------
1 | package protocol
2 |
3 | import (
4 | "net"
5 | "time"
6 |
7 | "github.com/google/uuid"
8 | )
9 |
10 | // ConnectionState tracks the lifecycle of a proxy connection
11 | type ConnectionState int
12 |
13 | const (
14 | // StateNew indicates a pending connection awaiting establishment
15 | StateNew ConnectionState = iota
16 |
17 | // StateConnected indicates an active connection with data flow
18 | StateConnected
19 |
20 | // StateClosed indicates a terminated connection
21 | StateClosed
22 | )
23 |
24 | // Connection manages a proxy connection between client and target.
25 | // It is safe for concurrent use by multiple goroutines.
26 | type Connection struct {
27 | // ID uniquely identifies the connection
28 | ID uuid.UUID
29 |
30 | // State indicates current connection lifecycle phase
31 | State ConnectionState
32 |
33 | // Conn holds the network connection (optional)
34 | Conn net.Conn
35 |
36 | // ReadBuffer receives data from the remote endpoint
37 | ReadBuffer chan []byte
38 |
39 | // Closed signals connection termination
40 | Closed chan struct{}
41 |
42 | // CreatedAt records connection creation time
43 | CreatedAt time.Time
44 |
45 | // LastActivity tracks most recent data transfer
46 | LastActivity time.Time
47 |
48 | // SecretKey holds encryption key for secure communication
49 | SecretKey []byte
50 | }
51 |
52 | // NewConnection creates a connection with specified ID.
53 | // Initializes channels and sets initial timestamps.
54 | func NewConnection(id uuid.UUID) *Connection {
55 | return &Connection{
56 | ID: id,
57 | State: StateNew,
58 | ReadBuffer: make(chan []byte),
59 | Closed: make(chan struct{}),
60 | CreatedAt: time.Now(),
61 | LastActivity: time.Now(),
62 | }
63 | }
64 |
65 | // Close terminates the connection and its resources.
66 | // Safe to call multiple times. Returns ErrNone on success.
67 | func (c *Connection) Close() byte {
68 | if c.State == StateClosed {
69 | return ErrNone
70 | }
71 |
72 | c.State = StateClosed
73 |
74 | select {
75 | case <-c.Closed:
76 | // Already closed
77 | default:
78 | close(c.Closed)
79 | }
80 |
81 | if c.Conn != nil {
82 | err := c.Conn.Close()
83 | if err != nil {
84 | return ErrConnectionClosed
85 | }
86 | }
87 |
88 | return ErrNone
89 | }
90 |
--------------------------------------------------------------------------------
/pkg/protocol/crypto.go:
--------------------------------------------------------------------------------
1 | package protocol
2 |
3 | import (
4 | "crypto/rand"
5 | "io"
6 |
7 | "golang.org/x/crypto/chacha20poly1305"
8 | "golang.org/x/crypto/curve25519"
9 | "golang.org/x/crypto/hkdf"
10 | "golang.org/x/crypto/sha3"
11 | )
12 |
13 | // GenerateKeyPair creates a new X25519 key pair for key exchange.
14 | // Returns a properly clamped private key and its corresponding public key.
15 | func GenerateKeyPair() (privateKey, publicKey []byte) {
16 | privateKey = make([]byte, curve25519.ScalarSize)
17 | io.ReadFull(rand.Reader, privateKey)
18 |
19 | // Clamp private key according to X25519 spec
20 | privateKey[0] &= 248
21 | privateKey[31] &= 127
22 | privateKey[31] |= 64
23 |
24 | publicKey, _ = curve25519.X25519(privateKey, curve25519.Basepoint)
25 | return privateKey, publicKey
26 | }
27 |
28 | // GenerateNonce creates a random nonce for ChaCha20-Poly1305.
29 | // Returns a cryptographically secure random nonce.
30 | func GenerateNonce() []byte {
31 | nonce := make([]byte, chacha20poly1305.NonceSizeX)
32 | io.ReadFull(rand.Reader, nonce)
33 | return nonce
34 | }
35 |
36 | // DeriveKey performs X25519 key exchange and HKDF key derivation.
37 | // Returns a symmetric key and status code. Key is nil on error.
38 | func DeriveKey(privateKey, peerPublicKey, nonce []byte) ([]byte, byte) {
39 | // Derive shared secret using X25519
40 | sharedSecret, err := curve25519.X25519(privateKey, peerPublicKey)
41 | if err != nil {
42 | return nil, ErrInvalidCrypto
43 | }
44 |
45 | // Derive symmetric key using HKDF-SHA3
46 | kdf := hkdf.New(sha3.New256, sharedSecret, nonce, nil)
47 | symmetricKey := make([]byte, chacha20poly1305.KeySize)
48 | if _, err := io.ReadFull(kdf, symmetricKey); err != nil {
49 | return nil, ErrInvalidCrypto
50 | }
51 |
52 | return symmetricKey, ErrNone
53 | }
54 |
55 | // Encrypt performs authenticated encryption using ChaCha20-Poly1305.
56 | // Returns (nonce || ciphertext || tag) or nil on error.
57 | func Encrypt(key, plaintext []byte) ([]byte, byte) {
58 | aead, err := chacha20poly1305.NewX(key)
59 | if err != nil {
60 | return nil, ErrInvalidCrypto
61 | }
62 |
63 | nonce := GenerateNonce()
64 | ciphertext := aead.Seal(nonce, nonce, plaintext, nil)
65 | return ciphertext, ErrNone
66 | }
67 |
68 | // Decrypt performs authenticated decryption using ChaCha20-Poly1305.
69 | // Returns decrypted plaintext or nil if authentication fails.
70 | func Decrypt(key, ciphertext []byte) ([]byte, byte) {
71 | aead, err := chacha20poly1305.NewX(key)
72 | if err != nil {
73 | return nil, ErrInvalidCrypto
74 | }
75 |
76 | if len(ciphertext) < chacha20poly1305.NonceSizeX {
77 | return nil, ErrInvalidCrypto
78 | }
79 |
80 | nonce := ciphertext[:chacha20poly1305.NonceSizeX]
81 | ciphertextBody := ciphertext[chacha20poly1305.NonceSizeX:]
82 |
83 | plaintext, err := aead.Open(nil, nonce, ciphertextBody, nil)
84 | if err != nil {
85 | return nil, ErrInvalidCrypto
86 | }
87 |
88 | return plaintext, ErrNone
89 | }
90 |
91 | // Xor performs byte-wise XOR of data with a repeating key.
92 | // Warning: This is NOT cryptographically secure, use only for basic obfuscation.
93 | func Xor(data []byte, key []byte) []byte {
94 | for i := range data {
95 | data[i] ^= key[i%len(key)]
96 | }
97 | return data
98 | }
99 |
--------------------------------------------------------------------------------
/pkg/protocol/errors.go:
--------------------------------------------------------------------------------
1 | // Package protocol defines the communication protocol between proxy and agent.
2 | package protocol
3 |
4 | import (
5 | "proxyblob/pkg/transport"
6 | )
7 |
8 | // Protocol error codes for agent-server communication.
9 | // Uses byte values to minimize binary size and network traffic.
10 | const (
11 | // General errors (0-9)
12 | ErrNone byte = 0 // Operation completed successfully
13 | ErrInvalidCommand byte = 1 // Command type is not recognized
14 | ErrContextCanceled byte = 2 // Context canceled
15 |
16 | // Connection errors (10-19)
17 | ErrConnectionClosed byte = 10 // Connection was terminated
18 | ErrConnectionNotFound byte = 11 // Connection ID does not exist
19 | ErrConnectionExists byte = 12 // Connection ID already in use
20 | ErrInvalidState byte = 13 // Connection in wrong state for operation
21 | ErrPacketSendFailed byte = 14 // Packet transmission failed
22 | ErrHandlerStopped byte = 15 // Protocol handler is not running
23 | ErrUnexpectedPacket byte = 16 // Received unexpected packet type
24 |
25 | // Transport errors (20-29)
26 | ErrTransportClosed byte = transport.ErrTransportClosed // Transport layer terminated
27 | ErrTransportTimeout byte = transport.ErrTransportTimeout // Transport operation timed out
28 | ErrTransportError byte = transport.ErrTransportError // Transport operation failed
29 |
30 | // SOCKS errors (30-39)
31 | ErrInvalidSocksVersion byte = 30 // Unsupported SOCKS protocol version
32 | ErrUnsupportedCommand byte = 31 // SOCKS command not implemented
33 | ErrHostUnreachable byte = 32 // Target host not accessible
34 | ErrConnectionRefused byte = 33 // Target refused connection
35 | ErrNetworkUnreachable byte = 34 // Network path not accessible
36 | ErrAddressNotSupported byte = 35 // Address format not supported
37 | ErrTTLExpired byte = 36 // Time-to-live exceeded
38 | ErrGeneralSocksFailure byte = 37 // Unspecified SOCKS failure
39 | ErrAuthFailed byte = 38 // Authentication rejected
40 |
41 | // Packet errors (40-49)
42 | ErrInvalidPacket byte = 40 // Malformed packet structure
43 | ErrInvalidCrypto byte = 41 // Cryptographic operation failed
44 | )
45 |
--------------------------------------------------------------------------------
/pkg/protocol/protocol.go:
--------------------------------------------------------------------------------
1 | // Package protocol implements the communication protocol between proxy server and agent.
2 | // It provides packet encoding/decoding, connection management, and secure data transfer
3 | // using ChaCha20-Poly1305.
4 | //
5 | // The protocol uses a binary packet format with fixed-size headers and variable-length
6 | // payloads. Each packet contains a command type, connection ID, and optional data.
7 | package protocol
8 |
9 | import (
10 | "bytes"
11 | "encoding/binary"
12 |
13 | "github.com/google/uuid"
14 | )
15 |
16 | // Command types for protocol operations.
17 | const (
18 | CmdNew byte = iota + 1 // Request new connection
19 | CmdAck // Acknowledge connection
20 | CmdData // Transfer data
21 | CmdClose // Terminate connection
22 | )
23 |
24 | // Protocol packet field sizes in bytes.
25 | const (
26 | CommandSize = 1 // Command field
27 | UUIDSize = 16 // Connection ID field
28 | DataLengthSize = 4 // Payload length field
29 | HeaderSize = CommandSize + UUIDSize + DataLengthSize
30 | )
31 |
32 | // Packet represents a protocol message with the following binary format:
33 | //
34 | // +---------+----------------+--------------+---------+
35 | // | Command | Connection ID | Data Length | Payload |
36 | // +---------+----------------+--------------+---------+
37 | // | 1B | 16B | 4B | var |
38 | type Packet struct {
39 | Command byte // Operation type (CmdNew, CmdAck, etc.)
40 | ConnectionID uuid.UUID // Unique connection identifier
41 | Data []byte // Optional payload data
42 | }
43 |
44 | // NewPacket creates a protocol packet with the given parameters.
45 | // The data parameter is optional and may be nil.
46 | func NewPacket(command byte, connectionID uuid.UUID, data []byte) *Packet {
47 | return &Packet{
48 | Command: command,
49 | ConnectionID: connectionID,
50 | Data: data,
51 | }
52 | }
53 |
54 | // Encode serializes the packet into a byte slice following the protocol format.
55 | // Returns nil if any encoding operation fails.
56 | func (p *Packet) Encode() []byte {
57 | buf := bytes.NewBuffer(make([]byte, 0, HeaderSize+len(p.Data)))
58 |
59 | if err := buf.WriteByte(p.Command); err != nil {
60 | return nil
61 | }
62 |
63 | if _, err := buf.Write(p.ConnectionID[:]); err != nil {
64 | return nil
65 | }
66 |
67 | if err := binary.Write(buf, binary.BigEndian, uint32(len(p.Data))); err != nil {
68 | return nil
69 | }
70 |
71 | if len(p.Data) > 0 {
72 | if _, err := buf.Write(p.Data); err != nil {
73 | return nil
74 | }
75 | }
76 |
77 | return buf.Bytes()
78 | }
79 |
80 | // Decode deserializes a byte slice into a protocol packet.
81 | // Returns nil if the data is malformed, incomplete, or contains an invalid command.
82 | // The input must contain at least HeaderSize bytes and match the encoded length.
83 | func Decode(data []byte) *Packet {
84 | if len(data) < HeaderSize {
85 | return nil
86 | }
87 |
88 | command := data[0]
89 | if command < CmdNew || command > CmdClose {
90 | return nil
91 | }
92 |
93 | var id uuid.UUID
94 | copy(id[:], data[CommandSize:CommandSize+UUIDSize])
95 |
96 | dataLength := binary.BigEndian.Uint32(data[CommandSize+UUIDSize : HeaderSize])
97 | if uint32(len(data)) != uint32(HeaderSize)+dataLength {
98 | return nil
99 | }
100 |
101 | var packetData []byte
102 | if dataLength > 0 {
103 | packetData = make([]byte, dataLength)
104 | copy(packetData, data[HeaderSize:])
105 | }
106 |
107 | return NewPacket(command, id, packetData)
108 | }
109 |
--------------------------------------------------------------------------------
/pkg/proxy/server/errors.go:
--------------------------------------------------------------------------------
1 | // Package proxy implements a SOCKS proxy server.
2 | package proxy
3 |
4 | import (
5 | "proxyblob/pkg/protocol"
6 | )
7 |
8 | // ErrToString maps protocol error codes to human-readable messages.
9 | // These messages are only used on the server side for logging and debugging.
10 | var ErrToString = map[byte]string{
11 | // General errors
12 | protocol.ErrNone: "no error",
13 | protocol.ErrInvalidCommand: "invalid command",
14 | protocol.ErrContextCanceled: "context canceled",
15 |
16 | // Connection state errors
17 | protocol.ErrConnectionClosed: "connection closed",
18 | protocol.ErrConnectionNotFound: "connection not found",
19 | protocol.ErrConnectionExists: "connection already exists",
20 | protocol.ErrInvalidState: "invalid connection state",
21 | protocol.ErrPacketSendFailed: "failed to send packet",
22 | protocol.ErrHandlerStopped: "handler stopped",
23 | protocol.ErrUnexpectedPacket: "unexpected packet received",
24 |
25 | // Transport layer errors
26 | protocol.ErrTransportClosed: "transport closed",
27 | protocol.ErrTransportTimeout: "transport timeout",
28 | protocol.ErrTransportError: "general transport error",
29 |
30 | // SOCKS reply codes
31 | protocol.ErrInvalidSocksVersion: "invalid SOCKS version",
32 | protocol.ErrUnsupportedCommand: "unsupported command",
33 | protocol.ErrHostUnreachable: "host unreachable",
34 | protocol.ErrConnectionRefused: "connection refused",
35 | protocol.ErrNetworkUnreachable: "network unreachable",
36 | protocol.ErrAddressNotSupported: "address type not supported",
37 | protocol.ErrTTLExpired: "TTL expired",
38 | protocol.ErrGeneralSocksFailure: "general SOCKS server failure",
39 | protocol.ErrAuthFailed: "authentication failed",
40 |
41 | // Protocol packet errors
42 | protocol.ErrInvalidPacket: "invalid protocol packet structure",
43 | protocol.ErrInvalidCrypto: "invalid cryptographic operation",
44 | }
--------------------------------------------------------------------------------
/pkg/proxy/server/server.go:
--------------------------------------------------------------------------------
1 | // Package proxy implements a SOCKS proxy server.
2 | // It accepts client connections and forwards traffic through transport channels
3 | // to remote agents. The server manages connection lifecycle, encryption, and
4 | // bidirectional data transfer.
5 | package proxy
6 |
7 | import (
8 | "context"
9 | "errors"
10 | "io"
11 | "net"
12 | "proxyblob/pkg/protocol"
13 | "proxyblob/pkg/transport"
14 | "time"
15 |
16 | "github.com/google/uuid"
17 | "github.com/rs/zerolog/log"
18 | )
19 |
20 | // ProxyServer implements a SOCKS proxy server that forwards traffic transparently.
21 | // It accepts client connections and manages the protocol flow between clients and
22 | // remote agents.
23 | type ProxyServer struct {
24 | // BaseHandler provides common protocol functionality
25 | *protocol.BaseHandler
26 |
27 | // Listener accepts incoming TCP connections
28 | Listener net.Listener
29 | }
30 |
31 | // NewProxyServer creates a proxy server instance with the given transport.
32 | // The transport is used for communication with remote agents.
33 | func NewProxyServer(ctx context.Context, transport transport.Transport) *ProxyServer {
34 | server := &ProxyServer{}
35 | server.BaseHandler = protocol.NewBaseHandler(ctx, transport)
36 | server.PacketHandler = server
37 | return server
38 | }
39 |
40 | // Start begins listening for client connections on the specified address.
41 | // It launches background goroutines for accepting connections and processing
42 | // protocol messages. If listening fails, the server is stopped.
43 | func (s *ProxyServer) Start(address string) {
44 | var err error
45 | s.Listener, err = net.Listen("tcp", address)
46 | if err != nil {
47 | log.Error().Err(err).Str("addr", address).Msg("Failed to listen on address")
48 | s.Stop()
49 | return
50 | }
51 |
52 | go s.ReceiveLoop()
53 | go s.acceptLoop()
54 | }
55 |
56 | // Stop gracefully terminates the proxy server by closing all active
57 | // connections, canceling the handler's context, and stopping the listener.
58 | func (s *ProxyServer) Stop() {
59 | s.CloseAllConnections()
60 | s.Cancel()
61 | if s.Listener != nil {
62 | s.Listener.Close()
63 | }
64 | }
65 |
66 | // OnNew handles new connection requests. The server is the only one initiating
67 | // connections, so this always returns ErrUnexpectedPacket.
68 | func (s *ProxyServer) OnNew(connectionID uuid.UUID, data []byte) byte {
69 | return protocol.ErrUnexpectedPacket
70 | }
71 |
72 | // OnAck processes connection acknowledgments from agents. It derives a shared
73 | // encryption key using the agent's public key and updates the connection state.
74 | // Returns an error code indicating success or failure.
75 | func (s *ProxyServer) OnAck(connectionID uuid.UUID, data []byte) byte {
76 | value, ok := s.Connections.Load(connectionID)
77 | if !ok {
78 | return protocol.ErrConnectionNotFound
79 | }
80 | conn := value.(*protocol.Connection)
81 |
82 | if conn.State != protocol.StateNew {
83 | return protocol.ErrInvalidState
84 | }
85 |
86 | clientPublicKey := data[:32]
87 |
88 | // At this point,conn.SecretKey contains [24B nonce][32B server private key]
89 | nonce := conn.SecretKey[:24]
90 | serverPrivateKey := conn.SecretKey[24:]
91 |
92 | // Derive the shared key
93 | symmetricKey, errCode := protocol.DeriveKey(serverPrivateKey, clientPublicKey, nonce)
94 | if errCode != protocol.ErrNone {
95 | return errCode
96 | }
97 |
98 | // Store the symmetric key
99 | conn.SecretKey = symmetricKey
100 |
101 | // Signal connection acknowledgment (non-blocking)
102 | conn.ReadBuffer <- []byte{}
103 | conn.State = protocol.StateConnected
104 | conn.LastActivity = time.Now()
105 | return protocol.ErrNone
106 | }
107 |
108 | // OnData processes data received from agents. It decrypts the data and forwards
109 | // it to the client. Returns an error code indicating success or failure.
110 | func (s *ProxyServer) OnData(connectionID uuid.UUID, data []byte) byte {
111 | value, ok := s.Connections.Load(connectionID)
112 | if !ok {
113 | return protocol.ErrConnectionNotFound
114 | }
115 | conn := value.(*protocol.Connection)
116 | conn.LastActivity = time.Now()
117 |
118 | decrypted, errCode := protocol.Decrypt(conn.SecretKey, data)
119 | if errCode != protocol.ErrNone {
120 | return errCode
121 | }
122 | data = decrypted
123 |
124 | // Writing to client is handled by forwardToClient goroutine
125 | select {
126 | case <-s.Ctx.Done():
127 | return protocol.ErrConnectionClosed
128 | case conn.ReadBuffer <- data:
129 | return protocol.ErrNone
130 |
131 | }
132 | }
133 |
134 | // OnClose handles connection termination from agents. It cleans up the
135 | // connection state.
136 | func (s *ProxyServer) OnClose(connectionID uuid.UUID, errorCode byte) byte {
137 | value, ok := s.Connections.Load(connectionID)
138 | if !ok {
139 | return protocol.ErrNone // Connection already removed, nothing to do
140 | }
141 | conn := value.(*protocol.Connection)
142 | conn.Close()
143 | s.Connections.Delete(connectionID)
144 | return errorCode
145 | }
146 |
147 | // acceptLoop accepts incoming TCP connections and spawns goroutines to handle
148 | // each one. It continues until the context is canceled or a non-temporary
149 | // error occurs.
150 | func (s *ProxyServer) acceptLoop() {
151 | for {
152 | select {
153 | case <-s.Ctx.Done():
154 | return
155 | default:
156 | conn, err := s.Listener.Accept()
157 | if err != nil {
158 | if s.Ctx.Err() != nil {
159 | return // Exit quietly on shutdown
160 | }
161 |
162 | if _, ok := err.(net.Error); ok {
163 | continue // Retry on temporary network errors
164 | }
165 | return
166 | }
167 |
168 | go s.handleConnection(conn)
169 | }
170 | }
171 | }
172 |
173 | // handleConnection processes a new client connection by:
174 | // - Generating a unique connection ID
175 | // - Initiating connection with remote agent
176 | // - Setting up bidirectional data forwarding
177 | // - Managing connection lifecycle and cleanup
178 | func (s *ProxyServer) handleConnection(clientConn net.Conn) {
179 | defer clientConn.Close()
180 |
181 | connID := uuid.New()
182 | proxyConn := protocol.NewConnection(connID)
183 | s.Connections.Store(proxyConn.ID, proxyConn)
184 |
185 | // 1. Initiate connection with the agent
186 | errCode := s.SendNewConnection(connID)
187 | if errCode != protocol.ErrNone {
188 | s.Connections.Delete(connID)
189 | return
190 | }
191 |
192 | // 2. Wait for agent acknowledgment with timeout
193 | select {
194 | case <-s.Ctx.Done():
195 | s.SendClose(connID, protocol.ErrHandlerStopped)
196 | s.Connections.Delete(connID)
197 | return
198 | case <-time.After(5 * time.Second):
199 | s.SendClose(connID, protocol.ErrTransportTimeout)
200 | s.Connections.Delete(connID)
201 | return
202 | case <-proxyConn.ReadBuffer:
203 | // Agent acknowledged connection
204 | }
205 |
206 | // 3. Connection established, start bidirectional forwarding
207 | proxyConn.State = protocol.StateConnected
208 | proxyConn.LastActivity = time.Now()
209 |
210 | errCh := make(chan byte, 2)
211 | go s.forwardToAgent(clientConn, proxyConn, errCh)
212 | go s.forwardToClient(clientConn, proxyConn, errCh)
213 |
214 | // Wait for error, closed connection, or context cancellation
215 | select {
216 | case <-s.Ctx.Done():
217 | // Context cancelled, closing connection
218 | case <-proxyConn.Closed:
219 | // Connection closed by agent
220 | case errCode := <-errCh:
221 | if errCode != protocol.ErrNone && errCode != protocol.ErrConnectionClosed {
222 | log.Error().Str("msg", ErrToString[errCode]).Msg("Connection error")
223 | }
224 | }
225 |
226 | // Clean up the connection
227 | s.SendClose(connID, protocol.ErrConnectionClosed)
228 | proxyConn.Close()
229 | s.Connections.Delete(connID)
230 | }
231 |
232 | // forwardToAgent reads data from the client connection and forwards it to
233 | // the remote agent. It continues until an error occurs or the connection
234 | // is closed.
235 | func (s *ProxyServer) forwardToAgent(clientConn net.Conn, proxyConn *protocol.Connection, errCh chan<- byte) {
236 | buffer := make([]byte, 64*1024)
237 |
238 | for {
239 | // Check early termination conditions
240 | if proxyConn.State == protocol.StateClosed {
241 | return
242 | }
243 |
244 | select {
245 | case <-s.Ctx.Done():
246 | return
247 | case <-proxyConn.Closed:
248 | return
249 | default:
250 | // Continue processing
251 | }
252 |
253 | n, err := clientConn.Read(buffer)
254 | if err != nil {
255 | if errors.Is(err, io.EOF) {
256 | errCh <- protocol.ErrConnectionClosed
257 | } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
258 | errCh <- protocol.ErrTransportTimeout
259 | } else {
260 | // General network error
261 | errCh <- protocol.ErrNetworkUnreachable
262 | }
263 | return
264 | }
265 |
266 | errCode := s.SendData(proxyConn.ID, buffer[:n])
267 | if errCode != protocol.ErrNone {
268 | errCh <- protocol.ErrPacketSendFailed
269 | return
270 | }
271 |
272 | proxyConn.LastActivity = time.Now()
273 | }
274 | }
275 |
276 | // forwardToClient reads data from the connection's read buffer and forwards
277 | // it to the client. It continues until an error occurs or the connection
278 | // is closed.
279 | func (s *ProxyServer) forwardToClient(clientConn net.Conn, proxyConn *protocol.Connection, errCh chan<- byte) {
280 | for {
281 | select {
282 | case <-s.Ctx.Done():
283 | return
284 | case <-proxyConn.Closed:
285 | return
286 | case data := <-proxyConn.ReadBuffer:
287 | proxyConn.LastActivity = time.Now()
288 | _, err := clientConn.Write(data)
289 | if err != nil {
290 | if errors.Is(err, io.EOF) {
291 | errCh <- protocol.ErrConnectionClosed
292 | } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
293 | errCh <- protocol.ErrTransportTimeout
294 | } else {
295 | // General network error
296 | errCh <- protocol.ErrNetworkUnreachable
297 | }
298 | return
299 | }
300 | }
301 | }
302 | }
303 |
--------------------------------------------------------------------------------
/pkg/proxy/socks/address.go:
--------------------------------------------------------------------------------
1 | // Package proxy implements SOCKS5 proxy functionality.
2 | package proxy
3 |
4 | import (
5 | "encoding/binary"
6 | "fmt"
7 | "net"
8 |
9 | "proxyblob/pkg/protocol"
10 | )
11 |
12 | // ParseAddress extracts a target address from SOCKS5 address data.
13 | // It returns the address in host:port format and any error encountered.
14 | // The address format follows RFC 1928 Section 4.
15 | func ParseAddress(data []byte) (string, byte) {
16 | addr, _, err := ParseNetworkAddress(data[0], data[1:])
17 | if err != protocol.ErrNone {
18 | return "", err
19 | }
20 | return addr, protocol.ErrNone
21 | }
22 |
23 | // ParseNetworkAddress parses a network address from SOCKS5 formatted data.
24 | // The format is:
25 | //
26 | // +------+----------+----------+
27 | // | ATYP | DST.ADDR | DST.PORT |
28 | // +------+----------+----------+
29 | // | 1 | Variable | 2 |
30 | //
31 | // Returns the address string in host:port format, bytes consumed, and any error.
32 | func ParseNetworkAddress(addrType byte, data []byte) (string, int, byte) {
33 | cursor := 0
34 | var addr string
35 |
36 | switch addrType {
37 | case IPv4:
38 | if len(data) < cursor+4+2 { // 4 bytes IPv4 + 2 bytes port
39 | return "", 0, protocol.ErrAddressNotSupported
40 | }
41 | ip := net.IPv4(data[cursor], data[cursor+1], data[cursor+2], data[cursor+3])
42 | addr = ip.String()
43 | cursor += 4
44 |
45 | case IPv6:
46 | if len(data) < cursor+16+2 { // 16 bytes IPv6 + 2 bytes port
47 | return "", 0, protocol.ErrAddressNotSupported
48 | }
49 | ip := net.IP(data[cursor : cursor+16])
50 | addr = fmt.Sprintf("[%s]", ip.String())
51 | cursor += 16
52 |
53 | case Domain:
54 | if len(data) < cursor+1 { // Need length byte
55 | return "", 0, protocol.ErrAddressNotSupported
56 | }
57 | domainLen := int(data[cursor])
58 | cursor++
59 | if len(data) < cursor+domainLen+2 { // +2 for port
60 | return "", 0, protocol.ErrAddressNotSupported
61 | }
62 | addr = string(data[cursor : cursor+domainLen])
63 | cursor += domainLen
64 |
65 | default:
66 | return "", 0, protocol.ErrAddressNotSupported
67 | }
68 |
69 | if len(data) < cursor+2 {
70 | return "", 0, protocol.ErrAddressNotSupported
71 | }
72 |
73 | port := binary.BigEndian.Uint16(data[cursor : cursor+2])
74 | cursor += 2
75 |
76 | return fmt.Sprintf("%s:%d", addr, port), cursor, protocol.ErrNone
77 | }
78 |
79 | // ExtractUDPHeader parses a SOCKS5 UDP datagram header and returns the target address.
80 | // The format is:
81 | //
82 | // +-----+------+------+----------+----------+----------+
83 | // | RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
84 | // +-----+------+------+----------+----------+----------+
85 | // | 2 | 1 | 1 | Variable | 2 | Variable |
86 | //
87 | // Returns the target address, header length, and any error encountered.
88 | func ExtractUDPHeader(data []byte) (string, int, byte) {
89 | headerLen := 4 // RSV(2) + FRAG(1) + ATYP(1)
90 |
91 | // Parse the address part of the header
92 | addr, addrLen, err := ParseNetworkAddress(data[3], data[4:]) // Use ATYP and pass remaining data
93 | if err != protocol.ErrNone {
94 | return "", 0, err
95 | }
96 | return addr, headerLen + addrLen, protocol.ErrNone
97 | }
98 |
--------------------------------------------------------------------------------
/pkg/proxy/socks/bind.go:
--------------------------------------------------------------------------------
1 | package proxy
2 |
3 | import (
4 | "proxyblob/pkg/protocol"
5 | )
6 |
7 | // handleBind processes the SOCKS5 BIND command.
8 | // The BIND command is used to accept incoming TCP connections
9 | // on behalf of the client. This implementation returns
10 | // ErrUnsupportedCommand as BIND is not currently supported.
11 | //
12 | // The command format follows RFC 1928 Section 4.
13 | func (h *SocksHandler) handleBind(conn *protocol.Connection, data []byte) byte {
14 | return protocol.ErrUnsupportedCommand
15 | }
16 |
--------------------------------------------------------------------------------
/pkg/proxy/socks/connect.go:
--------------------------------------------------------------------------------
1 | package proxy
2 |
3 | import (
4 | "encoding/binary"
5 | "io"
6 | "net"
7 | "time"
8 |
9 | "proxyblob/pkg/protocol"
10 | )
11 |
12 | // handleConnect processes the SOCKS5 CONNECT command.
13 | // It establishes a TCP connection to the requested target and
14 | // sets up bidirectional data transfer between client and target.
15 | //
16 | // The CONNECT command format is:
17 | //
18 | // +-----+-----+-----+------+----------+----------+
19 | // | VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
20 | // +-----+-----+-----+------+----------+----------+
21 | // | 1 | 1 | 1 | 1 | Variable | 2 |
22 | //
23 | // Returns an error code indicating success or specific failure reason.
24 | func (h *SocksHandler) handleConnect(conn *protocol.Connection, cmdData []byte) byte {
25 | if len(cmdData) < 4 {
26 | // Send malformed request response
27 | response := []byte{Version5, GeneralFailure, 0x00, IPv4, 0, 0, 0, 0, 0, 0}
28 | h.SendData(conn.ID, response)
29 | return protocol.ErrAddressNotSupported
30 | }
31 |
32 | // Parse target address
33 | target, errCode := ParseAddress(cmdData[3:])
34 | if errCode != protocol.ErrNone {
35 | h.SendError(conn, errCode)
36 | return errCode
37 | }
38 |
39 | // Establish TCP connection to target
40 | targetConn, err := net.DialTimeout("tcp", target, 10*time.Second)
41 | if err != nil {
42 | // Map network error to appropriate SOCKS5 error code
43 | if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
44 | errCode = protocol.ErrTTLExpired
45 | } else if opErr, ok := err.(*net.OpError); ok {
46 | if opErr.Op == "dial" {
47 | errCode = protocol.ErrNetworkUnreachable
48 | } else if opErr.Op == "read" {
49 | errCode = protocol.ErrHostUnreachable
50 | }
51 | } else if _, ok := err.(*net.DNSError); ok {
52 | errCode = protocol.ErrHostUnreachable
53 | } else {
54 | errCode = protocol.ErrConnectionRefused
55 | }
56 |
57 | // Send failure response with appropriate code
58 | h.SendError(conn, errCode)
59 | return errCode
60 | }
61 |
62 | // Send success response
63 | localAddr := targetConn.LocalAddr().(*net.TCPAddr)
64 | response := make([]byte, 10)
65 | response[0] = Version5
66 | response[1] = Succeeded
67 | response[2] = 0x00
68 | response[3] = IPv4
69 | copy(response[4:8], localAddr.IP.To4())
70 | binary.BigEndian.PutUint16(response[8:], uint16(localAddr.Port))
71 |
72 | errCode = h.SendData(conn.ID, response)
73 | if errCode != protocol.ErrNone {
74 | targetConn.Close()
75 | return protocol.ErrPacketSendFailed
76 | }
77 |
78 | // Store connection and set state
79 | conn.Conn = targetConn
80 | conn.State = protocol.StateConnected
81 |
82 | // Start data transfer
83 | return h.handleTCPDataTransfer(conn, targetConn)
84 | }
85 |
86 | // handleTCPDataTransfer manages bidirectional data transfer for TCP connections.
87 | // It spawns two goroutines:
88 | // - One reads from client and writes to target
89 | // - One reads from target and writes to client
90 | //
91 | // The transfer continues until either:
92 | // - The connection is closed by either end
93 | // - The context is canceled
94 | // - An error occurs
95 | func (h *SocksHandler) handleTCPDataTransfer(conn *protocol.Connection, tcpConn net.Conn) byte {
96 | // Create channels for communication
97 | clientToTarget := make(chan []byte)
98 | targetToClient := make(chan []byte)
99 | errorCh := make(chan byte, 2)
100 |
101 | // Read from SOCKS client and forward to target
102 | go func() {
103 | for {
104 | select {
105 | case <-conn.Closed:
106 | return
107 | case <-h.Ctx.Done():
108 | return
109 | case data, ok := <-conn.ReadBuffer:
110 | if !ok {
111 | return
112 | }
113 | clientToTarget <- data
114 | }
115 | }
116 | }()
117 |
118 | // Read from target and forward to SOCKS client
119 | go func() {
120 | buffer := make([]byte, 128*1024)
121 | for {
122 | n, err := tcpConn.Read(buffer)
123 | if err != nil {
124 | if err == io.EOF {
125 | errorCh <- protocol.ErrConnectionClosed
126 | } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
127 | errorCh <- protocol.ErrTTLExpired
128 | } else {
129 | errorCh <- protocol.ErrHostUnreachable
130 | }
131 | return
132 | }
133 | // Copy data since buffer will be reused
134 | data := make([]byte, n)
135 | copy(data, buffer[:n])
136 | targetToClient <- data
137 | }
138 | }()
139 |
140 | // Main data transfer loop
141 | for {
142 | select {
143 | case <-conn.Closed:
144 | tcpConn.Close()
145 | return protocol.ErrNone
146 |
147 | case <-h.Ctx.Done():
148 | tcpConn.Close()
149 | return protocol.ErrHandlerStopped
150 |
151 | case errCode := <-errorCh:
152 | tcpConn.Close()
153 | return errCode
154 |
155 | case data := <-clientToTarget:
156 | _, err := tcpConn.Write(data)
157 | if err != nil {
158 | tcpConn.Close()
159 | if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
160 | return protocol.ErrTTLExpired
161 | }
162 | return protocol.ErrHostUnreachable
163 | }
164 | case data := <-targetToClient:
165 | errCode := h.SendData(conn.ID, data)
166 | if errCode != protocol.ErrNone {
167 | tcpConn.Close()
168 | return protocol.ErrPacketSendFailed
169 | }
170 | }
171 | }
172 | }
173 |
--------------------------------------------------------------------------------
/pkg/proxy/socks/constants.go:
--------------------------------------------------------------------------------
1 | // Package proxy implements SOCKS5 proxy functionality.
2 | package proxy
3 |
4 | // SOCKS protocol versions.
5 | const (
6 | Version5 byte = 0x05 // SOCKS Protocol Version 5
7 | )
8 |
9 | // Authentication methods as defined in RFC 1928.
10 | const (
11 | NoAuth byte = 0x00 // No authentication required
12 | GSSAPI byte = 0x01 // GSSAPI
13 | UsernamePassword byte = 0x02 // Username/Password (RFC 1929)
14 | NoAcceptableMethods byte = 0xFF // No acceptable methods
15 | )
16 |
17 | // SOCKS5 commands that clients may request.
18 | const (
19 | Connect byte = 0x01 // Establish TCP/IP stream connection
20 | Bind byte = 0x02 // Listen for incoming TCP connection
21 | UDPAssociate byte = 0x03 // Set up UDP relay
22 | )
23 |
24 | // Address types for target addresses.
25 | const (
26 | IPv4 byte = 0x01 // IPv4 address (4 bytes)
27 | Domain byte = 0x03 // Domain name (variable length)
28 | IPv6 byte = 0x04 // IPv6 address (16 bytes)
29 | )
30 |
31 | // Reply codes sent from server to client.
32 | const (
33 | Succeeded byte = 0x00 // Request granted
34 | GeneralFailure byte = 0x01 // General failure
35 | ConnectionNotAllowed byte = 0x02 // Connection not allowed by ruleset
36 | NetworkUnreachable byte = 0x03 // Network unreachable
37 | HostUnreachable byte = 0x04 // Host unreachable
38 | ConnectionRefused byte = 0x05 // Connection refused by destination
39 | TTLExpired byte = 0x06 // TTL expired
40 | CommandNotSupported byte = 0x07 // Command not supported
41 | AddressTypeNotSupported byte = 0x08 // Address type not supported
42 | )
43 |
44 | // Buffer size limits.
45 | const (
46 | MaxSocksHeaderSize = 262 // Maximum size of SOCKS header in bytes
47 | MaxUDPPacketSize = 65535 // Maximum size of UDP datagram in bytes
48 | )
49 |
--------------------------------------------------------------------------------
/pkg/proxy/socks/socks.go:
--------------------------------------------------------------------------------
1 | // Package proxy implements SOCKS5 proxy functionality.
2 | // It provides a complete SOCKS5 implementation following RFC 1928, supporting
3 | // CONNECT and UDP ASSOCIATE (BIND not implemented) commands with NoAuth authentication.
4 | package proxy
5 |
6 | import (
7 | "context"
8 | "slices"
9 |
10 | "proxyblob/pkg/protocol"
11 | "proxyblob/pkg/transport"
12 |
13 | "github.com/google/uuid"
14 | )
15 |
16 | // SocksHandler implements a SOCKS5 protocol handler.
17 | // It processes authentication, commands, and data transfer between clients
18 | // and remote targets. The handler is safe for concurrent use.
19 | type SocksHandler struct {
20 | *protocol.BaseHandler
21 | }
22 |
23 | // NewSocksHandler creates a SOCKS5 handler with the given transport.
24 | // The transport is used for sending and receiving protocol messages.
25 | func NewSocksHandler(ctx context.Context, transport transport.Transport) *SocksHandler {
26 | handler := &SocksHandler{}
27 | handler.BaseHandler = protocol.NewBaseHandler(ctx, transport)
28 | handler.PacketHandler = handler
29 | return handler
30 | }
31 |
32 | // Start begins processing SOCKS5 requests. The address parameter is ignored
33 | // as there are no listeners on the agent side.
34 | func (h *SocksHandler) Start(address string) {
35 | go h.ReceiveLoop()
36 | }
37 |
38 | // Stop gracefully terminates the handler, closing all active connections
39 | // and canceling the context.
40 | func (h *SocksHandler) Stop() {
41 | h.CloseAllConnections()
42 | h.Cancel()
43 | }
44 |
45 | // OnNew handles new connection requests by initializing it and
46 | // starting the SOCKS5 protocol flow.
47 | func (h *SocksHandler) OnNew(connectionID uuid.UUID, data []byte) byte {
48 | // Check if the connection already exists
49 | if _, ok := h.Connections.Load(connectionID); ok {
50 | return protocol.ErrConnectionExists
51 | }
52 |
53 | // Create new connection
54 | conn := protocol.NewConnection(connectionID)
55 | h.Connections.Store(conn.ID, conn)
56 |
57 | // Process the server's nonce and public key from data
58 | if len(data) >= 24+32 {
59 | // Extract nonce and server public key
60 | nonce := data[:24]
61 | serverPublicKey := data[24 : 24+32]
62 |
63 | // Store temporary data for key derivation during ACK
64 | tmp := make([]byte, len(nonce)+len(serverPublicKey))
65 | copy(tmp[:len(nonce)], nonce)
66 | copy(tmp[len(nonce):], serverPublicKey)
67 | conn.SecretKey = tmp
68 | }
69 |
70 | // Send connection acknowledgment
71 | errCode := h.SendConnAck(connectionID)
72 | if errCode != protocol.ErrNone {
73 | return errCode
74 | }
75 |
76 | // Process the connection
77 | go h.processConnection(conn)
78 | return protocol.ErrNone
79 | }
80 |
81 | // OnAck reports ErrUnexpectedPacket as the agent only accepts incoming
82 | // connections and does not initiate them.
83 | func (h *SocksHandler) OnAck(connectionID uuid.UUID, data []byte) byte {
84 | return protocol.ErrUnexpectedPacket
85 | }
86 |
87 | // OnData processes incoming data for a connection.
88 | // It decrypts the data and forwards it to the connection's read buffer.
89 | func (h *SocksHandler) OnData(connectionID uuid.UUID, data []byte) byte {
90 | value, ok := h.Connections.Load(connectionID)
91 | if !ok {
92 | return protocol.ErrConnectionNotFound
93 | }
94 | conn := value.(*protocol.Connection)
95 |
96 | decrypted, errCode := protocol.Decrypt(conn.SecretKey, data)
97 | if errCode != protocol.ErrNone {
98 | h.SendClose(connectionID, protocol.ErrInvalidCrypto)
99 | return errCode
100 | }
101 | data = decrypted
102 |
103 | select {
104 | case <-h.Ctx.Done():
105 | return protocol.ErrConnectionClosed
106 | case conn.ReadBuffer <- data:
107 | return protocol.ErrNone
108 |
109 | }
110 | }
111 |
112 | // OnClose cleans up resources associated with a connection.
113 | // It is safe to call multiple times.
114 | func (h *SocksHandler) OnClose(connectionID uuid.UUID, errorCode byte) byte {
115 | value, ok := h.Connections.Load(connectionID)
116 | if !ok {
117 | return protocol.ErrNone // Connection already removed, nothing to do
118 | }
119 | conn := value.(*protocol.Connection)
120 | conn.Close()
121 |
122 | h.Connections.Delete(connectionID)
123 | return protocol.ErrNone
124 | }
125 |
126 | // processConnection handles the SOCKS5 protocol flow for a single connection.
127 | // The flow consists of three phases:
128 | //
129 | // 1. Authentication method negotiation
130 | // 2. Command processing (CONNECT, UDP ASSOCIATE)
131 | // 3. Data transfer between client and target
132 | func (h *SocksHandler) processConnection(conn *protocol.Connection) {
133 | // SOCKS protocol has 3 sequential phases
134 | errCode := h.handleAuthNegotiation(conn)
135 | if errCode != protocol.ErrNone {
136 | h.SendClose(conn.ID, errCode)
137 | return
138 | }
139 |
140 | errCode = h.handleCommand(conn)
141 | if errCode != protocol.ErrNone {
142 | h.SendClose(conn.ID, errCode)
143 | return
144 | }
145 |
146 | errCode = h.handleDataTransfer(conn)
147 | if errCode != protocol.ErrNone {
148 | h.SendClose(conn.ID, errCode)
149 | return
150 | }
151 | }
152 |
153 | // SendError sends a SOCKS5 error reply to the client.
154 | // It maps internal error codes to SOCKS5 reply codes as defined in RFC 1928.
155 | func (h *SocksHandler) SendError(conn *protocol.Connection, errCode byte) {
156 | // Default to general failure
157 | socksReplyCode := GeneralFailure
158 |
159 | // Map internal error codes to SOCKS reply codes
160 | switch errCode {
161 | case protocol.ErrNone:
162 | socksReplyCode = Succeeded
163 | case protocol.ErrNetworkUnreachable:
164 | socksReplyCode = NetworkUnreachable
165 | case protocol.ErrHostUnreachable:
166 | socksReplyCode = HostUnreachable
167 | case protocol.ErrConnectionRefused:
168 | socksReplyCode = ConnectionRefused
169 | case protocol.ErrTTLExpired:
170 | socksReplyCode = TTLExpired
171 | case protocol.ErrUnsupportedCommand:
172 | socksReplyCode = CommandNotSupported
173 | case protocol.ErrAddressNotSupported:
174 | socksReplyCode = AddressTypeNotSupported
175 | case protocol.ErrAuthFailed:
176 | socksReplyCode = NoAcceptableMethods
177 | }
178 |
179 | // Build and send error response
180 | response := []byte{Version5, socksReplyCode, 0x00, IPv4, 0, 0, 0, 0, 0, 0}
181 | h.SendData(conn.ID, response)
182 | }
183 |
184 | // handleAuthNegotiation processes the client's authentication method selection.
185 | // Currently only the NO AUTHENTICATION REQUIRED (0x00) method is supported.
186 | func (h *SocksHandler) handleAuthNegotiation(conn *protocol.Connection) byte {
187 | select {
188 | case methods := <-conn.ReadBuffer:
189 | // Currently we only support NoAuth (0x00)
190 | if !slices.Contains(methods, NoAuth) {
191 | h.SendError(conn, protocol.ErrAuthFailed)
192 | return protocol.ErrAuthFailed
193 | }
194 |
195 | // Send response
196 | errCode := h.SendData(conn.ID, []byte{Version5, NoAuth})
197 | if errCode != protocol.ErrNone {
198 | return errCode
199 | }
200 |
201 | return protocol.ErrNone
202 |
203 | case <-conn.Closed:
204 | return protocol.ErrConnectionClosed
205 |
206 | case <-h.Ctx.Done():
207 | return protocol.ErrHandlerStopped
208 | }
209 | }
210 |
211 | // handleCommand processes SOCKS5 commands from the client.
212 | // Supported commands are:
213 | //
214 | // - CONNECT (0x01): Establish TCP/IP stream connection
215 | // - UDP ASSOCIATE (0x03): UDP relay
216 | //
217 | // Unsupported commands are:
218 | //
219 | // - BIND (0x02): TCP/IP port binding
220 | func (h *SocksHandler) handleCommand(conn *protocol.Connection) byte {
221 | select {
222 | case cmdData := <-conn.ReadBuffer:
223 | // Validate command format
224 | if len(cmdData) < 4 {
225 | h.SendError(conn, protocol.ErrInvalidPacket)
226 | return protocol.ErrInvalidPacket
227 | }
228 |
229 | // Check SOCKS version
230 | if cmdData[0] != Version5 {
231 | h.SendError(conn, protocol.ErrInvalidSocksVersion)
232 | return protocol.ErrInvalidSocksVersion
233 | }
234 |
235 | var errCode byte
236 | switch cmdData[1] {
237 | case Connect:
238 | errCode = h.handleConnect(conn, cmdData)
239 | case Bind:
240 | errCode = h.handleBind(conn, cmdData)
241 | case UDPAssociate:
242 | errCode = h.handleUDPAssociate(conn)
243 | default:
244 | h.SendError(conn, protocol.ErrUnsupportedCommand)
245 | return protocol.ErrUnsupportedCommand
246 | }
247 |
248 | return errCode
249 |
250 | case <-conn.Closed:
251 | return protocol.ErrConnectionClosed
252 | case <-h.Ctx.Done():
253 | return protocol.ErrHandlerStopped
254 | }
255 | }
256 |
257 | // handleDataTransfer manages the flow of data between client and target.
258 | // Each command handler implements its own data transfer mechanism.
259 | func (h *SocksHandler) handleDataTransfer(conn *protocol.Connection) byte {
260 | // Each command handler takes care of data transfer
261 | // Just wait for connection to be closed
262 | <-conn.Closed
263 | return protocol.ErrNone
264 | }
265 |
--------------------------------------------------------------------------------
/pkg/proxy/socks/udp_associate.go:
--------------------------------------------------------------------------------
1 | package proxy
2 |
3 | import (
4 | "encoding/binary"
5 | "errors"
6 | "net"
7 | "time"
8 |
9 | "proxyblob/pkg/protocol"
10 | )
11 |
12 | // handleUDPAssociate processes the SOCKS5 UDP ASSOCIATE command.
13 | // It creates a UDP relay that allows clients to send and receive
14 | // UDP datagrams through the SOCKS server.
15 | //
16 | // The process involves:
17 | // 1. Creating a UDP socket for client communication
18 | // 2. Sending the socket address back to the client
19 | // 3. Maintaining the TCP control connection
20 | // 4. Relaying UDP datagrams between client and targets
21 | //
22 | // The command format follows RFC 1928 Section 4.
23 | func (h *SocksHandler) handleUDPAssociate(conn *protocol.Connection) byte {
24 | // Create UDP socket
25 | udpAddr, err := net.ResolveUDPAddr("udp", "0.0.0.0:0")
26 | if err != nil {
27 | // Send network unreachable error
28 | h.SendError(conn, protocol.ErrNetworkUnreachable)
29 | return protocol.ErrNetworkUnreachable
30 | }
31 |
32 | udpConn, err := net.ListenUDP("udp", udpAddr)
33 | if err != nil {
34 | // Determine specific error type
35 | errCode := protocol.ErrGeneralSocksFailure
36 | if opErr, ok := err.(*net.OpError); ok {
37 | if errors.Is(opErr, net.ErrClosed) {
38 | errCode = protocol.ErrTransportClosed
39 | } else if opErr.Op == "listen" {
40 | errCode = protocol.ErrNetworkUnreachable
41 | }
42 | }
43 |
44 | // Send appropriate error response
45 | h.SendError(conn, errCode)
46 | return errCode
47 | }
48 |
49 | // Get the allocated port
50 | localAddr := udpConn.LocalAddr().(*net.UDPAddr)
51 | port := localAddr.Port
52 |
53 | // Create response
54 | // Format: |VER|REP|RSV|ATYP|BND.ADDR|BND.PORT|
55 | response := []byte{
56 | Version5, // VER
57 | Succeeded, // REP - success
58 | 0, // RSV - reserved, must be 0
59 | IPv4, // ATYP - IPv4
60 | 0, 0, 0, 0, // BND.ADDR - 0.0.0.0 (any address)
61 | byte(port >> 8), // BND.PORT - high byte
62 | byte(port & 0xff), // BND.PORT - low byte
63 | }
64 |
65 | errCode := h.SendData(conn.ID, response)
66 | if errCode != protocol.ErrNone {
67 | udpConn.Close()
68 | return protocol.ErrPacketSendFailed
69 | }
70 |
71 | // Store UDP connection and start handling packets
72 | conn.Conn = udpConn
73 | conn.State = protocol.StateConnected
74 |
75 | go h.handleUDPPackets(conn)
76 |
77 | // Keep the control connection open until it's closed elsewhere
78 | select {
79 | case <-conn.Closed:
80 | // Control connection closed, UDP associate terminated
81 | case <-h.Ctx.Done():
82 | udpConn.Close()
83 | }
84 |
85 | return protocol.ErrNone
86 | }
87 |
88 | // handleUDPPackets manages the UDP relay for a client.
89 | // It:
90 | // - Receives UDP packets from the client
91 | // - Extracts target addresses from SOCKS headers
92 | // - Forwards packets to targets
93 | // - Receives responses from targets
94 | // - Wraps responses in SOCKS headers
95 | // - Returns them to the client
96 | //
97 | // The relay operates until the control connection closes or
98 | // the context is canceled.
99 | func (h *SocksHandler) handleUDPPackets(conn *protocol.Connection) {
100 | udpConn := conn.Conn.(*net.UDPConn)
101 | buffer := make([]byte, 64*1024)
102 | var clientAddr *net.UDPAddr
103 |
104 | // Create a UDP connection for sending to targets
105 | targetConn, err := net.ListenUDP("udp", nil)
106 | if err != nil {
107 | h.SendClose(conn.ID, protocol.ErrNetworkUnreachable)
108 | return
109 | }
110 |
111 | // Ensure connections are properly closed when this handler exits
112 | defer targetConn.Close()
113 |
114 | // Map to track target addresses and their corresponding responses
115 | type targetInfo struct {
116 | addr *net.UDPAddr
117 | lastActive time.Time
118 | }
119 | targets := make(map[string]*targetInfo)
120 |
121 | // Channel for receiving UDP responses
122 | responses := make(chan struct {
123 | data []byte
124 | addr *net.UDPAddr
125 | }, 100)
126 |
127 | // Start a goroutine to handle responses
128 | go func() {
129 | respBuf := make([]byte, 128*1024)
130 | for {
131 | // Check for cancellation
132 | select {
133 | case <-h.Ctx.Done():
134 | return
135 | case <-conn.Closed:
136 | return
137 | default:
138 | // Continue processing
139 | }
140 |
141 | // Set read deadline
142 | if err := targetConn.SetReadDeadline(time.Now().Add(300 * time.Millisecond)); err != nil {
143 | if errors.Is(err, net.ErrClosed) {
144 | return
145 | }
146 | continue // Non-fatal, just retry
147 | }
148 |
149 | n, addr, err := targetConn.ReadFromUDP(respBuf)
150 | if err != nil {
151 | if errors.Is(err, net.ErrClosed) {
152 | return
153 | }
154 | continue
155 | }
156 |
157 | if n > 0 {
158 | // Make a copy of the data since respBuf will be reused
159 | data := make([]byte, n)
160 | copy(data, respBuf[:n])
161 |
162 | // Send response through channel
163 | select {
164 | case responses <- struct {
165 | data []byte
166 | addr *net.UDPAddr
167 | }{data, addr}:
168 | // Successfully sent
169 | default:
170 | // Channel full, log and continue
171 | }
172 | }
173 | }
174 | }()
175 |
176 | // Timeout to clean up inactive targets
177 | ticker := time.NewTicker(30 * time.Second)
178 | defer ticker.Stop()
179 |
180 | for {
181 | select {
182 | case <-h.Ctx.Done():
183 | return
184 | case <-conn.Closed:
185 | return
186 | case resp := <-responses:
187 | // Find the target that matches this response
188 | var found bool
189 |
190 | for _, target := range targets {
191 | if target.addr.IP.Equal(resp.addr.IP) && target.addr.Port == resp.addr.Port {
192 | // Update last active time
193 | target.lastActive = time.Now()
194 | found = true
195 | break
196 | }
197 | }
198 |
199 | if !found {
200 | // Skip unknown targets
201 | continue
202 | }
203 |
204 | if clientAddr == nil {
205 | // Skip client address not set
206 | continue
207 | }
208 |
209 | // Create response packet with appropriate header
210 | // For simplicity, we'll just use a minimal header with the correct address type
211 | var respHeader []byte
212 |
213 | // Determine address type
214 | var addrType byte
215 | if resp.addr.IP.To4() != nil {
216 | addrType = IPv4
217 | } else {
218 | addrType = IPv6
219 | }
220 |
221 | // header: RSV(2) + FRAG(0) + ATYP(1) + ADDR + PORT(2)
222 | respHeader = append(respHeader, 0, 0, 0, addrType)
223 |
224 | if addrType == IPv4 {
225 | respHeader = append(respHeader, resp.addr.IP.To4()...)
226 | } else {
227 | respHeader = append(respHeader, resp.addr.IP.To16()...)
228 | }
229 |
230 | // Add port
231 | portBytes := make([]byte, 2)
232 | binary.BigEndian.PutUint16(portBytes, uint16(resp.addr.Port))
233 | respHeader = append(respHeader, portBytes...)
234 |
235 | // Combine header and payload
236 | respPacket := append(respHeader, resp.data...)
237 |
238 | _, err = udpConn.WriteToUDP(respPacket, clientAddr)
239 | if err != nil {
240 | if errors.Is(err, net.ErrClosed) {
241 | return
242 | }
243 | }
244 |
245 | case <-ticker.C:
246 | // Clean up inactive targets
247 | now := time.Now()
248 | for targetKey, targetInfo := range targets {
249 | if now.Sub(targetInfo.lastActive) > 1*time.Minute {
250 | delete(targets, targetKey)
251 | }
252 | }
253 |
254 | default:
255 | // Set read deadline to prevent blocking forever
256 | if err := udpConn.SetReadDeadline(time.Now().Add(300 * time.Millisecond)); err != nil {
257 | if errors.Is(err, net.ErrClosed) {
258 | return
259 | }
260 | continue // Non-fatal
261 | }
262 |
263 | n, remoteAddr, err := udpConn.ReadFromUDP(buffer)
264 | if err != nil {
265 | // Handle various error conditions
266 | if errors.Is(err, net.ErrClosed) {
267 | return
268 | }
269 |
270 | if netErr, ok := err.(net.Error); ok {
271 | if netErr.Timeout() {
272 | // This is expected due to deadline, don't log
273 | continue
274 | }
275 | }
276 |
277 | h.SendClose(conn.ID, protocol.ErrNetworkUnreachable)
278 | return
279 | }
280 |
281 | // Store client address from first packet
282 | if clientAddr == nil {
283 | clientAddr = remoteAddr
284 | }
285 |
286 | // Only accept packets from original client
287 | if !remoteAddr.IP.Equal(clientAddr.IP) {
288 | continue
289 | }
290 |
291 | // Handle UDP packet
292 | if n > 3 {
293 | // Extract target address from UDP header
294 | targetAddr, headerLen, errCode := ExtractUDPHeader(buffer[:n])
295 | if errCode != protocol.ErrNone {
296 | continue
297 | }
298 |
299 | // Resolve target address
300 | targetUDPAddr, err := net.ResolveUDPAddr("udp", targetAddr)
301 | if err != nil {
302 | continue
303 | }
304 |
305 | // Store target information
306 | targetKey := targetAddr
307 | targets[targetKey] = &targetInfo{
308 | addr: targetUDPAddr,
309 | lastActive: time.Now(),
310 | }
311 |
312 | // Send payload to target
313 | _, err = targetConn.WriteToUDP(buffer[headerLen:n], targetUDPAddr)
314 | if err != nil {
315 | if errors.Is(err, net.ErrClosed) {
316 | return
317 | }
318 | continue
319 | }
320 | }
321 | }
322 | }
323 | }
324 |
--------------------------------------------------------------------------------
/pkg/transport/blob.go:
--------------------------------------------------------------------------------
1 | // Package transport provides interfaces and implementations for communication
2 | // between proxy components. It abstracts the underlying transport mechanism
3 | // and ensures reliable data transfer with proper error handling.
4 | package transport
5 |
6 | import (
7 | "bytes"
8 | "context"
9 | "errors"
10 | "io"
11 | "time"
12 |
13 | "github.com/Azure/azure-storage-blob-go/azblob"
14 | )
15 |
16 | // Retry configuration for blob operations.
17 | const (
18 | InitialRetryDelay = 50 * time.Millisecond // Starting delay between retries
19 | MaxRetryDelay = 3 * time.Second // Maximum delay between retries
20 | BackoffFactor = 1.5 // Multiplier for exponential backoff
21 | )
22 |
23 | // BlobTransport implements the Transport interface using Azure Blob Storage.
24 | // It uses separate blobs for reading and writing to provide bidirectional
25 | // communication. All operations are retried with exponential backoff.
26 | type BlobTransport struct {
27 | readBlob azblob.BlockBlobURL // Blob for receiving data
28 | writeBlob azblob.BlockBlobURL // Blob for sending data
29 | }
30 |
31 | // NewBlobTransport creates a transport that uses the provided blobs for
32 | // bidirectional communication. The readBlob is used for receiving data,
33 | // and the writeBlob is used for sending data.
34 | func NewBlobTransport(readBlob, writeBlob azblob.BlockBlobURL) *BlobTransport {
35 | return &BlobTransport{
36 | readBlob: readBlob,
37 | writeBlob: writeBlob,
38 | }
39 | }
40 |
41 | // Send writes data to the write blob. It blocks until the data is written
42 | // or the context is canceled. Returns an error code indicating success or
43 | // specific failure reason.
44 | func (t *BlobTransport) Send(ctx context.Context, data []byte) byte {
45 | return WriteBlob(ctx, t.writeBlob, data)
46 | }
47 |
48 | // Receive reads and clears data from the read blob. It blocks until data
49 | // is available or the context is canceled. Returns the read data and an
50 | // error code indicating success or failure reason.
51 | func (t *BlobTransport) Receive(ctx context.Context) ([]byte, byte) {
52 | return WaitForData(ctx, t.readBlob)
53 | }
54 |
55 | // IsClosed reports whether the transport is permanently closed.
56 | func (t *BlobTransport) IsClosed(errCode byte) bool {
57 | return errCode == ErrTransportClosed
58 | }
59 |
60 | // WriteBlob attempts to write data to a blob with retry and exponential backoff.
61 | // The operation is retried until successful or the context is canceled.
62 | // Returns an error code indicating success or specific failure reason.
63 | func WriteBlob(ctx context.Context, blobURL azblob.BlockBlobURL, data []byte) byte {
64 | retryDelay := InitialRetryDelay
65 |
66 | // Try the operation with unlimited retries
67 | for {
68 | // Check if blob is empty
69 | isEmpty, errCode := IsBlobEmpty(ctx, blobURL)
70 | if errCode != ErrNone {
71 | return errCode
72 | }
73 |
74 | if !isEmpty {
75 | // If the blob isn't empty, wait before retrying
76 | retryDelay, errCode = WaitDelay(ctx, retryDelay)
77 | if errCode != ErrNone {
78 | return errCode
79 | }
80 | continue
81 | }
82 |
83 | // Reset delay when we find empty blob
84 | retryDelay = InitialRetryDelay
85 |
86 | // Upload data to the blob
87 | _, err := blobURL.Upload(
88 | ctx,
89 | bytes.NewReader(data),
90 | azblob.BlobHTTPHeaders{ContentType: "application/octet-stream"},
91 | azblob.Metadata{},
92 | azblob.BlobAccessConditions{},
93 | azblob.DefaultAccessTier,
94 | nil,
95 | azblob.ClientProvidedKeyOptions{},
96 | azblob.ImmutabilityPolicyOptions{},
97 | )
98 |
99 | if err != nil {
100 | // If upload fails, check context and retry
101 | if ctx.Err() != nil {
102 | return ErrContextCanceled
103 | }
104 |
105 | // Wait before retrying with exponential backoff
106 | retryDelay, errCode = WaitDelay(ctx, retryDelay)
107 | if errCode != ErrNone {
108 | return errCode
109 | }
110 | continue
111 | }
112 |
113 | // Success
114 | return ErrNone
115 | }
116 | }
117 |
118 | // WaitForData polls a blob until data is available, then reads and clears it.
119 | // The operation is retried with exponential backoff until data is found or
120 | // the context is canceled. Returns the read data and an error code indicating
121 | // success or failure reason.
122 | func WaitForData(ctx context.Context, blobURL azblob.BlockBlobURL) ([]byte, byte) {
123 | var data []byte
124 | retryDelay := InitialRetryDelay
125 |
126 | for {
127 | // Check for cancellation
128 | if ctx.Err() != nil {
129 | return nil, ErrContextCanceled
130 | }
131 |
132 | // Poll until the blob contains data
133 | isEmpty, errCode := IsBlobEmpty(ctx, blobURL)
134 | if errCode != ErrNone {
135 | return nil, errCode
136 | }
137 |
138 | if isEmpty {
139 | // If empty, wait before checking again with exponential backoff
140 | retryDelay, errCode = WaitDelay(ctx, retryDelay)
141 | if errCode != ErrNone {
142 | return nil, errCode
143 | }
144 | continue
145 | }
146 |
147 | // Reset delay when we find data
148 | retryDelay = InitialRetryDelay
149 |
150 | // Found data, download the blob content
151 | response, err := blobURL.Download(ctx, 0, azblob.CountToEnd, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
152 | if err != nil {
153 | return nil, BlobError(err)
154 | }
155 |
156 | bodyReader := response.Body(azblob.RetryReaderOptions{MaxRetryRequests: 3})
157 | defer bodyReader.Close()
158 |
159 | // Read the data
160 | data, err = io.ReadAll(bodyReader)
161 | if err != nil {
162 | return nil, ErrTransportError
163 | }
164 |
165 | // Clear the blob - no retries here
166 | errCode = ClearBlob(ctx, blobURL)
167 | if errCode != ErrNone {
168 | return nil, errCode
169 | }
170 |
171 | return data, ErrNone
172 | }
173 | }
174 |
175 | // IsBlobEmpty checks if a blob is empty by retrieving its properties.
176 | // Returns true if the blob has zero content length, and an error code
177 | // indicating success or failure reason.
178 | func IsBlobEmpty(ctx context.Context, blobURL azblob.BlockBlobURL) (bool, byte) {
179 | // Check for cancelation
180 | props, err := blobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
181 | if err != nil {
182 | return false, BlobError(err)
183 | }
184 |
185 | return props.ContentLength() == 0, ErrNone
186 | }
187 |
188 | // ClearBlob empties a blob's contents by uploading an empty byte slice.
189 | // The operation is retried with exponential backoff until successful or
190 | // the context is canceled. Returns an error code indicating success or
191 | // specific failure reason.
192 | func ClearBlob(ctx context.Context, blobURL azblob.BlockBlobURL) byte {
193 | var errCode byte
194 | retryDelay := InitialRetryDelay
195 |
196 | // Try the operation with unlimited retries
197 | for {
198 | _, err := blobURL.Upload(
199 | ctx,
200 | bytes.NewReader([]byte{}),
201 | azblob.BlobHTTPHeaders{ContentType: "application/octet-stream"},
202 | azblob.Metadata{},
203 | azblob.BlobAccessConditions{},
204 | azblob.DefaultAccessTier,
205 | nil,
206 | azblob.ClientProvidedKeyOptions{},
207 | azblob.ImmutabilityPolicyOptions{},
208 | )
209 |
210 | if err == nil {
211 | // Success, no error
212 | return ErrNone
213 | }
214 |
215 | // Wait before retrying with exponential backoff
216 | retryDelay, errCode = WaitDelay(ctx, retryDelay)
217 | if errCode != ErrNone {
218 | return errCode
219 | }
220 | }
221 | }
222 |
223 | // BlobError maps Azure Blob Storage errors to transport error codes.
224 | // It handles common error cases like container not found, network issues,
225 | // and authentication failures.
226 | func BlobError(err error) byte {
227 | // Quick check for nil
228 | if err == nil {
229 | return ErrNone
230 | }
231 |
232 | // Check for context cancellation
233 | if errors.Is(err, context.Canceled) {
234 | return ErrContextCanceled
235 | }
236 |
237 | // Check for container-related errors (indicating transport is closed)
238 | if storageErr, ok := err.(azblob.StorageError); ok {
239 | serviceCode := storageErr.ServiceCode()
240 | if serviceCode == azblob.ServiceCodeContainerNotFound ||
241 | serviceCode == azblob.ServiceCodeContainerBeingDeleted ||
242 | serviceCode == azblob.ServiceCodeAccountBeingCreated {
243 | return ErrTransportClosed
244 | }
245 | }
246 |
247 | // All other errors are treated as general transport errors
248 | return ErrTransportError
249 | }
250 |
251 | // WaitDelay implements exponential backoff for retry operations.
252 | // It sleeps for the current delay and returns the next delay duration,
253 | // which is the current delay multiplied by BackoffFactor, capped at
254 | // MaxRetryDelay. Returns an error code if the context is canceled.
255 | func WaitDelay(ctx context.Context, retryDelay time.Duration) (time.Duration, byte) {
256 | select {
257 | case <-ctx.Done():
258 | return 0, ErrContextCanceled
259 | case <-time.After(retryDelay):
260 | retryDelay = time.Duration(float64(retryDelay) * BackoffFactor)
261 | if retryDelay > MaxRetryDelay {
262 | retryDelay = MaxRetryDelay
263 | }
264 | return retryDelay, ErrNone
265 | }
266 | }
267 |
--------------------------------------------------------------------------------
/pkg/transport/transport.go:
--------------------------------------------------------------------------------
1 | // Package transport provides interfaces and implementations for communication
2 | // between proxy components. It abstracts the underlying transport mechanism
3 | // and ensures reliable data transfer with proper error handling.
4 | package transport
5 |
6 | import (
7 | "context"
8 | )
9 |
10 | // Error codes for transport operations.
11 | const (
12 | ErrNone byte = 0 // Operation completed successfully
13 | ErrContextCanceled byte = 2 // Context was canceled during operation
14 |
15 | // Transport errors (20-29)
16 | ErrTransportClosed byte = 20 // Transport is permanently closed
17 | ErrTransportTimeout byte = 21 // Operation exceeded time limit
18 | ErrTransportError byte = 22 // Generic transport error
19 | )
20 |
21 | // Transport defines an interface for bidirectional packet communication.
22 | // Implementations must ensure reliable delivery and proper error handling.
23 | // All methods are safe for concurrent use.
24 | type Transport interface {
25 | // Send transmits data to the recipient. It blocks until the data is sent
26 | // or the context is canceled. Returns an error code indicating success
27 | // or specific failure reason.
28 | Send(ctx context.Context, data []byte) byte
29 |
30 | // Receive waits for and returns available data. It blocks until data
31 | // is available or the context is canceled. Returns the received data
32 | // and an error code indicating success or failure reason.
33 | Receive(ctx context.Context) ([]byte, byte)
34 |
35 | // IsClosed reports whether the transport is permanently closed.
36 | // The error code parameter helps determine the closure reason.
37 | IsClosed(byte) bool
38 | }
39 |
--------------------------------------------------------------------------------