I've been writing a number of bash scripts lately which get variables from a parameter or from a file. Some of the scripts run as root (using sudo)This is on my notebook, so there aren't any other users to cause security problems in this situation, but ...I'd like to be able to write a script I can release into the wild.Probably, what this question does is make a strong case for not writing anything in bash where root/sudo is involved and input/parameters can't be trusted.Other than locking everything down with sudoers, is there a way to read an arbitrary string into a bash program and parse it without allowing bash to expand it, potentially executing something along the way?I don't see any solution for defending against a rogue parameter.For a file, there might be a way, but it's not simple.The string could be safely input to the script using read, but once it's in one or more variables, I can't see any method of accessing it that wouldn't involve potentially dangerous variable expansion.I think it would be possible to read from a file using read -n 1 to get one character at a time in a loop into an array. That ought to defang just about anything, but it's a bit cumbersome having to reassemble everything character by character later.I'm thinking of input like:'$(rm -rf ./*)'or'eval shutdown -h now'or similar given as input which would run when a variable containing it was referenced. If the script was running as root, this could be a real problem!Any ideas on how to address this other than, Get a real programming language?
Securely reading and parsing a string from a parameter or file in bash
bash;security;scripting
It's difficult to answer that without knowing what kind of information has to be provided in that file. That the script is stored on a system with several users is not automatically a security problem. Why should they (be able to) provide input for other users?However, you can safely read a line from a file by read -r line. And if you just need data of the kind foo=bar then you can easily check the line for invalid characters (or structures) by [[ =~ ]].If you are not limited to using a single file then an easy solution can be taken from DJB's software: one file per variable. The variables can then be defined by something like:for varname in ${vars[@]}; do  if [ -f ${path_to_var_files}/$varname ]; then    eval $varname='$(cat '${path_to_var_files}/$varname')'  fidone...if trailing newlines are not important.A lot of problems (for the system, not for the respective user though) can be solved by minimizing the code running under sudo. Don't let a sudo script source the file. Let a user level script source the file and make the sudo calls. sudo scripts should have a clear interface with easy to be checked input.