Not sure if this is the right place to ask.
Say I write a shell that takes stdin input, filters this input so let's say only certain commands like
ls (list contents of binary directory and subdirectory)
update (git clone)
build (go build)
test (go test)
start (systemctl start this.service only)
stop (systemctl stop this.service only)
running (is the binary being executed and with how many GOMAXPROCS?)
usage (memory, cpu usage)
gensvc (generate .service file)
exit (leave shell/logout)
work, you guessed it, I'm trying to give a user only very limited maintenance access over ssh.
Say I'm careful with \0 (I'd write it in Go anyway using bufio.Scanner)
Is there any way to stop the running shell and execute /bin/sh or similar or any way to get around this shell?
The idea is a user should push their stuff via git to a bare repo, this repo is cloned to the filesystem to a certain directory, then go build is called and the binary is ran with a systemd .service file that is generated previously.
Thinking logically, if the user is only able to write certain strings that are accepted, no there is no way. But maybe you know of one, some ctrl+z witchcraft ;) or whatever.
The only attack surface is the input string or rather bytes. Of course the user could git push a program that builds its own shell or runs certain commands, but that's out of scope (I would remove capabilities with systemd and restrict device access and forbid anything but the connection to the database server, private tmp and all, namespace and subnamespace it TODO)
The only problem I see is git pushing but I'm sure I could work around that in a git only mode argv and adding it to ~/.ssh/authorized_keys. something like lish gitmode and execute stdin commands if they start with git or something like it.
Example:
https://gist.github.com/dalu/ce2ef43a2ef5c390a819
If you're only allowed certain commands, your "shell" will read the command, parse it and then execute it then you should be fine, unless I misunderstood it.
Go "memory" can't be executed, not without you doing some nasty hacks with assembly anyway, so you don't have to worry about shell injection.
Something along these lines should be safe:
func getAction() (name string, args []string) {
// read stdin to get the command of the user
}
func doAction() {
for {
action, args := getAction()
switch action {
case "update": //let's assume the full command is: update https://repo/path.git
if len(args) != 1 {
//error
}
out, err := exec.Command("/usr/bin/git", "clone", "--recursive", args[0]).CombinedOutput()
// do stuff with out and err
}
}
}
If you are implementing the shell yourself and directly executing the commands via exec() or implementing them internally, then it is certainly possible to produce a secure restricted shell. If you are just superficially checking a command line before passing it on to a real shell then there will probably be edge cases you might not expect.
With that said, I'd be a bit concerned about the test command you've listed. Is it intended to run the test suite of a Go package the user uploads? If so, I wouldn't even try to exploit the restricted shell if I was an attacker: I'd simply upload a package with tests that perform the actions I want. The same could be said for build/start.
Have it reviewed by a pentesting team.
People can be very creative when breaking out a sandbox of any type. Only if you never accept the user's input you can consider yourself rather safe on premises (but here any command is an input) - paper security assumptions are considered a weak to assess the software. They are similar to 'no-bug' assumptions for an algorithm on paper: as soon as you implement it, 99% of time a bug raises
Related
Linux permissions can't stop Lua from going outside its own directory and into another.
Also, if declaring these values before:
os.execute = nil
io.popen = nil
It actually solves the problem, but disables many functions, like my clients not being able to use their other saved scripts.
You could create a new linux user, with permissions only for the needed directory, and run as that.
Otherwise there really is no solution. You can sandbox as much as you want, but if those functions are needed then you're out of luck.
You could always create your wrapper functions around the original os.execute before setting it to nil, so that you have more control of the actions taken. for example:
local osExecute = os.execute
os.execute = nil
os.createDir = function(dir)
osExecute("mkdir "..dir)
end
os.saveScript(script)
osExecute("command to save script goes here")
end
Of course, this example is prone to attacks, you would need to validate the parameters, to make sure it really is a folder name, and not folder;rm -rf /, for example.
Same goes for popen, you can always create your set of commands to execute.
You can then, of course create a user with restricted permissions, for extra security.
Now, I am writting a Groovy script to invoke other's interface. But I need change my current working path when running the script. I know it is not possible in Java. Is it possible in Groovy?
If you can run other script as separate process, you can give ProcessBuilder parameter working dir:
def processBuilder=new ProcessBuilder(command)
processBuilder.directory(new File("Working dir"))
def process = processBuilder.start()
or
command.execute(null, new File("Working dir"))
so that process will switch to your new folder and execute it there.
As Groovy runs on JVM, the same restrictions apply. Unfortunately it is not possible.
Changing the current working directory in Java?
JDK bug
Java/groovy doesn't really "Have" a working directory as far as I can tell. The shell that launched groovy has one and any child "commands" inherit from that shell diretly.
Java also seems to read the current directory of the shell and store it in "user.dir". This is used as a base for the "File" object so if you System.setProperty("user.dir", "c:/windows") it will change future invocations of new File(".") but will not change the parent shell directory (and therefore not the child directories).
Here are three "Work-Arounds" that may work for different scenarios:
1) I KIND OF overcame this for a very specific task... I wanted to implement "cd" as a groovy script. It was only possible because all my scripts were already being "wrapped" in a batch file. I made it so that my script could create a file called "afterburner.cmd" that, if it existed, would be executed when the script exits. There was some batch file trickery to make this work.
A startup cmd file could also "Set" the current directory before invoking your groovy script/app.
By the way, Having a startup cmd has been much more helpful than I'd thought it would be--It makes your environment constant and allows you to more easily deploy your "Scripts" to other machines. I even have mine compile my scripts to .classes because it turned out to be faster to compile a .groovy to a .class and start the .class with "Java" than it was to just run the script with "groovy"--and usually you can skip the compile step which makes it a LOT faster!
2) For a few small commands, you might write a method like this:
def currentDir = "C:\\"
def exec(command, dir = null) {
"cmd /c cd /d ${dir?:currentDir} && $command".execute().text
}
// Default dir is currentDir
assert exec("dir").endsWith("C:\\>")
// different dir for this command only
assert exec("dir", "c:\\users").endsWith("C:\\users")
// Change default dir
currentDir = "C:\\windows"
assert exec("dir").endsWith("C:\\windows")
it will be slower than "".execute() if "cmd" is not required.
3) Code a small class that maintains an "Open" command shell (I did this once, there is a bit of complexity), but the idea is:
def process="cmd".execute()
def in=process.in
def out=process.out
def err=process.err
Now "in" is an input stream that you could spin off/read from and "out" is an output stream that you can write commands to, keep an eye on "err" to detect errors.
The class should write a command to the output, read the input until the command has completed then return the output to the user.
The problem is detecting when the output of any given command is complete. In general you can detect a "C:..." prompt and assume that this means that the command has finished executing. You could also use a timeout. Both are pretty fallible. You can set that shell's prompt to something unique to make it much less fallible.
The advantage is that this shell can remain open for the entire life of your app and can significantly increase speed since you aren't repeatedly creating "cmd" shells. If you create a class (let's call it "CommandShell") that wraps your Process object then it should be really easy to use:
def cmd=new CommandShell()
println cmd.execute("cd /d c:\\")
println cmd.execute("dir") // Will be the dir of c:\
I wrote a groovy class like this once, it's a lot of experimenting and your instance can be trashed by commands like "exit" but it's possible.
you can wrap it up in a dir block.
eg :
dir('yourdirectory') {
codeblock
}
I'm trying to execute a child_process synchronously in node.js (Yes, I know this is bad, I have a good reason) and retrieve any output on stdout, but I can't quite figure out how...
I found this SO post: node.js execute system command synchronously that describes how to use a library (node-ffi) to execute the command, and this works great, but the only thing I'm able to get is the process exit code. Any data the command executes is sent directly to stdout -- how do I capture this?
> run('whoami')
username
0
in otherwords, username is echo'd to stdout, the result of run is 0.
I'd much rather figure out how to read stdout
So I have a solution working, but don't exactly like it... Just posting here for reference:
I'm using the node-ffi library referenced in the other SO post. I have a function that:
takes in a given command
appends >> run-sync-output
executes it
reads run-sync-output synchronously and stores the result
deletes this tmp file
returns result
There's an obvious issue where if the user doesn't have write access to the current directory, it will fail. Plus, it's just wasted effort. :-/
I have built a node.js module that solves this exact problem. Check it out :)
exec-plan
Update
The above module solves your original problem, because it allows for the synchronous chaining of child processes. Each link in the chain gets the stdout from the previous process in the chain.
I had a similar problem and I ended up writing a node extension for this. You can check out the git repository. It's open source and free and all that good stuff !
https://github.com/aponxi/npm-execxi
ExecXI is a node extension written in C++ to execute shell commands
one by one, outputting the command's output to the console in
real-time. Optional chained, and unchained ways are present; meaning
that you can choose to stop the script after a command fails
(chained), or you can continue as if nothing has happened !
Usage instructions are in the ReadMe file. Feel free to make pull requests or submit issues!
However it doesn't return the stdout yet... Well, I just released it today. Maybe we can build on it.
Anyway, I thought it was worth to mention it. I also posted this to a similar question: node.js execute system command synchronously
Since Node version v0.11.12, there is a child_process.execSync function for this.
Other than writing code a little diferent, there's actually no reason to do anything synched.
What don't you like about this? (docs)
var exec = require('child_process').exec;
exec('whoami', function (error, username) {
console.log('stdout: %s', username);
continueWithYourCode();
});
In order to get my setup a bit closer to "one click deployment", I would like to use groovy scripts to start/stop other processes controlled by bat scripts, running in different parts of the filesystem and even on different machines.
How to execute these scripts and how to do it from their respective working directory?
I know Java's
java.lang.Runtime's exec()
However there are lots of issues with this and I wondered if Groovy had some kind of shorthand for this as well?
Thanks!
Groovy added an execute() method to plain old String, so try this:
println "ls -la".execute().text
The execute() method can be used to change directories if you prefix it with the "cmd /c" command, and then use ampersand (assuming Windows) to chain commands together.
Example, assuming you want to go to subdirectory subdir and run a couple of batch files from there:
println "cmd /c cd subdir & batch1.bat & batch2.bat".execute().text
Not sure if there isn't a better way, but this does work.
You can also use ProcessBuilder which is a surprisingly convienent Java class introduced in java 5.
ProcessBuilder lets you
determine the working directory
determine which environmental variables the process should have
See http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html for a brief example and more documentation.
If you aren't afraid to create some reusable code you could create an object that wraps an .execute() process. I created something like this and use it regularly.
Create a new process with:
def proc="cmd".execute()
After that you can use "consumeProcessOutput()" to manage the input and output of "proc". Anything you send to it will be acted on as though you typed it into a shell, and all the output of that shell will be available to you.
I wrapped all this up in a closure so that you could do this:
cmd("cd \\ \n dir ") {
if(it.contains("AUTOEXEC.BAT"))
println it;
return true;
}
To get a display that shows only the autoexec.bat line. Note that until you return true from the closure, the stdin of that process is available so you can send more lines of text and interact with it indefinitely.
I use it quite a bit because commands like "cd" and "Dir" don't work in windows with .execute(), so a simple:
def directoryListing=cmd("cd\\\ndir")
will get me a quick directory listing with ease.
I'm working on an application controller for a program that is spitting text directly to /dev/tty.
This is a production application controller that must be able to catch all text going to the terminal. Generally, this isn't a problem. We simply redirect stdout and stderr. This particular application is making direct calls to echo and redirecting the result to /dev/tty (echo "some text" > /dev/tty). Redirects via my application controller are failing to catch the text.
I do have the source for this application, but am not in a position to modify it, nor is it being maintained anymore. Any ideas on how to catch and/or throw away the output?
screen -D -m yourEvilProgram
should work. Much time passed sinced I used it, but if you need to read some of its output it could even be possible that you could utilize some sockets to read it.
[Added: two links, Rackaid and Pixelbeat, and the home page at GNU]
The classic solution to controlling an application like this is Expect, which sets up pseudo-terminals, does logging, and drives the controlled application from a script. It comes with lots of sample scripts so you can probably just adapt one to fit your needs.
This is what I did in python
import pty, os
pid, fd = pty.fork()
if pid == 0: # In the child process execute another command
os.execv('./my-progr', [''])
print "Execv never returns :-)"
else:
while True:
try:
print os.read(fd,65536),
except OSError:
break
I can't quite determine whether the screen program mentioned by #flolo will do what you need or not. It may, but I'm not sure whether there is a logging facility built in, which appears to be what you need.
There probably is a program out there already to do what you need. I'd nominate sudosh as a possibility.
If you end up needing to write your own, you'll probably need to use a pseudo-tty (pty) and have your application controller sit in between the user's real terminal connection and the the pty device, where it can log whatever you need it to log. That's not trivial. You can find information about this in Rochkind's "Advanced UNIX Programming, 2nd Edn" book, and no doubt other similar books (Stevens' "Advanced Programming in the UNIX Environment" book is a likely candidate, but I don't have a copy to verify that).