diff --git a/README.md b/README.md index 2c97bee..6750902 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ Authentication parameters are passed as URI via `-auth` parameter. Scheme of URI * `basicfile` - use htpasswd-like file with login and password pairs for authentication. Such file can be created/updated like this: `touch /etc/dumbproxy.htpasswd && htpasswd -bBC 4 /etc/dumbproxy.htpasswd username password`. `path` parameter in URL for this provider must point to a local file with login and bcrypt-hashed password lines. Example: `basicfile://?path=/etc/dumbproxy.htpasswd`. * `path` - location of file with login and password pairs. File format is similar to htpasswd files. Each line must be in form `:`. Empty lines and lines starting with `#` are ignored. * `hidden_domain` - same as in `static` provider + * `reload` - interval for conditional password file reload, if it was modified since last load. Use negative duration to disable autoreload. Default: `15s`. * `cert` - use mutual TLS authentication with client certificates. In order to use this auth provider server must listen sockert in TLS mode (`-cert` and `-key` options) and client CA file must be specified (`-cacert`). Example: `cert://`. ## Synopsis diff --git a/auth.go b/auth.go index fde1570..d9cb6fc 100644 --- a/auth.go +++ b/auth.go @@ -1,16 +1,19 @@ package main import ( - "bufio" + "bytes" "crypto/subtle" "encoding/base64" "errors" + "fmt" "net/http" "net/url" - "os" "strconv" "strings" + "sync" + "time" + "github.com/tg123/go-htpasswd" "golang.org/x/crypto/bcrypt" ) @@ -21,9 +24,10 @@ const EPOCH_EXPIRE = "Thu, 01 Jan 1970 00:00:01 GMT" type Auth interface { Validate(wr http.ResponseWriter, req *http.Request) bool + Stop() } -func NewAuth(paramstr string) (Auth, error) { +func NewAuth(paramstr string, logger *CondLogger) (Auth, error) { url, err := url.Parse(paramstr) if err != nil { return nil, err @@ -31,9 +35,9 @@ func NewAuth(paramstr string) (Auth, error) { switch strings.ToLower(url.Scheme) { case "static": - return NewStaticAuth(url) + return NewStaticAuth(url, logger) case "basicfile": - return NewBasicFileAuth(url) + return NewBasicFileAuth(url, logger) case "cert": return CertAuth{}, nil case "none": @@ -43,7 +47,7 @@ func NewAuth(paramstr string) (Auth, error) { } } -func NewStaticAuth(param_url *url.URL) (*BasicAuth, error) { +func NewStaticAuth(param_url *url.URL, logger *CondLogger) (*BasicAuth, error) { values, err := url.ParseQuery(param_url.RawQuery) if err != nil { return nil, err @@ -60,11 +64,22 @@ func NewStaticAuth(param_url *url.URL) (*BasicAuth, error) { if err != nil { return nil, err } + buf := bytes.NewBufferString(username) + buf.WriteByte(':') + buf.Write(hashedPassword) + + pwFile, err := htpasswd.NewFromReader(buf, htpasswd.DefaultSystems, func(parseError error) { + logger.Error("static auth: password entry parse error: %v", err) + }) + if err != nil { + return nil, fmt.Errorf("can't instantiate pwFile: %w", err) + } + return &BasicAuth{ - users: map[string][]byte{ - username: hashedPassword, - }, hiddenDomain: strings.ToLower(values.Get("hidden_domain")), + logger: logger, + pwFile: pwFile, + stopChan: make(chan struct{}), }, nil } @@ -82,11 +97,17 @@ func requireBasicAuth(wr http.ResponseWriter, req *http.Request, hidden_domain s } type BasicAuth struct { - users map[string][]byte + pwFilename string + pwFile *htpasswd.File + pwMux sync.RWMutex + logger *CondLogger hiddenDomain string + stopOnce sync.Once + stopChan chan struct{} + lastReloaded time.Time } -func NewBasicFileAuth(param_url *url.URL) (*BasicAuth, error) { +func NewBasicFileAuth(param_url *url.URL, logger *CondLogger) (*BasicAuth, error) { values, err := url.ParseQuery(param_url.RawQuery) if err != nil { return nil, err @@ -96,38 +117,78 @@ func NewBasicFileAuth(param_url *url.URL) (*BasicAuth, error) { return nil, errors.New("\"path\" parameter is missing from auth config URI") } - f, err := os.Open(filename) - if err != nil { - return nil, err - } - defer f.Close() - - scanner := bufio.NewScanner(f) - users := make(map[string][]byte) - for scanner.Scan() { - line := scanner.Text() - trimmed := strings.TrimSpace(line) - if trimmed == "" || strings.HasPrefix(trimmed, "#") { - continue - } - pair := strings.SplitN(line, ":", 2) - if len(pair) != 2 { - return nil, errors.New("Malformed login and password line") - } - login := pair[0] - password := pair[1] - users[login] = []byte(password) - } - if err := scanner.Err(); err != nil { - return nil, err - } - if len(users) == 0 { - return nil, errors.New("No password lines were read from file") - } - return &BasicAuth{ - users: users, + auth := &BasicAuth{ hiddenDomain: strings.ToLower(values.Get("hidden_domain")), - }, nil + pwFilename: filename, + logger: logger, + stopChan: make(chan struct{}), + } + + if err := auth.reload(); err != nil { + return nil, fmt.Errorf("unable to load initial password list: %w", err) + } + + reloadIntervalOption := values.Get("reload") + reloadInterval, err := time.ParseDuration(reloadIntervalOption) + if err != nil { + reloadInterval = 0 + } + if reloadInterval == 0 { + reloadInterval = 15 * time.Second + } + if reloadInterval > 0 { + go auth.reloadLoop(reloadInterval) + } + + return auth, nil +} + +func (auth *BasicAuth) reload() error { + auth.logger.Info("reloading password file from %q...", auth.pwFilename) + newPwFile, err := htpasswd.New(auth.pwFilename, htpasswd.DefaultSystems, func(parseErr error) { + auth.logger.Error("failed to parse line in %q: %v", auth.pwFilename, parseErr) + }) + if err != nil { + return err + } + + now := time.Now() + + auth.pwMux.Lock() + auth.pwFile = newPwFile + auth.lastReloaded = now + auth.pwMux.Unlock() + auth.logger.Info("password file reloaded.") + + return nil +} + +func (auth *BasicAuth) condReload() error { + reload := func() bool { + pwFileModTime, err := fileModTime(auth.pwFilename) + if err != nil { + auth.logger.Warning("can't get password file modtime: %v", err) + return true + } + return !pwFileModTime.Before(auth.lastReloaded) + }() + if reload { + return auth.reload() + } + return nil +} + +func (auth *BasicAuth) reloadLoop(interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-auth.stopChan: + return + case <-ticker.C: + auth.condReload() + } + } } func (auth *BasicAuth) Validate(wr http.ResponseWriter, req *http.Request) bool { @@ -158,13 +219,11 @@ func (auth *BasicAuth) Validate(wr http.ResponseWriter, req *http.Request) bool login := pair[0] password := pair[1] - hashedPassword, ok := auth.users[login] - if !ok { - requireBasicAuth(wr, req, auth.hiddenDomain) - return false - } + auth.pwMux.RLock() + pwFile := auth.pwFile + auth.pwMux.RUnlock() - if bcrypt.CompareHashAndPassword(hashedPassword, []byte(password)) == nil { + if pwFile.Match(login, password) { if auth.hiddenDomain != "" && (req.Host == auth.hiddenDomain || req.URL.Host == auth.hiddenDomain) { wr.Header().Set("Content-Length", strconv.Itoa(len([]byte(AUTH_TRIGGERED_MSG)))) @@ -183,12 +242,20 @@ func (auth *BasicAuth) Validate(wr http.ResponseWriter, req *http.Request) bool return false } +func (auth *BasicAuth) Stop() { + auth.stopOnce.Do(func() { + close(auth.stopChan) + }) +} + type NoAuth struct{} func (_ NoAuth) Validate(wr http.ResponseWriter, req *http.Request) bool { return true } +func (_ NoAuth) Stop() {} + type CertAuth struct{} func (_ CertAuth) Validate(wr http.ResponseWriter, req *http.Request) bool { @@ -199,3 +266,5 @@ func (_ CertAuth) Validate(wr http.ResponseWriter, req *http.Request) bool { return true } } + +func (_ CertAuth) Stop() {} diff --git a/go.mod b/go.mod index 422eafc..3be7fed 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/Snawoot/dumbproxy go 1.13 require ( + github.com/tg123/go-htpasswd v1.2.0 // indirect golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b // indirect ) diff --git a/go.sum b/go.sum index f57a52f..205e35f 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,18 @@ +github.com/GehirnInc/crypt v0.0.0-20200316065508-bb7000b8a962 h1:KeNholpO2xKjgaaSyd+DyQRrsQjhbSeS7qe4nEw8aQw= +github.com/GehirnInc/crypt v0.0.0-20200316065508-bb7000b8a962/go.mod h1:kC29dT1vFpj7py2OvG1khBdQpo3kInWP+6QipLbdngo= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/tg123/go-htpasswd v1.2.0 h1:UKp34m9H467/xklxUxU15wKRru7fwXoTojtxg25ITF0= +github.com/tg123/go-htpasswd v1.2.0/go.mod h1:h7IzlfpvIWnVJhNZ0nQ9HaFxHb7pn5uFJYLlEUJa2sM= +golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 h1:Y/gsMcFOcR+6S6f3YeMKl5g+dZMEWqcz5Czj/GWYbkM= golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b h1:ZmngSVLe/wycRns9MKikG9OWIEjGcGAkacif7oYQaUY= golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -13,3 +23,5 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index e44ce64..f009c1c 100644 --- a/main.go +++ b/main.go @@ -119,12 +119,16 @@ func run() int { proxyLogger := NewCondLogger(log.New(logWriter, "PROXY : ", log.LstdFlags|log.Lshortfile), args.verbosity) + authLogger := NewCondLogger(log.New(logWriter, "AUTH : ", + log.LstdFlags|log.Lshortfile), + args.verbosity) - auth, err := NewAuth(args.auth) + auth, err := NewAuth(args.auth, authLogger) if err != nil { mainLogger.Critical("Failed to instantiate auth provider: %v", err) return 3 } + defer auth.Stop() server := http.Server{ Addr: args.bind_address, diff --git a/utils.go b/utils.go index c274165..96a2667 100644 --- a/utils.go +++ b/utils.go @@ -6,11 +6,13 @@ import ( "crypto/tls" "crypto/x509" "errors" + "fmt" "io" "io/ioutil" "log" "net" "net/http" + "os" "strings" "sync" "time" @@ -189,3 +191,18 @@ func makeCipherList(ciphers string) []uint16 { return cipherIDList } + +func fileModTime(filename string) (time.Time, error) { + f, err := os.Open(filename) + if err != nil { + return time.Time{}, fmt.Errorf("fileModTime(): can't open file %q: %w", filename, err) + } + defer f.Close() + + fi, err := f.Stat() + if err != nil { + return time.Time{}, fmt.Errorf("fileModTime(): can't stat file %q: %w", filename, err) + } + + return fi.ModTime(), nil +}