telebit/rvpn/genericlistener/listener_generic.go

293 lines
7.5 KiB
Go

package genericlistener
import (
"bytes"
"context"
"crypto/tls"
"encoding/hex"
"log"
"net"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"net/http"
"bufio"
"git.daplie.com/Daplie/go-rvpn-server/rvpn/connection"
)
type contextKey string
const (
ctxSecretKey contextKey = "secretKey"
ctxConnectionTable contextKey = "connectionTable"
ctxConfig contextKey = "config"
)
const (
encryptNone int = iota
encryptSSLV2
encryptSSLV3
encryptTLS10
encryptTLS11
encryptTLS12
)
//GenericListenAndServe -- used to lisen for any https traffic on 443 (8443)
// - setup generic TCP listener, unencrypted TCP, with a Deadtime out
// - leaverage the wedgeConn to peek into the buffer.
// - if TLS, consume connection with TLS certbundle, pass to request identifier
// - else, just pass to the request identififer
func GenericListenAndServe(ctx context.Context, connectionTable *connection.Table, secretKey string, serverBinding string, certbundle tls.Certificate, deadTime int) {
config := &tls.Config{Certificates: []tls.Certificate{certbundle}}
ctx = context.WithValue(ctx, ctxSecretKey, secretKey)
ctx = context.WithValue(ctx, ctxConnectionTable, connectionTable)
ctx = context.WithValue(ctx, ctxConfig, config)
listenAddr, err := net.ResolveTCPAddr("tcp", serverBinding)
if nil != err {
loginfo.Println(err)
return
}
ln, err := net.ListenTCP("tcp", listenAddr)
if err != nil {
loginfo.Println("unable to bind", err)
return
}
for {
select {
case <-ctx.Done():
loginfo.Println("Cancel signal hit")
return
default:
ln.SetDeadline(time.Now().Add(time.Duration(deadTime) * time.Second))
conn, err := ln.Accept()
loginfo.Println("Deadtime reached")
if nil != err {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
continue
}
log.Println(err)
return
}
wedgeConn := NewWedgeConn(conn)
go handleConnection(ctx, wedgeConn)
}
}
}
//handleConnection -
// - accept a wedgeConnection along with all the other required attritvues
// - peek into the buffer, determine TLS or unencrypted
// - if TSL, then terminate with a TLS endpoint, pass to handleStream
// - if clearText, pass to handleStream
func handleConnection(ctx context.Context, wConn *WedgeConn) {
defer wConn.Close()
peekCnt := 10
encryptMode := encryptNone
loginfo.Println("conn", wConn, wConn.LocalAddr().String(), wConn.RemoteAddr().String())
peek, err := wConn.Peek(peekCnt)
if err != nil {
loginfo.Println("error while peeking")
return
}
loginfo.Println(hex.Dump(peek[0:peekCnt]))
loginfo.Println(hex.Dump(peek[2:4]))
loginfo.Println("after peek")
//take a look for a TLS header.
if bytes.Contains(peek[0:0], []byte{0x80}) && bytes.Contains(peek[2:4], []byte{0x01, 0x03}) {
encryptMode = encryptSSLV2
} else if bytes.Contains(peek[0:3], []byte{0x16, 0x03, 0x00}) {
encryptMode = encryptSSLV3
} else if bytes.Contains(peek[0:3], []byte{0x16, 0x03, 0x01}) {
encryptMode = encryptTLS10
loginfo.Println("TLS10")
} else if bytes.Contains(peek[0:3], []byte{0x16, 0x03, 0x02}) {
encryptMode = encryptTLS11
} else if bytes.Contains(peek[0:3], []byte{0x16, 0x03, 0x03}) {
encryptMode = encryptTLS12
}
oneConn := &oneConnListener{wConn}
config := ctx.Value(ctxConfig).(*tls.Config)
if encryptMode == encryptSSLV2 {
loginfo.Println("SSLv2 is not accepted")
return
} else if encryptMode != encryptNone {
loginfo.Println("Handle Encryption")
tlsListener := tls.NewListener(oneConn, config)
conn, err := tlsListener.Accept()
if err != nil {
loginfo.Println(err)
return
}
tlsWedgeConn := NewWedgeConn(conn)
handleStream(ctx, tlsWedgeConn)
return
}
loginfo.Println("Handle Unencrypted")
handleStream(ctx, wConn)
return
}
//handleStream --
// - we have an unencrypted stream connection with the ability to peek
// - attempt to identify HTTP
// - handle http
// - attempt to identify as WSS session
// - attempt to identify as ADMIN/API session
// - else handle as raw https
// - handle other?
func handleStream(ctx context.Context, wConn *WedgeConn) {
loginfo.Println("handle Stream")
loginfo.Println("conn", wConn, wConn.LocalAddr().String(), wConn.RemoteAddr().String())
//peek for one byte to get the readers to converge
//look at buffer
//get the realrequest
peek, err := wConn.Peek(1)
loginfo.Println(hex.Dump(peek[0:]))
peek, err = wConn.Peek(wConn.Buffered())
loginfo.Println(hex.Dump(peek[0:]))
if err != nil {
loginfo.Println("error while peeking")
loginfo.Println(hex.Dump(peek[0:]))
return
}
// HTTP Identifcation
if bytes.Contains(peek[:], []byte{0x0d, 0x0a}) {
//string protocol
if bytes.ContainsAny(peek[:], "HTTP/") {
loginfo.Println("identifed HTTP")
r, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(peek)))
if err != nil {
loginfo.Println("identifed as HTTP, failed request", err)
return
}
loginfo.Println(r)
//now we have a request. Check to see if it is one of our own
secretKey := ctx.Value(ctxSecretKey).(string)
tokenString := r.URL.Query().Get("access_token")
result, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
if err == nil && result.Valid {
loginfo.Println("Valid WSS dected...sending to handler")
oneConn := &oneConnListener{wConn}
handleWssClient(ctx, oneConn)
} else {
loginfo.Println("not a valid WSS connection")
}
}
}
loginfo.Println(hex.Dump(peek[0:]))
}
//handleWssClient -
// - expecting an existing oneConnListener with a qualified wss client connected.
// - auth will happen again since we were just peeking at the token.
func handleWssClient(ctx context.Context, oneConn *oneConnListener) {
secretKey := ctx.Value(ctxSecretKey).(string)
connectionTable := ctx.Value(ctxConnectionTable).(*connection.Table)
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
loginfo.Println("HandleFunc /")
switch url := r.URL.Path; url {
case "/":
loginfo.Println("websocket opening ", r.RemoteAddr, " ", r.Host)
tokenString := r.URL.Query().Get("access_token")
result, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
if err != nil || !result.Valid {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("Not Authorized"))
loginfo.Println("access_token invalid...closing connection")
return
}
loginfo.Println("help access_token valid")
claims := result.Claims.(jwt.MapClaims)
domains, ok := claims["domains"].([]interface{})
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
loginfo.Println("WebSocket upgrade failed", err)
return
}
loginfo.Println("before connection table")
//newConnection := connection.NewConnection(connectionTable, conn, r.RemoteAddr, domains)
newRegistration := connection.NewRegistration(conn, r.RemoteAddr, domains)
connectionTable.Register() <- newRegistration
ok = <-newRegistration.CommCh()
if !ok {
loginfo.Println("connection registration failed ", newRegistration)
return
}
loginfo.Println("connection registration accepted ", newRegistration)
}
})
s := &http.Server{
Addr: ":80",
Handler: router,
}
err := s.Serve(oneConn)
if err != nil {
loginfo.Println("Serve error: ", err)
}
select {
case <-ctx.Done():
loginfo.Println("Cancel signal hit")
return
}
}