16 Commits

Author SHA1 Message Date
Bel LaPointe
e569f93469 more 2026-01-31 16:36:05 -07:00
Bel LaPointe
2421ea40f8 fix 2026-01-31 16:34:42 -07:00
bel
9f67c8c22c scheme from conf 2026-01-31 16:33:07 -07:00
Bel LaPointe
c283999b1a big w labels 2026-01-31 16:31:44 -07:00
Bel LaPointe
7d3da593ca impl home. 2026-01-31 16:18:25 -07:00
bel
057a0ab341 to bel.blue 2025-11-20 17:56:06 -07:00
Bel LaPointe
b6422eb0c0 support tcp AND ssl 2025-11-20 17:15:22 -07:00
Bel LaPointe
4a0e3c15e9 mto bel.blue thanks render 2025-11-20 17:14:50 -07:00
bel
3b53ef938d build.sh 2025-11-20 08:47:54 -07:00
bel
40d95d5b63 fix tests 2025-11-20 08:29:11 -07:00
bel
2ff12869cd impl cidr as password:CIDR:http://target 2025-11-20 08:28:25 -07:00
bel
9791f80b28 shhhh 2025-06-19 17:03:01 -06:00
bel
8d018aa236 oh 2025-06-19 16:56:52 -06:00
bel
00eda1e419 hrm 2025-06-19 16:52:36 -06:00
bel
5a0f567da3 _ lists 2025-06-19 16:49:06 -06:00
bel
e4451923e9 whatevs 2024-12-21 13:50:53 -07:00
15 changed files with 288 additions and 47 deletions

5
build.sh Normal file
View File

@@ -0,0 +1,5 @@
#! /usr/bin/env bash
export CGO_ENABLED=1
export CC=x86_64-linux-musl-gcc
exec go build -ldflags="-linkmode external -extldflags '-static'" -o exec-rproxy3

View File

@@ -13,6 +13,7 @@ import (
type Proxy struct { type Proxy struct {
Auth string Auth string
From string
To string To string
} }
@@ -60,14 +61,15 @@ func GetRoutes() map[string]Proxy {
s := conf.Get("proxy2").GetString() s := conf.Get("proxy2").GetString()
var dict map[string]string var dict map[string]string
if err := yaml.Unmarshal([]byte(s), &dict); err == nil && len(s) > 0 { if err := yaml.Unmarshal([]byte(s), &dict); err == nil && len(s) > 0 {
pattern := regexp.MustCompile(`(([^:]*):)?([a-z0-9]*:.*)`) pattern := regexp.MustCompile(`(([^:]*):)?(([^:]*):)?([a-z0-9]*:.*)`)
result := map[string]Proxy{} result := map[string]Proxy{}
for k, v := range dict { for k, v := range dict {
submatches := pattern.FindAllStringSubmatch(v, -1) submatches := pattern.FindAllStringSubmatch(v, -1)
log.Printf("%+v", submatches) log.Printf("%+v", submatches)
result[k] = Proxy{ result[k] = Proxy{
Auth: submatches[0][2], Auth: submatches[0][2],
To: submatches[0][3], From: submatches[0][4],
To: submatches[0][5],
} }
} }
return result return result

View File

@@ -7,11 +7,8 @@ import (
"strings" "strings"
"time" "time"
"gitea.inhome.blapointe.com/local/args" "gitea.bel.blue/local/args"
"gitea.inhome.blapointe.com/local/logb" "gitea.bel.blue/local/logb"
"gitea.inhome.blapointe.com/local/args"
"gitea.inhome.blapointe.com/local/logb"
) )
var conf *args.ArgSet var conf *args.ArgSet

6
go.mod
View File

@@ -1,10 +1,10 @@
module gitea.inhome.blapointe.com/local/rproxy3 module gitea.bel.blue/local/rproxy3
go 1.18 go 1.18
require ( require (
gitea.inhome.blapointe.com/local/args v0.0.0-20240109214601-658deda479a4 gitea.bel.blue/local/args v0.0.0-20251121001304-83c57f856714
gitea.inhome.blapointe.com/local/logb v0.0.0-20231109150430-1221d87a6dbc gitea.bel.blue/local/logb v0.0.0-20251121001353-d45d53fbaae9
github.com/google/uuid v1.3.0 github.com/google/uuid v1.3.0
golang.org/x/time v0.1.0 golang.org/x/time v0.1.0
) )

8
go.sum
View File

@@ -1,7 +1,7 @@
gitea.inhome.blapointe.com/local/args v0.0.0-20240109214601-658deda479a4 h1:4qBHjKAiEwRV1A1tN1JK6PsLV1+UwESXKrjGqfCCdNk= gitea.bel.blue/local/args v0.0.0-20251121001304-83c57f856714 h1:JHV86INH1QmPJoyIhdrDLJq7OKta+fJAwbK0pnxI4Hc=
gitea.inhome.blapointe.com/local/args v0.0.0-20240109214601-658deda479a4/go.mod h1:SqCOE3bE3wvrztVIQGHuyxHKfDjRKU9EWhBdkmkiwyc= gitea.bel.blue/local/args v0.0.0-20251121001304-83c57f856714/go.mod h1:GCzui3GPhOgKgGYNqtW55YkI3vIWCQEHPydGjFhaXV0=
gitea.inhome.blapointe.com/local/logb v0.0.0-20231109150430-1221d87a6dbc h1:u3akQkq12V8xWXlcDgjZxIK6hqo6f1eHd9KOxAKMoKc= gitea.bel.blue/local/logb v0.0.0-20251121001353-d45d53fbaae9 h1:lBkQPYgWZnPxt6CvsSwVh9EZtuvi2lIbGOHPqe/gn1Y=
gitea.inhome.blapointe.com/local/logb v0.0.0-20231109150430-1221d87a6dbc/go.mod h1:KwilawX4UgD4HxSJAVFEzkuckrnHeQrd49KwUX6GpYU= gitea.bel.blue/local/logb v0.0.0-20251121001353-d45d53fbaae9/go.mod h1:+8sJb8UksdadKy43czL7/3TcfBwCkuYT6hFY+RaxP48=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=

View File

@@ -1,8 +1,8 @@
package main package main
import ( import (
"gitea.inhome.blapointe.com/local/rproxy3/config" "gitea.bel.blue/local/rproxy3/config"
"gitea.inhome.blapointe.com/local/rproxy3/server" "gitea.bel.blue/local/rproxy3/server"
) )
func main() { func main() {

View File

@@ -34,7 +34,7 @@ func TestHTTPSMain(t *testing.T) {
"username", "username",
"-pass", "-pass",
"password", "password",
"-proxy", "-proxy2",
"hello," + addr, "hello," + addr,
"-crt", "-crt",
"./testdata/rproxy3server.crt", "./testdata/rproxy3server.crt",
@@ -89,7 +89,7 @@ func TestHTTPMain(t *testing.T) {
"username", "username",
"-pass", "-pass",
"password", "password",
"-proxy", "-proxy2",
"hello," + addr, "hello," + addr,
} }
main() main()

View File

@@ -1,8 +1,8 @@
package server package server
import ( import (
"gitea.inhome.blapointe.com/local/rproxy3/config" "gitea.bel.blue/local/rproxy3/config"
"gitea.inhome.blapointe.com/local/rproxy3/storage" "gitea.bel.blue/local/rproxy3/storage"
"golang.org/x/time/rate" "golang.org/x/time/rate"
) )

View File

@@ -10,11 +10,8 @@ import (
"net/url" "net/url"
"strings" "strings"
"gitea.inhome.blapointe.com/local/rproxy3/config" "gitea.bel.blue/local/rproxy3/config"
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable" "gitea.bel.blue/local/rproxy3/storage/packable"
"gitea.inhome.blapointe.com/local/rproxy3/config"
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable"
) )
type redirPurge struct { type redirPurge struct {
@@ -61,6 +58,12 @@ func (s *Server) lookupAuth(host string) (string, error) {
return v.String(), err return v.String(), err
} }
func (s *Server) lookupFrom(host string) (string, error) {
v := packable.NewString()
err := s.db.Get(nsRouting, host+"//from", v)
return v.String(), err
}
func mapKey(host string) string { func mapKey(host string) string {
host = strings.Split(host, ".")[0] host = strings.Split(host, ".")[0]
host = strings.Split(host, ":")[0] host = strings.Split(host, ":")[0]

View File

@@ -1,7 +1,7 @@
package server package server
import ( import (
"gitea.inhome.blapointe.com/local/rproxy3/config" "gitea.bel.blue/local/rproxy3/config"
) )
func (s *Server) Routes() error { func (s *Server) Routes() error {

View File

@@ -12,17 +12,15 @@ import (
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"regexp"
"strconv" "strconv"
"strings" "strings"
"text/template"
"time" "time"
"gitea.inhome.blapointe.com/local/rproxy3/config" "gitea.bel.blue/local/rproxy3/config"
"gitea.inhome.blapointe.com/local/rproxy3/storage" "gitea.bel.blue/local/rproxy3/storage"
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable" "gitea.bel.blue/local/rproxy3/storage/packable"
"gitea.inhome.blapointe.com/local/rproxy3/config"
"gitea.inhome.blapointe.com/local/rproxy3/storage"
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable"
"github.com/google/uuid" "github.com/google/uuid"
"golang.org/x/time/rate" "golang.org/x/time/rate"
@@ -34,8 +32,9 @@ type listenerScheme int
const ( const (
schemeHTTP listenerScheme = iota schemeHTTP listenerScheme = iota
schemeHTTPS listenerScheme = iota schemeHTTPS
schemeTCP listenerScheme = iota schemeTCP
schemeTCPTLS
) )
func (ls listenerScheme) String() string { func (ls listenerScheme) String() string {
@@ -46,6 +45,8 @@ func (ls listenerScheme) String() string {
return "https" return "https"
case schemeTCP: case schemeTCP:
return "tcp" return "tcp"
case schemeTCPTLS:
return "tcptls"
} }
return "" return ""
} }
@@ -66,6 +67,9 @@ func (s *Server) Route(src string, dst config.Proxy) error {
if err != nil { if err != nil {
return err return err
} }
if err := s.db.Set(nsRouting, src+"//from", packable.NewString(dst.From)); err != nil {
return err
}
if err := s.db.Set(nsRouting, src+"//auth", packable.NewString(dst.Auth)); err != nil { if err := s.db.Set(nsRouting, src+"//auth", packable.NewString(dst.Auth)); err != nil {
return err return err
} }
@@ -101,15 +105,52 @@ func (s *Server) Run() error {
case schemeTCP: case schemeTCP:
addr, _ := config.GetTCP() addr, _ := config.GetTCP()
return s.ServeTCP(addr) return s.ServeTCP(addr)
case schemeTCPTLS:
addr, _ := config.GetTCP()
cert, key, _ := config.GetSSL()
return s.ServeTCPTLS(addr, cert, key)
} }
return errors.New("did not load server") return errors.New("did not load server")
} }
func (s *Server) ServeTCPTLS(addr, c, k string) error {
certificate, err := tls.LoadX509KeyPair(c, k)
if err != nil {
return err
}
certificates := []tls.Certificate{certificate}
listen, err := net.Listen("tcp", s.addr)
if err != nil {
return err
}
defer listen.Close()
config := &tls.Config{
Certificates: certificates,
MinVersion: tls.VersionTLS12,
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
PreferServerCipherSuites: true,
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
},
}
config.BuildNameToCertificate()
tlsListener := tls.NewListener(listen, config)
return s.serveTCP(addr, tlsListener)
}
func (s *Server) ServeTCP(addr string) error { func (s *Server) ServeTCP(addr string) error {
listen, err := net.Listen("tcp", s.addr) listen, err := net.Listen("tcp", s.addr)
if err != nil { if err != nil {
return err return err
} }
defer listen.Close()
return s.serveTCP(addr, listen)
}
func (s *Server) serveTCP(addr string, listen net.Listener) error {
for { for {
c, err := listen.Accept() c, err := listen.Accept()
if err != nil { if err != nil {
@@ -158,6 +199,15 @@ func (s *Server) Pre(foo http.HandlerFunc) http.HandlerFunc {
return return
} }
switch mapKey(r.Host) {
case "_":
s.List(w)
return
case "home":
s.Home(w, r)
return
}
if auth, err := s.lookupAuth(mapKey(r.Host)); err != nil { if auth, err := s.lookupAuth(mapKey(r.Host)); err != nil {
log.Printf("failed to lookup auth for %s (%s): %v", r.Host, mapKey(r.Host), err) log.Printf("failed to lookup auth for %s (%s): %v", r.Host, mapKey(r.Host), err)
w.Header().Set("WWW-Authenticate", "Basic") w.Header().Set("WWW-Authenticate", "Basic")
@@ -166,12 +216,44 @@ func (s *Server) Pre(foo http.HandlerFunc) http.HandlerFunc {
log.Printf("failed to auth: expected %q but got %q", auth, p) log.Printf("failed to auth: expected %q but got %q", auth, p)
w.Header().Set("WWW-Authenticate", "Basic") w.Header().Set("WWW-Authenticate", "Basic")
http.Error(w, "unexpected basic auth", http.StatusUnauthorized) http.Error(w, "unexpected basic auth", http.StatusUnauthorized)
} else if from, err := s.lookupFrom(mapKey(r.Host)); err != nil {
log.Printf("failed to lookup from for %s (%s): %v", r.Host, mapKey(r.Host), err)
http.Error(w, err.Error(), http.StatusBadGateway)
} else if err := assertFrom(from, r.RemoteAddr); err != nil {
log.Printf("failed to from: expected %q but got %q: %v", from, r.RemoteAddr, err)
http.Error(w, "unexpected from", http.StatusUnauthorized)
} else { } else {
foo(w, r) foo(w, r)
} }
} }
} }
func assertFrom(from, remoteAddr string) error {
if from == "" {
return nil
}
pattern := regexp.MustCompile(`[0-9](:[0-9]+)$`).FindStringSubmatchIndex(remoteAddr)
if len(pattern) == 4 {
remoteAddr = remoteAddr[:pattern[2]]
}
remoteIP := net.ParseIP(remoteAddr)
if remoteIP == nil {
return fmt.Errorf("cannot parse remote %q", remoteAddr)
}
_, net, err := net.ParseCIDR(from)
if err != nil {
panic(err)
}
if net.Contains(remoteIP) {
return nil
}
return fmt.Errorf("expected like %q but got like %q", from, remoteAddr)
}
func withMeta(w http.ResponseWriter, r *http.Request) (*http.Request, func()) { func withMeta(w http.ResponseWriter, r *http.Request) (*http.Request, func()) {
meta := map[string]string{ meta := map[string]string{
"ts": strconv.FormatInt(time.Now().Unix(), 10), "ts": strconv.FormatInt(time.Now().Unix(), 10),
@@ -208,6 +290,93 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.Pre(s.Proxy)(w, r) s.Pre(s.Proxy)(w, r)
} }
func (s *Server) Home(w http.ResponseWriter, r *http.Request) {
keys := s.db.Keys(nsRouting)
routePrefixes := map[string]string{}
for _, key := range keys {
u, _ := s.lookup(key)
if u != nil && u.String() != "" {
routePrefixes[strings.Split(key, "/")[0]] = ""
}
}
priority := map[string]string{
"wyze0": "Home Camera 0",
"wyze1": "Home Camera 1",
"wyze2": "Home Camera 2",
"wyze3": "Home Camera 3",
"whereis": "Map of Belling",
"moolah": "Money",
"autobookshelf": "Ebooks",
"jackett": "The 7 Seas",
"vpntor": "The 7 Seas Downloader",
}
for k, v := range priority {
if _, ok := routePrefixes[k]; ok {
routePrefixes[k] = v
}
}
t := strings.ReplaceAll(`
<DOCTYPE! html>
<html>
<header>
</header>
<body>
{{- $baseDomain := .baseDomain }}
{{- $scheme := .scheme }}
{{- range $k, $v := .routePrefixes }}
{{- $url := printf "%s://%s.%s" $scheme $k $baseDomain }}
{{ if ne $v "" }}
<a style="font-size: 2em" href="{{ $url }}">{{ $k }} ({{ $v }})</a><br>
{{ end }}
{{- end }}
{{- range $k, $v := .routePrefixes }}
{{- $url := printf "%s://%s.%s" $scheme $k $baseDomain }}
{{ if eq $v "" }}
<a href="{{ $url }}">{{ $k }}</a><br>
{{ end }}
{{- end }}
</body>
<footer>
</footer>
</html>
`, "\t", " ")
tmpl, err := template.New("home").Parse(t)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
if err := tmpl.Execute(w, map[string]any{
"routePrefixes": routePrefixes,
"domain": r.Host,
"baseDomain": strings.Join(strings.Split(r.Host, ".")[1:], "."),
"scheme": getScheme().String(),
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (s *Server) List(w http.ResponseWriter) {
keys := s.db.Keys(nsRouting)
hostURL := map[string]string{}
hostFrom := map[string]string{}
for _, key := range keys {
u, _ := s.lookup(key)
if u != nil && strings.TrimSuffix(key, "//auth") == key {
hostURL[key] = u.String()
}
if u != nil && strings.TrimSuffix(key, "//from") == key {
hostFrom[key] = u.String()
}
}
json.NewEncoder(w).Encode(map[string]any{
"hostsToURLs": hostURL,
"hostsToFrom": hostFrom,
})
}
type corsResponseWriter struct { type corsResponseWriter struct {
r *http.Request r *http.Request
http.ResponseWriter http.ResponseWriter
@@ -282,11 +451,15 @@ func (s *Server) alt() {
func getScheme() listenerScheme { func getScheme() listenerScheme {
scheme := schemeHTTP scheme := schemeHTTP
if _, _, ok := config.GetSSL(); ok { _, _, ssl := config.GetSSL()
if ssl {
scheme = schemeHTTPS scheme = schemeHTTPS
} }
if _, ok := config.GetTCP(); ok { if _, ok := config.GetTCP(); ok {
scheme = schemeTCP scheme = schemeTCP
if ssl {
scheme = schemeTCPTLS
}
} }
return scheme return scheme
} }

View File

@@ -8,11 +8,8 @@ import (
"strings" "strings"
"testing" "testing"
"gitea.inhome.blapointe.com/local/rproxy3/config" "gitea.bel.blue/local/rproxy3/config"
"gitea.inhome.blapointe.com/local/rproxy3/storage" "gitea.bel.blue/local/rproxy3/storage"
"gitea.inhome.blapointe.com/local/rproxy3/config"
"gitea.inhome.blapointe.com/local/rproxy3/storage"
"golang.org/x/time/rate" "golang.org/x/time/rate"
) )
@@ -41,20 +38,42 @@ func TestServerStart(t *testing.T) {
} }
func mockServer() *Server { func mockServer() *Server {
s := _mockServer()
portServer := httptest.NewServer(nil) portServer := httptest.NewServer(nil)
port := strings.Split(portServer.URL, ":")[2] s.addr = ":" + strings.Split(portServer.URL, ":")[2]
portServer.Close() portServer.Close()
return s
}
func _mockServer() *Server {
s := &Server{ s := &Server{
db: storage.NewMap(), db: storage.NewMap(),
addr: ":" + port,
limiter: rate.NewLimiter(rate.Limit(50), 50), limiter: rate.NewLimiter(rate.Limit(50), 50),
} }
if err := s.Routes(); err != nil { if err := s.Routes(); err != nil {
panic(fmt.Sprintf("cannot initiate server routes; %v", err)) panic(fmt.Sprintf("cannot initiate server routes; %v", err))
} }
if err := s.Route("test", config.Proxy{To: "http://icanhazip.com"}); err != nil {
panic(err.Error())
}
if err := s.Route("wyze0", config.Proxy{To: "http://wyze0.scratch.com"}); err != nil {
panic(err.Error())
}
return s return s
} }
func TestServerHome(t *testing.T) {
s := _mockServer()
r := httptest.NewRequest(http.MethodGet, "https://home.int.bel.blue", nil)
w := httptest.NewRecorder()
s.Home(w, r)
if w.Code != http.StatusOK {
t.Fatalf("(%d) %s", w.Code, w.Body.Bytes())
}
t.Logf("%s", w.Body.Bytes())
}
func TestServerRoute(t *testing.T) { func TestServerRoute(t *testing.T) {
server := mockServer() server := mockServer()
p := config.Proxy{ p := config.Proxy{
@@ -108,3 +127,32 @@ func TestCORS(t *testing.T) {
} }
}) })
} }
func TestAssertFrom(t *testing.T) {
cases := map[string]struct {
from string
remote string
err bool
}{
"empty": {},
"ipv6 localhost": {
from: "::1/128",
remote: "::1:12345",
},
"ipv4 localhost": {
from: "127.0.0.1/32",
remote: "127.0.0.1:12345",
},
}
for name, d := range cases {
c := d
t.Run(name, func(t *testing.T) {
err := assertFrom(c.from, c.remote)
got := err != nil
if got != c.err {
t.Errorf("expected err=%v but got %v", c.err, err)
}
})
}
}

View File

@@ -2,7 +2,8 @@ package storage
import ( import (
"errors" "errors"
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable"
"gitea.bel.blue/local/rproxy3/storage/packable"
) )
var ErrNotFound = errors.New("not found") var ErrNotFound = errors.New("not found")
@@ -10,5 +11,6 @@ var ErrNotFound = errors.New("not found")
type DB interface { type DB interface {
Get(string, string, packable.Packable) error Get(string, string, packable.Packable) error
Set(string, string, packable.Packable) error Set(string, string, packable.Packable) error
Keys(string) []string
Close() error Close() error
} }

View File

@@ -1,9 +1,10 @@
package storage package storage
import ( import (
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable"
"os" "os"
"testing" "testing"
"gitea.bel.blue/local/rproxy3/storage/packable"
) )
func TestDB(t *testing.T) { func TestDB(t *testing.T) {

View File

@@ -2,7 +2,8 @@ package storage
import ( import (
"fmt" "fmt"
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable"
"gitea.bel.blue/local/rproxy3/storage/packable"
) )
type Map map[string]map[string][]byte type Map map[string]map[string][]byte
@@ -40,6 +41,15 @@ func (m Map) Close() error {
return nil return nil
} }
func (m Map) Keys(ns string) []string {
m2, _ := m[ns]
result := make([]string, 0, len(m2))
for k := range m2 {
result = append(result, k)
}
return result
}
func (m Map) Get(ns, key string, value packable.Packable) error { func (m Map) Get(ns, key string, value packable.Packable) error {
if _, ok := m[ns]; !ok { if _, ok := m[ns]; !ok {
m[ns] = make(map[string][]byte) m[ns] = make(map[string][]byte)