Skip to content
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

use stdin to send the password to ansible-vault command #359

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 80 additions & 20 deletions src/main/groovy/com/rundeck/plugins/ansible/ansible/AnsibleVault.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.*;
import java.util.concurrent.*;

@Data
@Builder
Expand Down Expand Up @@ -71,46 +72,59 @@ public String encryptVariable(String key,
System.out.println("encryptVariable " + key + ": " + procArgs);
}

//send values to STDIN in order
List<String> stdinVariables = new ArrayList<>();
stdinVariables.add(content);
File promptFile = File.createTempFile("vault-prompt", ".log");

Map<String, String> env = new HashMap<>();
env.put("VAULT_ID_SECRET", masterPassword);
env.put("LOG_PATH", promptFile.getAbsolutePath());

Process proc = null;

try {
proc = ProcessExecutor.builder().procArgs(procArgs)
.baseDirectory(baseDirectory.toFile())
.stdinVariables(stdinVariables)
.redirectErrorStream(true)
.environmentVariables(env)
.redirectErrorStream(true)
.build().run();

StringBuilder stringBuilder = new StringBuilder();

final InputStream stdoutInputStream = proc.getInputStream();
final BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdoutInputStream));

String line1 = null;
boolean capture = false;
while ((line1 = stdoutReader.readLine()) != null) {
if (line1.toLowerCase().contains("!vault")) {
capture = true;
}
if (capture) {
stringBuilder.append(line1).append("\n");
final InputStream proccesInputStream = proc.getInputStream();
final OutputStream processOutputStream = proc.getOutputStream();

//capture output thread
Callable<String> readOutputTask = () -> {
return readOutput(proccesInputStream);
};

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(readOutputTask);

Thread stdinThread = new Thread(() -> sendValuesStdin(processOutputStream, masterPassword, content));

//wait for prompt
boolean promptFound = false;
while (!promptFound) {
ltamaster marked this conversation as resolved.
Show resolved Hide resolved
BufferedReader reader = new BufferedReader(new FileReader(promptFile));
String currentLine = reader.readLine();
if(currentLine!=null && currentLine.contains("Enter Password:")){
promptFound = true;
//send password / content
stdinThread.start();
reader.close();
}else{
Thread.sleep(1500);
ltamaster marked this conversation as resolved.
Show resolved Hide resolved
}
}

int exitCode = proc.waitFor();

//get encrypted value
String result = future.get();
executor.shutdown();

if (exitCode != 0) {
System.err.println("ERROR: encryptFileAnsibleVault:" + procArgs);
return null;
}
return stringBuilder.toString();
return result;

} catch (Exception e) {
System.err.println("error encryptFileAnsibleVault file " + e.getMessage());
Expand All @@ -120,9 +134,55 @@ public String encryptVariable(String key,
if (proc != null) {
proc.destroy();
}

if(promptFile!=null && promptFile.delete()){
ltamaster marked this conversation as resolved.
Show resolved Hide resolved
promptFile.deleteOnExit();
}
}
}

String readOutput(InputStream proccesInputStream) {
try (
InputStreamReader isr = new InputStreamReader(proccesInputStream);
BufferedReader stdoutReader = new BufferedReader(isr);
) {

StringBuilder stringBuilder = new StringBuilder();
String line1 = null;
boolean capture = false;
while ((line1 = stdoutReader.readLine()) != null) {
if (line1.toLowerCase().contains("!vault")) {
capture = true;
}
if (capture) {
stringBuilder.append(line1).append("\n");
}
}
return stringBuilder.toString();
} catch (Throwable e) {
throw new RuntimeException("error reading output from ansible-vault", e);
}
}

void sendValuesStdin(OutputStream stdin, String masterPassword, String content){
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin))) {
//send master password
writer.write(masterPassword);
writer.newLine();
writer.flush();

//send content to encrypt
Thread.sleep(1500);
writer.write(content);
writer.flush();

writer.close();
stdin.close();

} catch (Throwable e) {
throw new RuntimeException("error sending stdin for ansible-vault", e);
}
}

public static File createVaultScriptAuth(String suffix) throws IOException {
File tempInternalVaultFile = File.createTempFile("ansible-runner", suffix + "-client.py");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@

import lombok.Builder;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.*;
import java.util.List;
import java.io.File;
import java.util.Map;

@Builder
Expand Down Expand Up @@ -42,22 +39,26 @@ public Process run() throws IOException {

Process proc = processBuilder.start();

OutputStream stdin = proc.getOutputStream();
OutputStreamWriter stdinw = new OutputStreamWriter(stdin);

if (stdinVariables != null) {
if (stdinVariables != null && !stdinVariables.isEmpty()){
OutputStream stdin = proc.getOutputStream();
OutputStreamWriter stdinw = new OutputStreamWriter(stdin);
BufferedWriter writer = new BufferedWriter(stdinw);
try {

for (String stdinVariable : stdinVariables) {
stdinw.write(stdinVariable);
writer.write(stdinVariable);
writer.newLine();
writer.flush();
}
stdinw.flush();

} catch (Exception e) {
System.err.println("error encryptFileAnsibleVault file " + e.getMessage());
}
writer.close();
stdinw.close();
stdin.close();
}
stdinw.close();
stdin.close();


return proc;
}
Expand Down
14 changes: 10 additions & 4 deletions src/main/resources/vault-client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@
import sys
import os
import getpass
import logging
from logging import handlers

secret=os.getenv('VAULT_ID_SECRET', None)
log = logging.getLogger('')
log.setLevel(logging.DEBUG)

if secret:
sys.stdout.write('%s\n' % (secret))
sys.exit(0)
log_path=os.getenv('LOG_PATH', None)

if log_path:
fh = handlers.RotatingFileHandler(log_path)
log.addHandler(fh)
log.info("Enter Password:")

if sys.stdin.isatty():
secret = getpass.getpass()
Expand Down
Loading