Compare commits

...

6 commits

Author SHA1 Message Date
Anders Pitman
09770d2c7a Split into separate files and add todo 2020-09-26 15:56:57 -06:00
Anders Pitman
c55b7283ec Implement tunnel delete 2020-09-26 15:47:56 -06:00
Anders Pitman
98a049b2e6 Implement basic SNI routing and HTTP admin stuff
* Tunnels work
* Can list and dynamically add tunnels via HTTP
2020-09-26 15:41:47 -06:00
Anders Pitman
faa4ca503b Rename to boreman for now 2020-09-26 15:41:01 -06:00
Anders Pitman
c4321d1bbd Rename main.go 2020-09-25 16:46:58 -06:00
Anders Pitman
8571e380a6 Remove license
May want to do BSL or similiar
2020-09-25 16:43:27 -06:00
8 changed files with 290 additions and 65 deletions

21
LICENSE
View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020 Anders Pitman
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.

33
admin_listener.go Normal file
View file

@ -0,0 +1,33 @@
package main
import(
"fmt"
"net"
)
type AdminListener struct {
connChan chan(net.Conn)
}
func NewAdminListener() *AdminListener {
connChan := make(chan(net.Conn))
return &AdminListener{connChan}
}
// implement net.Listener
func (l *AdminListener) Accept() (net.Conn, error) {
// TODO: error conditions?
conn := <-l.connChan
return conn, nil
}
func (l *AdminListener) Close() error {
// TODO
fmt.Println("AdminListener Close")
return nil
}
func (l *AdminListener) Addr() net.Addr {
// TODO
fmt.Println("AdminListener Addr")
return nil
}

191
boringproxy.go Normal file
View file

@ -0,0 +1,191 @@
package main
import (
"fmt"
"log"
"net"
"net/http"
"crypto/tls"
"io"
"sync"
"strconv"
"encoding/json"
)
type BoringProxy struct {
tunMan *TunnelManager
adminListener *AdminListener
}
func NewBoringProxy() *BoringProxy {
tunMan := NewTunnelManager()
adminListener := NewAdminListener()
p := &BoringProxy{tunMan, adminListener}
http.HandleFunc("/", p.handleAdminRequest)
go http.Serve(adminListener, nil)
return p
}
func (p *BoringProxy) Run() {
listener, err := net.Listen("tcp", ":443")
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err)
continue
}
go p.handleConnection(conn)
}
}
func (p *BoringProxy) handleAdminRequest(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/tunnels" {
p.handleTunnels(w, r)
}
}
func (p *BoringProxy) handleTunnels(w http.ResponseWriter, r *http.Request) {
fmt.Println("handleTunnels")
query := r.URL.Query()
if r.Method == "GET" {
body, err := json.Marshal(p.tunMan.tunnels)
if err != nil {
w.WriteHeader(500)
w.Write([]byte("Error encoding tunnels"))
return
}
w.Write([]byte(body))
} else if r.Method == "POST" {
p.handleCreateTunnel(w, r)
} else if r.Method == "DELETE" {
if len(query["host"]) != 1 {
w.WriteHeader(400)
w.Write([]byte("Invalid host parameter"))
return
}
host := query["host"][0]
p.tunMan.DeleteTunnel(host)
}
}
func (p *BoringProxy) handleCreateTunnel(w http.ResponseWriter, r *http.Request) {
fmt.Println("handleCreateTunnel")
query := r.URL.Query()
if len(query["host"]) != 1 {
w.WriteHeader(400)
w.Write([]byte("Invalid host parameter"))
return
}
host := query["host"][0]
if len(query["port"]) != 1 {
w.WriteHeader(400)
w.Write([]byte("Invalid port parameter"))
return
}
port, err := strconv.Atoi(query["port"][0])
if err != nil {
w.WriteHeader(400)
w.Write([]byte("Invalid port parameter"))
return
}
p.tunMan.SetTunnel(host, port)
}
func (p *BoringProxy) handleConnection(clientConn net.Conn) {
// TODO: does this need to be closed manually, or is it handled when decryptedConn is closed?
//defer clientConn.Close()
certBaseDir := "/home/anders/.local/share/caddy/certificates/acme-v02.api.letsencrypt.org-directory/"
var serverName string
decryptedConn := tls.Server(clientConn, &tls.Config{
GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
serverName = clientHello.ServerName
certPath := certBaseDir + clientHello.ServerName + "/" + clientHello.ServerName + ".crt"
keyPath := certBaseDir + clientHello.ServerName + "/" + clientHello.ServerName + ".key"
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
log.Println("getting cert failed")
return nil, err
}
return &cert, nil
},
})
//defer decryptedConn.Close()
// Need to manually do handshake to ensure serverName is populated by this point. Usually Handshake()
// is automatically called on first read/write
decryptedConn.Handshake()
adminDomain := "anders.webstreams.io"
if serverName == adminDomain {
p.handleAdminConnection(decryptedConn)
} else {
p.handleTunnelConnection(decryptedConn, serverName)
}
}
func (p *BoringProxy) handleAdminConnection(decryptedConn net.Conn) {
p.adminListener.connChan <- decryptedConn
}
func (p *BoringProxy) handleTunnelConnection(decryptedConn net.Conn, serverName string) {
defer decryptedConn.Close()
port, err := p.tunMan.GetPort(serverName)
if err != nil {
log.Print(err)
errMessage := fmt.Sprintf("HTTP/1.1 500 Internal server error\n\nNo tunnel attached to %s", serverName)
decryptedConn.Write([]byte(errMessage))
return
}
upstreamAddr := fmt.Sprintf("127.0.0.1:%d", port)
upstreamConn, err := net.Dial("tcp", upstreamAddr)
if err != nil {
log.Print(err)
return
}
defer upstreamConn.Close()
var wg sync.WaitGroup
wg.Add(2)
go func() {
io.Copy(decryptedConn, upstreamConn)
//decryptedConn.(*net.TCPConn).CloseWrite()
wg.Done()
}()
go func() {
io.Copy(upstreamConn, decryptedConn)
//upstreamConn.(*net.TCPConn).CloseWrite()
wg.Done()
}()
wg.Wait()
}

View file

@ -2,9 +2,26 @@
"apps": {
"http": {
"servers": {
"sirtunnel": {
"boreman": {
"listen": [":443"],
"routes": [
{
"match": [
{
"host": ["anders.webstreams.io"]
}
],
"handle": [
{
"handler": "reverse_proxy",
"upstreams": [
{
"dial": ":9001"
}
]
}
]
}
]
}
}

46
main.go
View file

@ -1,51 +1,13 @@
package main
import (
"fmt"
"os"
"os/signal"
"strings"
"net/http"
"bytes"
"log"
)
func main() {
log.Println("Starting up")
args := os.Args[1:]
tunnelSpecParts := strings.Split(args[0], ":")
tunnelId := args[0]
host := tunnelSpecParts[0]
port := tunnelSpecParts[1]
client := &http.Client{}
caddyAddRouteStr := fmt.Sprintf("{\"@id\":\"%s\",\"match\":[{\"host\":[\"%s\"]}],\"handle\":[{\"handler\":\"reverse_proxy\",\"upstreams\":[{\"dial\":\":%s\"}]}]}", tunnelId, host, port);
resp, err := http.Post("http://127.0.0.1:2019/config/apps/http/servers/sirtunnel/routes", "application/json", bytes.NewBuffer([]byte(caddyAddRouteStr)))
if err != nil {
fmt.Println("Tunnel creation failed")
panic(err)
}
defer resp.Body.Close()
fmt.Println("Tunnel created successfully")
// wait for CTRL-C
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
fmt.Println("Cleaning up tunnel")
req, err := http.NewRequest("DELETE", fmt.Sprintf("http://127.0.0.1:2019/id/%s", tunnelId), nil)
if err != nil {
panic(err)
}
req.Header.Add("Content-Type", "application/json")
_, err = client.Do(req)
fmt.Println("Exiting")
proxy := NewBoringProxy()
proxy.Run()
}

View file

@ -29,7 +29,7 @@ if __name__ == '__main__':
headers = {
'Content-Type': 'application/json'
}
create_url = 'http://127.0.0.1:2019/config/apps/http/servers/sirtunnel/routes'
create_url = 'http://127.0.0.1:2019/config/apps/http/servers/boreman/routes'
req = request.Request(method='POST', url=create_url, headers=headers)
request.urlopen(req, body)

1
todo.md Normal file
View file

@ -0,0 +1 @@
* Implement auth

42
tunnel_manager.go Normal file
View file

@ -0,0 +1,42 @@
package main
import (
"errors"
"sync"
)
type TunnelManager struct {
tunnels map[string]int
mutex *sync.Mutex
}
func NewTunnelManager() *TunnelManager {
tunnels := make(map[string]int)
mutex := &sync.Mutex{}
return &TunnelManager{tunnels, mutex}
}
func (m *TunnelManager) SetTunnel(host string, port int) {
m.mutex.Lock()
m.tunnels[host] = port
m.mutex.Unlock()
}
func (m *TunnelManager) DeleteTunnel(host string) {
m.mutex.Lock()
delete(m.tunnels, host)
m.mutex.Unlock()
}
func (m *TunnelManager) GetPort(serverName string) (int, error) {
m.mutex.Lock()
port, exists := m.tunnels[serverName]
m.mutex.Unlock()
if !exists {
return 0, errors.New("Doesn't exist")
}
return port, nil
}