Compare commits

..

15 Commits

Author SHA1 Message Date
b484981017 Merge pull request 'staging' (#35) from staging into main
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 4m22s
Reviewed-on: #35
2025-12-09 16:40:44 +00:00
102c975388 Merge branch 'staging' of https://git.fossy.my.id/bagas/tunnel-please into staging
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 4m17s
2025-12-09 23:40:06 +07:00
ad034ef681 fix: resolve random SSH disconnections caused by 'unexpected bytes remain' errors 2025-12-09 23:39:22 +07:00
aceecfd14c Merge pull request 'Update LICENSE.md' (#34) from staging into main
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 6m44s
Reviewed-on: #34
2025-12-08 16:03:33 +00:00
a2a688fc4e Update LICENSE.md
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 3m51s
2025-12-08 16:02:51 +00:00
1de7155771 Merge pull request 'fix: prevent race condition when channel is used before being set' (#33) from staging into main
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 3m46s
Reviewed-on: #33
2025-12-08 15:47:01 +00:00
c951c41a9b fix: prevent race condition when channel is used before being set
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 6m24s
2025-12-08 22:46:10 +07:00
79d77497a0 Merge pull request 'update: readme' (#32) from staging into main
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 6m22s
Reviewed-on: #32
2025-12-08 14:13:23 +00:00
cb08bb7673 update: readme
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 6m24s
2025-12-08 21:13:16 +07:00
20b90c1727 Merge pull request 'Update .gitea/workflows/build.yml' (#31) from staging into main
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 5m9s
Reviewed-on: #31
2025-12-08 13:37:07 +00:00
5d9f7aee92 Update .gitea/workflows/build.yml
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 5m26s
2025-12-08 13:35:46 +00:00
a1e920f6b5 Merge pull request 'refactor: remove magic numbers and replace with named constants' (#30) from staging into main
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 6m10s
Reviewed-on: bagas/tunnl_please#30
2025-12-08 12:46:56 +00:00
dd96c8fe75 refactor: remove magic numbers and replace with named constants
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 6m20s
2025-12-08 19:46:04 +07:00
b5045409cb Merge pull request 'feat: add droping conn command' (#29) from staging into main
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 4m30s
Reviewed-on: bagas/tunnl_please#29
2025-12-07 09:30:47 +00:00
ba5f702e36 feat: add droping conn command
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 4m38s
2025-12-07 15:26:37 +07:00
10 changed files with 637 additions and 614 deletions

View File

@ -30,7 +30,7 @@ jobs:
context: . context: .
push: true push: true
tags: | tags: |
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnl_please:latest git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:latest
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
if: github.ref == 'refs/heads/main' if: github.ref == 'refs/heads/main'
@ -40,6 +40,6 @@ jobs:
context: . context: .
push: true push: true
tags: | tags: |
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnl_please:staging git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:staging
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
if: github.ref == 'refs/heads/staging' if: github.ref == 'refs/heads/staging'

View File

106
README.md
View File

@ -1,93 +1,35 @@
# tunnel_pls # Tunnel Please
A lightweight SSH-based tunnel server written in Go that enables secure TCP and HTTP forwarding with an interactive terminal interface for managing connections and custom subdomains.
## Features
## Getting started - SSH interactive session with real-time command handling
- Custom subdomain management for HTTP tunnels
- Active connection control with drop functionality
- Dual protocol support: HTTP and TCP tunnels
- Real-time connection monitoring
## Requirements
To make it easy for you to get started with GitLab, here's a list of recommended next steps. - Go 1.18 or higher
- Valid domain name for subdomain routing
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin http://git.fossy.my.id/bagas/tunnel_pls.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](http://git.fossy.my.id/bagas/tunnel_pls/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing ## Contributing
State if you are open to contributions and what your requirements are for accepting them. Contributions are welcome!
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. If you'd like to contribute to this project, please follow the workflow below:
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. 1. **Fork** the repository
2. Create a new branch for your changes
## Authors and acknowledgment 3. Commit and push your updates
Show your appreciation to those who have contributed to the project. 4. Open a **Pull Request** targeting the **`staging`** branch
5. Clearly describe your changes and the reasoning behind them
## License ## License
For open source projects, say how it is licensed. This project is licensed under the [Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)](https://creativecommons.org/licenses/by-nc-nd/4.0/) license.
## Author
**Bagas (fossyy)**
- Website: [fossy.my.id](https://fossy.my.id)
- GitHub: [@fossyy](https://github.com/fossyy)
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

View File

@ -11,7 +11,6 @@ import (
"regexp" "regexp"
"strings" "strings"
"tunnel_pls/session" "tunnel_pls/session"
"tunnel_pls/types"
"tunnel_pls/utils" "tunnel_pls/utils"
) )
@ -30,7 +29,6 @@ type CustomWriter struct {
respMW []ResponseMiddleware respMW []ResponseMiddleware
reqStartMW []RequestMiddleware reqStartMW []RequestMiddleware
reqEndMW []RequestMiddleware reqEndMW []RequestMiddleware
overflow []byte
} }
func (cw *CustomWriter) SetInteraction(interaction Interaction) { func (cw *CustomWriter) SetInteraction(interaction Interaction) {
@ -38,14 +36,6 @@ func (cw *CustomWriter) SetInteraction(interaction Interaction) {
} }
func (cw *CustomWriter) Read(p []byte) (int, error) { func (cw *CustomWriter) Read(p []byte) (int, error) {
if len(cw.overflow) > 0 {
n := copy(p, cw.overflow)
cw.overflow = cw.overflow[n:]
if len(cw.overflow) == 0 {
cw.overflow = nil
}
return n, nil
}
tmp := make([]byte, len(p)) tmp := make([]byte, len(p))
read, err := cw.reader.Read(tmp) read, err := cw.reader.Read(tmp)
if read == 0 && err != nil { if read == 0 && err != nil {
@ -99,12 +89,6 @@ func (cw *CustomWriter) Read(p []byte) (int, error) {
n := copy(p, combined) n := copy(p, combined)
if n > len(p) {
cw.overflow = make([]byte, len(combined)-n)
copy(cw.overflow, combined[n:])
log.Printf("output buffer too small (%d vs %d)", len(p), n)
}
return n, nil return n, nil
} }
@ -118,7 +102,7 @@ func NewCustomWriter(writer io.Writer, reader io.Reader, remoteAddr net.Addr) *C
} }
} }
var DELIMITER = []byte{0x0D, 0x0A, 0x0D, 0x0A} // HTTP HEADER DELIMITER `\r\n\r\n` var DELIMITER = []byte{0x0D, 0x0A, 0x0D, 0x0A}
var requestLine = regexp.MustCompile(`^(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|TRACE|CONNECT) \S+ HTTP/\d\.\d$`) var requestLine = regexp.MustCompile(`^(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|TRACE|CONNECT) \S+ HTTP/\d\.\d$`)
var responseLine = regexp.MustCompile(`^HTTP/\d\.\d \d{3} .+`) var responseLine = regexp.MustCompile(`^HTTP/\d\.\d \d{3} .+`)
@ -143,8 +127,8 @@ func isHTTPHeader(buf []byte) bool {
} }
func (cw *CustomWriter) Write(p []byte) (int, error) { func (cw *CustomWriter) Write(p []byte) (int, error) {
if len(p) == len(types.BadGatewayResponse) && bytes.Equal(p, types.BadGatewayResponse) { if cw.respHeader != nil && len(cw.buf) == 0 && len(p) >= 5 && string(p[0:5]) == "HTTP/" {
return cw.writer.Write(p) cw.respHeader = nil
} }
if cw.respHeader != nil { if cw.respHeader != nil {
@ -166,9 +150,12 @@ func (cw *CustomWriter) Write(p []byte) (int, error) {
body := cw.buf[idx+len(DELIMITER):] body := cw.buf[idx+len(DELIMITER):]
if !isHTTPHeader(header) { if !isHTTPHeader(header) {
n, err := cw.writer.Write(cw.buf) _, err := cw.writer.Write(cw.buf)
cw.buf = nil cw.buf = nil
return n, err if err != nil {
return 0, err
}
return len(p), nil
} }
resphf := NewResponseHeaderFactory(header) resphf := NewResponseHeaderFactory(header)
@ -323,20 +310,12 @@ func forwardRequest(cw *CustomWriter, initialRequest *RequestHeaderFactory, sshS
} }
} }
}() }()
_, err = channel.Write(initialRequest.Finalize())
if err != nil {
log.Printf("Failed to forward request: %v", err)
return
}
//TODO: Implement wrapper func buat add/remove middleware
fingerprintMiddleware := NewTunnelFingerprint() fingerprintMiddleware := NewTunnelFingerprint()
loggerMiddleware := NewRequestLogger(cw.interaction, cw.RemoteAddr)
forwardedForMiddleware := NewForwardedFor(cw.RemoteAddr) forwardedForMiddleware := NewForwardedFor(cw.RemoteAddr)
cw.respMW = append(cw.respMW, fingerprintMiddleware) cw.respMW = append(cw.respMW, fingerprintMiddleware)
cw.reqStartMW = append(cw.reqStartMW, loggerMiddleware)
cw.reqStartMW = append(cw.reqStartMW, forwardedForMiddleware) cw.reqStartMW = append(cw.reqStartMW, forwardedForMiddleware)
//TODO: Tambah req Middleware
cw.reqEndMW = nil cw.reqEndMW = nil
cw.reqHeader = initialRequest cw.reqHeader = initialRequest
@ -348,6 +327,12 @@ func forwardRequest(cw *CustomWriter, initialRequest *RequestHeaderFactory, sshS
} }
} }
_, err = channel.Write(initialRequest.Finalize())
if err != nil {
log.Printf("Failed to forward request: %v", err)
return
}
sshSession.Forwarder.HandleConnection(cw, channel, cw.RemoteAddr) sshSession.Forwarder.HandleConnection(cw, channel, cw.RemoteAddr)
return return
} }

View File

@ -1,9 +1,7 @@
package server package server
import ( import (
"fmt"
"net" "net"
"time"
) )
type RequestMiddleware interface { type RequestMiddleware interface {
@ -30,18 +28,6 @@ type RequestLogger struct {
remoteAddr net.Addr remoteAddr net.Addr
} }
func NewRequestLogger(interaction Interaction, remoteAddr net.Addr) *RequestLogger {
return &RequestLogger{
interaction: interaction,
remoteAddr: remoteAddr,
}
}
func (rl *RequestLogger) HandleRequest(header *RequestHeaderFactory) error {
rl.interaction.SendMessage(fmt.Sprintf("\033[32m%s %s -> %s %s \033[0m\r\n", time.Now().UTC().Format(time.RFC3339), rl.remoteAddr.String(), header.Method, header.Path))
return nil
}
type ForwardedFor struct { type ForwardedFor struct {
addr net.Addr addr net.Addr
} }

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"errors" "errors"
"fmt"
"io" "io"
"log" "log"
"net" "net"
@ -20,6 +21,7 @@ type Forwarder struct {
ForwardedPort uint16 ForwardedPort uint16
SlugManager slug.Manager SlugManager slug.Manager
Lifecycle Lifecycle Lifecycle Lifecycle
ActiveForwarder []chan struct{}
} }
type Lifecycle interface { type Lifecycle interface {
@ -39,6 +41,27 @@ type ForwardingController interface {
SetLifecycle(lifecycle Lifecycle) SetLifecycle(lifecycle Lifecycle)
CreateForwardedTCPIPPayload(origin net.Addr) []byte CreateForwardedTCPIPPayload(origin net.Addr) []byte
WriteBadGatewayResponse(dst io.Writer) WriteBadGatewayResponse(dst io.Writer)
AddActiveForwarder(drop chan struct{})
DropAllForwarder() int
GetForwarderCount() int
}
func (f *Forwarder) AddActiveForwarder(drop chan struct{}) {
f.ActiveForwarder = append(f.ActiveForwarder, drop)
}
func (f *Forwarder) DropAllForwarder() int {
total := 0
for _, d := range f.ActiveForwarder {
close(d)
total += 1
}
f.ActiveForwarder = nil
return total
}
func (f *Forwarder) GetForwarderCount() int {
return len(f.ActiveForwarder)
} }
func (f *Forwarder) SetLifecycle(lifecycle Lifecycle) { func (f *Forwarder) SetLifecycle(lifecycle Lifecycle) {
@ -76,6 +99,7 @@ func (f *Forwarder) AcceptTCPConnections() {
} }
func (f *Forwarder) HandleConnection(dst io.ReadWriter, src ssh.Channel, remoteAddr net.Addr) { func (f *Forwarder) HandleConnection(dst io.ReadWriter, src ssh.Channel, remoteAddr net.Addr) {
drop := make(chan struct{})
defer func(src ssh.Channel) { defer func(src ssh.Channel) {
_, err := io.Copy(io.Discard, src) _, err := io.Copy(io.Discard, src)
if err != nil { if err != nil {
@ -96,6 +120,16 @@ func (f *Forwarder) HandleConnection(dst io.ReadWriter, src ssh.Channel, remoteA
} }
}() }()
go func() {
select {
case <-drop:
fmt.Println("Closinggggg")
return
}
}()
f.AddActiveForwarder(drop)
_, err := io.Copy(dst, src) _, err := io.Copy(dst, src)
if err != nil && !errors.Is(err, io.EOF) { if err != nil && !errors.Is(err, io.EOF) {

View File

@ -0,0 +1,27 @@
package interaction
const (
backspaceChar = 8
deleteChar = 127
enterChar = 13
escapeChar = 27
ctrlC = 3
forwardSlash = '/'
minPrintableChar = 32
maxPrintableChar = 126
minSlugLength = 3
maxSlugLength = 20
clearScreen = "\033[H\033[2J"
clearLine = "\033[K"
clearToLineEnd = "\r\033[K"
backspaceSeq = "\b \b"
minBoxWidth = 50
paddingRight = 4
)
var forbiddenSlugs = []string{
"ping",
}

View File

@ -14,10 +14,6 @@ import (
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
) )
var forbiddenSlug = []string{
"ping",
}
type Lifecycle interface { type Lifecycle interface {
Close() error Close() error
} }
@ -26,27 +22,32 @@ type Controller interface {
SendMessage(message string) SendMessage(message string)
HandleUserInput() HandleUserInput()
HandleCommand(command string) HandleCommand(command string)
HandleSlugEditMode(connection ssh.Channel, char byte) HandleSlugEditMode(char byte)
HandleSlugSave(conn ssh.Channel) HandleSlugSave()
HandleSlugCancel(connection ssh.Channel) HandleSlugCancel()
HandleSlugUpdateError() HandleSlugUpdateError()
ShowWelcomeMessage() ShowWelcomeMessage()
DisplaySlugEditor() DisplaySlugEditor()
SetChannel(channel ssh.Channel) SetChannel(channel ssh.Channel)
SetLifecycle(lifecycle Lifecycle) SetLifecycle(lifecycle Lifecycle)
SetSlugModificator(func(oldSlug, newSlug string) bool) SetSlugModificator(func(oldSlug, newSlug string) bool)
WaitForKeyPress()
ShowForwardingMessage()
} }
type Forwarder interface { type Forwarder interface {
Close() error Close() error
GetTunnelType() types.TunnelType GetTunnelType() types.TunnelType
GetForwardedPort() uint16 GetForwardedPort() uint16
DropAllForwarder() int
GetForwarderCount() int
} }
type Interaction struct { type Interaction struct {
InputLength int InputLength int
CommandBuffer *bytes.Buffer CommandBuffer *bytes.Buffer
EditMode bool InteractiveMode bool
InteractionType types.InteractionType
EditSlug string EditSlug string
channel ssh.Channel channel ssh.Channel
SlugManager slug.Manager SlugManager slug.Manager
@ -65,139 +66,174 @@ func (i *Interaction) SetChannel(channel ssh.Channel) {
} }
func (i *Interaction) SendMessage(message string) { func (i *Interaction) SendMessage(message string) {
if i.channel != nil { if i.channel == nil {
log.Printf("channel is nil")
}
_, err := i.channel.Write([]byte(message)) _, err := i.channel.Write([]byte(message))
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
log.Printf("Error writing to channel: %v", err) log.Printf("error writing to channel: %s", err)
}
return return
}
}
} }
func (i *Interaction) HandleUserInput() { func (i *Interaction) HandleUserInput() {
buf := make([]byte, 1) buf := make([]byte, 1)
i.EditMode = false i.InteractiveMode = false
for { for {
n, err := i.channel.Read(buf) n, err := i.channel.Read(buf)
if err != nil { if err != nil {
if err != io.EOF { i.handleReadError(err)
log.Printf("Error reading from client: %s", err)
}
break break
} }
if n > 0 { if n > 0 {
char := buf[0] i.processCharacter(buf[0])
if i.EditMode {
i.HandleSlugEditMode(i.channel, char)
continue
}
if i.pendingExit {
if char != 3 {
i.pendingExit = false
i.SendMessage("Operation canceled.\r\n")
} }
} }
}
if char == 3 { func (i *Interaction) handleReadError(err error) {
if err != io.EOF {
log.Printf("Error reading from client: %s", err)
}
}
func (i *Interaction) processCharacter(char byte) {
if i.InteractiveMode {
i.handleInteractiveMode(char)
return
}
if i.handleExitSequence(char) {
return
}
i.SendMessage(string(char))
i.handleNonInteractiveInput(char)
}
func (i *Interaction) handleInteractiveMode(char byte) {
switch i.InteractionType {
case types.Slug:
i.HandleSlugEditMode(char)
case types.Drop:
i.HandleDropMode(char)
}
}
func (i *Interaction) handleExitSequence(char byte) bool {
if char == ctrlC {
if i.pendingExit { if i.pendingExit {
i.SendMessage("Closing connection...\r\n") i.SendMessage("Closing connection...\r\n")
err = i.Lifecycle.Close() if err := i.Lifecycle.Close(); err != nil {
if err != nil {
log.Printf("failed to close session: %v", err) log.Printf("failed to close session: %v", err)
return
} }
return return true
} }
i.SendMessage("Please press Ctrl+C again to disconnect.\r\n") i.SendMessage("Please press Ctrl+C again to disconnect.\r\n")
i.pendingExit = true i.pendingExit = true
return true
} }
i.SendMessage(string(buf[:n])) if i.pendingExit && char != ctrlC {
i.pendingExit = false
i.SendMessage("Operation canceled.\r\n")
}
if char == 8 || char == 127 { return false
}
func (i *Interaction) handleNonInteractiveInput(char byte) {
switch {
case char == backspaceChar || char == deleteChar:
i.handleBackspace()
case char == forwardSlash:
i.handleCommandStart()
case i.CommandBuffer.Len() > 0:
i.handleCommandInput(char)
case char == enterChar:
i.SendMessage(clearLine)
default:
i.InputLength++
}
}
func (i *Interaction) handleBackspace() {
if i.InputLength > 0 { if i.InputLength > 0 {
i.SendMessage("\b \b") i.SendMessage(backspaceSeq)
} }
if i.CommandBuffer.Len() > 0 { if i.CommandBuffer.Len() > 0 {
i.CommandBuffer.Truncate(i.CommandBuffer.Len() - 1) i.CommandBuffer.Truncate(i.CommandBuffer.Len() - 1)
} }
continue }
}
i.InputLength += n func (i *Interaction) handleCommandStart() {
if char == '/' {
i.CommandBuffer.Reset() i.CommandBuffer.Reset()
i.CommandBuffer.WriteByte(char) i.CommandBuffer.WriteByte(forwardSlash)
continue }
}
if i.CommandBuffer.Len() > 0 { func (i *Interaction) handleCommandInput(char byte) {
if char == 13 { if char == enterChar {
i.SendMessage("\033[K") i.SendMessage(clearLine)
i.HandleCommand(i.CommandBuffer.String()) i.HandleCommand(i.CommandBuffer.String())
continue return
} }
i.CommandBuffer.WriteByte(char) i.CommandBuffer.WriteByte(char)
} i.InputLength++
}
if char == 13 { func (i *Interaction) HandleSlugEditMode(char byte) {
i.SendMessage("\033[K") switch {
} case char == enterChar:
i.HandleSlugSave()
} case char == escapeChar || char == ctrlC:
i.HandleSlugCancel()
case char == backspaceChar || char == deleteChar:
i.handleSlugBackspace()
case char >= minPrintableChar && char <= maxPrintableChar:
i.appendToSlug(char)
} }
} }
func (i *Interaction) HandleSlugEditMode(connection ssh.Channel, char byte) { func (i *Interaction) handleSlugBackspace() {
if char == 13 {
i.HandleSlugSave(connection)
} else if char == 27 || char == 3 {
i.HandleSlugCancel(connection)
} else if char == 8 || char == 127 {
if len(i.EditSlug) > 0 { if len(i.EditSlug) > 0 {
i.EditSlug = (i.EditSlug)[:len(i.EditSlug)-1] i.EditSlug = i.EditSlug[:len(i.EditSlug)-1]
_, err := connection.Write([]byte("\r\033[K")) i.refreshSlugDisplay()
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("➤ " + i.EditSlug + "." + utils.Getenv("domain")))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
}
} else if char >= 32 && char <= 126 {
if (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') || char == '-' {
i.EditSlug += string(char)
_, err := connection.Write([]byte("\r\033[K"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("➤ " + i.EditSlug + "." + utils.Getenv("domain")))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
}
} }
} }
func (i *Interaction) HandleSlugSave(connection ssh.Channel) { func (i *Interaction) appendToSlug(char byte) {
isValid := isValidSlug(i.EditSlug) if isValidSlugChar(char) {
i.EditSlug += string(char)
_, err := connection.Write([]byte("\033[H\033[2J")) i.refreshSlugDisplay()
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
} }
if isValid { }
func (i *Interaction) refreshSlugDisplay() {
domain := utils.Getenv("domain")
i.SendMessage(clearToLineEnd)
i.SendMessage("➤ " + i.EditSlug + "." + domain)
}
func (i *Interaction) HandleSlugSave() {
i.SendMessage(clearScreen)
switch {
case isForbiddenSlug(i.EditSlug):
i.showForbiddenSlugMessage()
case !isValidSlug(i.EditSlug):
i.showInvalidSlugMessage()
default:
i.updateSlug()
}
i.WaitForKeyPress()
i.returnToMainScreen()
}
func (i *Interaction) updateSlug() {
oldSlug := i.SlugManager.Get() oldSlug := i.SlugManager.Get()
newSlug := i.EditSlug newSlug := i.EditSlug
@ -206,150 +242,114 @@ func (i *Interaction) HandleSlugSave(connection ssh.Channel) {
return return
} }
_, err := connection.Write([]byte("\r\n\r\n✅ SUBDOMAIN UPDATED ✅\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Your new address is: " + newSlug + "." + utils.Getenv("domain") + "\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
} else if isForbiddenSlug(i.EditSlug) {
_, err := connection.Write([]byte("\r\n\r\n❌ FORBIDDEN SUBDOMAIN ❌\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("This subdomain is not allowed.\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Please try a different subdomain.\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
} else {
_, err := connection.Write([]byte("\r\n\r\n❌ INVALID SUBDOMAIN ❌\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Use only lowercase letters, numbers, and hyphens.\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Length must be 3-20 characters and cannot start or end with a hyphen.\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
}
waitForKeyPress(connection)
_, err = connection.Write([]byte("\033[H\033[2J"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
i.ShowWelcomeMessage()
domain := utils.Getenv("domain") domain := utils.Getenv("domain")
protocol := "http" i.SendMessage("\r\n\r\n✅ SUBDOMAIN UPDATED ✅\r\n\r\n")
if utils.Getenv("tls_enabled") == "true" { i.SendMessage("Your new address is: " + newSlug + "." + domain + "\r\n\r\n")
protocol = "https" i.SendMessage("Press any key to continue...\r\n")
} }
_, err = connection.Write([]byte(fmt.Sprintf("Forwarding your traffic to %s://%s.%s \r\n", protocol, i.SlugManager.Get(), domain)))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
i.EditMode = false func (i *Interaction) showForbiddenSlugMessage() {
i.SendMessage("\r\n\r\n❌ FORBIDDEN SUBDOMAIN ❌\r\n\r\n")
i.SendMessage("This subdomain is not allowed.\r\n")
i.SendMessage("Please try a different subdomain.\r\n\r\n")
i.SendMessage("Press any key to continue...\r\n")
}
func (i *Interaction) showInvalidSlugMessage() {
i.SendMessage("\r\n\r\n❌ INVALID SUBDOMAIN ❌\r\n\r\n")
i.SendMessage("Use only lowercase letters, numbers, and hyphens.\r\n")
i.SendMessage(fmt.Sprintf("Length must be %d-%d characters and cannot start or end with a hyphen.\r\n\r\n", minSlugLength, maxSlugLength))
i.SendMessage("Press any key to continue...\r\n")
}
func (i *Interaction) returnToMainScreen() {
i.SendMessage(clearScreen)
i.ShowWelcomeMessage()
i.ShowForwardingMessage()
i.InteractiveMode = false
i.CommandBuffer.Reset() i.CommandBuffer.Reset()
} }
func (i *Interaction) HandleSlugCancel(connection ssh.Channel) { func (i *Interaction) HandleSlugCancel() {
i.EditMode = false i.InteractiveMode = false
_, err := connection.Write([]byte("\033[H\033[2J")) i.showMessageAndWait("\r\n\r\n⚠ SUBDOMAIN EDIT CANCELLED ⚠️\r\n\r\n")
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("\r\n\r\n⚠ SUBDOMAIN EDIT CANCELLED ⚠️\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
waitForKeyPress(connection)
_, err = connection.Write([]byte("\033[H\033[2J"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
i.ShowWelcomeMessage()
i.CommandBuffer.Reset()
} }
func (i *Interaction) HandleSlugUpdateError() { func (i *Interaction) HandleSlugUpdateError() {
i.SendMessage("\r\n\r\n❌ SERVER ERROR ❌\r\n\r\n") i.SendMessage("\r\n\r\n❌ SERVER ERROR ❌\r\n\r\n")
i.SendMessage("Failed to update subdomain. You will be disconnected in 5 seconds.\r\n\r\n") i.SendMessage("Failed to update subdomain. You will be disconnected in 5 seconds.\r\n\r\n")
for iter := 5; iter > 0; iter-- { for countdown := 5; countdown > 0; countdown-- {
i.SendMessage(fmt.Sprintf("Disconnecting in %d...\r\n", iter)) i.SendMessage(fmt.Sprintf("Disconnecting in %d...\r\n", countdown))
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
} }
err := i.Lifecycle.Close()
if err != nil { if err := i.Lifecycle.Close(); err != nil {
log.Printf("failed to close session: %v", err) log.Printf("failed to close session: %v", err)
return
} }
} }
func (i *Interaction) HandleCommand(command string) { func (i *Interaction) HandleCommand(command string) {
switch command { handlers := map[string]func(){
case "/bye": "/bye": i.handleByeCommand,
"/help": i.handleHelpCommand,
"/clear": i.handleClearCommand,
"/slug": i.handleSlugCommand,
"/drop": i.handleDropCommand,
}
if handler, exists := handlers[command]; exists {
handler()
} else {
i.SendMessage("Unknown command\r\n")
}
i.CommandBuffer.Reset()
}
func (i *Interaction) handleByeCommand() {
i.SendMessage("Closing connection...\r\n") i.SendMessage("Closing connection...\r\n")
err := i.Lifecycle.Close() if err := i.Lifecycle.Close(); err != nil {
if err != nil {
log.Printf("failed to close session: %v", err) log.Printf("failed to close session: %v", err)
}
}
func (i *Interaction) handleHelpCommand() {
i.SendMessage("\r\nAvailable commands: /bye, /help, /clear, /slug, /drop\r\n")
}
func (i *Interaction) handleClearCommand() {
i.SendMessage(clearScreen)
i.ShowWelcomeMessage()
i.ShowForwardingMessage()
}
func (i *Interaction) handleSlugCommand() {
if i.Forwarder.GetTunnelType() != types.HTTP {
i.SendMessage(fmt.Sprintf("\r\n%s tunnels cannot have custom subdomains\r\n", i.Forwarder.GetTunnelType()))
return return
} }
return
case "/help": i.InteractiveMode = true
i.SendMessage("\r\nAvailable commands: /bye, /help, /clear, /slug\r\n") i.InteractionType = types.Slug
case "/clear": i.EditSlug = i.SlugManager.Get()
i.SendMessage("\033[H\033[2J") i.SendMessage(clearScreen)
i.ShowWelcomeMessage() i.DisplaySlugEditor()
domain := utils.Getenv("domain") domain := utils.Getenv("domain")
i.SendMessage("➤ " + i.EditSlug + "." + domain)
}
func (i *Interaction) handleDropCommand() {
i.InteractiveMode = true
i.InteractionType = types.Drop
i.SendMessage(clearScreen)
i.ShowDropMessage()
}
func (i *Interaction) ShowForwardingMessage() {
domain := utils.Getenv("domain")
if i.Forwarder.GetTunnelType() == types.HTTP { if i.Forwarder.GetTunnelType() == types.HTTP {
protocol := "http" protocol := "http"
if utils.Getenv("tls_enabled") == "true" { if utils.Getenv("tls_enabled") == "true" {
@ -359,21 +359,64 @@ func (i *Interaction) HandleCommand(command string) {
} else { } else {
i.SendMessage(fmt.Sprintf("Forwarding your traffic to tcp://%s:%d \r\n", domain, i.Forwarder.GetForwardedPort())) i.SendMessage(fmt.Sprintf("Forwarding your traffic to tcp://%s:%d \r\n", domain, i.Forwarder.GetForwardedPort()))
} }
case "/slug": }
if i.Forwarder.GetTunnelType() != types.HTTP {
i.SendMessage(fmt.Sprintf("\r\n%s tunnels cannot have custom subdomains", i.Forwarder.GetTunnelType()))
} else {
i.EditMode = true
i.EditSlug = i.SlugManager.Get()
i.SendMessage("\033[H\033[2J")
i.DisplaySlugEditor()
i.SendMessage("➤ " + i.EditSlug + "." + utils.Getenv("domain"))
}
default:
i.SendMessage("Unknown command\r\n")
}
i.CommandBuffer.Reset() func (i *Interaction) HandleDropMode(char byte) {
switch {
case char == enterChar || char == 'y' || char == 'Y':
i.executeDropAll()
case char == escapeChar || char == 'n' || char == 'N' || char == ctrlC:
i.cancelDrop()
}
}
func (i *Interaction) executeDropAll() {
count := i.Forwarder.DropAllForwarder()
message := fmt.Sprintf("Dropped %d forwarders\r\n", count)
i.showMessageAndWait(message)
}
func (i *Interaction) cancelDrop() {
i.showMessageAndWait("Dropping canceled.\r\n")
}
func (i *Interaction) showMessageAndWait(message string) {
i.SendMessage(clearScreen)
i.SendMessage(message)
i.SendMessage("Press any key to continue...\r\n")
i.InteractiveMode = false
i.InteractionType = ""
i.WaitForKeyPress()
i.SendMessage(clearScreen)
i.ShowWelcomeMessage()
i.ShowForwardingMessage()
}
func (i *Interaction) ShowDropMessage() {
confirmText := fmt.Sprintf(" ║ Drop ALL %d active connections?", i.Forwarder.GetForwarderCount())
boxWidth := calculateBoxWidth(confirmText)
box := buildDropConfirmationBox(boxWidth, confirmText)
i.SendMessage("\r\n" + box + "\r\n\r\n")
}
func buildDropConfirmationBox(boxWidth int, confirmText string) string {
topBorder := " ╔" + strings.Repeat("═", boxWidth-4) + "╗\r\n"
title := centerText("DROP CONFIRMATION", boxWidth-4)
header := " ║" + title + "║\r\n"
midBorder := " ╠" + strings.Repeat("═", boxWidth-4) + "╣\r\n"
emptyLine := " ║" + strings.Repeat(" ", boxWidth-4) + "║\r\n"
confirmLine := confirmText + strings.Repeat(" ", boxWidth-len(confirmText)+1) + "║\r\n"
controlText := " ║ [Enter/Y] Confirm [N/Esc] Cancel"
controlLine := controlText + strings.Repeat(" ", boxWidth-len(controlText)+1) + "║\r\n"
bottomBorder := " ╚" + strings.Repeat("═", boxWidth-4) + "╝\r\n"
return topBorder + header + midBorder + emptyLine + confirmLine + emptyLine + controlLine + emptyLine + bottomBorder
} }
func (i *Interaction) ShowWelcomeMessage() { func (i *Interaction) ShowWelcomeMessage() {
@ -393,6 +436,7 @@ func (i *Interaction) ShowWelcomeMessage() {
` - '/help' : Show this help message`, ` - '/help' : Show this help message`,
` - '/clear' : Clear the current line`, ` - '/clear' : Clear the current line`,
` - '/slug' : Set custom subdomain`, ` - '/slug' : Set custom subdomain`,
` - '/drop' : Drop all active forwarders`,
} }
for _, line := range asciiArt { for _, line := range asciiArt {
@ -405,14 +449,14 @@ func (i *Interaction) DisplaySlugEditor() {
domain := utils.Getenv("domain") domain := utils.Getenv("domain")
fullDomain := i.SlugManager.Get() + "." + domain fullDomain := i.SlugManager.Get() + "." + domain
const paddingRight = 4
contentLine := " ║ Current: " + fullDomain contentLine := " ║ Current: " + fullDomain
boxWidth := len(contentLine) + paddingRight + 1 boxWidth := calculateBoxWidth(contentLine)
if boxWidth < 50 {
boxWidth = 50
}
box := buildSlugEditorBox(boxWidth, fullDomain)
i.SendMessage("\r\n\r\n" + box + "\r\n\r\n")
}
func buildSlugEditorBox(boxWidth int, fullDomain string) string {
topBorder := " ╔" + strings.Repeat("═", boxWidth-4) + "╗\r\n" topBorder := " ╔" + strings.Repeat("═", boxWidth-4) + "╗\r\n"
title := centerText("SUBDOMAIN EDITOR", boxWidth-4) title := centerText("SUBDOMAIN EDITOR", boxWidth-4)
header := " ║" + title + "║\r\n" header := " ║" + title + "║\r\n"
@ -425,24 +469,31 @@ func (i *Interaction) DisplaySlugEditor() {
saveCancel := " ║ [Enter] Save | [Esc] Cancel" + strings.Repeat(" ", boxWidth-35) + "║\r\n" saveCancel := " ║ [Enter] Save | [Esc] Cancel" + strings.Repeat(" ", boxWidth-35) + "║\r\n"
bottomBorder := " ╚" + strings.Repeat("═", boxWidth-4) + "╝\r\n" bottomBorder := " ╚" + strings.Repeat("═", boxWidth-4) + "╝\r\n"
i.SendMessage("\r\n\r\n") return topBorder + header + midBorder + emptyLine + currentLine + emptyLine + emptyLine + midBorder + saveCancel + bottomBorder
i.SendMessage(topBorder)
i.SendMessage(header)
i.SendMessage(midBorder)
i.SendMessage(emptyLine)
i.SendMessage(currentLine)
i.SendMessage(emptyLine)
i.SendMessage(emptyLine)
i.SendMessage(midBorder)
i.SendMessage(saveCancel)
i.SendMessage(bottomBorder)
i.SendMessage("\r\n\r\n")
} }
func (i *Interaction) SetSlugModificator(modificator func(oldSlug, newSlug string) bool) { func (i *Interaction) SetSlugModificator(modificator func(oldSlug, newSlug string) bool) {
i.updateClientSlug = modificator i.updateClientSlug = modificator
} }
func (i *Interaction) WaitForKeyPress() {
keyBuf := make([]byte, 1)
for {
_, err := i.channel.Read(keyBuf)
if err == nil {
break
}
}
}
func calculateBoxWidth(contentLine string) int {
boxWidth := len(contentLine) + paddingRight + 1
if boxWidth < minBoxWidth {
boxWidth = minBoxWidth
}
return boxWidth
}
func centerText(text string, width int) string { func centerText(text string, width int) string {
padding := (width - len(text)) / 2 padding := (width - len(text)) / 2
if padding < 0 { if padding < 0 {
@ -452,7 +503,7 @@ func centerText(text string, width int) string {
} }
func isValidSlug(slug string) bool { func isValidSlug(slug string) bool {
if len(slug) < 3 || len(slug) > 20 { if len(slug) < minSlugLength || len(slug) > maxSlugLength {
return false return false
} }
@ -461,7 +512,7 @@ func isValidSlug(slug string) bool {
} }
for _, c := range slug { for _, c := range slug {
if !((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-') { if !isValidSlugChar(byte(c)) {
return false return false
} }
} }
@ -469,18 +520,12 @@ func isValidSlug(slug string) bool {
return true return true
} }
func waitForKeyPress(connection ssh.Channel) { func isValidSlugChar(c byte) bool {
keyBuf := make([]byte, 1) return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-'
for {
_, err := connection.Read(keyBuf)
if err == nil {
break
}
}
} }
func isForbiddenSlug(slug string) bool { func isForbiddenSlug(slug string) bool {
for _, s := range forbiddenSlug { for _, s := range forbiddenSlugs {
if slug == s { if slug == s {
return true return true
} }

View File

@ -44,7 +44,7 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan
} }
interactionManager := &interaction.Interaction{ interactionManager := &interaction.Interaction{
CommandBuffer: bytes.NewBuffer(make([]byte, 0, 20)), CommandBuffer: bytes.NewBuffer(make([]byte, 0, 20)),
EditMode: false, InteractiveMode: false,
EditSlug: "", EditSlug: "",
SlugManager: slugManager, SlugManager: slugManager,
Forwarder: forwarderManager, Forwarder: forwarderManager,
@ -71,9 +71,6 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan
SlugManager: slugManager, SlugManager: slugManager,
} }
go func() {
go session.Lifecycle.WaitForRunningStatus()
for channel := range sshChan { for channel := range sshChan {
ch, reqs, err := channel.Accept() ch, reqs, err := channel.Accept()
if err != nil { if err != nil {
@ -85,6 +82,7 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan
session.Interaction.SetChannel(ch) session.Interaction.SetChannel(ch)
session.Lifecycle.SetStatus(types.SETUP) session.Lifecycle.SetStatus(types.SETUP)
go session.HandleGlobalRequest(forwardingReq) go session.HandleGlobalRequest(forwardingReq)
session.Lifecycle.WaitForRunningStatus()
}) })
go session.HandleGlobalRequest(reqs) go session.HandleGlobalRequest(reqs)
@ -92,7 +90,6 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan
if err := session.Lifecycle.Close(); err != nil { if err := session.Lifecycle.Close(); err != nil {
log.Printf("failed to close session: %v", err) log.Printf("failed to close session: %v", err)
} }
}()
} }
func updateClientSlug(oldSlug, newSlug string) bool { func updateClientSlug(oldSlug, newSlug string) bool {

View File

@ -15,6 +15,13 @@ const (
TCP TunnelType = "TCP" TCP TunnelType = "TCP"
) )
type InteractionType string
const (
Slug InteractionType = "SLUG"
Drop InteractionType = "DROP"
)
var BadGatewayResponse = []byte("HTTP/1.1 502 Bad Gateway\r\n" + var BadGatewayResponse = []byte("HTTP/1.1 502 Bad Gateway\r\n" +
"Content-Length: 11\r\n" + "Content-Length: 11\r\n" +
"Content-Type: text/plain\r\n\r\n" + "Content-Type: text/plain\r\n\r\n" +