Fix data races, nil-record panics, scanner SSRF, log date layout, shutdown timeouts, and enable stricter linters (#54)

High (behavioral bugs):
- service.Geo: add RLock on lookups, handle Reload error, keep old DBs on failure
- models.GeoDB.Reload: open new DBs before closing old ones (no reader gap)
- router: guard nil geo records (404 instead of 500) in geo.go, generic.go, dns.go
- router/port_scanner: reject undetermined client IPs (nil->localhost dial)
- internal/httputils: fix access log date layout (02/Jan/2006, not literal Nov)
- server/quic: log.Printf instead of log.Fatal in request handler

Medium:
- server/*: 10s shutdown timeout; SIGTERM drains servers before closing geo DBs
- httputils: Clone() request headers instead of mutating the live map; strings.Builder
- setting/app: handle all os.Stat errors; fix "truster" typos; use errors.New;
  remove dead Token field
- cmd: errors.Is for sentinel checks; os.Stderr; log.Fatal instead of panic;
  pass http.Handler by value (not pointer-to-interface)
- resolver: validate config at startup (pre-parse RRs, validate IPs); check WriteMsg
  errors; Setup returns error

Low:
- .golangci.yaml: enable errcheck, govet, errorlint; fix all resulting findings
- server/tls: explicit TLSConfig{MinVersion: tls.VersionTLS12}
- router/dns: label-exact vhost suffix check, strip port; template.Must
- models: errors.Join instead of %s on []error
- service/geo_test: race-regression test (concurrent lookups during Reload)
- README: Go >= 1.25; fix latent test bug (store.Add->Set in dns_test.go)
This commit is contained in:
2026-07-19 12:09:52 +02:00
committed by GitHub
parent 210e8c7cdb
commit 49ffcadb0a
24 changed files with 273 additions and 143 deletions
+15 -8
View File
@@ -29,12 +29,13 @@ type dnsData struct {
// Implement a proper vhost manager instead of using a middleware
func GetDNSDiscoveryHandler(store *cache.Cache, domain string, redirectPort string) gin.HandlerFunc {
return func(ctx *gin.Context) {
if !strings.HasSuffix(ctx.Request.Host, domain) {
host := hostWithoutPort(ctx.Request.Host)
if host != domain && !strings.HasSuffix(host, "."+domain) {
ctx.Next()
return
}
if ctx.Request.Host == domain && ctx.Request.URL.Path == "/" {
if host == domain && ctx.Request.URL.Path == "/" {
ctx.Redirect(http.StatusFound, fmt.Sprintf("http://%s.%s%s", uuid.New().String(), domain, redirectPort))
ctx.Abort()
return
@@ -45,6 +46,13 @@ func GetDNSDiscoveryHandler(store *cache.Cache, domain string, redirectPort stri
}
}
func hostWithoutPort(host string) string {
if h, _, err := net.SplitHostPort(host); err == nil {
return h
}
return host
}
func handleDNS(ctx *gin.Context, store *cache.Cache) {
d := strings.Split(ctx.Request.Host, ".")[0]
if !validator.IsValid(d) {
@@ -72,12 +80,11 @@ func handleDNS(ctx *gin.Context, store *cache.Cache) {
geoResp := dnsGeoData{}
if geoSvc != nil {
cityRecord := geoSvc.LookUpCity(ip)
asnRecord := geoSvc.LookUpASN(ip)
geoResp = dnsGeoData{
Country: cityRecord.Country.Names["en"],
AsnOrganization: asnRecord.AutonomousSystemOrganization,
if cityRecord := geoSvc.LookUpCity(ip); cityRecord != nil {
geoResp.Country = cityRecord.Country.Names["en"]
}
if asnRecord := geoSvc.LookUpASN(ip); asnRecord != nil {
geoResp.AsnOrganization = asnRecord.AutonomousSystemOrganization
}
}
+2 -2
View File
@@ -100,7 +100,7 @@ func TestHandleDNS(t *testing.T) {
req.Host = tt.subDomain + "." + domain
if tt.stored != "" {
store.Add(tt.subDomain, tt.stored, cache.DefaultExpiration)
store.Set(tt.subDomain, tt.stored, cache.DefaultExpiration)
}
w := httptest.NewRecorder()
@@ -143,7 +143,7 @@ func TestAcceptDNSRequest(t *testing.T) {
c, _ := gin.CreateTestContext(w)
c.Request = req
store.Add(u, testIP.ipv4, cache.DefaultExpiration)
store.Set(u, testIP.ipv4, cache.DefaultExpiration)
handleDNS(c, store)
assert.Equal(t, http.StatusOK, w.Code)
+18 -15
View File
@@ -75,8 +75,12 @@ func getAllAsString(ctx *gin.Context) {
output += "Client Port: " + getClientPort(ctx) + "\n"
if geoSvc != nil {
output += geoCityRecordToString(geoSvc.LookUpCity(ip)) + "\n"
output += geoASNRecordToString(geoSvc.LookUpASN(ip)) + "\n"
if cityRecord := geoSvc.LookUpCity(ip); cityRecord != nil {
output += geoCityRecordToString(cityRecord) + "\n"
}
if asnRecord := geoSvc.LookUpASN(ip); asnRecord != nil {
output += geoASNRecordToString(asnRecord) + "\n"
}
}
h := httputils.GetHeadersWithoutTrustedHeaders(ctx)
@@ -100,19 +104,18 @@ func jsonOutput(ctx *gin.Context) JSONResponse {
geoResp := GeoResponse{}
if geoSvc != nil {
cityRecord := geoSvc.LookUpCity(ip)
asnRecord := geoSvc.LookUpASN(ip)
geoResp = GeoResponse{
Country: cityRecord.Country.Names["en"],
CountryCode: cityRecord.Country.ISOCode,
City: cityRecord.City.Names["en"],
Latitude: cityRecord.Location.Latitude,
Longitude: cityRecord.Location.Longitude,
PostalCode: cityRecord.Postal.Code,
TimeZone: cityRecord.Location.TimeZone,
ASN: asnRecord.AutonomousSystemNumber,
ASNOrganization: asnRecord.AutonomousSystemOrganization,
if cityRecord := geoSvc.LookUpCity(ip); cityRecord != nil {
geoResp.Country = cityRecord.Country.Names["en"]
geoResp.CountryCode = cityRecord.Country.ISOCode
geoResp.City = cityRecord.City.Names["en"]
geoResp.Latitude = cityRecord.Location.Latitude
geoResp.Longitude = cityRecord.Location.Longitude
geoResp.PostalCode = cityRecord.Postal.Code
geoResp.TimeZone = cityRecord.Location.TimeZone
}
if asnRecord := geoSvc.LookUpASN(ip); asnRecord != nil {
geoResp.ASN = asnRecord.AutonomousSystemNumber
geoResp.ASNOrganization = asnRecord.AutonomousSystemOrganization
}
}
+29 -10
View File
@@ -87,15 +87,24 @@ func getGeoAsString(ctx *gin.Context) {
return
}
field := strings.ToLower(ctx.Params.ByName("field"))
record := geoSvc.LookUpCity(net.ParseIP(ctx.ClientIP()))
if record == nil {
ctx.String(http.StatusNotFound, http.StatusText(http.StatusNotFound))
return
}
field := strings.ToLower(ctx.Params.ByName("field"))
if field == "" {
ctx.String(http.StatusOK, geoCityRecordToString(record))
} else if g, ok := geoOutput[field]; ok {
ctx.String(http.StatusOK, g.format(record))
} else {
ctx.String(http.StatusNotFound, http.StatusText(http.StatusNotFound))
return
}
g, ok := geoOutput[field]
if !ok {
ctx.String(http.StatusNotFound, http.StatusText(http.StatusNotFound))
return
}
ctx.String(http.StatusOK, g.format(record))
}
func getASNAsString(ctx *gin.Context) {
@@ -103,15 +112,25 @@ func getASNAsString(ctx *gin.Context) {
ctx.String(http.StatusNotFound, http.StatusText(http.StatusNotFound))
return
}
field := strings.ToLower(ctx.Params.ByName("field"))
record := geoSvc.LookUpASN(net.ParseIP(ctx.ClientIP()))
if record == nil {
ctx.String(http.StatusNotFound, http.StatusText(http.StatusNotFound))
return
}
field := strings.ToLower(ctx.Params.ByName("field"))
if field == "" {
ctx.String(http.StatusOK, geoASNRecordToString(record))
} else if g, ok := asnOutput[field]; ok {
ctx.String(http.StatusOK, g.format(record))
} else {
ctx.String(http.StatusNotFound, http.StatusText(http.StatusNotFound))
return
}
g, ok := asnOutput[field]
if !ok {
ctx.String(http.StatusNotFound, http.StatusText(http.StatusNotFound))
return
}
ctx.String(http.StatusOK, g.format(record))
}
func geoCityRecordToString(record *models.GeoRecord) string {
+9 -1
View File
@@ -29,8 +29,16 @@ func scanTCPPort(ctx *gin.Context) {
return
}
ip := net.ParseIP(ctx.ClientIP())
if ip == nil {
ctx.JSON(http.StatusBadRequest, JSONScanResponse{
Reason: "client ip could not be determined",
})
return
}
add := net.TCPAddr{
IP: net.ParseIP(ctx.ClientIP()),
IP: ip,
Port: port,
}
+1 -2
View File
@@ -13,8 +13,7 @@ var geoSvc *service.Geo
func SetupTemplate(r *gin.Engine) {
if setting.App.TemplatePath == "" {
t, _ := template.New("home").Parse(home)
r.SetHTMLTemplate(t)
r.SetHTMLTemplate(template.Must(template.New("home").Parse(home)))
} else {
log.Printf("Template %s has been loaded", setting.App.TemplatePath)
r.LoadHTMLFiles(setting.App.TemplatePath)