-
Notifications
You must be signed in to change notification settings - Fork 334
Add server.request.body.filenames and files_content for GlassFish/Payara #11267
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
Open
jandro996
wants to merge
16
commits into
master
Choose a base branch
from
alejandro.gonzalez/APPSEC-61873-payara
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
ad1dd81
feat(appsec/tomcat): add GlassFish/Payara multipart filename instrume…
jandro996 0d5fd68
fix(appsec): add muzzleDirective and requestFilesContent to GlassFish…
jandro996 9668f39
refactor(appsec): align GlassFish multipart advice with canonical Com…
jandro996 0878a25
fix(appsec): bypass Java module-system IllegalAccessException in Glas…
jandro996 2fc4494
fix(appsec): protect each GlassFish multipart part iteration with per…
jandro996 c08eb04
revert: remove unnecessary setAccessible(true) from ParameterCollector
jandro996 c5091b1
style: replace FQN datadog.trace.api.Config with regular import
jandro996 bf02571
style: skip filenames collection when filenamesCb is null
jandro996 6e7f129
feat(appsec): add blocking fallback for GlassFish/Payara multipart in…
jandro996 b0fe146
style(appsec): address PR review feedback on GlassFish multipart inst…
jandro996 13388cf
fix: restrict GlassFish muzzle range to [4.0, 6.1.0) to exclude jakar…
jandro996 2f1e1be
Merge branch 'master' into alejandro.gonzalez/APPSEC-61873-payara
jandro996 e3426cd
Merge branch 'master' into alejandro.gonzalez/APPSEC-61873-payara
jandro996 aaac59e
fix(appsec): make GlassFishBlockingHelper fields public and avoid Blo…
jandro996 a45b404
refactor(appsec): extract tryBlock() helper and add unit tests for Gl…
jandro996 f6f2feb
refactor: move GlassFish multipart processing into GlassFishBlockingH…
jandro996 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
164 changes: 164 additions & 0 deletions
164
...psec-7.0/src/main/java/datadog/trace/instrumentation/tomcat7/GlassFishBlockingHelper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| package datadog.trace.instrumentation.tomcat7; | ||
|
|
||
| import datadog.appsec.api.blocking.BlockingContentType; | ||
| import datadog.trace.api.Config; | ||
| import datadog.trace.api.gateway.BlockResponseFunction; | ||
| import datadog.trace.api.gateway.Flow; | ||
| import datadog.trace.api.gateway.RequestContext; | ||
| import datadog.trace.api.http.MultipartContentDecoder; | ||
| import datadog.trace.bootstrap.blocking.BlockingActionHelper; | ||
| import java.io.InputStream; | ||
| import java.util.ArrayList; | ||
| import java.util.Collection; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.function.BiFunction; | ||
| import javax.servlet.http.HttpServletRequest; | ||
| import javax.servlet.http.HttpServletResponse; | ||
| import javax.servlet.http.Part; | ||
|
|
||
| public final class GlassFishBlockingHelper { | ||
|
|
||
| public static final int MAX_FILE_CONTENT_COUNT = Config.get().getAppSecMaxFileContentCount(); | ||
| public static final int MAX_FILE_CONTENT_BYTES = Config.get().getAppSecMaxFileContentBytes(); | ||
|
|
||
| /** | ||
| * Attempts to commit a blocking response via the registered {@link BlockResponseFunction} or via | ||
| * the Servlet API fallback, then marks the trace segment as effectively blocked. | ||
| * | ||
| * <p>Returns {@code true} if the response was committed (regardless of whether {@link | ||
| * datadog.trace.api.internal.TraceSegment#effectivelyBlocked()} succeeded). Returns {@code false} | ||
| * if no response could be committed. | ||
| */ | ||
| public static boolean tryBlock( | ||
| RequestContext reqCtx, | ||
| HttpServletRequest fallbackReq, | ||
| HttpServletResponse fallbackResp, | ||
| Flow.Action.RequestBlockingAction rba) { | ||
| try { | ||
| BlockResponseFunction brf = reqCtx.getBlockResponseFunction(); | ||
| if (brf != null) { | ||
| brf.tryCommitBlockingResponse(reqCtx.getTraceSegment(), rba); | ||
| } else if (!commitBlocking(fallbackReq, fallbackResp, rba)) { | ||
| return false; | ||
| } | ||
| } catch (Exception ignored) { | ||
| return false; | ||
| } | ||
| // Response was committed — mark as blocked on a best-effort basis. | ||
| // effectivelyBlocked() can throw if the span is already finished; that must not suppress the | ||
| // true return value since the response has already been sent to the client. | ||
| try { | ||
| reqCtx.getTraceSegment().effectivelyBlocked(); | ||
| } catch (Exception ignored) { | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| /** | ||
| * Collects filenames and file contents from the given multipart parts, fires the AppSec IG | ||
| * callbacks, and commits a blocking response if the WAF requests one. | ||
| * | ||
| * <p>Returns {@code true} if a blocking response was committed (the caller should replace the | ||
| * parts collection with an empty list to prevent further processing). | ||
| */ | ||
| public static boolean processPartsAndBlock( | ||
| Collection<?> parts, | ||
| RequestContext reqCtx, | ||
| HttpServletRequest fallbackReq, | ||
| HttpServletResponse fallbackResp, | ||
| BiFunction<RequestContext, List<String>, Flow<Void>> filenamesCb, | ||
| BiFunction<RequestContext, List<String>, Flow<Void>> contentCb) { | ||
| List<String> filenames = null; | ||
| List<String> contents = null; | ||
| for (Object partObj : parts) { | ||
| try { | ||
| if (!(partObj instanceof Part)) { | ||
| continue; | ||
| } | ||
| Part part = (Part) partObj; | ||
| String filename = part.getSubmittedFileName(); | ||
| if (filename == null) { | ||
| continue; | ||
| } | ||
| if (filenamesCb != null && !filename.isEmpty()) { | ||
| if (filenames == null) { | ||
| filenames = new ArrayList<>(); | ||
| } | ||
| filenames.add(filename); | ||
| } | ||
| if (contentCb != null) { | ||
| if (contents == null) { | ||
| contents = new ArrayList<>(); | ||
| } | ||
| if (contents.size() < MAX_FILE_CONTENT_COUNT) { | ||
| try (InputStream is = part.getInputStream()) { | ||
| contents.add( | ||
| MultipartContentDecoder.readInputStream( | ||
| is, MAX_FILE_CONTENT_BYTES, part.getContentType())); | ||
| } catch (Exception ignored) { | ||
| contents.add(""); | ||
| } | ||
| } | ||
| } | ||
| } catch (Exception ignored) { | ||
| } | ||
| } | ||
|
|
||
| if (filenames != null && !filenames.isEmpty()) { | ||
| Flow<Void> flow = filenamesCb.apply(reqCtx, filenames); | ||
| Flow.Action action = flow.getAction(); | ||
| if (action instanceof Flow.Action.RequestBlockingAction) { | ||
| if (tryBlock( | ||
| reqCtx, fallbackReq, fallbackResp, (Flow.Action.RequestBlockingAction) action)) { | ||
| return true; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (contents != null && !contents.isEmpty()) { | ||
| Flow<Void> contentFlow = contentCb.apply(reqCtx, contents); | ||
| Flow.Action contentAction = contentFlow.getAction(); | ||
| if (contentAction instanceof Flow.Action.RequestBlockingAction) { | ||
| return tryBlock( | ||
| reqCtx, fallbackReq, fallbackResp, (Flow.Action.RequestBlockingAction) contentAction); | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| public static boolean commitBlocking( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| Flow.Action.RequestBlockingAction rba) { | ||
| if (response == null) { | ||
| return false; | ||
| } | ||
| try { | ||
| if (response.isCommitted()) { | ||
| return false; | ||
| } | ||
| response.reset(); | ||
| response.setStatus(BlockingActionHelper.getHttpCode(rba.getStatusCode())); | ||
| for (Map.Entry<String, String> e : rba.getExtraHeaders().entrySet()) { | ||
| response.setHeader(e.getKey(), e.getValue()); | ||
| } | ||
| if (rba.getBlockingContentType() != BlockingContentType.NONE) { | ||
| String accept = request != null ? request.getHeader("Accept") : null; | ||
| BlockingActionHelper.TemplateType type = | ||
| BlockingActionHelper.determineTemplateType(rba.getBlockingContentType(), accept); | ||
| byte[] body = BlockingActionHelper.getTemplate(type, rba.getSecurityResponseId()); | ||
| if (body != null) { | ||
| response.setHeader("Content-Type", BlockingActionHelper.getContentType(type)); | ||
| response.setHeader("Content-Length", Integer.toString(body.length)); | ||
| response.getOutputStream().write(body); | ||
| } | ||
| } | ||
| response.flushBuffer(); | ||
| return true; | ||
| } catch (Exception e) { | ||
| return false; | ||
| } | ||
| } | ||
| } |
130 changes: 130 additions & 0 deletions
130
...rc/main/java/datadog/trace/instrumentation/tomcat7/GlassFishMultipartInstrumentation.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| package datadog.trace.instrumentation.tomcat7; | ||
|
|
||
| import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.named; | ||
| import static datadog.trace.api.gateway.Events.EVENTS; | ||
| import static net.bytebuddy.matcher.ElementMatchers.isPublic; | ||
| import static net.bytebuddy.matcher.ElementMatchers.takesArguments; | ||
|
|
||
| import com.google.auto.service.AutoService; | ||
| import datadog.trace.agent.tooling.Instrumenter; | ||
| import datadog.trace.agent.tooling.InstrumenterModule; | ||
| import datadog.trace.api.gateway.CallbackProvider; | ||
| import datadog.trace.api.gateway.Flow; | ||
| import datadog.trace.api.gateway.RequestContext; | ||
| import datadog.trace.api.gateway.RequestContextSlot; | ||
| import datadog.trace.bootstrap.instrumentation.api.AgentSpan; | ||
| import datadog.trace.bootstrap.instrumentation.api.AgentTracer; | ||
| import java.lang.reflect.Field; | ||
| import java.lang.reflect.Method; | ||
| import java.util.Collection; | ||
| import java.util.Collections; | ||
| import java.util.List; | ||
| import java.util.function.BiFunction; | ||
| import javax.servlet.http.HttpServletRequest; | ||
| import javax.servlet.http.HttpServletResponse; | ||
| import net.bytebuddy.asm.Advice; | ||
|
|
||
| /** | ||
| * GlassFish/Payara does not have {@code Request.parseParts()} — instead {@code Request.getParts()} | ||
| * delegates to {@code org.apache.catalina.fileupload.Multipart.getParts()}. This instrumentation | ||
| * hooks that GlassFish-specific class to report uploaded file names and contents to the AppSec WAF | ||
| * via the {@code requestFilesFilenames} and {@code requestFilesContent} IG events. | ||
| * | ||
| * <p>Because {@code org.apache.catalina.fileupload.Multipart} does not exist in standard Tomcat, | ||
| * this instrumentation is automatically skipped by ByteBuddy on non-GlassFish containers. | ||
| * | ||
| * <p>This advice casts each {@code Part} through the {@code javax.servlet.http.Part} interface | ||
| * (which {@code org.apache.catalina.fileupload.PartItem} implements) to avoid Java module-system | ||
| * access restrictions that prevent reflective invocation of methods on GlassFish-internal classes. | ||
| */ | ||
| @AutoService(InstrumenterModule.class) | ||
| public class GlassFishMultipartInstrumentation extends InstrumenterModule.AppSec | ||
| implements Instrumenter.ForSingleType, Instrumenter.HasMethodAdvice { | ||
|
|
||
| public GlassFishMultipartInstrumentation() { | ||
| super("tomcat"); | ||
| } | ||
|
|
||
| @Override | ||
| public String muzzleDirective() { | ||
| return "glassfish"; | ||
| } | ||
|
|
||
| @Override | ||
| public String instrumentedType() { | ||
| return "org.apache.catalina.fileupload.Multipart"; | ||
| } | ||
|
|
||
| @Override | ||
| public String[] helperClassNames() { | ||
| return new String[] { | ||
| "datadog.trace.instrumentation.tomcat7.GlassFishBlockingHelper", | ||
| }; | ||
| } | ||
|
|
||
| @Override | ||
| public void methodAdvice(MethodTransformer transformer) { | ||
| transformer.applyAdvice( | ||
| named("getParts").and(takesArguments(0)).and(isPublic()), | ||
| getClass().getName() + "$GetPartsAdvice"); | ||
| } | ||
|
|
||
| public static class GetPartsAdvice { | ||
|
|
||
| @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) | ||
| static void after( | ||
| @Advice.This Object thisMultipart, | ||
| @Advice.Return(readOnly = false) Collection<?> parts, | ||
| @Advice.Thrown Throwable t) { | ||
| if (t != null || parts == null || parts.isEmpty()) { | ||
| return; | ||
| } | ||
|
|
||
| AgentSpan agentSpan = AgentTracer.activeSpan(); | ||
| if (agentSpan == null) { | ||
| return; | ||
| } | ||
| RequestContext reqCtx = agentSpan.getRequestContext(); | ||
| if (reqCtx == null || reqCtx.getData(RequestContextSlot.APPSEC) == null) { | ||
| return; | ||
| } | ||
|
|
||
| CallbackProvider cbp = AgentTracer.get().getCallbackProvider(RequestContextSlot.APPSEC); | ||
| BiFunction<RequestContext, List<String>, Flow<Void>> filenamesCb = | ||
| cbp.getCallback(EVENTS.requestFilesFilenames()); | ||
| BiFunction<RequestContext, List<String>, Flow<Void>> contentCb = | ||
| cbp.getCallback(EVENTS.requestFilesContent()); | ||
| if (filenamesCb == null && contentCb == null) { | ||
| return; | ||
| } | ||
|
|
||
| // Extract servlet request/response for fallback blocking when no BlockResponseFunction is | ||
| // registered (Payara: TomcatServerInstrumentation is muzzled out for Payara's response type). | ||
| // setAccessible works here because this code is inlined into Multipart.getParts() — | ||
| // the same module as the private field's owner class. | ||
| HttpServletRequest fallbackReq = null; | ||
| HttpServletResponse fallbackResp = null; | ||
| try { | ||
| Field f = thisMultipart.getClass().getDeclaredField("request"); | ||
| f.setAccessible(true); | ||
| Object catReq = f.get(thisMultipart); | ||
| if (catReq instanceof HttpServletRequest) { | ||
| fallbackReq = (HttpServletRequest) catReq; | ||
| } | ||
| if (catReq != null) { | ||
| Method m = catReq.getClass().getMethod("getResponse"); | ||
| Object catResp = m.invoke(catReq); | ||
| if (catResp instanceof HttpServletResponse) { | ||
| fallbackResp = (HttpServletResponse) catResp; | ||
| } | ||
| } | ||
| } catch (Exception ignored) { | ||
| } | ||
|
|
||
| if (GlassFishBlockingHelper.processPartsAndBlock( | ||
| parts, reqCtx, fallbackReq, fallbackResp, filenamesCb, contentCb)) { | ||
| parts = Collections.emptyList(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This advice only matches
Multipart.getParts(), so GlassFish/Payara requests where application code callsHttpServletRequest.getPart(name)bypass the new AppSec file-name/content publishing entirely. In the GlassFish/Payaraorg.apache.catalina.fileupload.Multipartsource,getPart(String)is a separate public method that callsinitParts()directly rather than delegating togetParts()(see https://www.javatips.net/api/glassfish-main-master/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/Multipart.java), so the addresses remain unset for that common Servlet API path; hookgetParttoo or move the collection logic to the parsing point.Useful? React with 👍 / 👎.