Skip to content

Commit

Permalink
Add frame ancestor configuration for web app to prevent clickjacking
Browse files Browse the repository at this point in the history
  • Loading branch information
FernandezBenjamin committed Jul 18, 2023
1 parent bfa6d61 commit ee39467
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/dex/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ type Web struct {
TLSCert string `json:"tlsCert"`
TLSKey string `json:"tlsKey"`
AllowedOrigins []string `json:"allowedOrigins"`
FrameAncestors []string `json:"frameAncestors"`
}

// Telemetry is the config format for telemetry including the HTTP server config.
Expand Down
4 changes: 4 additions & 0 deletions cmd/dex/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,10 @@ func runServe(options serveOptions) error {
logger.Infof("config allowed origins: %s", c.Web.AllowedOrigins)
}

if len(c.Web.FrameAncestors) > 0 {
logger.Infof("config allowed frame ancestors: %s", c.Web.FrameAncestors)
}

// explicitly convert to UTC.
now := func() time.Time { return time.Now().UTC() }

Expand Down
26 changes: 26 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ type Config struct {
// domain.
AllowedOrigins []string

// List of domain allowed to frame the content of the application.
// By default no one is accepted to prevent against clickjacking.
// Passing in "*" will allow any domain
FrameAncestors []string

// If enabled, the server won't prompt the user to approve authorization requests.
// Logging in implies approval.
SkipApprovalScreen bool
Expand Down Expand Up @@ -339,7 +344,28 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy)
}
}


// frame-ancestors middleware
frameAncestorsMidldleware := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var ancestors string
if len(c.FrameAncestors) > 0 {
for i := 0; i < len(c.FrameAncestors); i++ {
if c.FrameAncestors[i] == issuerURL.String() {
c.FrameAncestors[i] = "'self'"
}
}
ancestors = strings.Join(c.FrameAncestors, " ")
} else {
ancestors = "'none'"
}
w.Header().Set("Content-Security-Policy", "frame-ancestors "+ancestors)
next.ServeHTTP(w, r)
})
}

r := mux.NewRouter().SkipClean(true).UseEncodedPath()
r.Use(frameAncestorsMidldleware)
handle := func(p string, h http.Handler) {
r.Handle(path.Join(issuerURL.Path, p), instrumentHandlerCounter(p, h))
}
Expand Down

0 comments on commit ee39467

Please sign in to comment.