docstring_tokens
stringlengths
18
16.9k
code_tokens
stringlengths
75
1.81M
html_url
stringlengths
74
116
file_name
stringlengths
3
311
keep keep replace replace replace replace replace replace keep keep replace keep keep
<mask> config.AuthPass = newSettings.Password <mask> <mask> if config.DNS.Port != 0 { <mask> err = startDNSServer() <mask> if err != nil { <mask> httpError(w, http.StatusInternalServerError, "Couldn't start DNS server: %s", err) <mask> return <mask> } <mask> } <mask> <mask> httpUpdateConfigReloadDNSReturnOK(w, r) <mask> // this needs to be done in a goroutine because Shutdown() is a blocking call, and it will block <mask> // until all requests are finished, and _we_ are inside a request right now, so it will block indefinitely </s> * control: /install/configure: reset configuration back to its current state on error </s> add // Copy installation parameters between two configuration objects func copyInstallSettings(dst *configuration, src *configuration) { dst.BindHost = src.BindHost dst.BindPort = src.BindPort dst.DNS.BindHost = src.DNS.BindHost dst.DNS.Port = src.DNS.Port dst.AuthName = src.AuthName dst.AuthPass = src.AuthPass } </s> add var curConfig configuration copyInstallSettings(&curConfig, &config) </s> add returnOK(w)
https://github.com/AdguardTeam/AdGuardHome/commit/73fbe8b95aca6092b0beb7327a9c811a32464bcc
control.go
keep add keep keep keep keep keep keep
<mask> }() <mask> } <mask> } <mask> <mask> // -------------- <mask> // DNS-over-HTTPS <mask> // -------------- <mask> func handleDOH(w http.ResponseWriter, r *http.Request) { </s> * control: /install/configure: reset configuration back to its current state on error </s> add // Copy installation parameters between two configuration objects func copyInstallSettings(dst *configuration, src *configuration) { dst.BindHost = src.BindHost dst.BindPort = src.BindPort dst.DNS.BindHost = src.DNS.BindHost dst.DNS.Port = src.DNS.Port dst.AuthName = src.AuthName dst.AuthPass = src.AuthPass } </s> remove httpUpdateConfigReloadDNSReturnOK(w, r) </s> add </s> remove if config.DNS.Port != 0 { err = startDNSServer() if err != nil { httpError(w, http.StatusInternalServerError, "Couldn't start DNS server: %s", err) return } </s> add err = startDNSServer() if err != nil { config.firstRun = true copyInstallSettings(&config, &curConfig) httpError(w, http.StatusInternalServerError, "Couldn't start DNS server: %s", err) return } err = config.write() if err != nil { config.firstRun = true copyInstallSettings(&config, &curConfig) httpError(w, http.StatusInternalServerError, "Couldn't write config: %s", err) return </s> add var curConfig configuration copyInstallSettings(&curConfig, &config)
https://github.com/AdguardTeam/AdGuardHome/commit/73fbe8b95aca6092b0beb7327a9c811a32464bcc
control.go
keep keep add keep keep keep keep
<mask> package querylog <mask> <mask> import ( <mask> "fmt" <mask> "math" <mask> "net" <mask> "net/http" </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> add "math" </s> remove type qlogConfig struct { // Use float64 here to support fractional numbers and not mess the API // users by changing the units. Interval float64 `json:"interval"` Enabled bool `json:"enabled"` AnonymizeClientIP bool `json:"anonymize_client_ip"` </s> add // configJSON is the JSON structure for the querylog configuration. type configJSON struct { // Interval is the querylog rotation interval. Use float64 here to support // fractional numbers and not mess the API users by changing the units. Interval float64 `json:"interval"` // Enabled shows if the querylog is enabled. It is an [aghalg.NullBool] // to be able to tell when it's set without using pointers. Enabled aghalg.NullBool `json:"enabled"` // AnonymizeClientIP shows if the clients' IP addresses must be anonymized. // It is an [aghalg.NullBool] to be able to tell when it's set without using // pointers. AnonymizeClientIP aghalg.NullBool `json:"anonymize_client_ip"` </s> remove if req.Exists("anonymize_client_ip") { if conf.AnonymizeClientIP = d.AnonymizeClientIP; conf.AnonymizeClientIP { </s> add if newConf.AnonymizeClientIP != aghalg.NBNull { conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue if conf.AnonymizeClientIP { </s> remove if req.Exists("interval") { </s> add if hasIvl { </s> remove if req.Exists("enabled") { conf.Enabled = d.Enabled </s> add if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue </s> remove ivl := time.Duration(float64(timeutil.Day) * d.Interval) if req.Exists("interval") && !checkInterval(ivl) { aghhttp.Error(r, w, http.StatusBadRequest, "Unsupported interval") </s> add ivl := time.Duration(float64(timeutil.Day) * newConf.Interval) hasIvl := !math.IsNaN(newConf.Interval) if hasIvl && !checkInterval(ivl) { aghhttp.Error(r, w, http.StatusBadRequest, "unsupported interval")
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep add keep keep keep keep keep keep
<mask> <mask> import ( <mask> "encoding/json" <mask> "fmt" <mask> "net" <mask> "net/http" <mask> "net/url" <mask> "strconv" <mask> "strings" <mask> "time" </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> add "encoding/json" </s> add "github.com/AdguardTeam/AdGuardHome/internal/aghalg" </s> remove "github.com/AdguardTeam/golibs/jsonutil" </s> add </s> remove if req.Exists("anonymize_client_ip") { if conf.AnonymizeClientIP = d.AnonymizeClientIP; conf.AnonymizeClientIP { </s> add if newConf.AnonymizeClientIP != aghalg.NBNull { conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue if conf.AnonymizeClientIP { </s> remove if req.Exists("interval") { </s> add if hasIvl { </s> remove if req.Exists("enabled") { conf.Enabled = d.Enabled </s> add if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep add keep keep keep keep
<mask> "strconv" <mask> "strings" <mask> "time" <mask> <mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" <mask> "github.com/AdguardTeam/golibs/log" <mask> "github.com/AdguardTeam/golibs/stringutil" <mask> "github.com/AdguardTeam/golibs/timeutil" </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> remove "github.com/AdguardTeam/golibs/jsonutil" </s> add </s> add "math" </s> remove type qlogConfig struct { // Use float64 here to support fractional numbers and not mess the API // users by changing the units. Interval float64 `json:"interval"` Enabled bool `json:"enabled"` AnonymizeClientIP bool `json:"anonymize_client_ip"` </s> add // configJSON is the JSON structure for the querylog configuration. type configJSON struct { // Interval is the querylog rotation interval. Use float64 here to support // fractional numbers and not mess the API users by changing the units. Interval float64 `json:"interval"` // Enabled shows if the querylog is enabled. It is an [aghalg.NullBool] // to be able to tell when it's set without using pointers. Enabled aghalg.NullBool `json:"enabled"` // AnonymizeClientIP shows if the clients' IP addresses must be anonymized. // It is an [aghalg.NullBool] to be able to tell when it's set without using // pointers. AnonymizeClientIP aghalg.NullBool `json:"anonymize_client_ip"` </s> remove if req.Exists("anonymize_client_ip") { if conf.AnonymizeClientIP = d.AnonymizeClientIP; conf.AnonymizeClientIP { </s> add if newConf.AnonymizeClientIP != aghalg.NBNull { conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue if conf.AnonymizeClientIP { </s> remove if req.Exists("interval") { </s> add if hasIvl { </s> remove if req.Exists("enabled") { conf.Enabled = d.Enabled </s> add if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep keep replace keep keep keep keep keep
<mask> "strings" <mask> "time" <mask> <mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" <mask> "github.com/AdguardTeam/golibs/jsonutil" <mask> "github.com/AdguardTeam/golibs/log" <mask> "github.com/AdguardTeam/golibs/stringutil" <mask> "github.com/AdguardTeam/golibs/timeutil" <mask> "golang.org/x/net/idna" <mask> ) </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> add "github.com/AdguardTeam/AdGuardHome/internal/aghalg" </s> add "math" </s> remove type qlogConfig struct { // Use float64 here to support fractional numbers and not mess the API // users by changing the units. Interval float64 `json:"interval"` Enabled bool `json:"enabled"` AnonymizeClientIP bool `json:"anonymize_client_ip"` </s> add // configJSON is the JSON structure for the querylog configuration. type configJSON struct { // Interval is the querylog rotation interval. Use float64 here to support // fractional numbers and not mess the API users by changing the units. Interval float64 `json:"interval"` // Enabled shows if the querylog is enabled. It is an [aghalg.NullBool] // to be able to tell when it's set without using pointers. Enabled aghalg.NullBool `json:"enabled"` // AnonymizeClientIP shows if the clients' IP addresses must be anonymized. // It is an [aghalg.NullBool] to be able to tell when it's set without using // pointers. AnonymizeClientIP aghalg.NullBool `json:"anonymize_client_ip"` </s> remove if req.Exists("anonymize_client_ip") { if conf.AnonymizeClientIP = d.AnonymizeClientIP; conf.AnonymizeClientIP { </s> add if newConf.AnonymizeClientIP != aghalg.NBNull { conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue if conf.AnonymizeClientIP { </s> remove if req.Exists("interval") { </s> add if hasIvl { </s> remove if req.Exists("enabled") { conf.Enabled = d.Enabled </s> add if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep keep replace replace replace replace replace replace keep keep keep keep keep
<mask> "github.com/AdguardTeam/golibs/timeutil" <mask> "golang.org/x/net/idna" <mask> ) <mask> <mask> type qlogConfig struct { <mask> // Use float64 here to support fractional numbers and not mess the API <mask> // users by changing the units. <mask> Interval float64 `json:"interval"` <mask> Enabled bool `json:"enabled"` <mask> AnonymizeClientIP bool `json:"anonymize_client_ip"` <mask> } <mask> <mask> // Register web handlers <mask> func (l *queryLog) initWeb() { <mask> l.conf.HTTPRegister(http.MethodGet, "/control/querylog", l.handleQueryLog) </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> remove AnonymizeClientIP: l.conf.AnonymizeClientIP, } _ = aghhttp.WriteJSONResponse(w, r, resp) </s> add AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP), }) </s> remove "github.com/AdguardTeam/golibs/jsonutil" </s> add </s> remove // Set configuration </s> add // handleQueryLogConfig handles the POST /control/querylog_config queries. </s> remove d := &qlogConfig{} req, err := jsonutil.DecodeObject(d, r.Body) </s> add // Set NaN as initial value to be able to know if it changed later by // comparing it to NaN. newConf := &configJSON{ Interval: math.NaN(), } err := json.NewDecoder(r.Body).Decode(newConf) </s> remove if req.Exists("enabled") { conf.Enabled = d.Enabled </s> add if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue </s> remove resp := qlogConfig{ Enabled: l.conf.Enabled, </s> add _ = aghhttp.WriteJSONResponse(w, r, configJSON{ Enabled: aghalg.BoolToNullBool(l.conf.Enabled),
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep replace replace keep replace replace replace replace keep keep keep
<mask> <mask> // Get configuration <mask> func (l *queryLog) handleQueryLogInfo(w http.ResponseWriter, r *http.Request) { <mask> resp := qlogConfig{ <mask> Enabled: l.conf.Enabled, <mask> Interval: l.conf.RotationIvl.Hours() / 24, <mask> AnonymizeClientIP: l.conf.AnonymizeClientIP, <mask> } <mask> <mask> _ = aghhttp.WriteJSONResponse(w, r, resp) <mask> } <mask> <mask> // AnonymizeIP masks ip to anonymize the client if the ip is a valid one. </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> remove // Set configuration </s> add // handleQueryLogConfig handles the POST /control/querylog_config queries. </s> remove d := &qlogConfig{} req, err := jsonutil.DecodeObject(d, r.Body) </s> add // Set NaN as initial value to be able to know if it changed later by // comparing it to NaN. newConf := &configJSON{ Interval: math.NaN(), } err := json.NewDecoder(r.Body).Decode(newConf) </s> remove type qlogConfig struct { // Use float64 here to support fractional numbers and not mess the API // users by changing the units. Interval float64 `json:"interval"` Enabled bool `json:"enabled"` AnonymizeClientIP bool `json:"anonymize_client_ip"` </s> add // configJSON is the JSON structure for the querylog configuration. type configJSON struct { // Interval is the querylog rotation interval. Use float64 here to support // fractional numbers and not mess the API users by changing the units. Interval float64 `json:"interval"` // Enabled shows if the querylog is enabled. It is an [aghalg.NullBool] // to be able to tell when it's set without using pointers. Enabled aghalg.NullBool `json:"enabled"` // AnonymizeClientIP shows if the clients' IP addresses must be anonymized. // It is an [aghalg.NullBool] to be able to tell when it's set without using // pointers. AnonymizeClientIP aghalg.NullBool `json:"anonymize_client_ip"` </s> remove if req.Exists("enabled") { conf.Enabled = d.Enabled </s> add if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue </s> remove if req.Exists("interval") { </s> add if hasIvl {
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep replace keep replace replace keep keep keep keep
<mask> } <mask> } <mask> <mask> // Set configuration <mask> func (l *queryLog) handleQueryLogConfig(w http.ResponseWriter, r *http.Request) { <mask> d := &qlogConfig{} <mask> req, err := jsonutil.DecodeObject(d, r.Body) <mask> if err != nil { <mask> aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) <mask> <mask> return </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> remove ivl := time.Duration(float64(timeutil.Day) * d.Interval) if req.Exists("interval") && !checkInterval(ivl) { aghhttp.Error(r, w, http.StatusBadRequest, "Unsupported interval") </s> add ivl := time.Duration(float64(timeutil.Day) * newConf.Interval) hasIvl := !math.IsNaN(newConf.Interval) if hasIvl && !checkInterval(ivl) { aghhttp.Error(r, w, http.StatusBadRequest, "unsupported interval") </s> remove resp := qlogConfig{ Enabled: l.conf.Enabled, </s> add _ = aghhttp.WriteJSONResponse(w, r, configJSON{ Enabled: aghalg.BoolToNullBool(l.conf.Enabled), </s> remove AnonymizeClientIP: l.conf.AnonymizeClientIP, } _ = aghhttp.WriteJSONResponse(w, r, resp) </s> add AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP), }) </s> remove if req.Exists("enabled") { conf.Enabled = d.Enabled </s> add if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue </s> remove if req.Exists("anonymize_client_ip") { if conf.AnonymizeClientIP = d.AnonymizeClientIP; conf.AnonymizeClientIP { </s> add if newConf.AnonymizeClientIP != aghalg.NBNull { conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue if conf.AnonymizeClientIP {
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep keep replace replace replace keep keep keep keep keep
<mask> <mask> return <mask> } <mask> <mask> ivl := time.Duration(float64(timeutil.Day) * d.Interval) <mask> if req.Exists("interval") && !checkInterval(ivl) { <mask> aghhttp.Error(r, w, http.StatusBadRequest, "Unsupported interval") <mask> <mask> return <mask> } <mask> <mask> defer l.conf.ConfigModified() </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> remove d := &qlogConfig{} req, err := jsonutil.DecodeObject(d, r.Body) </s> add // Set NaN as initial value to be able to know if it changed later by // comparing it to NaN. newConf := &configJSON{ Interval: math.NaN(), } err := json.NewDecoder(r.Body).Decode(newConf) </s> remove // Set configuration </s> add // handleQueryLogConfig handles the POST /control/querylog_config queries. </s> remove if req.Exists("interval") { </s> add if hasIvl { </s> remove if req.Exists("anonymize_client_ip") { if conf.AnonymizeClientIP = d.AnonymizeClientIP; conf.AnonymizeClientIP { </s> add if newConf.AnonymizeClientIP != aghalg.NBNull { conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue if conf.AnonymizeClientIP { </s> remove if req.Exists("enabled") { conf.Enabled = d.Enabled </s> add if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue </s> remove AnonymizeClientIP: l.conf.AnonymizeClientIP, } _ = aghhttp.WriteJSONResponse(w, r, resp) </s> add AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP), })
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep replace replace keep replace keep keep
<mask> // Copy data, modify it, then activate. Other threads (readers) don't need <mask> // to use this lock. <mask> conf := *l.conf <mask> if req.Exists("enabled") { <mask> conf.Enabled = d.Enabled <mask> } <mask> if req.Exists("interval") { <mask> conf.RotationIvl = ivl <mask> } </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> remove if req.Exists("anonymize_client_ip") { if conf.AnonymizeClientIP = d.AnonymizeClientIP; conf.AnonymizeClientIP { </s> add if newConf.AnonymizeClientIP != aghalg.NBNull { conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue if conf.AnonymizeClientIP { </s> remove ivl := time.Duration(float64(timeutil.Day) * d.Interval) if req.Exists("interval") && !checkInterval(ivl) { aghhttp.Error(r, w, http.StatusBadRequest, "Unsupported interval") </s> add ivl := time.Duration(float64(timeutil.Day) * newConf.Interval) hasIvl := !math.IsNaN(newConf.Interval) if hasIvl && !checkInterval(ivl) { aghhttp.Error(r, w, http.StatusBadRequest, "unsupported interval") </s> remove d := &qlogConfig{} req, err := jsonutil.DecodeObject(d, r.Body) </s> add // Set NaN as initial value to be able to know if it changed later by // comparing it to NaN. newConf := &configJSON{ Interval: math.NaN(), } err := json.NewDecoder(r.Body).Decode(newConf) </s> remove AnonymizeClientIP: l.conf.AnonymizeClientIP, } _ = aghhttp.WriteJSONResponse(w, r, resp) </s> add AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP), }) </s> remove // Set configuration </s> add // handleQueryLogConfig handles the POST /control/querylog_config queries.
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep keep replace replace keep keep keep keep keep
<mask> } <mask> if req.Exists("interval") { <mask> conf.RotationIvl = ivl <mask> } <mask> if req.Exists("anonymize_client_ip") { <mask> if conf.AnonymizeClientIP = d.AnonymizeClientIP; conf.AnonymizeClientIP { <mask> l.anonymizer.Store(AnonymizeIP) <mask> } else { <mask> l.anonymizer.Store(nil) <mask> } <mask> } </s> Pull request: rm-jsonutil Merge in DNS/adguard-home from rm-jsonutil to master Squashed commit of the following: commit dec746d321adbeb41bfd0c44e71d198809c4731e Author: Ainar Garipov <[email protected]> Date: Fri Oct 28 18:41:39 2022 +0300 querylog: rm jsonutil </s> remove if req.Exists("interval") { </s> add if hasIvl { </s> remove if req.Exists("enabled") { conf.Enabled = d.Enabled </s> add if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue </s> remove ivl := time.Duration(float64(timeutil.Day) * d.Interval) if req.Exists("interval") && !checkInterval(ivl) { aghhttp.Error(r, w, http.StatusBadRequest, "Unsupported interval") </s> add ivl := time.Duration(float64(timeutil.Day) * newConf.Interval) hasIvl := !math.IsNaN(newConf.Interval) if hasIvl && !checkInterval(ivl) { aghhttp.Error(r, w, http.StatusBadRequest, "unsupported interval") </s> remove // Set configuration </s> add // handleQueryLogConfig handles the POST /control/querylog_config queries. </s> remove d := &qlogConfig{} req, err := jsonutil.DecodeObject(d, r.Body) </s> add // Set NaN as initial value to be able to know if it changed later by // comparing it to NaN. newConf := &configJSON{ Interval: math.NaN(), } err := json.NewDecoder(r.Body).Decode(newConf) </s> remove AnonymizeClientIP: l.conf.AnonymizeClientIP, } _ = aghhttp.WriteJSONResponse(w, r, resp) </s> add AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP), })
https://github.com/AdguardTeam/AdGuardHome/commit/746e9df727866a2ae90f1533fd2ee92f4d914de2
internal/querylog/http.go
keep keep keep add keep keep keep keep
<mask> } <mask> <mask> func httpError(w http.ResponseWriter, code int, format string, args ...interface{}) { <mask> text := fmt.Sprintf(format, args...) <mask> http.Error(w, text, code) <mask> } <mask> <mask> func handleSetUpstreamDNS(w http.ResponseWriter, r *http.Request) { </s> API filtering/add_url -- accept JSON instead of name=value lines </s> remove parameters, err := parseParametersFromBody(r.Body) </s> add filter := filter{} err := json.NewDecoder(r.Body).Decode(&filter) </s> remove errortext := fmt.Sprintf("failed to parse parameters from body: %s", err) log.Println(errortext) http.Error(w, errortext, 400) </s> add httpError(w, http.StatusBadRequest, "Failed to parse request body json: %s", err) </s> remove url, ok := parameters["url"] if !ok { </s> add filter.Enabled = true if len(filter.URL) == 0 { </s> remove filter := &config.Filters[i] if filter.URL == url { errortext := fmt.Sprintf("Filter URL already added -- %s", url) </s> add if config.Filters[i].URL == filter.URL { errortext := fmt.Sprintf("Filter URL already added -- %s", filter.URL) </s> remove if valid := govalidator.IsRequestURL(url); !valid { </s> add if valid := govalidator.IsRequestURL(filter.URL); !valid { </s> remove errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", url) </s> add errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", filter.URL)
https://github.com/AdguardTeam/AdGuardHome/commit/751be05a31e8479fb0e8ca318260264466871b16
control.go
keep keep keep replace keep replace replace replace keep keep keep
<mask> } <mask> <mask> func handleFilteringAddURL(w http.ResponseWriter, r *http.Request) { <mask> parameters, err := parseParametersFromBody(r.Body) <mask> if err != nil { <mask> errortext := fmt.Sprintf("failed to parse parameters from body: %s", err) <mask> log.Println(errortext) <mask> http.Error(w, errortext, 400) <mask> return <mask> } <mask> </s> API filtering/add_url -- accept JSON instead of name=value lines </s> add log.Println(text) </s> remove errortext := fmt.Sprintf("Couldn't fetch filter from url %s: %s", url, err) </s> add errortext := fmt.Sprintf("Couldn't fetch filter from url %s: %s", filter.URL, err) </s> remove var filter = filter{ Enabled: true, URL: url, } ok, err = filter.update(time.Now()) </s> add ok, err := filter.update(time.Now()) </s> remove url, ok := parameters["url"] if !ok { </s> add filter.Enabled = true if len(filter.URL) == 0 { </s> remove errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", url) </s> add errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", filter.URL)
https://github.com/AdguardTeam/AdGuardHome/commit/751be05a31e8479fb0e8ca318260264466871b16
control.go
keep keep replace replace keep keep keep keep replace keep keep
<mask> } <mask> <mask> url, ok := parameters["url"] <mask> if !ok { <mask> http.Error(w, "URL parameter was not specified", 400) <mask> return <mask> } <mask> <mask> if valid := govalidator.IsRequestURL(url); !valid { <mask> http.Error(w, "URL parameter is not valid request URL", 400) <mask> return </s> API filtering/add_url -- accept JSON instead of name=value lines </s> remove errortext := fmt.Sprintf("failed to parse parameters from body: %s", err) log.Println(errortext) http.Error(w, errortext, 400) </s> add httpError(w, http.StatusBadRequest, "Failed to parse request body json: %s", err) </s> remove errortext := fmt.Sprintf("Filter at url %s is invalid (maybe it points to blank page?)", url) </s> add errortext := fmt.Sprintf("Filter at url %s is invalid (maybe it points to blank page?)", filter.URL) </s> remove parameters, err := parseParametersFromBody(r.Body) </s> add filter := filter{} err := json.NewDecoder(r.Body).Decode(&filter) </s> remove errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", url) </s> add errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", filter.URL) </s> remove var filter = filter{ Enabled: true, URL: url, } ok, err = filter.update(time.Now()) </s> add ok, err := filter.update(time.Now())
https://github.com/AdguardTeam/AdGuardHome/commit/751be05a31e8479fb0e8ca318260264466871b16
control.go
keep keep keep keep replace replace replace keep keep keep keep keep
<mask> } <mask> <mask> // check for duplicates <mask> for i := range config.Filters { <mask> filter := &config.Filters[i] <mask> if filter.URL == url { <mask> errortext := fmt.Sprintf("Filter URL already added -- %s", url) <mask> log.Println(errortext) <mask> http.Error(w, errortext, http.StatusBadRequest) <mask> return <mask> } <mask> } </s> API filtering/add_url -- accept JSON instead of name=value lines </s> remove if valid := govalidator.IsRequestURL(url); !valid { </s> add if valid := govalidator.IsRequestURL(filter.URL); !valid { </s> remove errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", url) </s> add errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", filter.URL) </s> remove errortext := fmt.Sprintf("Filter at url %s is invalid (maybe it points to blank page?)", url) </s> add errortext := fmt.Sprintf("Filter at url %s is invalid (maybe it points to blank page?)", filter.URL) </s> remove errortext := fmt.Sprintf("Couldn't fetch filter from url %s: %s", url, err) </s> add errortext := fmt.Sprintf("Couldn't fetch filter from url %s: %s", filter.URL, err) </s> remove parameters, err := parseParametersFromBody(r.Body) </s> add filter := filter{} err := json.NewDecoder(r.Body).Decode(&filter) </s> remove url, ok := parameters["url"] if !ok { </s> add filter.Enabled = true if len(filter.URL) == 0 {
https://github.com/AdguardTeam/AdGuardHome/commit/751be05a31e8479fb0e8ca318260264466871b16
control.go
keep keep replace replace replace replace replace keep replace keep
<mask> } <mask> <mask> var filter = filter{ <mask> Enabled: true, <mask> URL: url, <mask> } <mask> ok, err = filter.update(time.Now()) <mask> if err != nil { <mask> errortext := fmt.Sprintf("Couldn't fetch filter from url %s: %s", url, err) <mask> log.Println(errortext) </s> API filtering/add_url -- accept JSON instead of name=value lines </s> remove parameters, err := parseParametersFromBody(r.Body) </s> add filter := filter{} err := json.NewDecoder(r.Body).Decode(&filter) </s> remove errortext := fmt.Sprintf("failed to parse parameters from body: %s", err) log.Println(errortext) http.Error(w, errortext, 400) </s> add httpError(w, http.StatusBadRequest, "Failed to parse request body json: %s", err) </s> remove url, ok := parameters["url"] if !ok { </s> add filter.Enabled = true if len(filter.URL) == 0 { </s> remove filter := &config.Filters[i] if filter.URL == url { errortext := fmt.Sprintf("Filter URL already added -- %s", url) </s> add if config.Filters[i].URL == filter.URL { errortext := fmt.Sprintf("Filter URL already added -- %s", filter.URL) </s> remove errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", url) </s> add errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", filter.URL)
https://github.com/AdguardTeam/AdGuardHome/commit/751be05a31e8479fb0e8ca318260264466871b16
control.go
keep keep keep keep replace keep keep keep keep keep
<mask> http.Error(w, errortext, http.StatusBadRequest) <mask> return <mask> } <mask> if filter.RulesCount == 0 { <mask> errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", url) <mask> log.Println(errortext) <mask> http.Error(w, errortext, http.StatusBadRequest) <mask> return <mask> } <mask> if !ok { </s> API filtering/add_url -- accept JSON instead of name=value lines </s> remove errortext := fmt.Sprintf("Filter at url %s is invalid (maybe it points to blank page?)", url) </s> add errortext := fmt.Sprintf("Filter at url %s is invalid (maybe it points to blank page?)", filter.URL) </s> remove filter := &config.Filters[i] if filter.URL == url { errortext := fmt.Sprintf("Filter URL already added -- %s", url) </s> add if config.Filters[i].URL == filter.URL { errortext := fmt.Sprintf("Filter URL already added -- %s", filter.URL) </s> remove errortext := fmt.Sprintf("Couldn't fetch filter from url %s: %s", url, err) </s> add errortext := fmt.Sprintf("Couldn't fetch filter from url %s: %s", filter.URL, err) </s> remove url, ok := parameters["url"] if !ok { </s> add filter.Enabled = true if len(filter.URL) == 0 { </s> remove errortext := fmt.Sprintf("failed to parse parameters from body: %s", err) log.Println(errortext) http.Error(w, errortext, 400) </s> add httpError(w, http.StatusBadRequest, "Failed to parse request body json: %s", err) </s> remove parameters, err := parseParametersFromBody(r.Body) </s> add filter := filter{} err := json.NewDecoder(r.Body).Decode(&filter)
https://github.com/AdguardTeam/AdGuardHome/commit/751be05a31e8479fb0e8ca318260264466871b16
control.go
keep keep keep keep replace keep keep keep keep keep
<mask> http.Error(w, errortext, http.StatusBadRequest) <mask> return <mask> } <mask> if !ok { <mask> errortext := fmt.Sprintf("Filter at url %s is invalid (maybe it points to blank page?)", url) <mask> log.Println(errortext) <mask> http.Error(w, errortext, http.StatusBadRequest) <mask> return <mask> } <mask> </s> API filtering/add_url -- accept JSON instead of name=value lines </s> remove errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", url) </s> add errortext := fmt.Sprintf("Filter at url %s has no rules (maybe it points to blank page?)", filter.URL) </s> remove filter := &config.Filters[i] if filter.URL == url { errortext := fmt.Sprintf("Filter URL already added -- %s", url) </s> add if config.Filters[i].URL == filter.URL { errortext := fmt.Sprintf("Filter URL already added -- %s", filter.URL) </s> remove if valid := govalidator.IsRequestURL(url); !valid { </s> add if valid := govalidator.IsRequestURL(filter.URL); !valid { </s> remove url, ok := parameters["url"] if !ok { </s> add filter.Enabled = true if len(filter.URL) == 0 { </s> remove errortext := fmt.Sprintf("failed to parse parameters from body: %s", err) log.Println(errortext) http.Error(w, errortext, 400) </s> add httpError(w, http.StatusBadRequest, "Failed to parse request body json: %s", err) </s> remove parameters, err := parseParametersFromBody(r.Body) </s> add filter := filter{} err := json.NewDecoder(r.Body).Decode(&filter)
https://github.com/AdguardTeam/AdGuardHome/commit/751be05a31e8479fb0e8ca318260264466871b16
control.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> export const setRules = (rules) => async (dispatch) => { <mask> dispatch(setRulesRequest()); <mask> try { <mask> const normalizedRules = normalizeRulesTextarea(rules); <mask> await apiClient.setRules(normalizedRules); <mask> dispatch(addSuccessToast('updated_custom_filtering_toast')); <mask> dispatch(setRulesSuccess()); <mask> } catch (error) { <mask> dispatch(addErrorToast({ error })); </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove await apiClient.changeLanguage(lang); </s> add await apiClient.changeLanguage({ language: lang }); </s> remove const language = await apiClient.getCurrentLanguage(); dispatch(getLanguageSuccess(language)); </s> add const langSettings = await apiClient.getCurrentLanguage(); dispatch(getLanguageSuccess(langSettings.language)); </s> remove const activeDhcp = await apiClient.findActiveDhcp(name); </s> add const req = { interface: name, }; const activeDhcp = await apiClient.findActiveDhcp(req); </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded const config = { data: parameter, headers: { 'Content-Type': 'text/plain' }, }; return this.makeRequest(path, method, config); </s> add return this.makeRequest(path, method); </s> remove findActiveDhcp(name) { </s> add findActiveDhcp(req) {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
client/src/actions/filtering.js
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> export const changeLanguage = (lang) => async (dispatch) => { <mask> dispatch(changeLanguageRequest()); <mask> try { <mask> await apiClient.changeLanguage(lang); <mask> dispatch(changeLanguageSuccess()); <mask> } catch (error) { <mask> dispatch(addErrorToast({ error })); <mask> dispatch(changeLanguageFailure()); <mask> } </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove const language = await apiClient.getCurrentLanguage(); dispatch(getLanguageSuccess(language)); </s> add const langSettings = await apiClient.getCurrentLanguage(); dispatch(getLanguageSuccess(langSettings.language)); </s> remove const normalizedRules = normalizeRulesTextarea(rules); </s> add const normalizedRules = { rules: normalizeRulesTextarea(rules)?.split('\n'), }; </s> remove const activeDhcp = await apiClient.findActiveDhcp(name); </s> add const req = { interface: name, }; const activeDhcp = await apiClient.findActiveDhcp(req); </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded const config = { data: parameter, headers: { 'Content-Type': 'text/plain' }, }; return this.makeRequest(path, method, config); </s> add return this.makeRequest(path, method); </s> remove findActiveDhcp(name) { </s> add findActiveDhcp(req) {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
client/src/actions/index.js
keep keep keep keep replace replace keep keep keep keep keep
<mask> <mask> export const getLanguage = () => async (dispatch) => { <mask> dispatch(getLanguageRequest()); <mask> try { <mask> const language = await apiClient.getCurrentLanguage(); <mask> dispatch(getLanguageSuccess(language)); <mask> } catch (error) { <mask> dispatch(addErrorToast({ error })); <mask> dispatch(getLanguageFailure()); <mask> } <mask> }; </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove const normalizedRules = normalizeRulesTextarea(rules); </s> add const normalizedRules = { rules: normalizeRulesTextarea(rules)?.split('\n'), }; </s> remove await apiClient.changeLanguage(lang); </s> add await apiClient.changeLanguage({ language: lang }); </s> remove const activeDhcp = await apiClient.findActiveDhcp(name); </s> add const req = { interface: name, }; const activeDhcp = await apiClient.findActiveDhcp(req); </s> remove findActiveDhcp(name) { </s> add findActiveDhcp(req) { </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded const config = { data: parameter, headers: { 'Content-Type': 'text/plain' }, }; return this.makeRequest(path, method, config); </s> add return this.makeRequest(path, method);
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
client/src/actions/index.js
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> export const findActiveDhcp = (name) => async (dispatch, getState) => { <mask> dispatch(findActiveDhcpRequest()); <mask> try { <mask> const activeDhcp = await apiClient.findActiveDhcp(name); <mask> dispatch(findActiveDhcpSuccess(activeDhcp)); <mask> const { check, interface_name, interfaces } = getState().dhcp; <mask> const selectedInterface = getState().form[FORM_NAME.DHCP_INTERFACES].values.interface_name; <mask> const v4 = check?.v4 ?? { static_ip: {}, other_server: {} }; <mask> const v6 = check?.v6 ?? { other_server: {} }; </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove const language = await apiClient.getCurrentLanguage(); dispatch(getLanguageSuccess(language)); </s> add const langSettings = await apiClient.getCurrentLanguage(); dispatch(getLanguageSuccess(langSettings.language)); </s> remove const normalizedRules = normalizeRulesTextarea(rules); </s> add const normalizedRules = { rules: normalizeRulesTextarea(rules)?.split('\n'), }; </s> remove await apiClient.changeLanguage(lang); </s> add await apiClient.changeLanguage({ language: lang }); </s> remove findActiveDhcp(name) { </s> add findActiveDhcp(req) { </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded const config = { data: parameter, headers: { 'Content-Type': 'text/plain' }, }; return this.makeRequest(path, method, config); </s> add return this.makeRequest(path, method);
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
client/src/actions/index.js
keep keep keep keep replace keep keep keep keep keep
<mask> setRules(rules) { <mask> const { path, method } = this.FILTERING_SET_RULES; <mask> const parameters = { <mask> data: rules, <mask> headers: { 'Content-Type': 'text/plain' }, <mask> }; <mask> return this.makeRequest(path, method, parameters); <mask> } <mask> <mask> setFiltersConfig(config) { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove data: name, headers: { 'Content-Type': 'text/plain' }, </s> add data: req, headers: { 'Content-Type': 'application/json' }, </s> remove data: lang, headers: { 'Content-Type': 'text/plain' }, </s> add data: config, headers: { 'Content-Type': 'application/json' }, </s> remove findActiveDhcp(name) { </s> add findActiveDhcp(req) { </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded const config = { data: parameter, headers: { 'Content-Type': 'text/plain' }, }; return this.makeRequest(path, method, config); </s> add return this.makeRequest(path, method); </s> remove const activeDhcp = await apiClient.findActiveDhcp(name); </s> add const req = { interface: name, }; const activeDhcp = await apiClient.findActiveDhcp(req);
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
client/src/api/Api.js
keep keep keep keep replace replace replace replace replace replace keep keep keep keep keep
<mask> } <mask> <mask> enableParentalControl() { <mask> const { path, method } = this.PARENTAL_ENABLE; <mask> const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded <mask> const config = { <mask> data: parameter, <mask> headers: { 'Content-Type': 'text/plain' }, <mask> }; <mask> return this.makeRequest(path, method, config); <mask> } <mask> <mask> disableParentalControl() { <mask> const { path, method } = this.PARENTAL_DISABLE; <mask> return this.makeRequest(path, method); </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove findActiveDhcp(name) { </s> add findActiveDhcp(req) { </s> remove headers: { 'Content-Type': 'text/plain' }, </s> add headers: { 'Content-Type': 'application/json' }, </s> remove data: name, headers: { 'Content-Type': 'text/plain' }, </s> add data: req, headers: { 'Content-Type': 'application/json' }, </s> remove data: lang, headers: { 'Content-Type': 'text/plain' }, </s> add data: config, headers: { 'Content-Type': 'application/json' }, </s> remove const activeDhcp = await apiClient.findActiveDhcp(name); </s> add const req = { interface: name, }; const activeDhcp = await apiClient.findActiveDhcp(req);
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
client/src/api/Api.js
keep replace keep keep replace replace keep
<mask> <mask> changeLanguage(lang) { <mask> const { path, method } = this.CHANGE_LANGUAGE; <mask> const parameters = { <mask> data: lang, <mask> headers: { 'Content-Type': 'text/plain' }, <mask> }; </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove data: name, headers: { 'Content-Type': 'text/plain' }, </s> add data: req, headers: { 'Content-Type': 'application/json' }, </s> remove headers: { 'Content-Type': 'text/plain' }, </s> add headers: { 'Content-Type': 'application/json' }, </s> remove findActiveDhcp(name) { </s> add findActiveDhcp(req) { </s> remove const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded const config = { data: parameter, headers: { 'Content-Type': 'text/plain' }, }; return this.makeRequest(path, method, config); </s> add return this.makeRequest(path, method); </s> remove const activeDhcp = await apiClient.findActiveDhcp(name); </s> add const req = { interface: name, }; const activeDhcp = await apiClient.findActiveDhcp(req);
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
client/src/api/Api.js
keep keep keep keep replace keep keep replace replace keep keep
<mask> }; <mask> return this.makeRequest(path, method, parameters); <mask> } <mask> <mask> findActiveDhcp(name) { <mask> const { path, method } = this.DHCP_FIND_ACTIVE; <mask> const parameters = { <mask> data: name, <mask> headers: { 'Content-Type': 'text/plain' }, <mask> }; <mask> return this.makeRequest(path, method, parameters); </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove headers: { 'Content-Type': 'text/plain' }, </s> add headers: { 'Content-Type': 'application/json' }, </s> remove data: lang, headers: { 'Content-Type': 'text/plain' }, </s> add data: config, headers: { 'Content-Type': 'application/json' }, </s> remove const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded const config = { data: parameter, headers: { 'Content-Type': 'text/plain' }, }; return this.makeRequest(path, method, config); </s> add return this.makeRequest(path, method); </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove const activeDhcp = await apiClient.findActiveDhcp(name); </s> add const req = { interface: name, }; const activeDhcp = await apiClient.findActiveDhcp(req);
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
client/src/api/Api.js
keep keep keep add keep keep keep keep
<mask> // Package aghhttp provides some common methods to work with HTTP. <mask> package aghhttp <mask> <mask> import ( <mask> "fmt" <mask> "io" <mask> "net/http" <mask> </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove "fmt" "io" </s> add "encoding/json" </s> remove "io" </s> add </s> remove "strings" </s> add </s> add "github.com/AdguardTeam/AdGuardHome/internal/version" </s> add "path" </s> remove "strings" </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/aghhttp/aghhttp.go
keep keep add keep keep keep keep keep
<mask> "io" <mask> "net/http" <mask> <mask> "github.com/AdguardTeam/golibs/log" <mask> ) <mask> <mask> // HTTP scheme constants. <mask> const ( </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove "strings" </s> add </s> remove "fmt" "io" </s> add "encoding/json" </s> remove "io" </s> add </s> add "encoding/json" </s> remove "strings" </s> add </s> remove expire uint32 // expiration time (in seconds) </s> add // expire is the expiration time, in seconds. expire uint32
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/aghhttp/aghhttp.go
keep keep replace keep keep keep replace keep
<mask> "encoding/json" <mask> "fmt" <mask> "io" <mask> "net" <mask> "net/http" <mask> "os" <mask> "strings" <mask> </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove "fmt" "io" </s> add "encoding/json" </s> add "path" </s> remove "strings" </s> add </s> add "encoding/json" </s> add "github.com/AdguardTeam/AdGuardHome/internal/version"
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/dhcpd/http_unix.go
keep replace replace replace replace keep replace replace keep keep keep keep
<mask> <mask> // Perform the following tasks: <mask> // . Search for another DHCP server running <mask> // . Check if a static IP is configured for the network interface <mask> // Respond with results <mask> func (s *server) handleDHCPFindActiveServer(w http.ResponseWriter, r *http.Request) { <mask> // This use of ReadAll is safe, because request's body is now limited. <mask> body, err := io.ReadAll(r.Body) <mask> if err != nil { <mask> msg := fmt.Sprintf("failed to read request body: %s", err) <mask> log.Error(msg) <mask> http.Error(w, msg, http.StatusBadRequest) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove msg := fmt.Sprintf("failed to read request body: %s", err) log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err) </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) if err != nil { msg := fmt.Sprintf("failed to read request body: %s", err) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { </s> remove return } </s> add func handleI18nCurrentLanguage(w http.ResponseWriter, r *http.Request) { log.Printf("home: language is %s", config.Language) _ = aghhttp.WriteJSONResponse(w, r, &languageJSON{ Language: config.Language, }) </s> remove func handleI18nCurrentLanguage(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain") log.Printf("config.Language is %s", config.Language) _, err := fmt.Fprintf(w, "%s\n", config.Language) if err != nil { msg := fmt.Sprintf("Unable to write response json: %s", err) log.Println(msg) http.Error(w, msg, http.StatusInternalServerError) </s> add // languageJSON is the JSON structure for language requests and responses. type languageJSON struct { Language string `json:"language"` } </s> remove ifaceName := strings.TrimSpace(string(body)) </s> add ifaceName := req.Interface
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/dhcpd/http_unix.go
keep keep keep keep replace replace replace keep keep keep keep keep
<mask> func (s *server) handleDHCPFindActiveServer(w http.ResponseWriter, r *http.Request) { <mask> // This use of ReadAll is safe, because request's body is now limited. <mask> body, err := io.ReadAll(r.Body) <mask> if err != nil { <mask> msg := fmt.Sprintf("failed to read request body: %s", err) <mask> log.Error(msg) <mask> http.Error(w, msg, http.StatusBadRequest) <mask> <mask> return <mask> } <mask> <mask> ifaceName := strings.TrimSpace(string(body)) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) if err != nil { msg := fmt.Sprintf("failed to read request body: %s", err) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { return } req := &findActiveServerReq{} err := json.NewDecoder(r.Body).Decode(req) </s> remove return } </s> add func handleI18nCurrentLanguage(w http.ResponseWriter, r *http.Request) { log.Printf("home: language is %s", config.Language) _ = aghhttp.WriteJSONResponse(w, r, &languageJSON{ Language: config.Language, }) </s> remove // Perform the following tasks: // . Search for another DHCP server running // . Check if a static IP is configured for the network interface // Respond with results </s> add // findActiveServerReq is the JSON structure for the request to find active DHCP // servers. type findActiveServerReq struct { Interface string `json:"interface"` } // handleDHCPFindActiveServer performs the following tasks: // 1. searches for another DHCP server in the network; // 2. check if a static IP is configured for the network interface; // 3. responds with the results. </s> remove ifaceName := strings.TrimSpace(string(body)) </s> add ifaceName := req.Interface </s> remove msg := "empty interface name specified" log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "empty interface name")
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/dhcpd/http_unix.go
keep keep keep replace keep replace replace replace
<mask> return <mask> } <mask> <mask> ifaceName := strings.TrimSpace(string(body)) <mask> if ifaceName == "" { <mask> msg := "empty interface name specified" <mask> log.Error(msg) <mask> http.Error(w, msg, http.StatusBadRequest) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove language := strings.TrimSpace(string(body)) if language == "" { msg := "empty language specified" log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add langReq := &languageJSON{} err := json.NewDecoder(r.Body).Decode(langReq) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "reading req: %s", err) </s> remove msg := fmt.Sprintf("failed to read request body: %s", err) log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err) </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) if err != nil { msg := fmt.Sprintf("failed to read request body: %s", err) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { </s> remove if !allowedLanguages.Has(language) { msg := fmt.Sprintf("unknown language specified: %s", language) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add lang := langReq.Language if !allowedLanguages.Has(lang) { aghhttp.Error(r, w, http.StatusBadRequest, "unknown language: %q", lang) </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { return } req := &findActiveServerReq{} err := json.NewDecoder(r.Body).Decode(req)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/dhcpd/http_unix.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> return <mask> } <mask> <mask> result := dhcpSearchResult{ <mask> V4: dhcpSearchV4Result{ <mask> OtherServer: dhcpSearchOtherResult{ <mask> Found: "no", <mask> }, <mask> StaticIP: dhcpStaticIPStatus{ </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove msg := "empty interface name specified" log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "empty interface name") </s> remove headers: { 'Content-Type': 'text/plain' }, </s> add headers: { 'Content-Type': 'application/json' }, </s> remove data: lang, headers: { 'Content-Type': 'text/plain' }, </s> add data: config, headers: { 'Content-Type': 'application/json' }, </s> remove data: name, headers: { 'Content-Type': 'text/plain' }, </s> add data: req, headers: { 'Content-Type': 'application/json' }, </s> remove findActiveDhcp(name) { </s> add findActiveDhcp(req) { </s> remove changeLanguage(lang) { </s> add changeLanguage(config) {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/dhcpd/http_unix.go
keep keep keep add keep keep keep keep keep keep
<mask> // TODO(e.burkov): The returned IP should only be of version 4. <mask> result.V4.StaticIP.IP = aghnet.GetSubnet(ifaceName).String() <mask> } <mask> <mask> found4, found6, err4, err6 := aghnet.CheckOtherDHCP(ifaceName) <mask> if err4 != nil { <mask> result.V4.OtherServer.Found = "error" <mask> result.V4.OtherServer.Error = err4.Error() <mask> } else if found4 { <mask> result.V4.OtherServer.Found = "yes" </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove cookie := r.Header.Get("Cookie") sess := parseCookie(cookie) </s> add respHdr := w.Header() c, err := r.Cookie(sessionCookieName) if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // The user is already logged out. respHdr.Set("Location", "/login.html") w.WriteHeader(http.StatusFound) return } </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add </s> remove w.Header().Set("Content-Type", "application/json") </s> add </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove } else if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, "/login.") { // process as usual // no additional auth requirements } else if Context.auth != nil && Context.auth.AuthRequired() { </s> add log.Debug("auth: invalid cookie value: %s", cookie) } } else if isPublicResource(p) { // Process as usual, no additional auth requirements. } else if authRequired {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/dhcpd/http_unix.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
<mask> result.V6.OtherServer.Error = err6.Error() <mask> } else if found6 { <mask> result.V6.OtherServer.Found = "yes" <mask> } <mask> <mask> w.Header().Set("Content-Type", "application/json") <mask> err = json.NewEncoder(w).Encode(result) <mask> if err != nil { <mask> aghhttp.Error( <mask> r, <mask> w, <mask> http.StatusInternalServerError, <mask> "Failed to marshal DHCP found json: %s", <mask> err, <mask> ) <mask> } <mask> } <mask> <mask> func (s *server) handleDHCPAddStaticLease(w http.ResponseWriter, r *http.Request) { <mask> l := &Lease{} <mask> err := json.NewDecoder(r.Body).Decode(l) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove err := json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal json with TLS status: %s", err, ) } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") </s> add </s> remove msg := fmt.Sprintf("failed to read request body: %s", err) log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/dhcpd/http_unix.go
keep keep add keep keep keep keep keep
<mask> "fmt" <mask> "net" <mask> "net/http" <mask> "strconv" <mask> "strings" <mask> "sync" <mask> "time" <mask> </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove "io" </s> add </s> remove "strings" </s> add </s> remove "strings" </s> add </s> remove "fmt" "io" </s> add "encoding/json" </s> add "encoding/json" </s> add "github.com/AdguardTeam/golibs/errors"
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep add keep keep keep keep
<mask> "time" <mask> <mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" <mask> "github.com/AdguardTeam/golibs/log" <mask> "github.com/AdguardTeam/golibs/netutil" <mask> "github.com/AdguardTeam/golibs/timeutil" <mask> "go.etcd.io/bbolt" </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove "strings" </s> add </s> remove "fmt" "io" </s> add "encoding/json" </s> add "path" </s> remove "strings" </s> add </s> add "github.com/AdguardTeam/AdGuardHome/internal/version" </s> remove return "", err </s> add return nil, fmt.Errorf("generating token: %w", err)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep keep keep keep
<mask> const sessionTokenSize = 16 <mask> <mask> type session struct { <mask> userName string <mask> expire uint32 // expiration time (in seconds) <mask> } <mask> <mask> func (s *session) serialize() []byte { <mask> const ( <mask> expireLen = 4 </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove db *bbolt.DB blocker *authRateLimiter sessions map[string]*session users []User lock sync.Mutex sessionTTL uint32 </s> add db *bbolt.DB raleLimiter *authRateLimiter sessions map[string]*session users []webUser lock sync.Mutex sessionTTL uint32 </s> remove // User object type User struct { </s> add // webUser represents a user of the Web UI. type webUser struct { </s> remove PasswordHash string `yaml:"password"` // bcrypt hash </s> add PasswordHash string `yaml:"password"` </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded const config = { data: parameter, headers: { 'Content-Type': 'text/plain' }, }; return this.makeRequest(path, method, config); </s> add return this.makeRequest(path, method); </s> remove const activeDhcp = await apiClient.findActiveDhcp(name); </s> add const req = { interface: name, }; const activeDhcp = await apiClient.findActiveDhcp(req);
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep replace replace replace replace replace replace keep keep replace replace keep keep
<mask> <mask> // Auth - global object <mask> type Auth struct { <mask> db *bbolt.DB <mask> blocker *authRateLimiter <mask> sessions map[string]*session <mask> users []User <mask> lock sync.Mutex <mask> sessionTTL uint32 <mask> } <mask> <mask> // User object <mask> type User struct { <mask> Name string `yaml:"name"` <mask> PasswordHash string `yaml:"password"` // bcrypt hash </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove PasswordHash string `yaml:"password"` // bcrypt hash </s> add PasswordHash string `yaml:"password"` </s> remove func InitAuth(dbFilename string, users []User, sessionTTL uint32, blocker *authRateLimiter) *Auth { </s> add func InitAuth(dbFilename string, users []webUser, sessionTTL uint32, rateLimiter *authRateLimiter) *Auth { </s> remove expire uint32 // expiration time (in seconds) </s> add // expire is the expiration time, in seconds. expire uint32 </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove handler(w, r) </s> add h(w, r)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep replace keep keep keep replace keep
<mask> // User object <mask> type User struct { <mask> Name string `yaml:"name"` <mask> PasswordHash string `yaml:"password"` // bcrypt hash <mask> } <mask> <mask> // InitAuth - create a global object <mask> func InitAuth(dbFilename string, users []User, sessionTTL uint32, blocker *authRateLimiter) *Auth { <mask> log.Info("Initializing auth module: %s", dbFilename) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove // User object type User struct { </s> add // webUser represents a user of the Web UI. type webUser struct { </s> remove db *bbolt.DB blocker *authRateLimiter sessions map[string]*session users []User lock sync.Mutex sessionTTL uint32 </s> add db *bbolt.DB raleLimiter *authRateLimiter sessions map[string]*session users []webUser lock sync.Mutex sessionTTL uint32 </s> remove sessionTTL: sessionTTL, blocker: blocker, sessions: make(map[string]*session), users: users, </s> add sessionTTL: sessionTTL, raleLimiter: rateLimiter, sessions: make(map[string]*session), users: users, </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove expire uint32 // expiration time (in seconds) </s> add // expire is the expiration time, in seconds. expire uint32
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace replace replace replace keep keep keep keep keep
<mask> func InitAuth(dbFilename string, users []User, sessionTTL uint32, blocker *authRateLimiter) *Auth { <mask> log.Info("Initializing auth module: %s", dbFilename) <mask> <mask> a := &Auth{ <mask> sessionTTL: sessionTTL, <mask> blocker: blocker, <mask> sessions: make(map[string]*session), <mask> users: users, <mask> } <mask> var err error <mask> a.db, err = bbolt.Open(dbFilename, 0o644, nil) <mask> if err != nil { <mask> log.Error("auth: open DB: %s: %s", dbFilename, err) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove func InitAuth(dbFilename string, users []User, sessionTTL uint32, blocker *authRateLimiter) *Auth { </s> add func InitAuth(dbFilename string, users []webUser, sessionTTL uint32, rateLimiter *authRateLimiter) *Auth { </s> remove PasswordHash string `yaml:"password"` // bcrypt hash </s> add PasswordHash string `yaml:"password"` </s> remove var sess []byte sess, err = newSessionToken() </s> add sess, err := newSessionToken() </s> remove if blocker != nil { blocker.remove(addr) </s> add if rateLimiter != nil { rateLimiter.remove(addr) </s> remove var cookie string cookie, err = Context.auth.httpCookie(req, remoteAddr) </s> add cookie, err := Context.auth.newCookie(req, remoteAddr) </s> remove u := User{ </s> add u := webUser{
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace keep keep replace keep keep
<mask> <mask> return randData, nil <mask> } <mask> <mask> // cookieTimeFormat is the format to be used in (time.Time).Format for cookie's <mask> // expiry field. <mask> const cookieTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" <mask> <mask> // cookieExpiryFormat returns the formatted exp to be used in cookie string. <mask> // It's quite simple for now, but probably will be expanded in the future. <mask> func cookieExpiryFormat(exp time.Time) (formatted string) { <mask> return exp.Format(cookieTimeFormat) <mask> } <mask> <mask> func (a *Auth) httpCookie(req loginJSON, addr string) (cookie string, err error) { <mask> blocker := a.blocker <mask> u := a.UserFind(req.Name, req.Password) <mask> if len(u.Name) == 0 { <mask> if blocker != nil { <mask> blocker.inc(addr) <mask> } <mask> <mask> return "", err <mask> } <mask> </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove func (a *Auth) UserAdd(u *User, password string) { </s> add func (a *Auth) UserAdd(u *webUser, password string) { </s> remove return User{} </s> add return webUser{}, false </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove // UserFind - find a user func (a *Auth) UserFind(login, password string) User { </s> add // findUser returns a user if there is one. func (a *Auth) findUser(login, password string) (u webUser, ok bool) { </s> add setOtherDHCPResult(ifaceName, result) _ = aghhttp.WriteJSONResponse(w, r, result) } // setOtherDHCPResult sets the results of the check for another DHCP server in // result. func setOtherDHCPResult(ifaceName string, result *dhcpSearchResult) {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep replace replace keep keep replace replace keep keep keep
<mask> return "", err <mask> } <mask> <mask> if blocker != nil { <mask> blocker.remove(addr) <mask> } <mask> <mask> var sess []byte <mask> sess, err = newSessionToken() <mask> if err != nil { <mask> return "", err <mask> } </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove return "", err </s> add return nil, fmt.Errorf("generating token: %w", err) </s> remove return "", err </s> add return nil, errors.Error("invalid username or password") </s> remove var cookie string cookie, err = Context.auth.httpCookie(req, remoteAddr) </s> add cookie, err := Context.auth.newCookie(req, remoteAddr) </s> remove // cookieTimeFormat is the format to be used in (time.Time).Format for cookie's // expiry field. const cookieTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" // cookieExpiryFormat returns the formatted exp to be used in cookie string. // It's quite simple for now, but probably will be expanded in the future. func cookieExpiryFormat(exp time.Time) (formatted string) { return exp.Format(cookieTimeFormat) } func (a *Auth) httpCookie(req loginJSON, addr string) (cookie string, err error) { blocker := a.blocker u := a.UserFind(req.Name, req.Password) if len(u.Name) == 0 { if blocker != nil { blocker.inc(addr) </s> add // newCookie creates a new authentication cookie. func (a *Auth) newCookie(req loginJSON, addr string) (c *http.Cookie, err error) { rateLimiter := a.raleLimiter u, ok := a.findUser(req.Name, req.Password) if !ok { if rateLimiter != nil { rateLimiter.inc(addr) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> var sess []byte <mask> sess, err = newSessionToken() <mask> if err != nil { <mask> return "", err <mask> } <mask> <mask> now := time.Now().UTC() <mask> <mask> a.addSession(sess, &session{ </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove var sess []byte sess, err = newSessionToken() </s> add sess, err := newSessionToken() </s> remove if blocker != nil { blocker.remove(addr) </s> add if rateLimiter != nil { rateLimiter.remove(addr) </s> remove return "", err </s> add return nil, errors.Error("invalid username or password") </s> remove var cookie string cookie, err = Context.auth.httpCookie(req, remoteAddr) </s> add cookie, err := Context.auth.newCookie(req, remoteAddr) </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) if err != nil { msg := fmt.Sprintf("failed to read request body: %s", err) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { </s> remove cookie := r.Header.Get("Cookie") sess := parseCookie(cookie) </s> add respHdr := w.Header() c, err := r.Cookie(sessionCookieName) if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // The user is already logged out. respHdr.Set("Location", "/login.html") w.WriteHeader(http.StatusFound) return }
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace replace replace replace replace keep keep keep keep keep
<mask> userName: u.Name, <mask> expire: uint32(now.Unix()) + a.sessionTTL, <mask> }) <mask> <mask> return fmt.Sprintf( <mask> "%s=%s; Path=/; HttpOnly; Expires=%s", <mask> sessionCookieName, hex.EncodeToString(sess), <mask> cookieExpiryFormat(now.Add(cookieTTL)), <mask> ), nil <mask> } <mask> <mask> // realIP extracts the real IP address of the client from an HTTP request using <mask> // the known HTTP headers. <mask> // </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove BindHost net.IP `yaml:"bind_host"` // BindHost is the IP address of the HTTP server to bind to BindPort int `yaml:"bind_port"` // BindPort is the port the HTTP server BetaBindPort int `yaml:"beta_bind_port"` // BetaBindPort is the port for new client Users []User `yaml:"users"` // Users that can access HTTP server </s> add BindHost net.IP `yaml:"bind_host"` // BindHost is the IP address of the HTTP server to bind to BindPort int `yaml:"bind_port"` // BindPort is the port the HTTP server BetaBindPort int `yaml:"beta_bind_port"` // BetaBindPort is the port for new client Users []webUser `yaml:"users"` // Users that can access HTTP server </s> remove // Perform the following tasks: // . Search for another DHCP server running // . Check if a static IP is configured for the network interface // Respond with results </s> add // findActiveServerReq is the JSON structure for the request to find active DHCP // servers. type findActiveServerReq struct { Interface string `json:"interface"` } // handleDHCPFindActiveServer performs the following tasks: // 1. searches for another DHCP server in the network; // 2. check if a static IP is configured for the network interface; // 3. responds with the results. </s> remove return User{} </s> add return webUser{}, false </s> remove aghhttp.Error(r, w, http.StatusBadRequest, "crypto rand reader: %s", err) </s> add aghhttp.Error(r, w, http.StatusForbidden, "%s", err) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace replace keep keep keep keep keep
<mask> <mask> return <mask> } <mask> <mask> if blocker := Context.auth.blocker; blocker != nil { <mask> if left := blocker.check(remoteAddr); left > 0 { <mask> w.Header().Set("Retry-After", strconv.Itoa(int(left.Seconds()))) <mask> aghhttp.Error(r, w, http.StatusTooManyRequests, "auth: blocked for %s", left) <mask> <mask> return <mask> } </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove return "", err </s> add return nil, errors.Error("invalid username or password") </s> remove var sess []byte sess, err = newSessionToken() </s> add sess, err := newSessionToken() </s> remove language := strings.TrimSpace(string(body)) if language == "" { msg := "empty language specified" log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add langReq := &languageJSON{} err := json.NewDecoder(r.Body).Decode(langReq) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "reading req: %s", err) </s> remove if !allowedLanguages.Has(language) { msg := fmt.Sprintf("unknown language specified: %s", language) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add lang := langReq.Language if !allowedLanguages.Has(lang) { aghhttp.Error(r, w, http.StatusBadRequest, "unknown language: %q", lang) </s> remove if blocker != nil { blocker.remove(addr) </s> add if rateLimiter != nil { rateLimiter.remove(addr) </s> remove // cookieTimeFormat is the format to be used in (time.Time).Format for cookie's // expiry field. const cookieTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" // cookieExpiryFormat returns the formatted exp to be used in cookie string. // It's quite simple for now, but probably will be expanded in the future. func cookieExpiryFormat(exp time.Time) (formatted string) { return exp.Format(cookieTimeFormat) } func (a *Auth) httpCookie(req loginJSON, addr string) (cookie string, err error) { blocker := a.blocker u := a.UserFind(req.Name, req.Password) if len(u.Name) == 0 { if blocker != nil { blocker.inc(addr) </s> add // newCookie creates a new authentication cookie. func (a *Auth) newCookie(req loginJSON, addr string) (c *http.Cookie, err error) { rateLimiter := a.raleLimiter u, ok := a.findUser(req.Name, req.Password) if !ok { if rateLimiter != nil { rateLimiter.inc(addr)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace replace keep keep keep keep keep
<mask> return <mask> } <mask> } <mask> <mask> var cookie string <mask> cookie, err = Context.auth.httpCookie(req, remoteAddr) <mask> if err != nil { <mask> aghhttp.Error(r, w, http.StatusBadRequest, "crypto rand reader: %s", err) <mask> <mask> return <mask> } </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove aghhttp.Error(r, w, http.StatusBadRequest, "crypto rand reader: %s", err) </s> add aghhttp.Error(r, w, http.StatusForbidden, "%s", err) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove language := strings.TrimSpace(string(body)) if language == "" { msg := "empty language specified" log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add langReq := &languageJSON{} err := json.NewDecoder(r.Body).Decode(langReq) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "reading req: %s", err) </s> remove if !allowedLanguages.Has(language) { msg := fmt.Sprintf("unknown language specified: %s", language) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add lang := langReq.Language if !allowedLanguages.Has(lang) { aghhttp.Error(r, w, http.StatusBadRequest, "unknown language: %q", lang) </s> remove msg := fmt.Sprintf("failed to read request body: %s", err) log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err) </s> remove if blocker != nil { blocker.remove(addr) </s> add if rateLimiter != nil { rateLimiter.remove(addr)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> var cookie string <mask> cookie, err = Context.auth.httpCookie(req, remoteAddr) <mask> if err != nil { <mask> aghhttp.Error(r, w, http.StatusBadRequest, "crypto rand reader: %s", err) <mask> <mask> return <mask> } <mask> <mask> // Use realIP here, since this IP address is only used for logging. </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove var cookie string cookie, err = Context.auth.httpCookie(req, remoteAddr) </s> add cookie, err := Context.auth.newCookie(req, remoteAddr) </s> remove msg := fmt.Sprintf("failed to read request body: %s", err) log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove language := strings.TrimSpace(string(body)) if language == "" { msg := "empty language specified" log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add langReq := &languageJSON{} err := json.NewDecoder(r.Body).Decode(langReq) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "reading req: %s", err) </s> remove w.Header().Set("Content-Type", "application/json") err := json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't write response: %s", err) } </s> add _ = aghhttp.WriteJSONResponse(w, r, data)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
<mask> // Technically shouldn't happen. <mask> log.Error("auth: unknown ip") <mask> } <mask> <mask> if len(cookie) == 0 { <mask> log.Info("auth: failed to login user %q from ip %v", req.Name, ip) <mask> <mask> time.Sleep(1 * time.Second) <mask> <mask> http.Error(w, "invalid username or password", http.StatusBadRequest) <mask> <mask> return <mask> } <mask> <mask> log.Info("auth: user %q successfully logged in from ip %v", req.Name, ip) <mask> <mask> h := w.Header() <mask> h.Set("Set-Cookie", cookie) <mask> h.Set("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate") </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove h.Set("Set-Cookie", cookie) </s> add </s> add http.SetCookie(w, cookie) </s> remove cookie := r.Header.Get("Cookie") sess := parseCookie(cookie) </s> add respHdr := w.Header() c, err := r.Cookie(sessionCookieName) if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // The user is already logged out. respHdr.Set("Location", "/login.html") w.WriteHeader(http.StatusFound) return } </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> add } else { res := Context.auth.checkSession(cookie.Value) isAuthenticated = res == checkSessionOK if !isAuthenticated { log.Debug("auth: invalid cookie value: %s", cookie) } </s> remove if !ok { if r.URL.Path == "/" || r.URL.Path == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) } </s> add if isAuthenticated { return false } if p := r.URL.Path; p == "/" || p == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule")
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep add keep keep keep keep keep keep
<mask> } <mask> <mask> log.Info("auth: user %q successfully logged in from ip %v", req.Name, ip) <mask> <mask> h := w.Header() <mask> h.Set("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate") <mask> h.Set("Pragma", "no-cache") <mask> h.Set("Expires", "0") <mask> <mask> aghhttp.OK(w) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove h.Set("Set-Cookie", cookie) </s> add </s> remove if len(cookie) == 0 { log.Info("auth: failed to login user %q from ip %v", req.Name, ip) time.Sleep(1 * time.Second) http.Error(w, "invalid username or password", http.StatusBadRequest) return } </s> add </s> remove cookie := r.Header.Get("Cookie") sess := parseCookie(cookie) </s> add respHdr := w.Header() c, err := r.Cookie(sessionCookieName) if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // The user is already logged out. respHdr.Set("Location", "/login.html") w.WriteHeader(http.StatusFound) return } </s> add } else { res := Context.auth.checkSession(cookie.Value) isAuthenticated = res == checkSessionOK if !isAuthenticated { log.Debug("auth: invalid cookie value: %s", cookie) } </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove w.Header().Set("Content-Type", "application/json") </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> log.Info("auth: user %q successfully logged in from ip %v", req.Name, ip) <mask> <mask> h := w.Header() <mask> h.Set("Set-Cookie", cookie) <mask> h.Set("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate") <mask> h.Set("Pragma", "no-cache") <mask> h.Set("Expires", "0") <mask> <mask> aghhttp.OK(w) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> add http.SetCookie(w, cookie) </s> remove if len(cookie) == 0 { log.Info("auth: failed to login user %q from ip %v", req.Name, ip) time.Sleep(1 * time.Second) http.Error(w, "invalid username or password", http.StatusBadRequest) return } </s> add </s> remove cookie := r.Header.Get("Cookie") sess := parseCookie(cookie) </s> add respHdr := w.Header() c, err := r.Cookie(sessionCookieName) if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // The user is already logged out. respHdr.Set("Location", "/login.html") w.WriteHeader(http.StatusFound) return } </s> add } else { res := Context.auth.checkSession(cookie.Value) isAuthenticated = res == checkSessionOK if !isAuthenticated { log.Debug("auth: invalid cookie value: %s", cookie) } </s> remove user := User{Name: "name"} </s> add user := webUser{Name: "name"} </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep replace replace keep replace keep
<mask> } <mask> <mask> func handleLogout(w http.ResponseWriter, r *http.Request) { <mask> cookie := r.Header.Get("Cookie") <mask> sess := parseCookie(cookie) <mask> <mask> Context.auth.RemoveSession(sess) <mask> </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove w.Header().Set("Location", "/login.html") </s> add c = &http.Cookie{ Name: sessionCookieName, Value: "", Path: "/", Expires: time.Unix(0, 0), </s> remove func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { authFirst = false </s> add func optionalAuthThird(w http.ResponseWriter, r *http.Request) (mustAuth bool) { if glProcessCookie(r) { log.Debug("auth: authentication is handled by GL-Inet submodule") return false } </s> remove return } </s> add func handleI18nCurrentLanguage(w http.ResponseWriter, r *http.Request) { log.Printf("home: language is %s", config.Language) _ = aghhttp.WriteJSONResponse(w, r, &languageJSON{ Language: config.Language, }) </s> remove if r.URL.Path == "/login.html" { // redirect to dashboard if already authenticated authRequired := Context.auth != nil && Context.auth.AuthRequired() </s> add p := r.URL.Path authRequired := Context.auth != nil && Context.auth.AuthRequired() if p == "/login.html" { </s> remove w.Header().Set("Content-Type", "application/json") </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep replace replace replace keep
<mask> sess := parseCookie(cookie) <mask> <mask> Context.auth.RemoveSession(sess) <mask> <mask> w.Header().Set("Location", "/login.html") <mask> <mask> s := fmt.Sprintf("%s=; Path=/; HttpOnly; Expires=Thu, 01 Jan 1970 00:00:00 GMT", <mask> sessionCookieName) <mask> w.Header().Set("Set-Cookie", s) <mask> </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove Context.auth.RemoveSession(sess) </s> add Context.auth.RemoveSession(c.Value) </s> remove cookie := r.Header.Get("Cookie") sess := parseCookie(cookie) </s> add respHdr := w.Header() c, err := r.Cookie(sessionCookieName) if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // The user is already logged out. respHdr.Set("Location", "/login.html") w.WriteHeader(http.StatusFound) return } </s> remove w.WriteHeader(http.StatusForbidden) _, _ = w.Write([]byte("Forbidden")) </s> add log.Debug("auth: redirected to login page") w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) </s> remove user := User{Name: "name"} </s> add user := webUser{Name: "name"} </s> remove users := []User{{ </s> add users := []webUser{{
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep add keep keep keep keep
<mask> SameSite: http.SameSiteLaxMode, <mask> } <mask> <mask> w.WriteHeader(http.StatusFound) <mask> } <mask> <mask> // RegisterAuthHandlers - register handlers </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove s := fmt.Sprintf("%s=; Path=/; HttpOnly; Expires=Thu, 01 Jan 1970 00:00:00 GMT", sessionCookieName) w.Header().Set("Set-Cookie", s) </s> add HttpOnly: true, SameSite: http.SameSiteLaxMode, } </s> remove w.WriteHeader(http.StatusForbidden) _, _ = w.Write([]byte("Forbidden")) </s> add log.Debug("auth: redirected to login page") w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) </s> remove return fmt.Sprintf( "%s=%s; Path=/; HttpOnly; Expires=%s", sessionCookieName, hex.EncodeToString(sess), cookieExpiryFormat(now.Add(cookieTTL)), ), nil </s> add return &http.Cookie{ Name: sessionCookieName, Value: hex.EncodeToString(sess), Path: "/", Expires: now.Add(cookieTTL), HttpOnly: true, SameSite: http.SameSiteLaxMode, }, nil </s> remove } else if r == checkSessionNotFound { log.Debug("auth: invalid cookie value: %s", cookie) </s> add </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove return User{} </s> add return webUser{}
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace keep replace replace
<mask> Context.mux.Handle("/control/login", postInstallHandler(ensureHandler(http.MethodPost, handleLogin))) <mask> httpRegister(http.MethodGet, "/control/logout", handleLogout) <mask> } <mask> <mask> func parseCookie(cookie string) string { <mask> pairs := strings.Split(cookie, ";") <mask> for _, pair := range pairs { <mask> pair = strings.TrimSpace(pair) <mask> kv := strings.SplitN(pair, "=", 2) <mask> if len(kv) != 2 { <mask> continue <mask> } <mask> if kv[0] == sessionCookieName { <mask> return kv[1] <mask> } <mask> } <mask> return "" <mask> } <mask> <mask> // optionalAuthThird return true if user should authenticate first. <mask> func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { <mask> authFirst = false </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove return authFirst </s> add return true </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove ok := false </s> add isAuthenticated := false </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove return u </s> add return u, true
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep keep keep keep
<mask> func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { <mask> authFirst = false <mask> <mask> // redirect to login page if not authenticated <mask> ok := false <mask> cookie, err := r.Cookie(sessionCookieName) <mask> <mask> if glProcessCookie(r) { <mask> log.Debug("auth: authentication was handled by GL-Inet submodule") <mask> ok = true </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { authFirst = false </s> add func optionalAuthThird(w http.ResponseWriter, r *http.Request) (mustAuth bool) { if glProcessCookie(r) { log.Debug("auth: authentication is handled by GL-Inet submodule") return false } </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove func parseCookie(cookie string) string { pairs := strings.Split(cookie, ";") for _, pair := range pairs { pair = strings.TrimSpace(pair) kv := strings.SplitN(pair, "=", 2) if len(kv) != 2 { continue } if kv[0] == sessionCookieName { return kv[1] } } return "" } </s> add </s> remove if !ok { if r.URL.Path == "/" || r.URL.Path == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) } </s> add if isAuthenticated { return false } if p := r.URL.Path; p == "/" || p == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") </s> remove func optionalAuth(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { </s> add // TODO(a.garipov): Use [http.Handler] consistently everywhere throughout the // project. func optionalAuth( h func(http.ResponseWriter, *http.Request), ) (wrapped func(http.ResponseWriter, *http.Request)) { </s> remove if r.URL.Path == "/login.html" { // redirect to dashboard if already authenticated authRequired := Context.auth != nil && Context.auth.AuthRequired() </s> add p := r.URL.Path authRequired := Context.auth != nil && Context.auth.AuthRequired() if p == "/login.html" {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
<mask> <mask> // redirect to login page if not authenticated <mask> ok := false <mask> cookie, err := r.Cookie(sessionCookieName) <mask> <mask> if glProcessCookie(r) { <mask> log.Debug("auth: authentication was handled by GL-Inet submodule") <mask> ok = true <mask> } else if err == nil { <mask> r := Context.auth.checkSession(cookie.Value) <mask> if r == checkSessionOK { <mask> ok = true <mask> } else if r < 0 { <mask> log.Debug("auth: invalid cookie value: %s", cookie) <mask> } <mask> } else { <mask> // there's no Cookie, check Basic authentication <mask> user, pass, ok2 := r.BasicAuth() <mask> if ok2 { <mask> u := Context.auth.UserFind(user, pass) <mask> if len(u.Name) != 0 { <mask> ok = true <mask> } else { <mask> log.Info("auth: invalid Basic Authorization value") <mask> } <mask> } <mask> } <mask> if !ok { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove ok := false </s> add isAuthenticated := false </s> add } else { res := Context.auth.checkSession(cookie.Value) isAuthenticated = res == checkSessionOK if !isAuthenticated { log.Debug("auth: invalid cookie value: %s", cookie) } </s> remove if !ok { if r.URL.Path == "/" || r.URL.Path == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) } </s> add if isAuthenticated { return false } if p := r.URL.Path; p == "/" || p == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") </s> remove func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { authFirst = false </s> add func optionalAuthThird(w http.ResponseWriter, r *http.Request) (mustAuth bool) { if glProcessCookie(r) { log.Debug("auth: authentication is handled by GL-Inet submodule") return false } </s> remove return Context.auth.UserFind(user, pass) </s> add u, _ = Context.auth.findUser(user, pass) return u </s> remove } else if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, "/login.") { // process as usual // no additional auth requirements } else if Context.auth != nil && Context.auth.AuthRequired() { </s> add log.Debug("auth: invalid cookie value: %s", cookie) } } else if isPublicResource(p) { // Process as usual, no additional auth requirements. } else if authRequired {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep add keep keep keep keep
<mask> log.Info("auth: invalid Basic Authorization value") <mask> } <mask> } <mask> } <mask> <mask> if isAuthenticated { <mask> return false </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove if !ok { if r.URL.Path == "/" || r.URL.Path == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) } </s> add if isAuthenticated { return false } if p := r.URL.Path; p == "/" || p == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove } else if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, "/login.") { // process as usual // no additional auth requirements } else if Context.auth != nil && Context.auth.AuthRequired() { </s> add log.Debug("auth: invalid cookie value: %s", cookie) } } else if isPublicResource(p) { // Process as usual, no additional auth requirements. } else if authRequired { </s> remove } else if r == checkSessionNotFound { log.Debug("auth: invalid cookie value: %s", cookie) </s> add </s> remove } </s> add </s> remove return Context.auth.UserFind(user, pass) </s> add u, _ = Context.auth.findUser(user, pass) return u
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep replace replace replace replace replace replace replace replace keep replace replace keep keep
<mask> } <mask> if !ok { <mask> if r.URL.Path == "/" || r.URL.Path == "/index.html" { <mask> if glProcessRedirect(w, r) { <mask> log.Debug("auth: redirected to login page by GL-Inet submodule") <mask> } else { <mask> w.Header().Set("Location", "/login.html") <mask> w.WriteHeader(http.StatusFound) <mask> } <mask> } else { <mask> w.WriteHeader(http.StatusForbidden) <mask> _, _ = w.Write([]byte("Forbidden")) <mask> } <mask> authFirst = true </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove authFirst = true </s> add } else { log.Debug("auth: responded with forbidden to %s %s", r.Method, p) w.WriteHeader(http.StatusForbidden) _, _ = w.Write([]byte("Forbidden")) </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove } else if r == checkSessionNotFound { log.Debug("auth: invalid cookie value: %s", cookie) </s> add </s> remove return authFirst </s> add return true </s> remove } else if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, "/login.") { // process as usual // no additional auth requirements } else if Context.auth != nil && Context.auth.AuthRequired() { </s> add log.Debug("auth: invalid cookie value: %s", cookie) } } else if isPublicResource(p) { // Process as usual, no additional auth requirements. } else if authRequired {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep replace keep keep replace keep keep keep keep
<mask> _, _ = w.Write([]byte("Forbidden")) <mask> } <mask> authFirst = true <mask> } <mask> <mask> return authFirst <mask> } <mask> <mask> func optionalAuth(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { <mask> return func(w http.ResponseWriter, r *http.Request) { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove func optionalAuth(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { </s> add // TODO(a.garipov): Use [http.Handler] consistently everywhere throughout the // project. func optionalAuth( h func(http.ResponseWriter, *http.Request), ) (wrapped func(http.ResponseWriter, *http.Request)) { </s> remove if r.URL.Path == "/login.html" { // redirect to dashboard if already authenticated authRequired := Context.auth != nil && Context.auth.AuthRequired() </s> add p := r.URL.Path authRequired := Context.auth != nil && Context.auth.AuthRequired() if p == "/login.html" { </s> remove w.WriteHeader(http.StatusForbidden) _, _ = w.Write([]byte("Forbidden")) </s> add log.Debug("auth: redirected to login page") w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) </s> remove func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { authFirst = false </s> add func optionalAuthThird(w http.ResponseWriter, r *http.Request) (mustAuth bool) { if glProcessCookie(r) { log.Debug("auth: authentication is handled by GL-Inet submodule") return false } </s> remove func parseCookie(cookie string) string { pairs := strings.Split(cookie, ";") for _, pair := range pairs { pair = strings.TrimSpace(pair) kv := strings.SplitN(pair, "=", 2) if len(kv) != 2 { continue } if kv[0] == sessionCookieName { return kv[1] } } return "" } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep replace keep replace replace replace keep keep keep keep
<mask> } <mask> <mask> func optionalAuth(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { <mask> return func(w http.ResponseWriter, r *http.Request) { <mask> if r.URL.Path == "/login.html" { <mask> // redirect to dashboard if already authenticated <mask> authRequired := Context.auth != nil && Context.auth.AuthRequired() <mask> cookie, err := r.Cookie(sessionCookieName) <mask> if authRequired && err == nil { <mask> r := Context.auth.checkSession(cookie.Value) <mask> if r == checkSessionOK { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { </s> add // Redirect to the dashboard if already authenticated. res := Context.auth.checkSession(cookie.Value) if res == checkSessionOK { </s> remove return authFirst </s> add return true </s> remove func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { authFirst = false </s> add func optionalAuthThird(w http.ResponseWriter, r *http.Request) (mustAuth bool) { if glProcessCookie(r) { log.Debug("auth: authentication is handled by GL-Inet submodule") return false } </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove ok := false </s> add isAuthenticated := false
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace replace keep keep keep keep replace replace keep keep
<mask> // redirect to dashboard if already authenticated <mask> authRequired := Context.auth != nil && Context.auth.AuthRequired() <mask> cookie, err := r.Cookie(sessionCookieName) <mask> if authRequired && err == nil { <mask> r := Context.auth.checkSession(cookie.Value) <mask> if r == checkSessionOK { <mask> w.Header().Set("Location", "/") <mask> w.WriteHeader(http.StatusFound) <mask> <mask> return <mask> } else if r == checkSessionNotFound { <mask> log.Debug("auth: invalid cookie value: %s", cookie) <mask> } <mask> } </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove if r.URL.Path == "/login.html" { // redirect to dashboard if already authenticated authRequired := Context.auth != nil && Context.auth.AuthRequired() </s> add p := r.URL.Path authRequired := Context.auth != nil && Context.auth.AuthRequired() if p == "/login.html" { </s> remove func optionalAuth(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { </s> add // TODO(a.garipov): Use [http.Handler] consistently everywhere throughout the // project. func optionalAuth( h func(http.ResponseWriter, *http.Request), ) (wrapped func(http.ResponseWriter, *http.Request)) { </s> remove } else if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, "/login.") { // process as usual // no additional auth requirements } else if Context.auth != nil && Context.auth.AuthRequired() { </s> add log.Debug("auth: invalid cookie value: %s", cookie) } } else if isPublicResource(p) { // Process as usual, no additional auth requirements. } else if authRequired { </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> add } else { res := Context.auth.checkSession(cookie.Value) isAuthenticated = res == checkSessionOK if !isAuthenticated { log.Debug("auth: invalid cookie value: %s", cookie) }
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep replace keep replace replace replace replace replace keep
<mask> log.Debug("auth: invalid cookie value: %s", cookie) <mask> } <mask> } <mask> <mask> } else if strings.HasPrefix(r.URL.Path, "/assets/") || <mask> strings.HasPrefix(r.URL.Path, "/login.") { <mask> // process as usual <mask> // no additional auth requirements <mask> } else if Context.auth != nil && Context.auth.AuthRequired() { <mask> if optionalAuthThird(w, r) { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove } else if r == checkSessionNotFound { log.Debug("auth: invalid cookie value: %s", cookie) </s> add </s> add } else { res := Context.auth.checkSession(cookie.Value) isAuthenticated = res == checkSessionOK if !isAuthenticated { log.Debug("auth: invalid cookie value: %s", cookie) } </s> remove if !ok { if r.URL.Path == "/" || r.URL.Path == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) } </s> add if isAuthenticated { return false } if p := r.URL.Path; p == "/" || p == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { </s> add // Redirect to the dashboard if already authenticated. res := Context.auth.checkSession(cookie.Value) if res == checkSessionOK {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep keep keep keep
<mask> return <mask> } <mask> } <mask> <mask> handler(w, r) <mask> } <mask> } <mask> <mask> type authHandler struct { <mask> handler http.Handler </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> add if r.Header.Get(aghhttp.HdrNameContentType) != aghhttp.HdrValApplicationJSON { aghhttp.Error( r, w, http.StatusUnsupportedMediaType, "only %s is allowed", aghhttp.HdrValApplicationJSON, ) return } </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove // User object type User struct { </s> add // webUser represents a user of the Web UI. type webUser struct { </s> remove db *bbolt.DB blocker *authRateLimiter sessions map[string]*session users []User lock sync.Mutex sessionTTL uint32 </s> add db *bbolt.DB raleLimiter *authRateLimiter sessions map[string]*session users []webUser lock sync.Mutex sessionTTL uint32 </s> remove if !ok { if r.URL.Path == "/" || r.URL.Path == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) } </s> add if isAuthenticated { return false } if p := r.URL.Path; p == "/" || p == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep keep keep keep
<mask> return &authHandler{handler} <mask> } <mask> <mask> // UserAdd - add new user <mask> func (a *Auth) UserAdd(u *User, password string) { <mask> if len(password) == 0 { <mask> return <mask> } <mask> <mask> hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove // UserFind - find a user func (a *Auth) UserFind(login, password string) User { </s> add // findUser returns a user if there is one. func (a *Auth) findUser(login, password string) (u webUser, ok bool) { </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove // cookieTimeFormat is the format to be used in (time.Time).Format for cookie's // expiry field. const cookieTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" // cookieExpiryFormat returns the formatted exp to be used in cookie string. // It's quite simple for now, but probably will be expanded in the future. func cookieExpiryFormat(exp time.Time) (formatted string) { return exp.Format(cookieTimeFormat) } func (a *Auth) httpCookie(req loginJSON, addr string) (cookie string, err error) { blocker := a.blocker u := a.UserFind(req.Name, req.Password) if len(u.Name) == 0 { if blocker != nil { blocker.inc(addr) </s> add // newCookie creates a new authentication cookie. func (a *Auth) newCookie(req loginJSON, addr string) (c *http.Cookie, err error) { rateLimiter := a.raleLimiter u, ok := a.findUser(req.Name, req.Password) if !ok { if rateLimiter != nil { rateLimiter.inc(addr) </s> remove func (a *Auth) GetUsers() []User { </s> add func (a *Auth) GetUsers() []webUser { </s> remove return User{} </s> add return webUser{} </s> remove return User{} </s> add return webUser{}, false
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep replace replace keep keep replace keep keep keep
<mask> log.Debug("auth: added user: %s", u.Name) <mask> } <mask> <mask> // UserFind - find a user <mask> func (a *Auth) UserFind(login, password string) User { <mask> a.lock.Lock() <mask> defer a.lock.Unlock() <mask> for _, u := range a.users { <mask> if u.Name == login && <mask> bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) == nil { <mask> return u </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove return u </s> add return u, true </s> remove return User{} </s> add return webUser{} </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove func (a *Auth) UserAdd(u *User, password string) { </s> add func (a *Auth) UserAdd(u *webUser, password string) { </s> remove return User{} </s> add return webUser{}, false
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep replace keep keep replace keep keep
<mask> for _, u := range a.users { <mask> if u.Name == login && <mask> bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) == nil { <mask> return u <mask> } <mask> } <mask> return User{} <mask> } <mask> </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove return User{} </s> add return webUser{} </s> remove // UserFind - find a user func (a *Auth) UserFind(login, password string) User { </s> add // findUser returns a user if there is one. func (a *Auth) findUser(login, password string) (u webUser, ok bool) { </s> remove func parseCookie(cookie string) string { pairs := strings.Split(cookie, ";") for _, pair := range pairs { pair = strings.TrimSpace(pair) kv := strings.SplitN(pair, "=", 2) if len(kv) != 2 { continue } if kv[0] == sessionCookieName { return kv[1] } } return "" } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep keep keep keep
<mask> } <mask> <mask> // getCurrentUser returns the current user. It returns an empty User if the <mask> // user is not found. <mask> func (a *Auth) getCurrentUser(r *http.Request) User { <mask> cookie, err := r.Cookie(sessionCookieName) <mask> if err != nil { <mask> // There's no Cookie, check Basic authentication. <mask> user, pass, ok := r.BasicAuth() <mask> if ok { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove return User{} </s> add return webUser{}, false </s> remove return Context.auth.UserFind(user, pass) </s> add u, _ = Context.auth.findUser(user, pass) return u </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove // UserFind - find a user func (a *Auth) UserFind(login, password string) User { </s> add // findUser returns a user if there is one. func (a *Auth) findUser(login, password string) (u webUser, ok bool) { </s> remove func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { authFirst = false </s> add func optionalAuthThird(w http.ResponseWriter, r *http.Request) (mustAuth bool) { if glProcessCookie(r) { log.Debug("auth: authentication is handled by GL-Inet submodule") return false } </s> remove ok := false </s> add isAuthenticated := false
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep replace keep keep keep keep
<mask> if err != nil { <mask> // There's no Cookie, check Basic authentication. <mask> user, pass, ok := r.BasicAuth() <mask> if ok { <mask> return Context.auth.UserFind(user, pass) <mask> } <mask> <mask> return User{} <mask> } <mask> <mask> a.lock.Lock() <mask> defer a.lock.Unlock() </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove func (a *Auth) getCurrentUser(r *http.Request) User { </s> add func (a *Auth) getCurrentUser(r *http.Request) (u webUser) { </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove return User{} </s> add return webUser{} </s> remove return u </s> add return u, true </s> remove func (a *Auth) GetUsers() []User { </s> add func (a *Auth) GetUsers() []webUser {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep replace keep keep replace keep keep keep keep
<mask> <mask> s, ok := a.sessions[cookie.Value] <mask> if !ok { <mask> return User{} <mask> } <mask> <mask> for _, u := range a.users { <mask> if u.Name == s.userName { <mask> return u <mask> } <mask> } </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove return u </s> add return u, true </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove // UserFind - find a user func (a *Auth) UserFind(login, password string) User { </s> add // findUser returns a user if there is one. func (a *Auth) findUser(login, password string) (u webUser, ok bool) { </s> remove return Context.auth.UserFind(user, pass) </s> add u, _ = Context.auth.findUser(user, pass) return u </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep replace keep keep keep replace keep keep keep keep
<mask> } <mask> <mask> return User{} <mask> } <mask> <mask> // GetUsers - get users <mask> func (a *Auth) GetUsers() []User { <mask> a.lock.Lock() <mask> users := a.users <mask> a.lock.Unlock() <mask> return users </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove users := []User{u} </s> add users := []webUser{u} </s> remove return User{} </s> add return webUser{} </s> remove // UserFind - find a user func (a *Auth) UserFind(login, password string) User { </s> add // findUser returns a user if there is one. func (a *Auth) findUser(login, password string) (u webUser, ok bool) { </s> remove func (a *Auth) UserAdd(u *User, password string) { </s> add func (a *Auth) UserAdd(u *webUser, password string) {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth.go
keep keep keep keep replace keep keep keep keep keep
<mask> func TestAuth(t *testing.T) { <mask> dir := t.TempDir() <mask> fn := filepath.Join(dir, "sessions.db") <mask> <mask> users := []User{{ <mask> Name: "name", <mask> PasswordHash: "$2y$05$..vyzAECIhJPfaQiOK17IukcQnqEgKJHy0iETyYqxn3YXJl8yZuo2", <mask> }} <mask> a := InitAuth(fn, nil, 60, nil) <mask> s := session{} </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove users := []User{ </s> add users := []webUser{ </s> remove user := User{Name: "name"} </s> add user := webUser{Name: "name"} </s> remove users := []User{u} </s> add users := []webUser{u} </s> remove u := User{ </s> add u := webUser{ </s> remove Context.auth.RemoveSession(sess) </s> add Context.auth.RemoveSession(c.Value) </s> remove w.Header().Set("Location", "/login.html") </s> add c = &http.Cookie{ Name: sessionCookieName, Value: "", Path: "/", Expires: time.Unix(0, 0),
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth_test.go
keep keep keep keep replace keep keep keep keep keep
<mask> }} <mask> a := InitAuth(fn, nil, 60, nil) <mask> s := session{} <mask> <mask> user := User{Name: "name"} <mask> a.UserAdd(&user, "password") <mask> <mask> assert.Equal(t, checkSessionNotFound, a.checkSession("notfound")) <mask> a.RemoveSession("notfound") <mask> </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove users := []User{{ </s> add users := []webUser{{ </s> remove users := []User{ </s> add users := []webUser{ </s> remove u := a.UserFind("name", "password") </s> add u, ok := a.findUser("name", "password") assert.True(t, ok) </s> remove Context.auth.RemoveSession(sess) </s> add Context.auth.RemoveSession(c.Value) </s> remove w.Header().Set("Location", "/login.html") </s> add c = &http.Cookie{ Name: sessionCookieName, Value: "", Path: "/", Expires: time.Unix(0, 0), </s> remove return "", err </s> add return nil, fmt.Errorf("generating token: %w", err)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth_test.go
keep keep keep keep replace keep keep keep keep keep
<mask> s.expire = uint32(time.Now().UTC().Unix() + 2) <mask> a.storeSession(sess, &s) <mask> a.Close() <mask> <mask> u := a.UserFind("name", "password") <mask> assert.NotEmpty(t, u.Name) <mask> <mask> time.Sleep(3 * time.Second) <mask> <mask> // load and remove expired sessions </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove if len(cookie) == 0 { log.Info("auth: failed to login user %q from ip %v", req.Name, ip) time.Sleep(1 * time.Second) http.Error(w, "invalid username or password", http.StatusBadRequest) return } </s> add </s> remove user := User{Name: "name"} </s> add user := webUser{Name: "name"} </s> remove // UserFind - find a user func (a *Auth) UserFind(login, password string) User { </s> add // findUser returns a user if there is one. func (a *Auth) findUser(login, password string) (u webUser, ok bool) { </s> remove db *bbolt.DB blocker *authRateLimiter sessions map[string]*session users []User lock sync.Mutex sessionTTL uint32 </s> add db *bbolt.DB raleLimiter *authRateLimiter sessions map[string]*session users []webUser lock sync.Mutex sessionTTL uint32 </s> remove u := &User{ </s> add u := &webUser{ </s> remove cookie, err := Context.auth.httpCookie(loginJSON{Name: "name", Password: "password"}, "") </s> add cookie, err := Context.auth.newCookie(loginJSON{Name: "name", Password: "password"}, "")
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth_test.go
keep keep keep keep replace keep keep keep keep keep
<mask> func TestAuthHTTP(t *testing.T) { <mask> dir := t.TempDir() <mask> fn := filepath.Join(dir, "sessions.db") <mask> <mask> users := []User{ <mask> {Name: "name", PasswordHash: "$2y$05$..vyzAECIhJPfaQiOK17IukcQnqEgKJHy0iETyYqxn3YXJl8yZuo2"}, <mask> } <mask> Context.auth = InitAuth(fn, users, 60, nil) <mask> <mask> handlerCalled := false </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove users := []User{{ </s> add users := []webUser{{ </s> remove user := User{Name: "name"} </s> add user := webUser{Name: "name"} </s> remove users := []User{u} </s> add users := []webUser{u} </s> remove u := User{ </s> add u := webUser{ </s> remove sessionTTL: sessionTTL, blocker: blocker, sessions: make(map[string]*session), users: users, </s> add sessionTTL: sessionTTL, raleLimiter: rateLimiter, sessions: make(map[string]*session), users: users, </s> remove func (a *Auth) GetUsers() []User { </s> add func (a *Auth) GetUsers() []webUser {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth_test.go
keep keep keep keep replace keep keep keep keep keep
<mask> handler2(&w, &r) <mask> assert.True(t, handlerCalled) <mask> <mask> // perform login <mask> cookie, err := Context.auth.httpCookie(loginJSON{Name: "name", Password: "password"}, "") <mask> require.NoError(t, err) <mask> assert.NotEmpty(t, cookie) <mask> <mask> // get / <mask> handler2 = optionalAuth(handler) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove assert.NotEmpty(t, cookie) </s> add require.NotNil(t, cookie) </s> remove r.Header.Set("Cookie", cookie) </s> add r.Header.Set("Cookie", cookie.String()) </s> remove r.Header.Set("Cookie", cookie) </s> add r.Header.Set("Cookie", cookie.String()) </s> remove u := a.UserFind("name", "password") </s> add u, ok := a.findUser("name", "password") assert.True(t, ok) </s> remove var cookie string cookie, err = Context.auth.httpCookie(req, remoteAddr) </s> add cookie, err := Context.auth.newCookie(req, remoteAddr) </s> remove ok := false </s> add isAuthenticated := false
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth_test.go
keep replace keep keep keep keep replace keep keep
<mask> require.NoError(t, err) <mask> assert.NotEmpty(t, cookie) <mask> <mask> // get / <mask> handler2 = optionalAuth(handler) <mask> w.hdr = make(http.Header) <mask> r.Header.Set("Cookie", cookie) <mask> r.URL = &url.URL{Path: "/"} <mask> handlerCalled = false </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove r.Header.Set("Cookie", cookie) </s> add r.Header.Set("Cookie", cookie.String()) </s> remove cookie, err := Context.auth.httpCookie(loginJSON{Name: "name", Password: "password"}, "") </s> add cookie, err := Context.auth.newCookie(loginJSON{Name: "name", Password: "password"}, "") </s> add } else { res := Context.auth.checkSession(cookie.Value) isAuthenticated = res == checkSessionOK if !isAuthenticated { log.Debug("auth: invalid cookie value: %s", cookie) } </s> remove users := []User{ </s> add users := []webUser{ </s> remove } else if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, "/login.") { // process as usual // no additional auth requirements } else if Context.auth != nil && Context.auth.AuthRequired() { </s> add log.Debug("auth: invalid cookie value: %s", cookie) } } else if isPublicResource(p) { // Process as usual, no additional auth requirements. } else if authRequired {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth_test.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> // get login page with a valid cookie - we're redirected to / <mask> handler2 = optionalAuth(handler) <mask> w.hdr = make(http.Header) <mask> r.Header.Set("Cookie", cookie) <mask> r.URL = &url.URL{Path: loginURL} <mask> handlerCalled = false <mask> handler2(&w, &r) <mask> assert.NotEmpty(t, w.hdr.Get("Location")) <mask> assert.False(t, handlerCalled) </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove r.Header.Set("Cookie", cookie) </s> add r.Header.Set("Cookie", cookie.String()) </s> remove assert.NotEmpty(t, cookie) </s> add require.NotNil(t, cookie) </s> remove cookie, err := Context.auth.httpCookie(loginJSON{Name: "name", Password: "password"}, "") </s> add cookie, err := Context.auth.newCookie(loginJSON{Name: "name", Password: "password"}, "") </s> remove if !ok { if r.URL.Path == "/" || r.URL.Path == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) } </s> add if isAuthenticated { return false } if p := r.URL.Path; p == "/" || p == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") </s> remove ok := false </s> add isAuthenticated := false </s> remove func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { authFirst = false </s> add func optionalAuthThird(w http.ResponseWriter, r *http.Request) (mustAuth bool) { if glProcessCookie(r) { log.Debug("auth: authentication is handled by GL-Inet submodule") return false }
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/auth_test.go
keep keep keep keep replace replace replace replace replace replace replace keep keep keep keep keep
<mask> }) <mask> <mask> data.Tags = clientTags <mask> <mask> w.Header().Set("Content-Type", "application/json") <mask> e := json.NewEncoder(w).Encode(data) <mask> if e != nil { <mask> aghhttp.Error(r, w, http.StatusInternalServerError, "failed to encode to json: %v", e) <mask> <mask> return <mask> } <mask> } <mask> <mask> // Convert JSON object to Client object <mask> func jsonToClient(cj clientJSON) (c *Client) { <mask> return &Client{ </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err := json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't write response: %s", err) } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/clientshttp.go
keep keep keep keep replace replace replace replace replace keep keep keep keep keep
<mask> idStr: cj, <mask> }) <mask> } <mask> <mask> w.Header().Set("Content-Type", "application/json") <mask> err := json.NewEncoder(w).Encode(data) <mask> if err != nil { <mask> aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't write response: %s", err) <mask> } <mask> } <mask> <mask> // findRuntime looks up the IP in runtime and temporary storages, like <mask> // /etc/hosts tables, DHCP leases, or blocklists. cj is guaranteed to be <mask> // non-nil. </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") e := json.NewEncoder(w).Encode(data) if e != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "failed to encode to json: %v", e) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/clientshttp.go
keep keep keep keep replace replace replace replace keep keep keep keep keep
<mask> // Raw file data to avoid re-reading of configuration file <mask> // It's reset after config is parsed <mask> fileData []byte <mask> <mask> BindHost net.IP `yaml:"bind_host"` // BindHost is the IP address of the HTTP server to bind to <mask> BindPort int `yaml:"bind_port"` // BindPort is the port the HTTP server <mask> BetaBindPort int `yaml:"beta_bind_port"` // BetaBindPort is the port for new client <mask> Users []User `yaml:"users"` // Users that can access HTTP server <mask> // AuthAttempts is the maximum number of failed login attempts a user <mask> // can do before being blocked. <mask> AuthAttempts uint `yaml:"auth_attempts"` <mask> // AuthBlockMin is the duration, in minutes, of the block of new login <mask> // attempts after AuthAttempts unsuccessful login attempts. </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove // Perform the following tasks: // . Search for another DHCP server running // . Check if a static IP is configured for the network interface // Respond with results </s> add // findActiveServerReq is the JSON structure for the request to find active DHCP // servers. type findActiveServerReq struct { Interface string `json:"interface"` } // handleDHCPFindActiveServer performs the following tasks: // 1. searches for another DHCP server in the network; // 2. check if a static IP is configured for the network interface; // 3. responds with the results. </s> remove return fmt.Sprintf( "%s=%s; Path=/; HttpOnly; Expires=%s", sessionCookieName, hex.EncodeToString(sess), cookieExpiryFormat(now.Add(cookieTTL)), ), nil </s> add return &http.Cookie{ Name: sessionCookieName, Value: hex.EncodeToString(sess), Path: "/", Expires: now.Add(cookieTTL), HttpOnly: true, SameSite: http.SameSiteLaxMode, }, nil </s> add 'DhcpFindActiveReq': 'description': > Request for checking for other DHCP servers in the network. 'properties': 'interface': 'description': 'The name of the network interface' 'example': 'eth0' 'type': 'string' 'type': 'object' </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { return } req := &findActiveServerReq{} err := json.NewDecoder(r.Body).Decode(req) </s> add setOtherDHCPResult(ifaceName, result) _ = aghhttp.WriteJSONResponse(w, r, result) } // setOtherDHCPResult sets the results of the check for another DHCP server in // result. func setOtherDHCPResult(ifaceName string, result *dhcpSearchResult) { </s> remove log.Println(version.Full()) </s> add log.Info(version.Full())
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/config.go
keep keep keep keep replace replace replace replace replace replace replace keep keep keep keep keep
<mask> if runtime.GOOS != "windows" { <mask> resp.IsDHCPAvailable = Context.dhcpServer != nil <mask> } <mask> <mask> w.Header().Set("Content-Type", "application/json") <mask> err = json.NewEncoder(w).Encode(resp) <mask> if err != nil { <mask> aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) <mask> <mask> return <mask> } <mask> } <mask> <mask> type profileJSON struct { <mask> Name string `json:"name"` <mask> } </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove func handleI18nCurrentLanguage(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain") log.Printf("config.Language is %s", config.Language) _, err := fmt.Fprintf(w, "%s\n", config.Language) if err != nil { msg := fmt.Sprintf("Unable to write response json: %s", err) log.Println(msg) http.Error(w, msg, http.StatusInternalServerError) </s> add // languageJSON is the JSON structure for language requests and responses. type languageJSON struct { Language string `json:"language"` } </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add </s> remove w.Header().Set("Content-Type", "application/json") err := json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't write response: %s", err) } </s> add _ = aghhttp.WriteJSONResponse(w, r, data)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/control.go
keep keep keep keep replace keep keep keep keep keep
<mask> return func(w http.ResponseWriter, r *http.Request) { <mask> log.Debug("%s %v", r.Method, r.URL) <mask> <mask> if r.Method != method { <mask> http.Error(w, "This request must be "+method, http.StatusMethodNotAllowed) <mask> return <mask> } <mask> <mask> if method == http.MethodPost || method == http.MethodPut || method == http.MethodDelete { <mask> Context.controlLock.Lock() </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> add if r.Header.Get(aghhttp.HdrNameContentType) != aghhttp.HdrValApplicationJSON { aghhttp.Error( r, w, http.StatusUnsupportedMediaType, "only %s is allowed", aghhttp.HdrValApplicationJSON, ) return } </s> remove return authFirst </s> add return true </s> remove if r.URL.Path == "/login.html" { // redirect to dashboard if already authenticated authRequired := Context.auth != nil && Context.auth.AuthRequired() </s> add p := r.URL.Path authRequired := Context.auth != nil && Context.auth.AuthRequired() if p == "/login.html" { </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove } else if r == checkSessionNotFound { log.Debug("auth: invalid cookie value: %s", cookie) </s> add </s> remove const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded const config = { data: parameter, headers: { 'Content-Type': 'text/plain' }, }; return this.makeRequest(path, method, config); </s> add return this.makeRequest(path, method);
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/control.go
keep add keep keep keep keep keep keep
<mask> <mask> if method == http.MethodPost || method == http.MethodPut || method == http.MethodDelete { <mask> Context.controlLock.Lock() <mask> defer Context.controlLock.Unlock() <mask> } <mask> <mask> handler(w, r) <mask> } </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove http.Error(w, "This request must be "+method, http.StatusMethodNotAllowed) </s> add aghhttp.Error(r, w, http.StatusMethodNotAllowed, "only %s is allowed", method) </s> remove if !ok { if r.URL.Path == "/" || r.URL.Path == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) } </s> add if isAuthenticated { return false } if p := r.URL.Path; p == "/" || p == "/index.html" { if glProcessRedirect(w, r) { log.Debug("auth: redirected to login page by GL-Inet submodule") </s> remove } else if r == checkSessionNotFound { log.Debug("auth: invalid cookie value: %s", cookie) </s> add </s> remove changeLanguage(lang) { </s> add changeLanguage(config) { </s> remove } </s> add </s> remove handler(w, r) </s> add h(w, r)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/control.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
<mask> for _, iface := range ifaces { <mask> data.Interfaces[iface.Name] = iface <mask> } <mask> <mask> w.Header().Set("Content-Type", "application/json") <mask> err = json.NewEncoder(w).Encode(data) <mask> if err != nil { <mask> aghhttp.Error( <mask> r, <mask> w, <mask> http.StatusInternalServerError, <mask> "Unable to marshal default addresses to json: %s", <mask> err, <mask> ) <mask> <mask> return <mask> } <mask> } <mask> <mask> type checkConfReqEnt struct { <mask> IP net.IP `json:"ip"` <mask> Port int `json:"port"` </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove err := json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal json with TLS status: %s", err, ) } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") e := json.NewEncoder(w).Encode(data) if e != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "failed to encode to json: %v", e) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove func handleI18nCurrentLanguage(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain") log.Printf("config.Language is %s", config.Language) _, err := fmt.Fprintf(w, "%s\n", config.Language) if err != nil { msg := fmt.Sprintf("Unable to write response json: %s", err) log.Println(msg) http.Error(w, msg, http.StatusInternalServerError) </s> add // languageJSON is the JSON structure for language requests and responses. type languageJSON struct { Language string `json:"language"` }
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/controlinstall.go
keep keep keep keep replace replace replace replace replace replace replace keep keep keep keep keep
<mask> } else if !req.DNS.IP.IsUnspecified() { <mask> resp.StaticIP = handleStaticIP(req.DNS.IP, req.SetStaticIP) <mask> } <mask> <mask> w.Header().Set("Content-Type", "application/json") <mask> err = json.NewEncoder(w).Encode(resp) <mask> if err != nil { <mask> aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err) <mask> <mask> return <mask> } <mask> } <mask> <mask> // handleStaticIP - handles static IP request <mask> // It either checks if we have a static IP <mask> // Or if set=true, it tries to set it </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "writing body: %s", err) } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") err := json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't write response: %s", err) } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/controlinstall.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> return <mask> } <mask> <mask> u := &User{ <mask> Name: req.Username, <mask> } <mask> Context.auth.UserAdd(u, req.Password) <mask> <mask> err = config.write() </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove u := User{ </s> add u := webUser{ </s> remove users := []User{u} </s> add users := []webUser{u} </s> remove for _, u := range a.users { </s> add for _, u = range a.users { </s> remove // cookieTimeFormat is the format to be used in (time.Time).Format for cookie's // expiry field. const cookieTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" // cookieExpiryFormat returns the formatted exp to be used in cookie string. // It's quite simple for now, but probably will be expanded in the future. func cookieExpiryFormat(exp time.Time) (formatted string) { return exp.Format(cookieTimeFormat) } func (a *Auth) httpCookie(req loginJSON, addr string) (cookie string, err error) { blocker := a.blocker u := a.UserFind(req.Name, req.Password) if len(u.Name) == 0 { if blocker != nil { blocker.inc(addr) </s> add // newCookie creates a new authentication cookie. func (a *Auth) newCookie(req loginJSON, addr string) (c *http.Cookie, err error) { rateLimiter := a.raleLimiter u, ok := a.findUser(req.Name, req.Password) if !ok { if rateLimiter != nil { rateLimiter.inc(addr) </s> remove return u </s> add return u, true </s> remove return Context.auth.UserFind(user, pass) </s> add u, _ = Context.auth.findUser(user, pass) return u
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/controlinstall.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
<mask> } <mask> <mask> data.Interfaces = ifaces <mask> <mask> w.Header().Set("Content-Type", "application/json") <mask> err = json.NewEncoder(w).Encode(data) <mask> if err != nil { <mask> aghhttp.Error( <mask> r, <mask> w, <mask> http.StatusInternalServerError, <mask> "Unable to marshal default addresses to json: %s", <mask> err, <mask> ) <mask> <mask> return <mask> } <mask> } <mask> <mask> // registerBetaInstallHandlers registers the install handlers for new client <mask> // with the structures it supports. <mask> // </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove err := json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal json with TLS status: %s", err, ) } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") e := json.NewEncoder(w).Encode(data) if e != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "failed to encode to json: %v", e) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/controlinstall.go
keep keep keep keep replace replace keep keep keep keep keep
<mask> } <mask> <mask> // Get the latest available version from the Internet <mask> func handleGetVersionJSON(w http.ResponseWriter, r *http.Request) { <mask> w.Header().Set("Content-Type", "application/json") <mask> <mask> resp := &versionResponse{} <mask> if Context.disableUpdate { <mask> resp.Disabled = true <mask> err := json.NewEncoder(w).Encode(resp) <mask> if err != nil { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add </s> remove w.Header().Set("Content-Type", "application/json") </s> add </s> remove err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "writing body: %s", err) } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove if r.URL.Path == "/login.html" { // redirect to dashboard if already authenticated authRequired := Context.auth != nil && Context.auth.AuthRequired() </s> add p := r.URL.Path authRequired := Context.auth != nil && Context.auth.AuthRequired() if p == "/login.html" { </s> remove func optionalAuthThird(w http.ResponseWriter, r *http.Request) (authFirst bool) { authFirst = false </s> add func optionalAuthThird(w http.ResponseWriter, r *http.Request) (mustAuth bool) { if glProcessCookie(r) { log.Debug("auth: authentication is handled by GL-Inet submodule") return false } </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/controlupdate.go
keep keep keep keep replace replace replace replace keep keep keep keep keep
<mask> <mask> return <mask> } <mask> <mask> err = json.NewEncoder(w).Encode(resp) <mask> if err != nil { <mask> aghhttp.Error(r, w, http.StatusInternalServerError, "writing body: %s", err) <mask> } <mask> } <mask> <mask> // requestVersionInfo sets the VersionInfo field of resp if it can reach the <mask> // update server. <mask> func requestVersionInfo(resp *versionResponse, recheck bool) (err error) { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "encoding the response: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(resp) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Unable to write response json: %s", err) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, resp) </s> remove w.Header().Set("Content-Type", "application/json") </s> add </s> remove language := strings.TrimSpace(string(body)) if language == "" { msg := "empty language specified" log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add langReq := &languageJSON{} err := json.NewDecoder(r.Body).Decode(langReq) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "reading req: %s", err) </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Unable to marshal default addresses to json: %s", err, ) return } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove msg := fmt.Sprintf("failed to read request body: %s", err) log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err)
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/controlupdate.go
keep keep keep keep replace keep keep keep keep keep
<mask> // configure log level and output <mask> configureLogger(args) <mask> <mask> // Print the first message after logger is configured. <mask> log.Println(version.Full()) <mask> log.Debug("current working directory is %s", Context.workDir) <mask> if args.runningAsService { <mask> log.Info("AdGuard Home is running as a service") <mask> } <mask> </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove // Perform the following tasks: // . Search for another DHCP server running // . Check if a static IP is configured for the network interface // Respond with results </s> add // findActiveServerReq is the JSON structure for the request to find active DHCP // servers. type findActiveServerReq struct { Interface string `json:"interface"` } // handleDHCPFindActiveServer performs the following tasks: // 1. searches for another DHCP server in the network; // 2. check if a static IP is configured for the network interface; // 3. responds with the results. </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { return } req := &findActiveServerReq{} err := json.NewDecoder(r.Body).Decode(req) </s> remove func handleI18nCurrentLanguage(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain") log.Printf("config.Language is %s", config.Language) _, err := fmt.Fprintf(w, "%s\n", config.Language) if err != nil { msg := fmt.Sprintf("Unable to write response json: %s", err) log.Println(msg) http.Error(w, msg, http.StatusInternalServerError) </s> add // languageJSON is the JSON structure for language requests and responses. type languageJSON struct { Language string `json:"language"` } </s> remove BindHost net.IP `yaml:"bind_host"` // BindHost is the IP address of the HTTP server to bind to BindPort int `yaml:"bind_port"` // BindPort is the port the HTTP server BetaBindPort int `yaml:"beta_bind_port"` // BetaBindPort is the port for new client Users []User `yaml:"users"` // Users that can access HTTP server </s> add BindHost net.IP `yaml:"bind_host"` // BindHost is the IP address of the HTTP server to bind to BindPort int `yaml:"bind_port"` // BindPort is the port the HTTP server BetaBindPort int `yaml:"beta_bind_port"` // BetaBindPort is the port for new client Users []webUser `yaml:"users"` // Users that can access HTTP server </s> remove w.Header().Set("Content-Type", "application/json") err := json.NewEncoder(w).Encode(data) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't write response: %s", err) } </s> add _ = aghhttp.WriteJSONResponse(w, r, data) </s> remove } else if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, "/login.") { // process as usual // no additional auth requirements } else if Context.auth != nil && Context.auth.AuthRequired() { </s> add log.Debug("auth: invalid cookie value: %s", cookie) } } else if isPublicResource(p) { // Process as usual, no additional auth requirements. } else if authRequired {
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/home.go
keep keep keep keep replace keep replace keep keep keep keep
<mask> } <mask> <mask> sessFilename := filepath.Join(Context.getDataDir(), "sessions.db") <mask> GLMode = args.glinetMode <mask> var arl *authRateLimiter <mask> if config.AuthAttempts > 0 && config.AuthBlockMin > 0 { <mask> arl = newAuthRateLimiter( <mask> time.Duration(config.AuthBlockMin)*time.Minute, <mask> config.AuthAttempts, <mask> ) <mask> } else { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove if blocker := Context.auth.blocker; blocker != nil { if left := blocker.check(remoteAddr); left > 0 { </s> add if rateLimiter := Context.auth.raleLimiter; rateLimiter != nil { if left := rateLimiter.check(remoteAddr); left > 0 { </s> remove if glProcessCookie(r) { log.Debug("auth: authentication was handled by GL-Inet submodule") ok = true } else if err == nil { r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { ok = true } else if r < 0 { log.Debug("auth: invalid cookie value: %s", cookie) } } else { // there's no Cookie, check Basic authentication user, pass, ok2 := r.BasicAuth() if ok2 { u := Context.auth.UserFind(user, pass) if len(u.Name) != 0 { ok = true } else { </s> add if err != nil { // The only error that is returned from r.Cookie is [http.ErrNoCookie]. // Check Basic authentication. user, pass, hasBasic := r.BasicAuth() if hasBasic { _, isAuthenticated = Context.auth.findUser(user, pass) if !isAuthenticated { </s> remove } else if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, "/login.") { // process as usual // no additional auth requirements } else if Context.auth != nil && Context.auth.AuthRequired() { </s> add log.Debug("auth: invalid cookie value: %s", cookie) } } else if isPublicResource(p) { // Process as usual, no additional auth requirements. } else if authRequired { </s> remove func (a *Auth) UserAdd(u *User, password string) { </s> add func (a *Auth) UserAdd(u *webUser, password string) { </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/home.go
keep keep keep keep replace keep keep keep keep keep
<mask> Context.auth = InitAuth( <mask> sessFilename, <mask> config.Users, <mask> config.WebSessionTTLHours*60*60, <mask> arl, <mask> ) <mask> if Context.auth == nil { <mask> log.Fatalf("Couldn't initialize Auth module") <mask> } <mask> config.Users = nil </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove if r.URL.Path == "/login.html" { // redirect to dashboard if already authenticated authRequired := Context.auth != nil && Context.auth.AuthRequired() </s> add p := r.URL.Path authRequired := Context.auth != nil && Context.auth.AuthRequired() if p == "/login.html" { </s> remove r := Context.auth.checkSession(cookie.Value) if r == checkSessionOK { </s> add // Redirect to the dashboard if already authenticated. res := Context.auth.checkSession(cookie.Value) if res == checkSessionOK { </s> remove func optionalAuth(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { </s> add // TODO(a.garipov): Use [http.Handler] consistently everywhere throughout the // project. func optionalAuth( h func(http.ResponseWriter, *http.Request), ) (wrapped func(http.ResponseWriter, *http.Request)) { </s> remove } else if strings.HasPrefix(r.URL.Path, "/assets/") || strings.HasPrefix(r.URL.Path, "/login.") { // process as usual // no additional auth requirements } else if Context.auth != nil && Context.auth.AuthRequired() { </s> add log.Debug("auth: invalid cookie value: %s", cookie) } } else if isPublicResource(p) { // Process as usual, no additional auth requirements. } else if authRequired { </s> add if r.Header.Get(aghhttp.HdrNameContentType) != aghhttp.HdrValApplicationJSON { aghhttp.Error( r, w, http.StatusUnsupportedMediaType, "only %s is allowed", aghhttp.HdrValApplicationJSON, ) return } </s> remove users := []User{ </s> add users := []webUser{
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/home.go
keep keep keep replace replace keep replace
<mask> package home <mask> <mask> import ( <mask> "fmt" <mask> "io" <mask> "net/http" <mask> "strings" </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove "io" </s> add </s> add "encoding/json" </s> add "path" </s> remove "strings" </s> add </s> add "github.com/AdguardTeam/AdGuardHome/internal/version"
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/i18n.go
keep keep keep keep replace replace replace replace replace replace replace replace keep replace replace keep keep keep keep
<mask> "zh-hk", <mask> "zh-tw", <mask> ) <mask> <mask> func handleI18nCurrentLanguage(w http.ResponseWriter, _ *http.Request) { <mask> w.Header().Set("Content-Type", "text/plain") <mask> log.Printf("config.Language is %s", config.Language) <mask> _, err := fmt.Fprintf(w, "%s\n", config.Language) <mask> if err != nil { <mask> msg := fmt.Sprintf("Unable to write response json: %s", err) <mask> log.Println(msg) <mask> http.Error(w, msg, http.StatusInternalServerError) <mask> <mask> return <mask> } <mask> } <mask> <mask> func handleI18nChangeLanguage(w http.ResponseWriter, r *http.Request) { <mask> // This use of ReadAll is safe, because request's body is now limited. </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) if err != nil { msg := fmt.Sprintf("failed to read request body: %s", err) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { </s> remove msg := fmt.Sprintf("failed to read request body: %s", err) log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err) </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { return } req := &findActiveServerReq{} err := json.NewDecoder(r.Body).Decode(req) </s> remove // Perform the following tasks: // . Search for another DHCP server running // . Check if a static IP is configured for the network interface // Respond with results </s> add // findActiveServerReq is the JSON structure for the request to find active DHCP // servers. type findActiveServerReq struct { Interface string `json:"interface"` } // handleDHCPFindActiveServer performs the following tasks: // 1. searches for another DHCP server in the network; // 2. check if a static IP is configured for the network interface; // 3. responds with the results. </s> remove w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(result) if err != nil { aghhttp.Error( r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err, ) } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/i18n.go
keep keep keep keep replace replace replace replace replace replace replace keep keep keep keep keep
<mask> } <mask> } <mask> <mask> func handleI18nChangeLanguage(w http.ResponseWriter, r *http.Request) { <mask> // This use of ReadAll is safe, because request's body is now limited. <mask> body, err := io.ReadAll(r.Body) <mask> if err != nil { <mask> msg := fmt.Sprintf("failed to read request body: %s", err) <mask> log.Println(msg) <mask> http.Error(w, msg, http.StatusBadRequest) <mask> <mask> return <mask> } <mask> <mask> language := strings.TrimSpace(string(body)) <mask> if language == "" { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove msg := fmt.Sprintf("failed to read request body: %s", err) log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err) </s> remove return } </s> add func handleI18nCurrentLanguage(w http.ResponseWriter, r *http.Request) { log.Printf("home: language is %s", config.Language) _ = aghhttp.WriteJSONResponse(w, r, &languageJSON{ Language: config.Language, }) </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { return } req := &findActiveServerReq{} err := json.NewDecoder(r.Body).Decode(req) </s> remove language := strings.TrimSpace(string(body)) if language == "" { msg := "empty language specified" log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add langReq := &languageJSON{} err := json.NewDecoder(r.Body).Decode(langReq) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "reading req: %s", err) </s> remove // Perform the following tasks: // . Search for another DHCP server running // . Check if a static IP is configured for the network interface // Respond with results </s> add // findActiveServerReq is the JSON structure for the request to find active DHCP // servers. type findActiveServerReq struct { Interface string `json:"interface"` } // handleDHCPFindActiveServer performs the following tasks: // 1. searches for another DHCP server in the network; // 2. check if a static IP is configured for the network interface; // 3. responds with the results. </s> remove func handleI18nCurrentLanguage(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain") log.Printf("config.Language is %s", config.Language) _, err := fmt.Fprintf(w, "%s\n", config.Language) if err != nil { msg := fmt.Sprintf("Unable to write response json: %s", err) log.Println(msg) http.Error(w, msg, http.StatusInternalServerError) </s> add // languageJSON is the JSON structure for language requests and responses. type languageJSON struct { Language string `json:"language"` }
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/i18n.go
keep keep keep keep replace replace replace replace replace keep keep keep keep keep
<mask> <mask> return <mask> } <mask> <mask> language := strings.TrimSpace(string(body)) <mask> if language == "" { <mask> msg := "empty language specified" <mask> log.Println(msg) <mask> http.Error(w, msg, http.StatusBadRequest) <mask> <mask> return <mask> } <mask> <mask> if !allowedLanguages.Has(language) { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove ifaceName := strings.TrimSpace(string(body)) </s> add ifaceName := req.Interface </s> remove if !allowedLanguages.Has(language) { msg := fmt.Sprintf("unknown language specified: %s", language) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add lang := langReq.Language if !allowedLanguages.Has(lang) { aghhttp.Error(r, w, http.StatusBadRequest, "unknown language: %q", lang) </s> remove msg := "empty interface name specified" log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "empty interface name") </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) if err != nil { msg := fmt.Sprintf("failed to read request body: %s", err) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { </s> remove func handleI18nCurrentLanguage(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain") log.Printf("config.Language is %s", config.Language) _, err := fmt.Fprintf(w, "%s\n", config.Language) if err != nil { msg := fmt.Sprintf("Unable to write response json: %s", err) log.Println(msg) http.Error(w, msg, http.StatusInternalServerError) </s> add // languageJSON is the JSON structure for language requests and responses. type languageJSON struct { Language string `json:"language"` } </s> remove return } </s> add func handleI18nCurrentLanguage(w http.ResponseWriter, r *http.Request) { log.Printf("home: language is %s", config.Language) _ = aghhttp.WriteJSONResponse(w, r, &languageJSON{ Language: config.Language, })
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/i18n.go
keep keep keep keep replace replace replace replace keep keep keep keep keep
<mask> <mask> return <mask> } <mask> <mask> if !allowedLanguages.Has(language) { <mask> msg := fmt.Sprintf("unknown language specified: %s", language) <mask> log.Println(msg) <mask> http.Error(w, msg, http.StatusBadRequest) <mask> <mask> return <mask> } <mask> <mask> func() { </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove language := strings.TrimSpace(string(body)) if language == "" { msg := "empty language specified" log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add langReq := &languageJSON{} err := json.NewDecoder(r.Body).Decode(langReq) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "reading req: %s", err) </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) if err != nil { msg := fmt.Sprintf("failed to read request body: %s", err) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { </s> remove ifaceName := strings.TrimSpace(string(body)) </s> add ifaceName := req.Interface </s> remove msg := "empty interface name specified" log.Error(msg) http.Error(w, msg, http.StatusBadRequest) </s> add aghhttp.Error(r, w, http.StatusBadRequest, "empty interface name") </s> remove func handleI18nCurrentLanguage(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain") log.Printf("config.Language is %s", config.Language) _, err := fmt.Fprintf(w, "%s\n", config.Language) if err != nil { msg := fmt.Sprintf("Unable to write response json: %s", err) log.Println(msg) http.Error(w, msg, http.StatusInternalServerError) </s> add // languageJSON is the JSON structure for language requests and responses. type languageJSON struct { Language string `json:"language"` } </s> remove return } </s> add func handleI18nCurrentLanguage(w http.ResponseWriter, r *http.Request) { log.Printf("home: language is %s", config.Language) _ = aghhttp.WriteJSONResponse(w, r, &languageJSON{ Language: config.Language, })
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/i18n.go
keep keep keep keep replace keep keep keep keep keep
<mask> func() { <mask> config.Lock() <mask> defer config.Unlock() <mask> <mask> config.Language = language <mask> }() <mask> <mask> onConfigModified() <mask> aghhttp.OK(w) <mask> } </s> Pull request: HOFTIX-csrf Merge in DNS/adguard-home from HOFTIX-csrf to master Squashed commit of the following: commit 75ab27bf6c52b80ab4e7347d7c254fa659eac244 Author: Ainar Garipov <[email protected]> Date: Thu Sep 29 18:45:54 2022 +0300 all: imp cookie security; rm plain-text apis </s> remove if !allowedLanguages.Has(language) { msg := fmt.Sprintf("unknown language specified: %s", language) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add lang := langReq.Language if !allowedLanguages.Has(lang) { aghhttp.Error(r, w, http.StatusBadRequest, "unknown language: %q", lang) </s> remove language := strings.TrimSpace(string(body)) if language == "" { msg := "empty language specified" log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add langReq := &languageJSON{} err := json.NewDecoder(r.Body).Decode(langReq) if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "reading req: %s", err) </s> remove return User{} </s> add return webUser{} </s> remove return u </s> add return u, true </s> remove // This use of ReadAll is safe, because request's body is now limited. body, err := io.ReadAll(r.Body) if err != nil { msg := fmt.Sprintf("failed to read request body: %s", err) log.Println(msg) http.Error(w, msg, http.StatusBadRequest) </s> add if aghhttp.WriteTextPlainDeprecated(w, r) { </s> remove return User{} </s> add return webUser{}
https://github.com/AdguardTeam/AdGuardHome/commit/756b14a61de138889130c239406dae43f1f115cb
internal/home/i18n.go