luchunliang commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3533400153


##########
inlong-agent/agent-installer/src/main/java/org/apache/inlong/agent/installer/validator/ModuleCommandValidator.java:
##########
@@ -0,0 +1,449 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.inlong.agent.installer.validator;
+
+import lombok.Getter;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Structured whitelist validator applied to raw command strings coming from
+ * {@code ModuleConfig}. It enforces four layers of defence:
+ *
+ * <ol>
+ *   <li><b>Structured splitting</b>: the raw command is split into 
sub-commands on {@code ;},
+ *       each sub-command is further split into pipe segments on {@code |}, 
and every pipe
+ *       segment is tokenized into an {@code argv[]}. Once split this way, 
{@code ;} and
+ *       {@code |} are Java-side delimiters instead of shell 
metacharacters.</li>
+ *   <li><b>Metacharacter blacklist</b>: reject the whole command if it 
contains a backtick,
+ *       {@code $(}, {@code &&}, {@code ||}, {@code >}, {@code >>}, {@code <}, 
or a line break
+ *       character. ({@code |} and {@code ;} are already consumed by the 
previous layer.)</li>
+ *   <li><b>argv[0] whitelist</b>: the first token of every pipe segment must 
appear in
+ *       {@link #COMMAND_WHITELIST}, otherwise {@link 
#RULE_NOT_IN_WHITELIST}.</li>
+ *   <li><b>Argument policy</b>: for write-oriented commands, path arguments 
are tilde-expanded,
+ *       normalized via {@link Path#normalize()}, and then checked with
+ *       {@link AllowedRootsResolver#isUnderAllowedRoot(Path)}; {@code 
sh}/{@code bash} may not
+ *       receive a {@code -c} flag ({@link #RULE_FORBIDDEN_SH_C_FLAG}).</li>
+ * </ol>
+ */
+public final class ModuleCommandValidator {
+
+    /** First-level command whitelist. */
+    public static final Set<String> COMMAND_WHITELIST = buildImmutableSet(
+            "cd", "sh", "bash", "ps", "grep", "awk", "kill", "rm", "mkdir", 
"cp", "mv", "ln",
+            "tar", "unzip", "chmod", "chown", "echo", "cat", "test", "[", 
"true", "false", "java");
+
+    /** Write-oriented commands whose path arguments must live under an 
allowed root. */
+    public static final Set<String> WRITE_LIKE_COMMANDS = buildImmutableSet(
+            "rm", "cp", "mv", "mkdir", "ln", "chmod", "chown", "tar", "unzip");
+
+    private static Set<String> buildImmutableSet(String... items) {
+        Set<String> s = new HashSet<>(items.length * 2);
+        Collections.addAll(s, items);
+        return Collections.unmodifiableSet(s);
+    }
+
+    /** Substring blacklist for the metacharacter check. */
+    private static final String[] META_CHAR_BLACKLIST = new String[]{
+            "`", "$(", "&&", "||", ">>", ">", "<"
+    };
+
+    public static final String RULE_DISALLOWED_META_CHAR = 
"DISALLOWED_META_CHAR";
+    public static final String RULE_NOT_IN_WHITELIST = "NOT_IN_WHITELIST";
+    public static final String RULE_PATH_NOT_UNDER_ALLOWED_ROOT = 
"PATH_NOT_UNDER_ALLOWED_ROOT";
+    public static final String RULE_FORBIDDEN_SH_C_FLAG = 
"FORBIDDEN_SH_C_FLAG";
+    public static final String RULE_EMPTY_COMMAND = "EMPTY_COMMAND";
+
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(ModuleCommandValidator.class);
+
+    private final AllowedRootsResolver allowedRootsResolver;
+
+    public ModuleCommandValidator(AllowedRootsResolver allowedRootsResolver) {
+        this.allowedRootsResolver = allowedRootsResolver;
+    }
+
+    /** Validate a raw command string. */
+    public ValidationResult validate(String rawCmd) {
+        if (StringUtils.isBlank(rawCmd)) {
+            return ValidationResult.fail(RULE_EMPTY_COMMAND, rawCmd, "raw 
command is blank");
+        }
+
+        // Scan the whole command for metacharacters first, so a hostile 
sub-command cannot
+        // bypass the check by hiding after ';'.
+        String metaHit = firstMetaCharHit(rawCmd);
+        if (metaHit != null) {
+            return ValidationResult.fail(RULE_DISALLOWED_META_CHAR, rawCmd,
+                    "hit meta char: " + metaHit);
+        }
+        if (rawCmd.indexOf('\n') >= 0 || rawCmd.indexOf('\r') >= 0) {
+            return ValidationResult.fail(RULE_DISALLOWED_META_CHAR, rawCmd,
+                    "hit line-break char");
+        }
+
+        // split by ';' into sub-commands, then by '|' into pipe segments, then
+        // tokenize each segment into argv.
+        List<ParsedSubCmd> subs = new ArrayList<>();
+        String[] segments = rawCmd.split(";");
+        for (String seg : segments) {
+            String trimmed = seg == null ? "" : seg.trim();
+            if (trimmed.isEmpty()) {
+                continue;
+            }
+            ParsedSubCmd sub = parseSubCmd(trimmed);
+            if (sub == null) {
+                return ValidationResult.fail(RULE_EMPTY_COMMAND, trimmed,
+                        "sub-command tokenized to empty");
+            }
+            subs.add(sub);
+        }
+        if (subs.isEmpty()) {
+            return ValidationResult.fail(RULE_EMPTY_COMMAND, rawCmd,
+                    "no sub-command after split by ';'");
+        }
+
+        // run the argv[0] whitelist and the argument policy check.
+        for (ParsedSubCmd sub : subs) {
+            ValidationResult r = validateSubCmd(sub);
+            if (!r.isOk()) {
+                return r;
+            }
+        }
+
+        // Absorb 'cd' sub-commands into the working directory of the 
following sub-command.
+        List<ParsedSubCmd> parsed = extractCdAndBind(subs);
+
+        return ValidationResult.ok(parsed);
+    }
+
+    private ValidationResult validateSubCmd(ParsedSubCmd sub) {
+        for (String[] argv : sub.getPipeline()) {
+            if (argv == null || argv.length == 0) {
+                return ValidationResult.fail(RULE_EMPTY_COMMAND, 
sub.getRawSegment(),
+                        "empty pipeline segment");
+            }
+            String cmd = argv[0];
+
+            if (!COMMAND_WHITELIST.contains(cmd)) {
+                return ValidationResult.fail(RULE_NOT_IN_WHITELIST, 
sub.getRawSegment(),
+                        "command '" + cmd + "' is not in whitelist");
+            }
+
+            ValidationResult r = validateArguments(argv, sub.getRawSegment());
+            if (!r.isOk()) {
+                return r;
+            }
+        }
+        return ValidationResult.okPending();
+    }
+
+    private ValidationResult validateArguments(String[] argv, String 
rawSegment) {
+        String cmd = argv[0];
+
+        if ("sh".equals(cmd) || "bash".equals(cmd)) {
+            for (int i = 1; i < argv.length; i++) {
+                if ("-c".equals(argv[i]) || argv[i].startsWith("-c")) {

Review Comment:
   Duplication.
   if (argv[i].startsWith("-c"))



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to