packagehttpimport("context""honeypot/internal/logger""honeypot/internal/types""honeypot/internal/utils""net/http")// portMiddleware injects the destination port into the request context.func(h*httpHoneypot)portMiddleware(nexthttp.Handler,portuint16)http.Handler{returnhttp.HandlerFunc(func(whttp.ResponseWriter,r*http.Request){dstPort:=port// If request is from localhost, check for proxy headersremoteHost,_:=utils.SplitAddr(r.RemoteAddr,h.logger)ifremoteHost=="127.0.0.1"||remoteHost=="::1"{proto:=r.Header.Get("X-Forwarded-Proto")switchproto{case"https":dstPort=443case"http":dstPort=80}}ctx:=context.WithValue(r.Context(),dstPortKey,dstPort)next.ServeHTTP(w,r.WithContext(ctx))})}// bodySizeMiddleware limits the request body size.func(h*httpHoneypot)bodySizeMiddleware(nexthttp.Handler)http.Handler{returnhttp.HandlerFunc(func(whttp.ResponseWriter,r*http.Request){// Check Content-Length header first for methods that typically have bodiesifMethodsWithBody[r.Method]{ifr.ContentLength>h.maxBodySize{http.Error(w,"Request Entity Too Large",http.StatusRequestEntityTooLarge)return}// Limit body size for streaming requestsifr.Body!=nil{r.Body=http.MaxBytesReader(w,r.Body,h.maxBodySize)}}next.ServeHTTP(w,r)})}// loggingMiddleware logs all requests.func(h*httpHoneypot)loggingMiddleware(nexthttp.Handler)http.Handler{returnhttp.HandlerFunc(func(whttp.ResponseWriter,r*http.Request){h.logRequest(r)next.ServeHTTP(w,r)})}// basicAuthMiddleware handles basic authentication.func(h*httpHoneypot)basicAuthMiddleware(realmstring,nexthttp.Handler)http.Handler{returnhttp.HandlerFunc(func(whttp.ResponseWriter,r*http.Request){user,pass,ok:=r.BasicAuth()fields:=h.buildRequestFields(r)h.addHeadersToFields(r,fields)event:=types.LogEvent{}ifok{fields["username"]=userfields["password"]=passfields["auth_type"]="basic"fields["realm"]=realmevent.Event=types.EventAuthAttempt}else{event.Event=types.EventRequest}remoteHost,remotePort:=h.getRemoteAddr(r)vardstPortuint16ifport,ok:=r.Context().Value(dstPortKey).(uint16);ok{dstPort=port}event.Type=HoneypotTypeevent.RemoteAddr=remoteHostevent.RemotePort=remotePortevent.DstPort=dstPortevent.Fields=fieldslogger.LogEvent(h.logger,event)h.recordHTTPMetrics(event)w.Header().Set("WWW-Authenticate",`Basic realm="`+realm+`"`)h.writeNginxError(w,http.StatusUnauthorized)})}