Add password to package in gradle - gradle

I packed a zip containing a list of webapps with gradle.
At the end, I would like to add a password to the zip.
I tried to user commandLine passing the linuz command "zipcloak", then the psw in required twice and I'm not able to send it to the command line:
commandLine ("zipcloak", zip_name + ".zip")
setStandardInput ("psw")
setStandardInput ("psw")
Maybe there is a better solution to do this...
Thanks
EDIT:
I progressed by adding this lines:
commandLine "zipcloak", "zipname.zip"
ByteArrayOutputStream bytes = new ByteArrayOutputStream()
PrintWriter out = new PrintWriter(bytes)
out.println("psw")
out.println("psw")
out.flush()
ByteArrayInputStream input = new ByteArrayInputStream(bytes.toByteArray())
standardInput = input
Now the command is executed and I see on the console the request of the password, but I'm not still able to send a string to this request directly from the script, I have to add it manually on the console...
EDIT - SOLUTION FOUND:
I found the solution: instead of adding a password to an existing zip, I packed the zip WITH password
task encodeZip(type: Exec) {
workingDir path_target_workspace
commandLine "zip", "-P", "password", "-r", "zipname.zip", "file1", "file2", "fil3" .....
}
Hope it helps

Related

How should ESAPI executeSystemCommand sanitise the file path properly to satisfy Veracode check?

I invoke the external command within my Java app with Runtime.getRuntime().exec() or ProcessBuilder. Works fine but Veracode complains on it with CWE-78. I'm trying to use ESAPI wrapper to sanitise the input and path the check.
The arfifact is the latest
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.2.3.1</version>
</dependency>
ESAPI.properties are
ESAPI.Logger=org.owasp.esapi.logging.slf4j.Slf4JLogFactory
Logger.LogEncodingRequired=false
Logger.UserInfo=false
Logger.ClientInfo=false
Logger.LogApplicationName=false
Logger.ApplicationName=my-app
Logger.LogServerIP=false
IntrusionDetector.Disable=true
Executor.ApprovedExecutables=/usr/bin/less
The code is:
#Test
void esapiTest() throws ExecutorException {
Executor executor = DefaultExecutor.getInstance();
ExecuteResult executeResult = executor.executeSystemCommand(
new File("/usr/bin/less"),
new ArrayList<>(Collections.singletonList("/etc/hosts"))
);
System.out.println("out = " + executeResult.getOutput());
System.out.println("err = " + executeResult.getErrors());
}
The output is
out =
err = \/etc\/hosts: No such file or directory
As far as I got the issue is that ESAPI's UnixCodec sanitises all non-alpha character with the backslash. This is fine for the shell i.e.
/usr/bin/less \/etc\/hosts
but not for the ProcessBuilder that is under the hood.
What am I doing wrong? How to invoke the command?
I think your main "problem" is misunderstanding that the ESAPI Codecs that are used with the DefaultExecutor class are assuming that any "OS command injection" is being interpreted via a "command line interpreter", i.e., a "shell". You are not invoking a shell here. If you were, the shell would remove the (in this case) backslash escaped argument from your path for "/etc/hosts". So if this were written as (say) the command:
/bin/sh -c /usr/bin/less /etc/hosts
it would [sort of] work (except if you tried running it over HTTP, the input to 'less' my be hosed; but "/bin/cat" ought to work fine).
Instead, try writing your test something like this:
#Test
void esapiTest() throws ExecutorException {
Executor executor = ESAPI.executor();
File binSh = new File("/bin/sh").getCanonicalFile();
List params = new ArrayList();
params.add("-c");
//Use '/bin/cat' because 'less' may be troublesome
params.add("\"" + "/bin/cat" + "/etc/hosts" + "\"");
ExecuteResult executeResult = executor.executeSystemCommand(binSh, params);
System.out.println("out = " + executeResult.getOutput());
System.out.println("err = " + executeResult.getErrors());
}
Note 1: If you I'm not sure how user-friendly ProcessBuilder is with commands that eventually try to do ioctl system calls to set the tty device in 'raw' mode, like commands such as "vim" or "less", which is why I changed your "/usr/bin/less" to "/bin/cat". YMMV.
Note 2: In your ESAPI.properties file, you'd have to make sure that the property 'Executor.ApprovedExecutables' is set to whatever the canonical name of "/bin/sh" is on your system. E.g., on my system, "/bin/sh" is a symbolic link to "/bin/dash", so you would have to include something like
Executor.ApprovedExecutables=/bin/bash,/bin/dash
(or at least "/bin/dash") should work.

How to save a PDF file downloaded as byte[] array obtained from a Rest WS

I trying to save a PDF file, previously obtained from a REST WS as byte[] array.
byte[] response = await caller.DownloadFile(url);
string documentPath = FileSystem.CacheDirectory;
string fileName = "downloadfile.pdf";
string path = Path.Combine(documentPath, fileName);
File.WriteAllBytes(path, response);
My actual implementation don't shows any errors but when I looking for the file on cache folder, nothing are there, just a empty folder. Also try put the file in FileSystem.AppDataDirectory and Environment.GetFolderPath(Environment.SpecialFolder.Personal) but there are no files in any folder
What I'm missing?
Thank's in advance.
string documentPath = FileSystem.CacheDirectory;
string fileName = "downloadfile.pdf";
string path = Path.Combine(documentPath, fileName);
the path will like
"/data/user/0/packagename/cache/downloadfile.pdf"
As you save it to Internal Storage,you couldn't see the files without root permission,if you want to view it,you could use adb tool (application signed by Android Debug)
adb shell
run-as packagename
cd /data/data/packagename
cd cache
ls
then you could see the downloadfile.pdf
or you could save it to External storage,then you could find it in your device File Manager:
//"/storage/emulated/0/Android/data/packagename/files/downloadfile.pdf"
string path = Android.App.Application.Context.GetExternalFilesDir(null).ToString();

Using SystemCommandTasklet to split file

I want to run System Commands via SystemCommandTasklet.Itried this with the sample code below but I get an error.
I think this because of command parameter,But I could not fix it.
I would be very glad if it will help.
Reference Examples ;
Using SystemCommandTasklet for split the large flat file into small files
Trying to split files using SystemCommandTasklet - Execution of system command did not finish within the timeout
Error Detail ;
"CreateProcess error=2, The system cannot find the file specified"
Code Sample ;
#Bean
#StepScope
public SystemCommandTasklet fileSplitterSystemCommandTasklet(#Value("#{jobParameters['file']}") File file) throws Exception {
final String fileSeparator = System.getProperty("file.separator");
String outputDirectory = file.getPath().substring(0, file.getPath().lastIndexOf(fileSeparator)) + fileSeparator + "out" + fileSeparator;
File output = new File(outputDirectory);
if (!output.exists()) {
output.mkdir();
}
final String command = String.format("split -a 5 -l 10000 %s %s",file.getName(),outputDirectory);
var fileSplitterTasklet = new SystemCommandTasklet();
fileSplitterTasklet.setCommand(command);
fileSplitterTasklet.setTimeout(60000L);
fileSplitterTasklet.setWorkingDirectory(outputDirectory);
fileSplitterTasklet.setTaskExecutor(new SimpleAsyncTaskExecutor());
fileSplitterTasklet.setSystemProcessExitCodeMapper(touchCodeMapper());
fileSplitterTasklet.afterPropertiesSet();
fileSplitterTasklet.setInterruptOnCancel(true);
fileSplitterTasklet.setEnvironmentParams(new String[]{
"JAVA_HOME=/java",
"BATCH_HOME=/Users/batch"});
return fileSplitterTasklet;
}
You need to use file.getAbsolutePath() instead of file.getPath().
Also, you are using file.getName() in the command:
final String command = String.format("split -a 5 -l 10000 %s %s",file.getName(),outputDirectory);
You should pass the absolute path of the file or make sure to set
the working directory correctly so that the split command is executed
in the same directory as the file.

executing jar with arguments Hide text of some arguments

I have a jar file that accepts the arguments, one of the argument is a password, is there a way to mask password when executing jar in CMD? maybe in Java code argument can be masked or I don't reveal sensitive information? something like there is in Linux command when typing the password noting is shown in terminal?
public static void main(String [] args) {
String username = args[0]; //=="user"
String password = args[1]; //=="pass"
}
and in cmd executing it
java -jar jarFile.jar username password
is there a way to hide that password in the second argument?

Java Runtime Exec on Windows Fails with Unicode in Arguments

I want to launch a browser and load a web page using Java's Runtime exec. The exact call looks like this:
String[] explorer = {"C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE",
"-noframemerging",
"C:\\ ... path containing unicode chars ... \\Main.html"};
Runtime.getRuntime().exec(explorer);
In my case, the path contains "\u65E5\u672C\u8A9E", the characters 日本語.
Apparently it's a java bug:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4947220
My question is: is there a viable workaround that can be done solely using Java? It appears that it is possible to write a JNI library for this, but I'd like to avoid that if possible. I have tried URI-encoding the path as ascii and writing the commands to a batch file, without success.
At the mentioned Java bug page you will find a workaround that is reported to work using ProcessBuilder and wrapping the parameters in environment variables. Here is the source code from Parag Thakur:
String[] cmd = new String[]{"yourcmd.exe", "Japanese CLI argument: \ufeff\u30cb\u30e5\u30fc\u30b9"};
Map<String, String> newEnv = new HashMap<String, String>();
newEnv.putAll(System.getenv());
String[] i18n = new String[cmd.length + 2];
i18n[0] = "cmd";
i18n[1] = "/C";
i18n[2] = cmd[0];
for (int counter = 1; counter < cmd.length; counter++)
{
String envName = "JENV_" + counter;
i18n[counter + 2] = "%" + envName + "%";
newEnv.put(envName, cmd[counter]);
}
cmd = i18n;
ProcessBuilder pb = new ProcessBuilder(cmd);
Map<String, String> env = pb.environment();
env.putAll(newEnv);
final Process p = pb.start();
Create a .bat/.sh file. Write your commands to that file and execute it. Make sure that you have changed the code page to unicode in case of windows(chcp 65001).
For example to execute the below command in windows:
String[] command ={"C:\\aconex\\学校\\mysql\\bin\\mysql", "-esource", "大村箕島a\\data.sql"};
Create a temp file called temp.bat and execute with the Runtime.getRuntime().exec
temp.bat
chcp 65001
C:\aconex\学校\mysql\bin\mysql -esource 大村箕島a\data.sql
These are the two solutions I considered, each of which are more or less workarounds:
Create a temp html redirect file which will redirect the browser to the proper page.
Note that IE will expect unencoded unicode for local files, while other browsers may accept only uri-encoded file paths
Use the short filename for the windows file. It won't contain unicode characters.
We've been using a JNI to start processes from Java for years. Neither Runtime.exec or ProcessBuilder will work, and it seems unlikely that they will fix this, given how long it's been already.
However, you should be able to work around the issue by using the input stream, a socket, or environment variables to pass parameters. If you don't have direct control over the executable, you'll have to make a wrapper.
You could use JNA. With version 3.3.0 or later call CreateProcess:
WinBase.PROCESS_INFORMATION.ByReference processInfo =
new WinBase.PROCESS_INFORMATION.ByReference();
WinBase.STARTUPINFO startupInfo = new WinBase.STARTUPINFO();
String command = "C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE " +
"-noframemerging \"C:\\\u65E5\u672C\u8A9E\\Main.html\"";
if (!Kernel32.INSTANCE.CreateProcess(
null, // Application name, not needed if supplied in command line
command, // Command line
null, // Process security attributes
null, // Thread security attributes
true, // Inherit handles
0, // Creation flags
null, // Environment
null, // Directory
startupInfo,
processInfo))
{
throw new IllegalStateException("Error creating process. Last error: " +
Kernel32.INSTANCE.GetLastError());
}
// The CreateProcess documentation indicates that it is very important to
// close the returned handles
Kernel32.INSTANCE.CloseHandle(processInfo.hThread);
Kernel32.INSTANCE.CloseHandle(processInfo.hProcess);
long pid = processInfo.dwProcessId.longValue();
Redirecting output from the child process is a bit harder but not impossible.
I think you can use Apache Commons Exec library or ProcessBuilder to give a try;)

Resources