Skip to content

Commit 2ddb1d6

Browse files
committed
Backend: Add HTTP security middleware
1 parent f443e3f commit 2ddb1d6

File tree

2 files changed

+204
-3
lines changed

2 files changed

+204
-3
lines changed

internal/server/security.go

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
package server
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
"strings"
7+
8+
"github.com/gin-gonic/gin"
9+
10+
"github.com/photoprism/photoprism/pkg/txt"
11+
)
12+
13+
const (
14+
stsHeader = "Strict-Transport-Security"
15+
stsSubdomainString = "; includeSubdomains"
16+
frameOptionsHeader = "X-Frame-Options"
17+
frameOptionsValue = "DENY"
18+
contentTypeHeader = "X-Content-Type-Options"
19+
contentTypeValue = "nosniff"
20+
xssProtectionHeader = "X-XSS-Protection"
21+
xssProtectionValue = "1; mode=block"
22+
cspHeader = "Content-Security-Policy"
23+
)
24+
25+
func defaultBadHostHandler(w http.ResponseWriter, r *http.Request) {
26+
http.Error(w, "Bad Host", http.StatusInternalServerError)
27+
}
28+
29+
// SecurityOptions is a struct for specifying configuration options for the HTTP security middleware.
30+
type SecurityOptions struct {
31+
// AllowedHosts is a list of fully qualified domain names that are allowed. Default is empty list, which allows any and all host names.
32+
AllowedHosts []string
33+
// If SSLRedirect is set to true, then only allow https requests. Default is false.
34+
SSLRedirect bool
35+
// If SSLTemporaryRedirect is true, a 302 will be used while redirecting. Default is false (301).
36+
SSLTemporaryRedirect bool
37+
// SSLHost is the host name that is used to redirect http requests to https. Default is "", which indicates to use the same host.
38+
SSLHost string
39+
// SSLProxyHeaders is set of header keys with associated values that would indicate a valid https request. Useful when using Nginx: `map[string]string{"X-Forwarded-Proto": "https"}`. Default is blank map.
40+
SSLProxyHeaders map[string]string
41+
// STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header.
42+
STSSeconds int64
43+
// If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false.
44+
STSIncludeSubdomains bool
45+
// If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false.
46+
FrameDeny bool
47+
// CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option.
48+
CustomFrameOptionsValue string
49+
// If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false.
50+
ContentTypeNosniff bool
51+
// If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false.
52+
BrowserXssFilter bool
53+
// ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "".
54+
ContentSecurityPolicy string
55+
// When developing, the AllowedHosts, SSL, and STS options can cause some unwanted effects. Usually testing happens on http, not https, and on localhost, not your production domain... so set this to true for dev environment.
56+
// If you would like your development environment to mimic production with complete Host blocking, SSL redirects, and STS headers, leave this as false. Default if false.
57+
IsDevelopment bool
58+
59+
// Handlers for when an error occurs (ie bad host).
60+
BadHostHandler http.Handler
61+
}
62+
63+
// security is an HTTP middleware that enables basic security features. A single SecurityOptions struct can be
64+
// provided to configure which features should be enabled, and the ability to override a few of the default values.
65+
// Code is based on https://github.com/gin-gonic/contrib/tree/master/secure released under the MIT license:
66+
// https://github.com/gin-gonic/contrib/blob/master/LICENSE
67+
type security struct {
68+
// Customize with an SecurityOptions struct.
69+
opt SecurityOptions
70+
}
71+
72+
// process handles an HTTP request.
73+
func (s *security) process(w http.ResponseWriter, r *http.Request) error {
74+
// Allowed hosts check.
75+
if len(s.opt.AllowedHosts) > 0 && !s.opt.IsDevelopment {
76+
isGoodHost := false
77+
for _, allowedHost := range s.opt.AllowedHosts {
78+
if strings.EqualFold(allowedHost, r.Host) {
79+
isGoodHost = true
80+
break
81+
}
82+
}
83+
84+
if !isGoodHost {
85+
s.opt.BadHostHandler.ServeHTTP(w, r)
86+
return fmt.Errorf("http: bad host %s", txt.Quote(r.Host))
87+
}
88+
}
89+
90+
// SSL check.
91+
if s.opt.SSLRedirect && s.opt.IsDevelopment == false {
92+
isSSL := false
93+
if strings.EqualFold(r.URL.Scheme, "https") || r.TLS != nil {
94+
isSSL = true
95+
} else {
96+
for k, v := range s.opt.SSLProxyHeaders {
97+
if r.Header.Get(k) == v {
98+
isSSL = true
99+
break
100+
}
101+
}
102+
}
103+
104+
if isSSL == false {
105+
url := r.URL
106+
url.Scheme = "https"
107+
url.Host = r.Host
108+
109+
if len(s.opt.SSLHost) > 0 {
110+
url.Host = s.opt.SSLHost
111+
}
112+
113+
status := http.StatusMovedPermanently
114+
if s.opt.SSLTemporaryRedirect {
115+
status = http.StatusTemporaryRedirect
116+
}
117+
118+
http.Redirect(w, r, url.String(), status)
119+
return fmt.Errorf("http: https redirect")
120+
}
121+
}
122+
123+
// Strict Transport Security header.
124+
if s.opt.STSSeconds != 0 && !s.opt.IsDevelopment {
125+
stsSub := ""
126+
if s.opt.STSIncludeSubdomains {
127+
stsSub = stsSubdomainString
128+
}
129+
130+
w.Header().Add(stsHeader, fmt.Sprintf("max-age=%d%s", s.opt.STSSeconds, stsSub))
131+
}
132+
133+
// Frame Options header.
134+
if len(s.opt.CustomFrameOptionsValue) > 0 {
135+
w.Header().Add(frameOptionsHeader, s.opt.CustomFrameOptionsValue)
136+
} else if s.opt.FrameDeny {
137+
w.Header().Add(frameOptionsHeader, frameOptionsValue)
138+
}
139+
140+
// Content Type Options header.
141+
if s.opt.ContentTypeNosniff {
142+
w.Header().Add(contentTypeHeader, contentTypeValue)
143+
}
144+
145+
// XSS Protection header.
146+
if s.opt.BrowserXssFilter {
147+
w.Header().Add(xssProtectionHeader, xssProtectionValue)
148+
}
149+
150+
// Content Security Policy header.
151+
if len(s.opt.ContentSecurityPolicy) > 0 {
152+
w.Header().Add(cspHeader, s.opt.ContentSecurityPolicy)
153+
}
154+
155+
return nil
156+
157+
}
158+
159+
// Security registers the HTTP security middleware.
160+
func Security(options SecurityOptions) gin.HandlerFunc {
161+
if options.BadHostHandler == nil {
162+
options.BadHostHandler = http.HandlerFunc(defaultBadHostHandler)
163+
}
164+
165+
s := &security{
166+
opt: options,
167+
}
168+
169+
return func(c *gin.Context) {
170+
err := s.process(c.Writer, c.Request)
171+
if err != nil {
172+
if c.Writer.Written() {
173+
c.AbortWithStatus(c.Writer.Status())
174+
} else {
175+
_ = c.AbortWithError(http.StatusInternalServerError, err)
176+
}
177+
}
178+
}
179+
180+
}

internal/server/server.go

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,35 @@ func Start(ctx context.Context, conf *config.Config) {
2121
}
2222
}()
2323

24-
// Set http server mode.
24+
// Set HTTP server mode.
2525
if conf.HttpMode() != "" {
2626
gin.SetMode(conf.HttpMode())
2727
} else if conf.Debug() == false {
2828
gin.SetMode(gin.ReleaseMode)
2929
}
3030

31-
// Create router and add routing middleware.
31+
// Create new HTTP router engine without standard middleware.
3232
router := gin.New()
33+
34+
// Register logger middleware.
3335
router.Use(Logger(), Recovery())
3436

35-
// Enable http compression (if any).
37+
// Register security middleware.
38+
router.Use(Security(SecurityOptions{
39+
IsDevelopment: gin.Mode() != gin.ReleaseMode || conf.Test(),
40+
AllowedHosts: []string{},
41+
SSLRedirect: false,
42+
SSLHost: "",
43+
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
44+
STSSeconds: 0,
45+
STSIncludeSubdomains: false,
46+
FrameDeny: true,
47+
ContentTypeNosniff: false,
48+
BrowserXssFilter: false,
49+
ContentSecurityPolicy: "frame-ancestors 'none';",
50+
}))
51+
52+
// Enable HTTP compression?
3653
switch conf.HttpCompression() {
3754
case "gzip":
3855
log.Infof("http: enabling gzip compression")
@@ -50,13 +67,16 @@ func Start(ctx context.Context, conf *config.Config) {
5067
// Set template directory
5168
router.LoadHTMLGlob(conf.TemplatesPath() + "/*")
5269

70+
// Register HTTP route handlers.
5371
registerRoutes(router, conf)
5472

73+
// Create new HTTP server instance.
5574
server := &http.Server{
5675
Addr: fmt.Sprintf("%s:%d", conf.HttpHost(), conf.HttpPort()),
5776
Handler: router,
5877
}
5978

79+
// Start HTTP server.
6080
go func() {
6181
log.Infof("http: starting web server at %s", server.Addr)
6282

@@ -69,6 +89,7 @@ func Start(ctx context.Context, conf *config.Config) {
6989
}
7090
}()
7191

92+
// Graceful HTTP server shutdown.
7293
<-ctx.Done()
7394
log.Info("http: shutting down web server")
7495
err := server.Close()

0 commit comments

Comments
 (0)