You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@inlong.apache.org by "spiritxishi (via GitHub)" <gi...@apache.org> on 2026/07/01 11:41:43 UTC
[PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilde… [inlong]
spiritxishi opened a new pull request, #12151:
URL: https://github.com/apache/inlong/pull/12151
…r (#12148)
<!-- Prepare a Pull Request
Change the title of pull request refer to the following example:
[INLONG-XYZ][Component] Title of the pull request
-->
<!-- Specify the issue this pull request going to fix.
The following *XYZ* should be replaced by the actual [GitHub Issue](https://github.com/apache/inlong/issues) number)-->
Fixes #XYZ
### Motivation
<!--Explain here the context, and why you're making that change. What is the problem you're trying to solve.-->
### Modifications
<!--Describe the modifications you've done.-->
### Verifying this change
*(Please pick either of the following options)*
- [ ] This change is a trivial rework/code cleanup without any test coverage.
- [ ] This change is already covered by existing tests, such as:
*(please describe tests)*
- [ ] This change added tests and can be verified as follows:
*(example:)*
- *Added integration tests for end-to-end deployment with large payloads (10MB)*
- *Extended integration test for recovery after broker failure*
### Documentation
- Does this pull request introduce a new feature? (yes / no)
- If yes, how is the feature documented? (not applicable / docs / JavaDocs / not documented)
- If a feature is not applicable for documentation, explain why?
- If a feature is not documented yet in this PR, please create a follow-up issue for adding the documentation
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "luchunliang (via GitHub)" <gi...@apache.org>.
luchunliang commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3533266748
##########
inlong-agent/agent-common/src/main/java/org/apache/inlong/agent/utils/AgentUtils.java:
##########
@@ -329,12 +329,11 @@ public static String fetchLocalUuid() {
uuid = localUuid;
return uuid;
}
- String result = ExcuteLinux.exeCmd("dmidecode | grep UUID");
- if (StringUtils.isNotEmpty(result)
- && StringUtils.containsIgnoreCase(result, "UUID")) {
- uuid = result.split(":")[1].trim();
+ String result = ExcuteLinux.exeCmd(new String[]{"dmidecode", "-s", "system-uuid"});
Review Comment:
Support "dmidecode -s " from Linux 2.10. Suggest to add a fallback.
String uuid = null;
try {
String result = ExcuteLinux.exeCmd(new String[]{"dmidecode", "-s", "system-uuid"});
if (StringUtils.isNotEmpty(result)) {
result = result.trim();
// check format
if (result.matches("^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$")) {
return result;
}
}
} catch (Exception e) {
LOG.warn("dmidecode -s system-uuid failed, fallback to grep", e);
}
// Fallback
try {
String result = ExcuteLinux.exeCmd("dmidecode | grep UUID");
if (StringUtils.isNotEmpty(result) && StringUtils.containsIgnoreCase(result, "UUID")) {
String[] parts = result.split(":");
if (parts.length >= 2) {
return parts[1].trim();
}
}
} catch (Exception e) {
LOG.warn("dmidecode | grep UUID failed", e);
}
return uuid;
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "luchunliang (via GitHub)" <gi...@apache.org>.
luchunliang commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3533385803
##########
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[]{
Review Comment:
Miss these character.
private static final String[] META_CHAR_BLACKLIST = new String[]{
"`", "$(", "${", "$",
"&&", "||", ">>", ">", "<",
"\\",
"\u0000"
};
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "luchunliang (via GitHub)" <gi...@apache.org>.
luchunliang commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3533271897
##########
inlong-agent/agent-common/src/main/java/org/apache/inlong/agent/utils/ExcuteLinux.java:
##########
@@ -17,40 +17,377 @@
package org.apache.inlong.agent.utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
/**
- * ExecuteLinux cmd
+ * Utility for executing local OS commands.
+ *
+ * <p>{@link #exeCmd(String[])}, {@link #exeCmd(List, File, long)} and
+ * {@link #exePipedCmd(List, File, long)} are the recommended argv-array / piped entry points.
+ * They use {@link ProcessBuilder} directly and never go through {@code /bin/sh -c}, so shell
+ * metacharacters ({@code ;}, {@code |}, {@code &&}, backticks, {@code $(...)}) are never
+ * interpreted.</p>
+ *
+ * <p>{@link #exeCmd(String)} is a legacy string-based fallback that runs commands through
+ * {@code /bin/sh -c}; it is {@link Deprecated} and must only be used with strings already
+ * validated by {@code ModuleCommandValidator}.</p>
+ *
+ * <p>Piping is emulated by chaining several {@link ProcessBuilder} instances via background
+ * threads that copy stdout to the next process's stdin, so no shell is required.</p>
*/
public class ExcuteLinux {
Review Comment:
Please check the spelling error.
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "spiritxishi (via GitHub)" <gi...@apache.org>.
spiritxishi commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3534079165
##########
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[]{
Review Comment:
done
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "luchunliang (via GitHub)" <gi...@apache.org>.
luchunliang commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3533311857
##########
inlong-agent/agent-installer/src/main/java/org/apache/inlong/agent/installer/validator/AllowedRootsResolver.java:
##########
@@ -0,0 +1,158 @@
+/*
+ * 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.inlong.agent.constant.AgentConstants;
+import org.apache.inlong.agent.installer.conf.InstallerConfiguration;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+/**
+ * Resolves the whitelist of root directories under which write-oriented commands
+ * (e.g. {@code rm/cp/mv/mkdir/ln/chmod/chown/tar/unzip}) are allowed to operate. Paths are
+ * compared with normalized {@link Path#startsWith(Path)}, which naturally rejects traversal
+ * attempts such as {@code ~/inlong/../../../etc}.
+ *
+ * <p>Default roots: {@code $user.home/inlong}, {@code $user.home/inlong-agent},
+ * {@code agent.home} (from {@code -Dagent.home} JVM property or {@code installer.properties}),
+ * {@code $java.io.tmpdir}. Extra roots may be appended via the configuration key
+ * {@code installer.command.extraAllowedRoots} (comma separated).
+ */
+@Getter
+public final class AllowedRootsResolver {
+
+ /** Configuration key for extra allowed root directories (comma separated). */
+ public static final String KEY_EXTRA_ALLOWED_ROOTS = "installer.command.extraAllowedRoots";
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AllowedRootsResolver.class);
+
+ private static volatile AllowedRootsResolver instance;
+
+ /**
+ * -- GETTER --
+ * Return the immutable set of roots, mainly for logging and tests.
+ */
+ private final Set<Path> roots;
+
+ private AllowedRootsResolver(Set<Path> roots) {
+ this.roots = Collections.unmodifiableSet(roots);
+ }
+
+ /** Build an instance from the given path set (normalized). Intended primarily for tests. */
+ public static AllowedRootsResolver ofPaths(Path... paths) {
+ Set<Path> roots = new LinkedHashSet<>();
+ if (paths != null) {
+ for (Path p : paths) {
+ addRoot(roots, p);
+ }
+ }
+ return new AllowedRootsResolver(roots);
+ }
+
+ /** Return the default singleton, backed by {@link InstallerConfiguration}. */
+ public static AllowedRootsResolver getDefault() {
+ if (instance == null) {
+ synchronized (AllowedRootsResolver.class) {
+ if (instance == null) {
+ instance = build(InstallerConfiguration.getInstallerConf());
+ }
+ }
+ }
+ return instance;
+ }
+
+ /** Build an instance from the given configuration. */
+ public static AllowedRootsResolver build(InstallerConfiguration conf) {
+ Set<Path> roots = new LinkedHashSet<>();
+
+ String userHome = System.getProperty("user.home");
+ if (StringUtils.isNotBlank(userHome)) {
+ addRoot(roots, Paths.get(userHome, "inlong"));
+ addRoot(roots, Paths.get(userHome, "inlong-agent"));
+ }
+
+ // agent.home resolution: -Dagent.home JVM system property first, then the same key
+ // from installer.properties as an override.
+ String agentHome = System.getProperty(AgentConstants.AGENT_HOME);
+ if (conf != null) {
+ String fromConf = conf.get(AgentConstants.AGENT_HOME, null);
+ if (StringUtils.isNotBlank(fromConf)) {
+ agentHome = fromConf;
+ }
+ }
+ if (StringUtils.isNotBlank(agentHome)) {
+ addRoot(roots, Paths.get(agentHome));
+ }
+
+ String tmpDir = System.getProperty("java.io.tmpdir");
+ if (StringUtils.isNotBlank(tmpDir)) {
+ addRoot(roots, Paths.get(tmpDir));
+ }
+
+ if (conf != null) {
+ String extra = conf.get(KEY_EXTRA_ALLOWED_ROOTS, "");
+ if (StringUtils.isNotBlank(extra)) {
+ for (String item : extra.split(",")) {
+ String trimmed = item == null ? "" : item.trim();
+ if (StringUtils.isNotBlank(trimmed)) {
+ addRoot(roots, Paths.get(trimmed));
+ }
+ }
+ }
+ }
+
+ LOGGER.info("AllowedRootsResolver initialized with roots: {}", roots);
+ return new AllowedRootsResolver(roots);
+ }
+
+ private static void addRoot(Set<Path> roots, Path p) {
+ if (p == null) {
+ return;
+ }
+ Path normalized = p.toAbsolutePath().normalize();
+ roots.add(normalized);
+ }
+
+ /**
+ * Test whether the given path lies under any allowed root (equal to a root also counts).
+ *
+ * @param p a path; it is made absolute and normalized internally before the comparison.
+ */
+ public boolean isUnderAllowedRoot(Path p) {
+ if (p == null) {
+ return false;
+ }
+ Path normalized = p.toAbsolutePath().normalize();
+ for (Path root : roots) {
+ if (normalized.startsWith(root)) {
Review Comment:
For symlink path, it is risk.
It is better to use toRealPath.
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "luchunliang (via GitHub)" <gi...@apache.org>.
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "spiritxishi (via GitHub)" <gi...@apache.org>.
spiritxishi commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3533409022
##########
inlong-agent/agent-common/src/main/java/org/apache/inlong/agent/utils/ExecuteLinux.java:
##########
@@ -17,40 +17,377 @@
package org.apache.inlong.agent.utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
/**
- * ExecuteLinux cmd
+ * Utility for executing local OS commands.
+ *
+ * <p>{@link #exeCmd(String[])}, {@link #exeCmd(List, File, long)} and
+ * {@link #exePipedCmd(List, File, long)} are the recommended argv-array / piped entry points.
+ * They use {@link ProcessBuilder} directly and never go through {@code /bin/sh -c}, so shell
+ * metacharacters ({@code ;}, {@code |}, {@code &&}, backticks, {@code $(...)}) are never
+ * interpreted.</p>
+ *
+ * <p>{@link #exeCmd(String)} is a legacy string-based fallback that runs commands through
+ * {@code /bin/sh -c}; it is {@link Deprecated} and must only be used with strings already
+ * validated by {@code ModuleCommandValidator}.</p>
+ *
+ * <p>Piping is emulated by chaining several {@link ProcessBuilder} instances via background
+ * threads that copy stdout to the next process's stdin, so no shell is required.</p>
*/
public class ExcuteLinux {
Review Comment:
done
##########
inlong-agent/agent-common/src/main/java/org/apache/inlong/agent/utils/AgentUtils.java:
##########
@@ -329,12 +329,11 @@ public static String fetchLocalUuid() {
uuid = localUuid;
return uuid;
}
- String result = ExcuteLinux.exeCmd("dmidecode | grep UUID");
- if (StringUtils.isNotEmpty(result)
- && StringUtils.containsIgnoreCase(result, "UUID")) {
- uuid = result.split(":")[1].trim();
+ String result = ExcuteLinux.exeCmd(new String[]{"dmidecode", "-s", "system-uuid"});
Review Comment:
done
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "spiritxishi (via GitHub)" <gi...@apache.org>.
spiritxishi commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3534070731
##########
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:
OK remove equals
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "spiritxishi (via GitHub)" <gi...@apache.org>.
spiritxishi commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3533516791
##########
inlong-agent/agent-installer/src/main/java/org/apache/inlong/agent/installer/validator/AllowedRootsResolver.java:
##########
@@ -0,0 +1,158 @@
+/*
+ * 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.inlong.agent.constant.AgentConstants;
+import org.apache.inlong.agent.installer.conf.InstallerConfiguration;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+/**
+ * Resolves the whitelist of root directories under which write-oriented commands
+ * (e.g. {@code rm/cp/mv/mkdir/ln/chmod/chown/tar/unzip}) are allowed to operate. Paths are
+ * compared with normalized {@link Path#startsWith(Path)}, which naturally rejects traversal
+ * attempts such as {@code ~/inlong/../../../etc}.
+ *
+ * <p>Default roots: {@code $user.home/inlong}, {@code $user.home/inlong-agent},
+ * {@code agent.home} (from {@code -Dagent.home} JVM property or {@code installer.properties}),
+ * {@code $java.io.tmpdir}. Extra roots may be appended via the configuration key
+ * {@code installer.command.extraAllowedRoots} (comma separated).
+ */
+@Getter
+public final class AllowedRootsResolver {
+
+ /** Configuration key for extra allowed root directories (comma separated). */
+ public static final String KEY_EXTRA_ALLOWED_ROOTS = "installer.command.extraAllowedRoots";
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AllowedRootsResolver.class);
+
+ private static volatile AllowedRootsResolver instance;
+
+ /**
+ * -- GETTER --
+ * Return the immutable set of roots, mainly for logging and tests.
+ */
+ private final Set<Path> roots;
+
+ private AllowedRootsResolver(Set<Path> roots) {
+ this.roots = Collections.unmodifiableSet(roots);
+ }
+
+ /** Build an instance from the given path set (normalized). Intended primarily for tests. */
+ public static AllowedRootsResolver ofPaths(Path... paths) {
+ Set<Path> roots = new LinkedHashSet<>();
+ if (paths != null) {
+ for (Path p : paths) {
+ addRoot(roots, p);
+ }
+ }
+ return new AllowedRootsResolver(roots);
+ }
+
+ /** Return the default singleton, backed by {@link InstallerConfiguration}. */
+ public static AllowedRootsResolver getDefault() {
+ if (instance == null) {
+ synchronized (AllowedRootsResolver.class) {
+ if (instance == null) {
+ instance = build(InstallerConfiguration.getInstallerConf());
+ }
+ }
+ }
+ return instance;
+ }
+
+ /** Build an instance from the given configuration. */
+ public static AllowedRootsResolver build(InstallerConfiguration conf) {
+ Set<Path> roots = new LinkedHashSet<>();
+
+ String userHome = System.getProperty("user.home");
+ if (StringUtils.isNotBlank(userHome)) {
+ addRoot(roots, Paths.get(userHome, "inlong"));
+ addRoot(roots, Paths.get(userHome, "inlong-agent"));
+ }
+
+ // agent.home resolution: -Dagent.home JVM system property first, then the same key
+ // from installer.properties as an override.
+ String agentHome = System.getProperty(AgentConstants.AGENT_HOME);
+ if (conf != null) {
+ String fromConf = conf.get(AgentConstants.AGENT_HOME, null);
+ if (StringUtils.isNotBlank(fromConf)) {
+ agentHome = fromConf;
+ }
+ }
+ if (StringUtils.isNotBlank(agentHome)) {
+ addRoot(roots, Paths.get(agentHome));
+ }
+
+ String tmpDir = System.getProperty("java.io.tmpdir");
+ if (StringUtils.isNotBlank(tmpDir)) {
+ addRoot(roots, Paths.get(tmpDir));
+ }
+
+ if (conf != null) {
+ String extra = conf.get(KEY_EXTRA_ALLOWED_ROOTS, "");
+ if (StringUtils.isNotBlank(extra)) {
+ for (String item : extra.split(",")) {
+ String trimmed = item == null ? "" : item.trim();
+ if (StringUtils.isNotBlank(trimmed)) {
+ addRoot(roots, Paths.get(trimmed));
+ }
+ }
+ }
+ }
+
+ LOGGER.info("AllowedRootsResolver initialized with roots: {}", roots);
+ return new AllowedRootsResolver(roots);
+ }
+
+ private static void addRoot(Set<Path> roots, Path p) {
+ if (p == null) {
+ return;
+ }
+ Path normalized = p.toAbsolutePath().normalize();
+ roots.add(normalized);
+ }
+
+ /**
+ * Test whether the given path lies under any allowed root (equal to a root also counts).
+ *
+ * @param p a path; it is made absolute and normalized internally before the comparison.
+ */
+ public boolean isUnderAllowedRoot(Path p) {
+ if (p == null) {
+ return false;
+ }
+ Path normalized = p.toAbsolutePath().normalize();
+ for (Path root : roots) {
+ if (normalized.startsWith(root)) {
Review Comment:
done
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Improve] [Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "spiritxishi (via GitHub)" <gi...@apache.org>.
spiritxishi commented on code in PR #12151:
URL: https://github.com/apache/inlong/pull/12151#discussion_r3534118148
##########
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[]{
Review Comment:
"$" appears in legitimate contexts such as "awk '{print $2}'" (field references), so it was omitted
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [INLONG-12148][Agent] Replace /bin/sh -c with ProcessBuilder [inlong]
Posted by "vernedeng (via GitHub)" <gi...@apache.org>.
vernedeng merged PR #12151:
URL: https://github.com/apache/inlong/pull/12151
--
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: commits-unsubscribe@inlong.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org