How does Spring prevents request body deserialization attacks? - spring-boot

I have read about deserialization attacks recently and I wonder how does Spring prevent JSON injections. For example let’s consider a request body of a post request, we can instantiate an arbitrary malicious class and execute commands on the server. Are there any mechanisms that check for malicious behavior?
I expect Jackson or other libraries solved these kind of problems.

Related

Is it correct to make a call to another Spring microservice inside a filter?

I built a Spring authentication microservice that takes care of authenticating each REST request. The authentication mechanism has been built using JWT. Each request should present an Authentication: Bearer header.
I also built a gateway microservice that exposes some of the API of the back end microservices. Each request to the gateway should be authenticated. I was thinking about implementing a OncePerRequestFilter, from which I could call the authentication microservice.
#Component
public class AuthFilter extends OncePerRequestFilter {
#Autowired
private RestTemplate restTemplate;
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
// User restTemplate to call the authentication microservice and authenticate the request.
}
}
My question is probably a little too broad, but I wanted to try anyway.
Are there any issues on making a HTTP request inside a Spring filter? Could this lead to hangs or anything in some edge cases or is it just a poor design?
It is okay to call the external service inside a Filter. Spring Security also often does it in various cases (e.g. authenticate against LDAP, get JWK to verify JWT signature etc.) It may not call the external service directly inside the filter , but the filter will delegate to other object to call the external service. But the idea is the same, just make sure that you handle the case when the external service is not available such as setting a reasonable timeout on the HTTP request when calling the external service. Consider it as fail if it cannot receive the response from the external service after timeout.
P.S. Look like you are implementing your own authorization flow. If your authentication service support OAuth2 , you can consider to try Spring Security 5 's OAuth2 support which may make your life easier.
I agree with you that this approach is contradictory.
I see 2 main constraints in this approach:
this filter in request scope, so you can face with connection/read timeout;
more complex error handling (nested structure requires more accuracy in that).
If you can avoid these constraints, you can use this approach: RestTemplate is synchronous and blocking, so your filter will wait for results of RestTemplate call. With WebClient, such task could be unachievable.
Obviously that this implementation contradicts to SOLID, so better change your design/architecture.
It's a general practice to make HTTP calls from one microservice to another.
When dealing with authentication in REST API using JWT tokens it's a common practice to load cryptographic keys from a well known URL (https://YOUR_DOMAIN/.well-known/jwks.json) as JSON Web Key Set (JWKS).
According to SOLID principles, it's a good practice to create a dedicated class (Spring service) responsible for calling another service instead of injecting RestTemplate directly into the Filter.
The less responsibilities class has, the easier (less error-prone) it is to make changes to it in the future and cover code with unit tests. When all the logic is located in a single class, you have a lot of test cases and complicated mocking. When class has a single responsibility and calls another classes, it's easy to mock these classes and test only this single responsibility.
When a microservice calls another microservice via REST API, there are a few aspects that should be taken into account:
Failover - have multiple instances of the microservice to tolerate failure if a single instance
Scalability - dynamically start more microservice instances to handle growing load
Load balancing - route requests to different instances of the microservice
Service discovery - allow microservices to find each other by logical name instead of hard-coding host and port values
Timeouts - drop a request to a downstream microservice after exceeding timeout instead of waiting for the response forever
Retries - retry failed requests to a downstream microservice
Circuit breaker - prevent network or service failure from cascading to other services
These aspects are covered by Kubernetes + Istio or Spring Cloud stack.
If synchronous REST API calls between microservices are replaced with asynchronous messaging then almost all of these aspects are not so important.
For example, service A, instead of calling service B via REST API, subscribes on events emitted by service B to a Kafka topic. Every time event occurs, service A receives notification and persists the required data in own DB.
Such approach allows to achieve maximum decoupling between services but leads to eventual consistency. It means, it doesn't suit authentication and other strongly consistent cases. E.g. checking account balance is strongly consistent and should be done using synchronous call.

Is it possible to disable Spring Cloud Sleuth header propagation based on destination URL?

We're using Brave's ExtraFieldPropagation feature to propagate custom fields (e.g. an internal-only request identifier) between services as HTTP headers.
Some of our services make requests to external services using a RestTemplate or Feign client in the course of processing a request. Since Sleuth enhances all RestTemplate beans and Feign clients with the propagation feature, this means that external services receive the internal-only headers, which I'd like to avoid.
I know of two workarounds that allow me to avoid this behavior, both of which are flawed:
Instantiate a client object manually as opposed to using a #Bean so that Sleuth does not add an interceptor. The downside I see here is that developers have to remember to follow this pattern to avoid leaking information, and this is difficult to enforce.
Add an interceptor that removes these headers from outgoing requests. The downsides here are that a) I need separate interceptors for RestTemplate and Feign clients (not a huge deal); b) it looks like Feign client interceptors do not have a way to influence order of execution (see javadoc here), so I can't guarantee that the new interceptor will run last / after the Sleuth one.
Is there a way to customize Sleuth (e.g. via some kind of injector bean) such that, prior to injecting headers in an outgoing HTTP request, I can reason about the destination of the request? I saw documentation regarding custom injector beans, but it appears those no longer exist in spring boot >= 2. I can't seem to find an equivalent construct in Brave.
You can unsample a given URL which means that the headers will be propagated but not sent to Zipkin. You can't disable instrumentation for only some of the URLs cause we're instrumenting all of the components that are registered as beans.

How to pass HTTP request to Web-Service

From my portlet JSP, I am trying to make a Ajax call to web-service.
My aim is to pass HTTP request object as a parameter to web-service method.
Please suggest.
Suggesting to rethink your problem. A servlet request object does not make any sense as parameter for a web service call. Those are two totally different frameworks. A servlet request only makes sense within the processing of a servlet and is defined within that context.
You are probably interested in some data from that object, e.g. attributes or some data from the session. Use exactly that data as parameters and forget about your original plans

Spring Integration - handlers vs interceptors

In Spring Integration, handlers and interceptors look like they basically achieve the same thing. There are even some 'duped' implementations, such as MessageTransformingChannelInterceptor and MessageTransformingHandler, which as far as I can tell provide the same functionality with different semantics.
Is there a time when one is appropriate and not another? If it's a matter of preference then I'm guessing that there'd be some sort of convention?
Thanks,
Roy
My general rule of thumb is to use interceptors sparingly; and typically, only for "passive" things like logging, wire tap etc.
Some users like to do message validation in interceptors; especially if they want to apply the same validation to multiple channels, perhaps with a global interceptor with an appropriate channel pattern.
The transforming interceptor was created in a very early iteration of the framework (2008) and we should probably remove (at least) the only mention of it in the reference (in the XML section).
Handlers
Handler means a Class which handles with certain thing.
For example, in the Spring framework, a HandlerMapping is used to map requests to specific controllers or handlers based on the URL pattern or request method.
Handler is responsible for processing a request and generating a response while a Filter is responsible for modifying or inspecting a request or response
Interceptors
Interceptors share a common API for the server and the client side.
Interceptors are often used to implement cross-cutting concerns such as transaction management, security, or logging.
Interceptors are part of Spring's AOP framework and are used to intercept method calls to Spring beans. They allow you to add behaviour to a method call before or after it is executed. Interceptors can be configured using annotations or XML configuration. Interceptors are used to intercept method calls to Spring beans.

What is the correct way to configure spring security to accept JSON based requests

I'm trying to figure out what the correct way to configure SpringSecurity is to receive, respond to json based authentication requests.
There appear to be two ways to do this :
Use the spring security configuration to route authentication requests to a Controller...see http://raibledesigns.com/rd/entry/implementing_ajax_authentication_using_jquery
Create a new AuthenticationFilter, AuthenticationSuccessHandler, AuthenticationFailureHandler...see https://github.com/loiane/spring-security-extjs-login
It looks like the AuthenticationFilter method fits into the framework better, and ensures that filters that come afterward in the chain execute.
Anyone know what the pros/cons of either approach are?

Resources