You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fortify检测到Java中JSON注入错误:Gson处理SUBSCRIPTION_JSON遇安全告警

Fixing the Fortify JSON Injection Warning for Your Gson Deserialization

Hey there, let's work through this Fortify JSON injection warning you're hitting in ActionHelper.java line 159. The core issue here is that you’re taking unvalidated JSON input directly from the client (your SUBSCRIPTION_JSON) and deserializing it into a model object without proper checks—Fortify flags this because an attacker could craft malicious JSON that injects unexpected properties or bypasses your model’s intended structure.

Here are concrete steps to fix this:

1. Enforce Strict Gson Deserialization

Gson’s default behavior is lenient—it ignores unknown fields, which leaves room for injection. Instead, configure Gson to fail fast if it encounters unexpected properties, so malicious extra fields are rejected immediately.

// Create a strict Gson instance
Gson strictGson = new GsonBuilder()
    .setLenient(false) // Disable lenient parsing of malformed JSON
    .create();

// Deserialize only with this strict instance
YourSubscriptionModel model = strictGson.fromJson(subscriptionJsonString, YourSubscriptionModel.class);

If the client sends JSON with fields your model doesn’t define, this will throw a JsonSyntaxException—you can catch this and reject the invalid input.

2. Validate Input Against a JSON Schema

For the most robust protection, validate the incoming JSON against a predefined schema before deserializing. This ensures the input matches your expected structure, data types, and allowed values exactly.

First, add a JSON schema validation library (like org.everit.json.schema) to your project. Then:

// Load your schema (could be from a file or embedded string)
JSONObject schemaJson = new JSONObject(Files.readString(Paths.get("subscription-schema.json")));
Schema schema = SchemaLoader.load(schemaJson);

try {
    // Validate the input JSON first
    schema.validate(new JSONObject(subscriptionJsonString));
    // Only proceed to deserialize if validation passes
    YourSubscriptionModel model = new Gson().fromJson(subscriptionJsonString, YourSubscriptionModel.class);
} catch (ValidationException e) {
    // Handle invalid input—log and reject the request
    throw new IllegalArgumentException("Invalid subscription data: " + e.getMessage());
}

Example JSON schema for your subscription model (adjust to match your actual fields):

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "subscriptionId": { "type": "string", "minLength": 1 },
    "planTier": { "type": "string", "enum": ["FREE", "PRO", "ENTERPRISE"] },
    "startDate": { "type": "string", "format": "date-time" }
  },
  "required": ["subscriptionId", "planTier"],
  "additionalProperties": false // Block any extra, unapproved fields
}

3. Sanitize Input by Whitelisting Allowed Fields

If schema validation isn’t an option, explicitly sanitize the JSON by keeping only the fields your model expects. This filters out any unexpected or malicious properties before deserialization:

// Parse raw JSON into a JsonObject
JsonObject rawInput = JsonParser.parseString(subscriptionJsonString).getAsJsonObject();
JsonObject sanitizedInput = new JsonObject();

// Define a whitelist of allowed fields (match your model's fields)
Set<String> allowedFields = Set.of("subscriptionId", "planTier", "startDate");

for (Map.Entry<String, JsonElement> entry : rawInput.entrySet()) {
    if (allowedFields.contains(entry.getKey())) {
        sanitizedInput.add(entry.getKey(), entry.getValue());
    } else {
        // Log unexpected fields for auditing
        logger.warn("Rejected unexpected field in subscription JSON: {}", entry.getKey());
    }
}

// Deserialize the sanitized JSON
YourSubscriptionModel model = new Gson().fromJson(sanitizedInput, YourSubscriptionModel.class);

4. Use Gson's @Expose Annotation (If You Already Use It)

If you’re using @Expose to mark which fields should be deserialized, configure Gson to only process those annotated fields. This automatically ignores any unannotated, unexpected fields:

Gson exposedGson = new GsonBuilder()
    .excludeFieldsWithoutExposeAnnotation()
    .create();

YourSubscriptionModel model = exposedGson.fromJson(subscriptionJsonString, YourSubscriptionModel.class);

Why These Fixes Work

Fortify’s warning stems from unvalidated input being processed into your system. By enforcing strict structure, validating against a schema, or whitelisting fields, you ensure only safe, expected data makes it into your model—blocking any injection attempts.

内容的提问来源于stack exchange,提问作者shrey mathuria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:53:31