Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
jackcvr committed Sep 19, 2024
0 parents commit b3af478
Show file tree
Hide file tree
Showing 11 changed files with 437 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.idea/
*.log
dist/
*.crt
*.key
69 changes: 69 additions & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com

# The lines below are called `modelines`. See `:help modeline`
# Feel free to remove those if you don't want/need to use them.
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj

version: 2

before:
hooks:
- go mod tidy

builds:
- env:
- CGO_ENABLED=0
goos:
- linux
goarch:
- amd64
- arm
- arm64
goarm:
- 6
- 7

upx:
- enabled: true
compress: best

archives:
- format: tar.gz
# this name template makes the OS and Arch compatible with the results of `uname`.
name_template: >-
{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
format: zip

changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"

nfpms:
- package_name: concierge
maintainer: Andrii Kuzmin <jack.cvr@gmail.com>
bindir: /usr/local/bin
formats:
- apk
- deb
contents:
- src: openrc/concierge
dst: /etc/init.d/concierge
type: config|noreplace
packager: apk
- src: systemd/concierge.service
dst: /lib/systemd/system/concierge.service
type: config|noreplace
packager: deb
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2024 Andrii Kuzmin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Concierge

TODO

## Installation

See [Releases](https://github.com/jackcvr/reverssh/releases)

## Usage

```shell
Usage of concierge:
-a value
Endpoint in format 'url:host:port' (e.g. /ssh:localhost:22)
-b string
Local address to listen on (default "0.0.0.0:80")
-crt string
Crt file for TLS
-f string
Log file (default stdout)
-key string
Key file for TLS
-q Do not print anything
-t duration
Timeout for new connections (default 2s)
-v Verbose mode
```

## Examples

Configure SSH server binding it to localhost.

Start Concierge HTTPS server which replies on `/ssh` URL:

```shell
$ sudo concierge -a /ssh:localhost:22 -crt server.crt -key server.key
{"time":"2024-09-19T22:38:16.973240816+03:00","level":"INFO","msg":"http/listening","addr":{"IP":"0.0.0.0","Port":443,"Zone":""}}
{"time":"2024-09-19T22:38:18.867798191+03:00","level":"INFO","msg":"http","remoteAddr":{"IP":"127.0.0.1","Port":45304,"Zone":""},"agent":"curl/7.68.0","method":"GET","url":"/ssh"}
{"time":"2024-09-19T22:38:18.867841689+03:00","level":"INFO","msg":"tcp/listening","addr":{"IP":"::","Port":39575,"Zone":""}}
{"time":"2024-09-19T22:38:18.870319064+03:00","level":"INFO","msg":"connected","laddr":{"IP":"127.0.0.1","Port":39575,"Zone":""},"raddr":{"IP":"127.0.0.1","Port":48886,"Zone":""}}
{"time":"2024-09-19T22:38:18.870525647+03:00","level":"INFO","msg":"connected","laddr":{"IP":"127.0.0.1","Port":46658,"Zone":""},"raddr":{"IP":"127.0.0.1","Port":22,"Zone":""}}
```

Connect to your server:

```shell
$ ssh root@localhost -p $(curl -sk https://localhost/ssh)
```

## License

[MIT](https://spdx.org/licenses/MIT.html)
127 changes: 127 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package main

import (
"errors"
"fmt"
"io"
"log/slog"
"net"
"os"
"time"
)

type Item struct {
listener net.Listener
count int
}

type App struct {
quiet bool
timeout time.Duration
listeners map[string]*Item
}

func (app *App) PrintError(format string, args ...any) {
if !app.quiet {
fmt.Fprintf(os.Stderr, format+"\n", args...)
}
}

func (app *App) LogInfo(format string, args ...any) {
if !app.quiet {
slog.Info(format, args...)
}
}

func (app *App) LogDebug(format string, args ...any) {
if !app.quiet {
slog.Debug(format, args...)
}
}

func (app *App) LogError(format string, args ...any) {
if !app.quiet {
slog.Error(format, args...)
}
}

func (app *App) StartListener(clientIP, endpoint string) (net.Listener, error) {
if app.listeners == nil {
app.listeners = make(map[string]*Item)
}
item, ok := app.listeners[clientIP]
if !ok {
ln, err := net.Listen("tcp", ":0")
if err != nil {
return nil, err
}
item = &Item{listener: ln, count: 0}
app.listeners[clientIP] = item
app.LogInfo("tcp/listening", "addr", ln.Addr())
go app.AcceptLoop(clientIP, ln, endpoint)
}
return item.listener, nil
}

func (app *App) AcceptLoop(requestIP string, listener net.Listener, endpoint string) {
ln, _ := listener.(*net.TCPListener)
defer func() {
_ = ln.Close()
delete(app.listeners, requestIP)
app.LogInfo("closed", "addr", ln.Addr())
}()

for {
if err := ln.SetDeadline(time.Now().Add(app.timeout)); err != nil {
app.LogDebug(err.Error())
return
}
remoteConn, err := ln.Accept()
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
if item, ok := app.listeners[requestIP]; ok && item.count > 0 {
continue
}
}
app.LogError(err.Error())
return
}
app.LogInfo("connected", "laddr", remoteConn.LocalAddr(), "raddr", remoteConn.RemoteAddr())
addr, _ := remoteConn.RemoteAddr().(*net.TCPAddr)
remoteIP := fmt.Sprintf("%s", addr.IP)
item, ok := app.listeners[remoteIP]
if !ok {
app.LogError("ip_mismatch", "requestIP", requestIP, "clientIP", remoteIP)
return
}
item.count += 1
go func() {
if err = app.Connect(remoteConn, endpoint); err != nil {
app.LogError(err.Error())
}
item.count -= 1
}()
}
}

func (app *App) Connect(remoteConn net.Conn, localAddr string) error {
defer func() {
_ = remoteConn.Close()
app.LogDebug("closed", "laddr", remoteConn.LocalAddr(), "raddr", remoteConn.RemoteAddr())
}()

localConn, err := net.Dial("tcp", localAddr)
if err != nil {
return err
}
defer func() {
_ = localConn.Close()
app.LogDebug("closed", "laddr", localConn.LocalAddr(), "raddr", localConn.RemoteAddr())
}()

app.LogInfo("connected", "laddr", localConn.LocalAddr(), "raddr", localConn.RemoteAddr())
go io.Copy(remoteConn, localConn)
_, err = io.Copy(localConn, remoteConn)

return err
}
5 changes: 5 additions & 0 deletions gencrt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/sh
set -e

openssl ecparam -genkey -name secp384r1 -out server.key
openssl req -new -x509 -sha256 -key server.key -out server.crt -days 3650
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/jackcvr/concierge

go 1.23.0
107 changes: 107 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package main

import (
"flag"
"fmt"
"io"
"log"
"log/slog"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
)

func main() {
var (
verbose bool
logFile string
bindAddress string
certFile string
keyFile string
endpoints Endpoints
mu sync.Mutex
app App
)

flag.BoolVar(&verbose, "v", false, "Verbose mode")
flag.StringVar(&logFile, "f", "", "Log file (default stdout)")
flag.StringVar(&bindAddress, "b", "0.0.0.0:80", "Local address to listen on")
flag.StringVar(&certFile, "crt", "", "Crt file for TLS")
flag.StringVar(&keyFile, "key", "", "Key file for TLS")
flag.Var(&endpoints, "a", "Endpoint in format 'url:host:port' (e.g. /ssh:localhost:22)")
flag.BoolVar(&app.quiet, "q", false, "Do not print anything")
flag.DurationVar(&app.timeout, "t", 2*time.Second, "Timeout for new connections")
flag.Parse()

log.SetFlags(log.LstdFlags | log.Lmicroseconds)
level := slog.LevelInfo
if verbose {
level = slog.LevelDebug
}
logger, err := NewLogger(logFile, level)
if err != nil {
app.PrintError(err.Error())
return
}
slog.SetDefault(logger)

for _, ep := range endpoints {
http.HandleFunc(fmt.Sprintf("GET %s", ep.url), func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()

requestIP := strings.SplitN(r.RemoteAddr, ":", 2)[0]
var ln net.Listener
ln, err = app.StartListener(requestIP, ep.endpoint)
if err != nil {
app.PrintError(err.Error())
}
addr, _ := ln.Addr().(*net.TCPAddr)
port := fmt.Sprintf("%d", addr.Port)
if _, err = io.WriteString(w, port); err != nil {
app.LogError(err.Error())
}
})
}

logRequest := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
addr, _ := net.ResolveTCPAddr("tcp", r.RemoteAddr)
app.LogInfo("http",
"remoteAddr", addr,
"agent", r.UserAgent(),
"method", r.Method,
"url", r.URL.String())
http.DefaultServeMux.ServeHTTP(w, r)
})

addr, _ := net.ResolveTCPAddr("tcp", bindAddress)
if certFile != "" && keyFile != "" {
if addr.Port == 80 {
addr.Port = 443
}
app.LogInfo("http/listening", "addr", addr)
err = http.ListenAndServeTLS(addr.String(), certFile, keyFile, logRequest)
} else {
app.LogInfo("Cert and key files are not provided: TLS is disabled...")
app.LogInfo("http/listening", "addr", addr)
err = http.ListenAndServe(addr.String(), logRequest)
}
if err != nil {
app.PrintError(err.Error())
}
}

func NewLogger(file string, level slog.Level) (*slog.Logger, error) {
w := os.Stdout
if file != "" {
var err error
w, err = os.OpenFile(file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, err
}
}
return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level})), nil
}
Loading

0 comments on commit b3af478

Please sign in to comment.