|
| 1 | +package datadog.trace.instrumentation.okhttp3; |
| 2 | + |
| 3 | +import static datadog.trace.api.gateway.Events.EVENTS; |
| 4 | + |
| 5 | +import datadog.appsec.api.blocking.BlockingException; |
| 6 | +import datadog.trace.api.Config; |
| 7 | +import datadog.trace.api.appsec.HttpClientPayload; |
| 8 | +import datadog.trace.api.appsec.HttpClientRequest; |
| 9 | +import datadog.trace.api.appsec.HttpClientResponse; |
| 10 | +import datadog.trace.api.appsec.MediaType; |
| 11 | +import datadog.trace.api.gateway.BlockResponseFunction; |
| 12 | +import datadog.trace.api.gateway.CallbackProvider; |
| 13 | +import datadog.trace.api.gateway.Flow; |
| 14 | +import datadog.trace.api.gateway.RequestContext; |
| 15 | +import datadog.trace.api.gateway.RequestContextSlot; |
| 16 | +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; |
| 17 | +import datadog.trace.bootstrap.instrumentation.api.AgentTracer; |
| 18 | +import datadog.trace.bootstrap.instrumentation.api.Tags; |
| 19 | +import java.io.ByteArrayInputStream; |
| 20 | +import java.io.ByteArrayOutputStream; |
| 21 | +import java.io.IOException; |
| 22 | +import java.util.Collections; |
| 23 | +import java.util.HashMap; |
| 24 | +import java.util.List; |
| 25 | +import java.util.Map; |
| 26 | +import java.util.function.BiFunction; |
| 27 | +import okhttp3.Headers; |
| 28 | +import okhttp3.Interceptor; |
| 29 | +import okhttp3.Request; |
| 30 | +import okhttp3.RequestBody; |
| 31 | +import okhttp3.Response; |
| 32 | +import okhttp3.ResponseBody; |
| 33 | +import okio.BufferedSink; |
| 34 | +import okio.BufferedSource; |
| 35 | +import okio.Okio; |
| 36 | +import okio.Sink; |
| 37 | +import org.slf4j.Logger; |
| 38 | +import org.slf4j.LoggerFactory; |
| 39 | + |
| 40 | +public class AppSecInterceptor implements Interceptor { |
| 41 | + |
| 42 | + private static final int BODY_PARSING_SIZE_LIMIT = Config.get().getAppSecBodyParsingSizeLimit(); |
| 43 | + |
| 44 | + private static final Logger LOGGER = LoggerFactory.getLogger(AppSecInterceptor.class); |
| 45 | + |
| 46 | + @Override |
| 47 | + public Response intercept(final Chain chain) throws IOException { |
| 48 | + try { |
| 49 | + final AgentSpan span = AgentTracer.activeSpan(); |
| 50 | + final RequestContext ctx = span == null ? null : span.getRequestContext(); |
| 51 | + if (ctx == null) { |
| 52 | + return chain.proceed(chain.request()); |
| 53 | + } |
| 54 | + final long requestId = span.getSpanId(); |
| 55 | + final boolean sampled = sampleRequest(ctx, requestId); |
| 56 | + final Request request = onRequest(span, sampled, chain.request()); |
| 57 | + final Response response = chain.proceed(request); |
| 58 | + return onResponse(span, sampled, response); |
| 59 | + } catch (final Exception e) { |
| 60 | + LOGGER.debug("Failed to intercept request", e); |
| 61 | + return chain.proceed(chain.request()); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + private Request onRequest(final AgentSpan span, final boolean sampled, final Request request) { |
| 66 | + Request result = request; |
| 67 | + CallbackProvider cbp = AgentTracer.get().getCallbackProvider(RequestContextSlot.APPSEC); |
| 68 | + BiFunction<RequestContext, HttpClientRequest, Flow<Void>> requestCb = |
| 69 | + cbp.getCallback(EVENTS.httpClientRequest()); |
| 70 | + if (requestCb == null) { |
| 71 | + return request; |
| 72 | + } |
| 73 | + |
| 74 | + final RequestBody requestBody = request.body(); |
| 75 | + final RequestContext ctx = span.getRequestContext(); |
| 76 | + final long requestId = span.getSpanId(); |
| 77 | + final String url = span.getTag(Tags.HTTP_URL).toString(); |
| 78 | + final HttpClientRequest clientRequest = |
| 79 | + new HttpClientRequest(requestId, url, request.method(), mapHeaders(request.headers())); |
| 80 | + if (sampled && requestBody != null) { |
| 81 | + // we are going to effectively read all the request body in memory to be analyzed by the WAF, |
| 82 | + // we also modify the outbound request accordingly |
| 83 | + final MediaType mediaType = contentType(requestBody); |
| 84 | + try { |
| 85 | + final long contentLength = requestBody.contentLength(); |
| 86 | + if (shouldProcessBody(contentLength, mediaType)) { |
| 87 | + final byte[] payload = readBody(requestBody, (int) contentLength); |
| 88 | + if (payload.length <= BODY_PARSING_SIZE_LIMIT) { |
| 89 | + clientRequest.setBody(mediaType, new ByteArrayInputStream(payload)); |
| 90 | + } |
| 91 | + result = |
| 92 | + request |
| 93 | + .newBuilder() |
| 94 | + .method(request.method(), RequestBody.create(requestBody.contentType(), payload)) |
| 95 | + .build(); // update request |
| 96 | + } |
| 97 | + } catch (IOException e) { |
| 98 | + // ignore it and keep the original request |
| 99 | + } |
| 100 | + } |
| 101 | + publish(ctx, clientRequest, requestCb); |
| 102 | + return result; |
| 103 | + } |
| 104 | + |
| 105 | + private Response onResponse( |
| 106 | + final AgentSpan span, final boolean sampled, final Response response) { |
| 107 | + Response result = response; |
| 108 | + CallbackProvider cbp = AgentTracer.get().getCallbackProvider(RequestContextSlot.APPSEC); |
| 109 | + BiFunction<RequestContext, HttpClientResponse, Flow<Void>> responseCb = |
| 110 | + cbp.getCallback(EVENTS.httpClientResponse()); |
| 111 | + if (responseCb == null) { |
| 112 | + return response; |
| 113 | + } |
| 114 | + final ResponseBody responseBody = response.body(); |
| 115 | + final RequestContext ctx = span.getRequestContext(); |
| 116 | + final long requestId = span.getSpanId(); |
| 117 | + final HttpClientResponse clientResponse = |
| 118 | + new HttpClientResponse(requestId, response.code(), mapHeaders(response.headers())); |
| 119 | + if (sampled && responseBody != null) { |
| 120 | + // we are going to effectively read all the response body in memory to be analyzed by the WAF, |
| 121 | + // we also |
| 122 | + // modify the inbound response accordingly |
| 123 | + final MediaType mediaType = contentType(responseBody); |
| 124 | + try { |
| 125 | + final long contentLength = responseBody.contentLength(); |
| 126 | + if (shouldProcessBody(contentLength, mediaType)) { |
| 127 | + final byte[] payload = readBody(responseBody, (int) contentLength); |
| 128 | + if (payload.length <= BODY_PARSING_SIZE_LIMIT) { |
| 129 | + clientResponse.setBody(mediaType, new ByteArrayInputStream(payload)); |
| 130 | + } |
| 131 | + result = |
| 132 | + response |
| 133 | + .newBuilder() |
| 134 | + .body(ResponseBody.create(responseBody.contentType(), payload)) |
| 135 | + .build(); |
| 136 | + } |
| 137 | + } catch (IOException e) { |
| 138 | + // ignore it and keep the original response |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + publish(ctx, clientResponse, responseCb); |
| 143 | + return result; |
| 144 | + } |
| 145 | + |
| 146 | + private <P extends HttpClientPayload> void publish( |
| 147 | + final RequestContext ctx, |
| 148 | + final P request, |
| 149 | + final BiFunction<RequestContext, P, Flow<Void>> callback) { |
| 150 | + Flow<Void> flow = callback.apply(ctx, request); |
| 151 | + Flow.Action action = flow.getAction(); |
| 152 | + if (action instanceof Flow.Action.RequestBlockingAction) { |
| 153 | + BlockResponseFunction brf = ctx.getBlockResponseFunction(); |
| 154 | + if (brf != null) { |
| 155 | + Flow.Action.RequestBlockingAction rba = (Flow.Action.RequestBlockingAction) action; |
| 156 | + brf.tryCommitBlockingResponse( |
| 157 | + ctx.getTraceSegment(), |
| 158 | + rba.getStatusCode(), |
| 159 | + rba.getBlockingContentType(), |
| 160 | + rba.getExtraHeaders()); |
| 161 | + } |
| 162 | + throw new BlockingException("Blocked request (for http downstream request)"); |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + private boolean sampleRequest(final RequestContext ctx, final long requestId) { |
| 167 | + // Check if the current http request was sampled |
| 168 | + CallbackProvider cbp = AgentTracer.get().getCallbackProvider(RequestContextSlot.APPSEC); |
| 169 | + BiFunction<RequestContext, Long, Flow<Boolean>> samplingCb = |
| 170 | + cbp.getCallback(EVENTS.httpClientSampling()); |
| 171 | + if (samplingCb == null) { |
| 172 | + return false; |
| 173 | + } |
| 174 | + final Flow<Boolean> sampled = samplingCb.apply(ctx, requestId); |
| 175 | + return sampled.getResult() != null && sampled.getResult(); |
| 176 | + } |
| 177 | + |
| 178 | + /** |
| 179 | + * Ensure we are only consuming payloads we can safely deserialize with a bounded size to prevent |
| 180 | + * from OOM |
| 181 | + */ |
| 182 | + private boolean shouldProcessBody(final long contentLength, final MediaType mediaType) { |
| 183 | + if (contentLength <= 0) { |
| 184 | + return false; // prevent from copying from unbounded source (just to be safe) |
| 185 | + } |
| 186 | + if (BODY_PARSING_SIZE_LIMIT <= 0) { |
| 187 | + return false; // effectively disabled by configuration |
| 188 | + } |
| 189 | + if (contentLength > BODY_PARSING_SIZE_LIMIT) { |
| 190 | + return false; |
| 191 | + } |
| 192 | + return mediaType.isDeserializable(); |
| 193 | + } |
| 194 | + |
| 195 | + private byte[] readBody(final RequestBody body, final int contentLength) throws IOException { |
| 196 | + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(contentLength); |
| 197 | + try (final BufferedSink sink = Okio.buffer(Okio.sink(buffer))) { |
| 198 | + body.writeTo(sink); |
| 199 | + } |
| 200 | + return buffer.toByteArray(); |
| 201 | + } |
| 202 | + |
| 203 | + private byte[] readBody(final ResponseBody body, final int contentLength) throws IOException { |
| 204 | + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(contentLength); |
| 205 | + try (final BufferedSource source = body.source(); |
| 206 | + final Sink sink = Okio.sink(buffer)) { |
| 207 | + source.readAll(sink); |
| 208 | + } |
| 209 | + return buffer.toByteArray(); |
| 210 | + } |
| 211 | + |
| 212 | + private Map<String, List<String>> mapHeaders(final Headers headers) { |
| 213 | + if (headers == null) { |
| 214 | + return Collections.emptyMap(); |
| 215 | + } |
| 216 | + final Map<String, List<String>> result = new HashMap<>(headers.size()); |
| 217 | + for (final String name : headers.names()) { |
| 218 | + result.put(name, headers.values(name)); |
| 219 | + } |
| 220 | + return result; |
| 221 | + } |
| 222 | + |
| 223 | + private MediaType contentType(final RequestBody body) { |
| 224 | + return MediaType.parse( |
| 225 | + body == null || body.contentType() == null ? null : body.contentType().toString()); |
| 226 | + } |
| 227 | + |
| 228 | + private MediaType contentType(final ResponseBody body) { |
| 229 | + return MediaType.parse( |
| 230 | + body == null || body.contentType() == null ? null : body.contentType().toString()); |
| 231 | + } |
| 232 | +} |
0 commit comments