parent
fb6d7af6d3
commit
abf628d2bb
|
|
@ -4,15 +4,19 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
type Proxy struct {
|
||||
To string
|
||||
Auth string
|
||||
To string
|
||||
}
|
||||
|
||||
func parseProxy(s string) (string, Proxy) {
|
||||
func parseOneProxyCSV(s string) (string, Proxy) {
|
||||
p := Proxy{}
|
||||
key := ""
|
||||
l := strings.Split(s, ",")
|
||||
|
|
@ -25,16 +29,6 @@ func parseProxy(s string) (string, Proxy) {
|
|||
return key, p
|
||||
}
|
||||
|
||||
func GetAuthelia() (string, bool) {
|
||||
authelia := conf.Get("authelia").GetString()
|
||||
return authelia, authelia != ""
|
||||
}
|
||||
|
||||
func GetBOAuthZ() (string, bool) {
|
||||
boauthz := conf.Get("oauth").GetString()
|
||||
return boauthz, boauthz != ""
|
||||
}
|
||||
|
||||
func GetAuth() (string, string, bool) {
|
||||
user := conf.Get("user").GetString()
|
||||
pass := conf.Get("pass").GetString()
|
||||
|
|
@ -63,11 +57,30 @@ func GetRate() (int, int) {
|
|||
}
|
||||
|
||||
func GetRoutes() map[string]Proxy {
|
||||
list := conf.Get("proxy").GetString()
|
||||
s := conf.Get("proxy2").GetString()
|
||||
var dict map[string]string
|
||||
if err := yaml.Unmarshal([]byte(s), &dict); err == nil && len(s) > 0 {
|
||||
pattern := regexp.MustCompile(`(([^:]*):)?([a-z0-9]*:.*)`)
|
||||
result := map[string]Proxy{}
|
||||
for k, v := range dict {
|
||||
submatches := pattern.FindAllStringSubmatch(v, -1)
|
||||
log.Printf("%+v", submatches)
|
||||
result[k] = Proxy{
|
||||
Auth: submatches[0][2],
|
||||
To: submatches[0][3],
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
return getRoutesCSV()
|
||||
}
|
||||
|
||||
func getRoutesCSV() map[string]Proxy {
|
||||
list := conf.Get("proxy2").GetString()
|
||||
definitions := strings.Split(list, ",,")
|
||||
routes := make(map[string]Proxy)
|
||||
for _, definition := range definitions {
|
||||
k, v := parseProxy(definition)
|
||||
k, v := parseOneProxyCSV(definition)
|
||||
routes[k] = v
|
||||
}
|
||||
return routes
|
||||
|
|
|
|||
|
|
@ -2,12 +2,13 @@ package config
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"gitea.inhome.blapointe.com/local/args"
|
||||
"gitea.inhome.blapointe.com/local/logb"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.inhome.blapointe.com/local/args"
|
||||
"gitea.inhome.blapointe.com/local/logb"
|
||||
)
|
||||
|
||||
var conf *args.ArgSet
|
||||
|
|
@ -50,9 +51,7 @@ func parseArgs() (*args.ArgSet, error) {
|
|||
as.Append(args.STRING, "trim", "path prefix to trim, like '/abc' to change '/abc/def' to '/def'", "")
|
||||
as.Append(args.STRING, "tcp", "address for tcp only tunnel", "")
|
||||
as.Append(args.DURATION, "timeout", "timeout for tunnel", time.Minute)
|
||||
as.Append(args.STRING, "proxy", "double-comma separated (+ if auth)from,scheme://to.tld:port,,", "")
|
||||
as.Append(args.STRING, "oauth", "url for boauthz", "")
|
||||
as.Append(args.STRING, "authelia", "url for authelia", "")
|
||||
as.Append(args.STRING, "proxy2", "double-comma separated 'from,scheme://to.tld:port,,' OR a yaml dictionary of 'from: (password:)scheme://to.tld:port'", "")
|
||||
as.Append(args.STRING, "cors", "json dict key:true for keys to set CORS permissive headers, like {\"from\":true}", "{}")
|
||||
as.Append(args.STRING, "nopath", "json dict key:true for keys to remove all path info from forwarded request, like -cors", "{}")
|
||||
as.Append(args.STRING, "level", "log level", "info")
|
||||
|
|
|
|||
|
|
@ -7,5 +7,7 @@ crt: ""
|
|||
key: ""
|
||||
tcp: ""
|
||||
timeout: 1m
|
||||
proxy: a,http://localhost:41912,,+b,http://localhost:41912
|
||||
proxy2: |
|
||||
a: http://localhost:41912
|
||||
b: password:http://localhost:41912
|
||||
oauth: http://localhost:23456
|
||||
|
|
|
|||
|
|
@ -17,7 +17,5 @@ func New() *Server {
|
|||
altaddr: altport,
|
||||
limiter: rate.NewLimiter(rate.Limit(r), b),
|
||||
}
|
||||
_, server.auth.BOAuthZ = config.GetBOAuthZ()
|
||||
_, server.auth.Authelia = config.GetAuthelia()
|
||||
return server
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,13 +4,14 @@ import (
|
|||
"bytes"
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"gitea.inhome.blapointe.com/local/rproxy3/config"
|
||||
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"gitea.inhome.blapointe.com/local/rproxy3/config"
|
||||
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable"
|
||||
)
|
||||
|
||||
type redirPurge struct {
|
||||
|
|
@ -51,10 +52,10 @@ func (s *Server) lookup(host string) (*url.URL, error) {
|
|||
return v.URL(), err
|
||||
}
|
||||
|
||||
func (s *Server) lookupAuth(host string) (bool, error) {
|
||||
func (s *Server) lookupAuth(host string) (string, error) {
|
||||
v := packable.NewString()
|
||||
err := s.db.Get(nsBOAuthZ, host, v)
|
||||
return v.String() == "true", err
|
||||
err := s.db.Get(nsRouting, host+"//auth", v)
|
||||
return v.String(), err
|
||||
}
|
||||
|
||||
func mapKey(host string) string {
|
||||
|
|
|
|||
156
server/server.go
156
server/server.go
|
|
@ -12,13 +12,10 @@ import (
|
|||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.inhome.blapointe.com/local/logb"
|
||||
"gitea.inhome.blapointe.com/local/oauth2/oauth2client"
|
||||
"gitea.inhome.blapointe.com/local/rproxy3/config"
|
||||
"gitea.inhome.blapointe.com/local/rproxy3/storage"
|
||||
"gitea.inhome.blapointe.com/local/rproxy3/storage/packable"
|
||||
|
|
@ -28,7 +25,6 @@ import (
|
|||
)
|
||||
|
||||
const nsRouting = "routing"
|
||||
const nsBOAuthZ = "oauth"
|
||||
|
||||
type listenerScheme int
|
||||
|
||||
|
|
@ -57,21 +53,18 @@ type Server struct {
|
|||
username string
|
||||
password string
|
||||
limiter *rate.Limiter
|
||||
auth struct {
|
||||
BOAuthZ bool
|
||||
Authelia bool
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Route(src string, dst config.Proxy) error {
|
||||
hasOAuth := strings.HasPrefix(src, "+")
|
||||
src = strings.TrimPrefix(src, "+")
|
||||
log.Printf("Adding route %q -> %v...\n", src, dst)
|
||||
u, err := url.Parse(dst.To)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.db.Set(nsBOAuthZ, src, packable.NewString(fmt.Sprint(hasOAuth)))
|
||||
if err := s.db.Set(nsRouting, src+"//auth", packable.NewString(dst.Auth)); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.db.Set(nsRouting, src, packable.NewURL(u))
|
||||
}
|
||||
|
||||
|
|
@ -108,135 +101,6 @@ func (s *Server) Run() error {
|
|||
return errors.New("did not load server")
|
||||
}
|
||||
|
||||
func (s *Server) doAuthelia(foo http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
authelia, ok := config.GetAuthelia()
|
||||
if !ok {
|
||||
panic("howd i get here")
|
||||
}
|
||||
url, err := url.Parse(authelia)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("bad config for authelia url: %v", err))
|
||||
}
|
||||
url.Path = "/api/verify"
|
||||
logb.Verbosef("authelia @ %s", url.String())
|
||||
req, err := http.NewRequest(http.MethodGet, url.String(), nil)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
r2 := r.Clone(r.Context())
|
||||
if r2.URL.Host == "" {
|
||||
r2.URL.Host = r2.Host
|
||||
}
|
||||
if r2.URL.Scheme == "" {
|
||||
r2.URL.Scheme = "https"
|
||||
}
|
||||
for _, httpreq := range []*http.Request{r, req} {
|
||||
for k, v := range map[string]string{
|
||||
"X-Original-Url": r2.URL.String(),
|
||||
"X-Forwarded-Proto": r2.URL.Scheme,
|
||||
"X-Forwarded-Host": r2.URL.Host,
|
||||
"X-Forwarded-Uri": r2.URL.String(),
|
||||
} {
|
||||
if _, ok := httpreq.Header[k]; !ok {
|
||||
logb.Verbosef("authelia header setting %s:%s", k, v)
|
||||
httpreq.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
if cookie, err := r.Cookie("authelia_session"); err == nil {
|
||||
logb.Verbosef("authelia session found in cookies; %+v", cookie)
|
||||
req.AddCookie(cookie)
|
||||
}
|
||||
c := &http.Client{
|
||||
Timeout: time.Minute,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
},
|
||||
}
|
||||
|
||||
autheliaKey := mapKey(req.Host)
|
||||
logb.Verbosef("request to %s is authelia %s? %v", r.Host, autheliaKey, strings.HasPrefix(r.Host, autheliaKey))
|
||||
if strings.HasPrefix(r.Host, autheliaKey) {
|
||||
logb.Debugf("no authelia for %s because it has prefix %s", r.Host, autheliaKey)
|
||||
foo(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
logb.Debugf(
|
||||
"authelia: %+v, %+v \n\t-> \n\t(%d) %+v, %+v",
|
||||
req,
|
||||
req.Cookies(),
|
||||
resp.StatusCode,
|
||||
resp.Header,
|
||||
resp.Cookies(),
|
||||
)
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
for k := range resp.Header {
|
||||
if strings.HasPrefix(k, "Remote-") {
|
||||
cookie := &http.Cookie{
|
||||
Name: k,
|
||||
Value: resp.Header.Get(k),
|
||||
Path: "/",
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Expires: time.Now().Add(24 * time.Hour * 30),
|
||||
}
|
||||
logb.Verbosef("setting authelia cookie in response: %+v", cookie)
|
||||
http.SetCookie(w, cookie)
|
||||
logb.Verbosef("setting authelia cookie in request: %+v", cookie)
|
||||
r.AddCookie(cookie)
|
||||
}
|
||||
}
|
||||
foo(w, r)
|
||||
return
|
||||
}
|
||||
url.Path = ""
|
||||
q := url.Query()
|
||||
q.Set("rd", r2.URL.String())
|
||||
url.RawQuery = q.Encode()
|
||||
logb.Verbosef("authelia status %d, rd'ing %s", resp.StatusCode, url.String())
|
||||
http.Redirect(w, r, url.String(), http.StatusFound)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) doBOAuthZ(foo http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
key := mapKey(r.Host)
|
||||
rusr, rpwd, ok := config.GetAuth()
|
||||
if ok {
|
||||
usr, pwd, ok := r.BasicAuth()
|
||||
if !ok || rusr != usr || rpwd != pwd {
|
||||
w.Header().Set("WWW-Authenticate", "Basic")
|
||||
w.WriteHeader(403)
|
||||
log.Printf("denying proxy basic auth")
|
||||
return
|
||||
}
|
||||
}
|
||||
ok, err := s.lookupAuth(key)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if url, exists := config.GetBOAuthZ(); ok && exists {
|
||||
err := oauth2client.Authenticate(url, key, w, r)
|
||||
if err != nil {
|
||||
log.Printf("failed proxy oauth2: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if config.GetNoPath(key) && path.Ext(r.URL.Path) == "" {
|
||||
r.URL.Path = "/"
|
||||
}
|
||||
foo(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) ServeTCP(addr string) error {
|
||||
listen, err := net.Listen("tcp", s.addr)
|
||||
if err != nil {
|
||||
|
|
@ -286,12 +150,14 @@ func (s *Server) Pre(foo http.HandlerFunc) http.HandlerFunc {
|
|||
return
|
||||
}
|
||||
|
||||
if s.auth.BOAuthZ {
|
||||
logb.Verbosef("doing boauthz for request to %s", r.URL.String())
|
||||
s.doBOAuthZ(foo)(w, r)
|
||||
} else if s.auth.Authelia {
|
||||
logb.Verbosef("doing authelia for request to %s", r.URL.String())
|
||||
s.doAuthelia(foo)(w, r)
|
||||
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)
|
||||
w.Header().Set("WWW-Authenticate", "Basic")
|
||||
http.Error(w, err.Error(), http.StatusForbidden)
|
||||
} else if _, p, _ := r.BasicAuth(); auth != p {
|
||||
log.Printf("failed to auth: expected %q but got %q", auth, p)
|
||||
w.Header().Set("WWW-Authenticate", "Basic")
|
||||
http.Error(w, "unexpected basic auth", http.StatusForbidden)
|
||||
} else {
|
||||
foo(w, r)
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue