Skip to content

Feat/hardening #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ specifications promoted by the SDA SE.

## Features

| **Starter** | **Description** |
|-------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [sda-commons-starter-web](web/index.md) | Provides the required features for an SDA-compliant microservice including OIDC authentication, OPA authorization, health checks, OpenTracing and Prometheus metrics. |
| [sda-commons-starter-mongodb](mongodb/index.md) | Provides default configuration based on the `org.springframework.boot:spring-boot-starter-data-mongodb` |
| [sda-commons-starter-kafka](kafka/index.md) | Provides default producer und consumer configuration based on `org.springframework.kafka:spring-kafka` |
| [sda-commons-starter-s3](s3/index.md) | Provides features for dealing with the Amazon S3 file storage |
| **Starter** | **Description** |
|-------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [sda-commons-starter-web](web/index.md) | Provides the required features for an SDA-compliant microservice including OIDC authentication, OPA authorization, health checks, OpenTelemetry, Prometheus metrics and [hardening the service](security/index.md). |
| [sda-commons-starter-mongodb](mongodb/index.md) | Provides default configuration based on the `org.springframework.boot:spring-boot-starter-data-mongodb` |
| [sda-commons-starter-kafka](kafka/index.md) | Provides default producer und consumer configuration based on `org.springframework.kafka:spring-kafka` |
| [sda-commons-starter-s3](s3/index.md) | Provides features for dealing with the Amazon S3 file storage |

The provided documentation aims to provide SDA-specific information.
All other information are referenced in the Spring and [Spring Boot documentation](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#documentation).
Expand Down
69 changes: 69 additions & 0 deletions docs/security/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Security Hardening

sda-spring-boot-commons changes some default configuration for security reasons.
This document provides a brief overview about the addressed risks.

## Risk: Accessing critical resources from untrusted environments

To avoid exposing internal resources, Spring Boot Actuator is configured to listen on a separate
port.
Health, metrics and other sensitive information can't be exposed to the internet by accident, e.g.
by missing to exclude the actuator path.

Custom critical resources can be exposed at the management port by implementing
`org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint` or
`org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpoint`.
Note that there is an [open discussion](https://github.com/spring-projects/spring-boot/issues/31768)
about these annotations.
As long as they are not deprecated, it is suggested to use them because the use is most similar to
controllers used in regular REST APIs.

## Risk: Root start

If the service is started with extended privileges as the root user, an attacker can more easily
attack the operating system after taking over from the container.

The default configuration is capable to run as no root, listening to ports 8080 and 8081.
Deployment checks must ensure, that the container is not configured with a root user.

## Risk: Exploitation of HTTP methods

The HTTP method `TRACE` is disabled by default to mitigate [Cross Site Tracing](https://owasp.org/www-community/attacks/Cross_Site_Tracing).

## Risk: Loss of source IP address

We expect, the services built with sda-spring-boot-commons are deployed behind a proxy, e.g. an
Ingress in Kubernetes.

This library is configured by default to consider `X-Forwarded-*` headers to identify the original
caller.

## Risk: Detection of confidential components

Knowing the components used in a software makes it easier to look for and exploit specific CVEs.

Custom error handlers and other configurations are used to avoid identifiable default output from
the framework and its components.

## Risk: Lack of visibility

If there is no visibility, there is no response to an abusive action and attackers can explore risks
undisturbed.

Logs are written to standard out by default to comply with Kubernetes environments.
Prometheus metrics are exposed as expected by SDA environments.

## Risk: Buffer Overflow

The size of request and response headers is limited to 8KiB.

## Header

By configuring the default headers, the following risks are addressed:

- Cross-Site Scripting
- Content interpretation by the browser
- Content loading in Flash and PDFs
- Clickjacking
- Sharing visited URLs with third parties
- Abuse from Cross-Origin Resource Sharing
16 changes: 7 additions & 9 deletions docs/web/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ Features:
- [Jackson Object Mapping](#jackson)
- [Monitoring](#monitoring)
- [Tracing](#tracing)
- [Health Checks](#health-checks)
- [Testing](#testing)
- [Health Checks](#health-checks--actuator)
- [Logging](#logging)

Based on:
Expand Down Expand Up @@ -41,6 +40,7 @@ Based on:
| `oidc.client.id` _string_ | The client ID for the registration. | `` | `exampleClient` | `OPA_CLIENT_ID` |
| `oid.client.secret` _string_ | The Client secret of the registration. | `` | `s3cret` | `OIDC_CLIENT_SECRET` |
| `oidc.client.issuer.uri` _string_ | URI that can either be an OpenID Connect discovery endpoint or an OAuth 2.0 Authorization Server Metadata endpoint defined by RFC 8414. | `` | `https://keycloak.sdadev.sda-se.io/auth/realms/exampleRealm` | `OIDC_CLIENT_ISSUER_URI` |
| `cors.allowed-origin-patterns` _string_ | Comma separated list of URL patterns for which CORS requests are allowed. | _none allowed_ | `https://*.all-subdomains.com, https://static-domain.com` | `CORS_ALLOWEDORIGINPATTERNS` |

For further information have a look at the [Spring Boot documentation](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#documentation).

Expand Down Expand Up @@ -111,9 +111,10 @@ public class MyConstraints extends AbstractConstraints {
```java
@RestController
public class AuthTestApp {

@Autowired private MyConstraints myConstraints;
...
@Autowired
private MyConstraints myConstraints;
// ...
}
```

### Testing
Expand Down Expand Up @@ -176,7 +177,7 @@ allow {
# set some example constraints
constraint1 := true # always true
constraint2 := [ "v2.1", "v2.2" ] # always an array of "v2.1" and "v2.2"
constraint3[token.payload.sub]. # always a set that contains the 'sub' claim from the token
constraint3[token.payload.sub] # always a set that contains the 'sub' claim from the token
# or is empty if no token is present

```
Expand Down Expand Up @@ -543,6 +544,3 @@ The Spring Boot default is enabled.
* `classpath:org/sdase/commons/spring/logging/logback-json.xml` for Json Logging
* Example: `classpath:org/sdase/commons/spring/logging/logback-json.xml`
* Default: `org/springframework/boot/logging/logback/defaults.xml`


## Testing
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import org.sdase.commons.spring.boot.web.docs.EnableSdaDocs;
import org.sdase.commons.spring.boot.web.jackson.EnableSdaRestGuide;
import org.sdase.commons.spring.boot.web.monitoring.EnableSdaMonitoring;
import org.sdase.commons.spring.boot.web.security.EnableSdaWebSecurity;
import org.springframework.context.annotation.Import;

/**
Expand All @@ -38,8 +39,9 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@EnableSdaDocs
@EnableSdaRestGuide
@EnableSdaWebSecurity
@EnableSdaDocs
@EnableSdaSecurity
@EnableSdaClients
@EnableSdaAsyncWithRequestContext
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
package org.sdase.commons.spring.boot.web.auth;

import java.util.List;
import org.sdase.commons.spring.boot.web.auth.management.ManagementAccessDecisionVoter;
import org.sdase.commons.spring.boot.web.auth.opa.OpaAccessDecisionVoter;
import org.sdase.commons.spring.boot.web.auth.opa.OpaExcludesDecisionVoter;
import org.springframework.security.access.vote.UnanimousBased;
Expand All @@ -17,8 +18,9 @@
public class SdaAccessDecisionManager extends UnanimousBased {

public SdaAccessDecisionManager(
ManagementAccessDecisionVoter managementAccessDecisionVoter,
OpaExcludesDecisionVoter opaExcludesDecisionVoter,
OpaAccessDecisionVoter opaAccessDecisionVoter) {
super(List.of(opaExcludesDecisionVoter, opaAccessDecisionVoter));
super(List.of(managementAccessDecisionVoter, opaExcludesDecisionVoter, opaAccessDecisionVoter));
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
package org.sdase.commons.spring.boot.web.auth;

import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
import org.sdase.commons.spring.boot.web.security.headers.SdaSecurityHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
Expand All @@ -26,6 +28,7 @@
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.resource.authentication.JwtIssuerAuthenticationManagerResolver;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
import org.springframework.util.StringUtils;

@EnableWebSecurity
Expand All @@ -41,6 +44,8 @@ public class SdaSecurityConfiguration {

private final SdaAccessDecisionManager sdaAccessDecisionManager;

private final SdaSecurityHeaders sdaSecurityHeaders;

/**
* @param issuers Comma separated string of open id discovery key sources with required issuers.
* @param disableAuthentication Disables all authentication
Expand All @@ -50,10 +55,12 @@ public class SdaSecurityConfiguration {
public SdaSecurityConfiguration(
@Value("${auth.issuers:}") String issuers,
@Value("${auth.disable:false}") boolean disableAuthentication,
SdaAccessDecisionManager sdaAccessDecisionManager) {
SdaAccessDecisionManager sdaAccessDecisionManager,
Optional<SdaSecurityHeaders> sdaSecurityHeaders) {
this.issuers = issuers;
this.disableAuthentication = disableAuthentication;
this.sdaAccessDecisionManager = sdaAccessDecisionManager;
this.sdaSecurityHeaders = sdaSecurityHeaders.orElse(List::of);
}

@Bean
Expand Down Expand Up @@ -82,7 +89,11 @@ private void oidcAuthentication(HttpSecurity http) throws Exception {
authorize ->
authorize.anyRequest().permitAll().accessDecisionManager(sdaAccessDecisionManager))
.oauth2ResourceServer(
oauth2 -> oauth2.authenticationManagerResolver(authenticationManagerResolver));
oauth2 -> oauth2.authenticationManagerResolver(authenticationManagerResolver))
.headers(
configurer ->
configurer.addHeaderWriter(
new StaticHeadersWriter(sdaSecurityHeaders.getSecurityHeaders())));
}

private AuthenticationManagerResolver<HttpServletRequest> createAuthenticationManagerResolver() {
Expand Down Expand Up @@ -111,7 +122,11 @@ private void noAuthentication(HttpSecurity http) throws Exception {
.disable() // NOSONAR
.authorizeRequests(
authorize ->
authorize.anyRequest().permitAll().accessDecisionManager(sdaAccessDecisionManager));
authorize.anyRequest().permitAll().accessDecisionManager(sdaAccessDecisionManager))
.headers(
configurer ->
configurer.addHeaderWriter(
new StaticHeadersWriter(sdaSecurityHeaders.getSecurityHeaders())));
}

private List<String> commaSeparatedStringToList(String issuers) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright 2022- SDA SE Open Industry Solutions (https://www.sda.se)
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package org.sdase.commons.spring.boot.web.auth.management;

import java.util.Collection;
import org.springframework.boot.actuate.autoconfigure.web.server.ConditionalOnManagementPort;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

public interface ManagementAccessDecisionVoter extends AccessDecisionVoter<FilterInvocation> {

@Override
default boolean supports(ConfigAttribute attribute) {
return true;
}

@Override
default boolean supports(Class<?> clazz) {
return FilterInvocation.class.isAssignableFrom(clazz);
}

@Component
@ConditionalOnManagementPort(ManagementPortType.DIFFERENT)
class DifferentPortManagementAccessDecisionVoter implements ManagementAccessDecisionVoter {

/**
* The management port discovered in {@link
* #onApplicationEvent(ServletWebServerInitializedEvent)}. Initially a value that can't be an
* existing port to avoid granting access by accident to the application API.
*/
private int managementPort = -1;

@EventListener
public void onApplicationEvent(ServletWebServerInitializedEvent event) {
if ("management".equals(event.getApplicationContext().getServerNamespace())) {
this.managementPort = event.getWebServer().getPort();
}
}

@Override
public int vote(
Authentication authentication,
FilterInvocation filterInvocation,
Collection<ConfigAttribute> attributes) {
int requestLocalPort = filterInvocation.getRequest().getLocalPort();
return requestLocalPort == this.managementPort ? ACCESS_GRANTED : ACCESS_ABSTAIN;
}
}

@Component
@ConditionalOnManagementPort(ManagementPortType.SAME)
class IgnoreSamePortManagementAccessDecisionVoter implements ManagementAccessDecisionVoter {
@Override
public int vote(
Authentication authentication,
FilterInvocation filterInvocation,
Collection<ConfigAttribute> attributes) {
return ACCESS_ABSTAIN;
}
}

@Component
@ConditionalOnManagementPort(ManagementPortType.DISABLED)
class DisabledManagementAccessDecisionVoter implements ManagementAccessDecisionVoter {
@Override
public int vote(
Authentication authentication,
FilterInvocation filterInvocation,
Collection<ConfigAttribute> attributes) {
return ACCESS_ABSTAIN;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
package org.sdase.commons.spring.boot.web.error;

import javax.servlet.http.HttpServletRequest;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
Expand All @@ -16,6 +18,7 @@
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {

@ResponseBody
Expand Down
Loading