Skip to content

Commit

Permalink
[backend] handle cmd variables (#1604)
Browse files Browse the repository at this point in the history
Signed-off-by: Marine LM <[email protected]>
  • Loading branch information
MarineLeM authored Dec 10, 2024
1 parent 4cdb3c0 commit 0b0afb3
Showing 1 changed file with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.openbas.rest.inject.service;

import static org.springframework.util.StringUtils.hasText;

import com.fasterxml.jackson.databind.node.ObjectNode;
import io.openbas.database.model.*;
import io.openbas.database.repository.InjectRepository;
Expand All @@ -18,6 +20,7 @@ public class ExecutableInjectService {

private final InjectRepository injectRepository;
private static final Pattern argumentsRegex = Pattern.compile("#\\{([^#{}]+)}");
private static final Pattern cmdVariablesRegex = Pattern.compile("%(\\w+)%");

private List<String> getArgumentsFromCommandLines(String command) {
Matcher matcher = argumentsRegex.matcher(command);
Expand Down Expand Up @@ -57,6 +60,19 @@ private String replaceArgumentsByValue(
return command;
}

public static String replaceCmdVariables(String cmd) {
Matcher matcher = cmdVariablesRegex.matcher(cmd);

StringBuilder result = new StringBuilder();
while (matcher.find()) {
String variableName = matcher.group(1);
matcher.appendReplacement(result, "!" + variableName + "!");
}
matcher.appendTail(result);

return result.toString();
}

private String processAndEncodeCommand(
String command,
String executor,
Expand All @@ -66,6 +82,7 @@ private String processAndEncodeCommand(
String computedCommand = replaceArgumentsByValue(command, defaultArguments, injectContent);

if (executor.equals("cmd")) {
computedCommand = replaceCmdVariables(computedCommand);
computedCommand = computedCommand.trim().replace("\n", " & ");
}

Expand All @@ -88,7 +105,7 @@ public Payload getExecutablePayloadInject(String injectId) {
.getPrerequisites()
.forEach(
prerequisite -> {
if (prerequisite.getCheckCommand() != null) {
if (hasText(prerequisite.getCheckCommand())) {
prerequisite.setCheckCommand(
processAndEncodeCommand(
prerequisite.getCheckCommand(),
Expand All @@ -97,7 +114,7 @@ public Payload getExecutablePayloadInject(String injectId) {
inject.getContent(),
"base64"));
}
if (prerequisite.getGetCommand() != null) {
if (hasText(prerequisite.getGetCommand())) {
prerequisite.setGetCommand(
processAndEncodeCommand(
prerequisite.getGetCommand(),
Expand Down

0 comments on commit 0b0afb3

Please sign in to comment.