black spider on brown wooden table

Bash files vs configuration

You guys know me, I do script a lot of stuff to make my life easier. Starting from my (smart)home to my server maintenance – it just saves too much time. And today I would like to share some ideas on how (not?) to work with configuration stuff in bash.

First of all: Configuration on some scripts may be needed. If it’s for uploading stuff onto a remote repository, FTP server or whatever – you need to have at least the remote host specified somewhere. In case of you’re making your script public, it’s for sure no good idea to share that information as other folks may try their luck and snoop around using their findings.

So what’s the solution to that? At first I decided to move all of my config stuff into variables at the beginning of the file to save me some headache on changing configuration to solve the mistakes we described in the previous step. Nothing big, but it works.

Next would be reading the configuration from an external file. In bash it can be as simple as just including another script like

source /home/myuser/test/config

But that’s where I want to think about what this line does. Sourcing another script is executing it. In other words, source is not secure as it will execute arbitrary code. This may not be a concern for you, but if file permissions are incorrect, it may be possible for an attacker with filesystem access to execute code as a privileged user by injecting code into a config file loaded by an otherwise-secured script such as an init script.

But what’s the solution? Mine was parsing the configuration instead of executing it. As json is simple, I decided to put it to good use here as the program ‘jq’ is a nifty little shell parser for that. If you’re more into xml, I’m sure the XML starlet has you covered.

Now let’s do an example – shall we? Let’s try with a very simple config that I would use:

"username": "username-or-email",
"password": "the-password" 

Now for our main script I can fetch the data using jq:

USERNAME="$( jq -r '.username' "$config_file" )"

The moral of the story: parse your config, do not execute it.


Leave a Reply

Your email address will not be published. Required fields are marked *