How to run code stored in environment variable explicitly - bash

I want to store password which is being used by other script as a environment variable. These are stored in a separate file which is being sourced anytime when a new terminal window is being opened.
The thing is, that it is insecure, so I decided it to store in a Apple Keychain and prompt user to enter password.
THE MAIN PROBLEM: I don't want it to run when sourcing variables (on new term window), but explicitly - anytime I call echo '$NAME', then I want to run the function stored in that variable, not on new term window.
.bash_variables:
get_pw()
{
key=$1
security unlock-keychain
security find-generic-password -a ${USER} -s $key -w
}
export E_PASSWORD="$(get_pw E_PASSWORD)"
This file is being sourced in .bash_profile:
if [ -f ~/.bash_variables ]; then
. ~/.bash_variables
fi

While I wouldn't recommend this approach in any environment that needs to be secure, but you can use the DEBUG trap.
function set_pw() {
if echo $BASH_COMMAND | grep '${*E_PASSWORD}*'; then
E_PASSWORD="$(get_pw E_PASSWORD)"
else
E_PASSWORD=""
fi
}
trap set_pw DEBUG
Explanation:
the DEBUG trap is executed before any command is executed
$BASH_COMMAND is the command that is about to be executed
${*E_PASSWORD}* checks if the $BASH_COMMAND tries to access the $E_PASSWORD variable (note that it doesn't take in account non interpolated strings ('$E_PASSWORD')
the else branch "deletes" the value when is not used (security ??)
NOTE: this is just an example! I'm not a security expert, so I can't even begin to understand the implications!

Related

Cannot use source to execute Bash script on zsh

I have a Mac, on which I have installed and configured zsh to be my default shell. It has worked very well with simple Bash scripts. Until today.
I was trying to set up my AWS CLI access with MFA and used a script to do the same. Since I have multiple accounts, I used an aws_accounts file to store the account numbers with 400 permissions on it. (No real reason why, just felt like it and it works).
I then source this file and get to the part where I need to provide my MFA key, and those work too. The last step, where I export the access key, secret key and session token, works as long as the script is executing, but once done, echoing it shows a blank, because it now no longer has set it in the current shell.
I know the workaround is to do source aws_mfa_access default to run the script, but it doesn't work and I get a bad substitution error. I've tried various combinations of #!/usr/bin/env bash, #!/bin/bash and #!/usr/bin/env zsh, but to no avail. What's going on?
[aws_account_numbers]
default_account_number=<number>
sandbox_account_number=<number>
production_account_number=<number>
[aws_mfa_access]
#!/usr/bin/env bash
source aws_account_numbers
AWS_ENV="${1}"
AWS_ACCT_NBR="${AWS_ENV}"_account_number
#export your aws access key that matches with your account, username
export AWS_PROFILE="${AWS_ENV}"
#If there are existing environment variables set, this can cause issues so we unset them first
unset AWS_SESSION_TOKEN
unset AWS_SECRET_ACCESS_KEY
unset AWS_ACCESS_KEY_ID
#Set the serial number of your MFA token
MFA="arn:aws:iam::${!AWS_ACCT_NBR}:mfa/codingincircles"
#Get the code from the MFA device
echo "Please enter the MFA code for the ${AWS_ENV} account: "
read -r code
#Get the credentials from AWS and store the response in a variable
creds="$( aws sts get-session-token --serial-number "${MFA}" --token-code "${code}" )"
#Parse the response into separate variables
AWS_ACCESS_KEY_ID="$( echo "${creds}" | jq -r .Credentials.AccessKeyId )"
AWS_SECRET_ACCESS_KEY="$( echo "${creds}" | jq -r .Credentials.SecretAccessKey )"
AWS_SESSION_TOKEN="$( echo "${creds}" | jq -r .Credentials.SessionToken )"
#Display the keys to the user for reference/confirm proper working
echo "${access_key}"
echo "${secret_key}"
echo "${session_token}"
#Set the appropriate environment variables
export AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID}"
export AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY}"
export AWS_SESSION_TOKEN="${AWS_SESSION_TOKEN}"
EDIT: Two things of note:
The parameter substitution is not an issue at all. It works just fine as is, though the other methods suggested in the comments and answer work too. (I used the jq -r tip and it works like a charm! Thank you!)
I removed the source command in my script (on line 3) and then was able to, without any errors of any kind, able to invoke my script as source aws_mfa_access default. The exported variables persisted and I am able to use the CLI with no problems.
So why does this not like me using source in my script? I've also edited the script to reflect some of the changes.
Indirect parameter expansion is different in zsh than it is in bash
MFA="arn:aws:iam::${(P)AWS_ACCT_NBR}:mfa/codingincircles"
However, you can avoid indirect parameter expansion in the first place by using an associative array to store the account numbers.
typeset -A account_numbers
account_numbers[default]=...
account_numbers[sandbox]=...
account_numbers[production]=...
Then
MFA="arn:aws:iam::${account_numbers[$1]}:mfa/codingincircles"
Finally, source is not an external command that means "execute a bash script here". It's a shell built-in that executes a file in the current shell. If the current shell is bash, it will attempt to execute the contents of a file as a bash script; if it's zsh, as a zsh script; if it's dash, as a dash script.

How to distinguish function from bash_profile is running at start or called by user later?

I am writing a function in bash_profile that needs to be silence when first load by bash at start(eg. each time in a new xterminal), and then be verbose if user calls it later within that bash.
I need the function to run when bash starts and also run upon user's request.
Is there a way to distinguish this ?
I tried "$PS1" and "$-", both are interactive.
Sorry for my poor English, I mean a function to create a per user memdisk for cache. It should be created once a interactive login, thus I put it into ~/.profile. It also should be switch off and on by user, so the function should be verbose when user called it later.
During login, it should be silence, and when user try to switch, it must be verbose.
For short, I need sth. like swap on to be silence when user login, but be verbose when user type it later.
Heard from others:
Two ways to are to pass an argument, or to check the environment.
I just find a way to use etime of $$.
setit() {
BashRun=$(ps -p "$$" -o etime=|tr '-' ':'|awk -F: '{total=0;m=1;} {for (i=0;i<NF;i++) {total+=$(NF-i)*m;m*=i>=2?24:60}} {print total}')
... ...
if [ $? -eq 0 ]; then
if [ $BashRun -gt 1 ]; then
echo "It has already been set !"
fi
fi
}

Declare variable on unix server

I am trying to login on one of the remote server(Box1) and trying to read one file on remote server(Box1).
That contain the another server(Box2) details, base upon that details I have to come back to the local server and ssh to another server(Box2) for some data crunching. and so on.....
ssh box1.com << EOF
if [[ ! -f /home/rakesh/tomar.log ]]
then
echo "LOG file not found"
else
echo " LOG file present"
export server_node1= `cat /home/rakesh/tomar.log`
fi
EOF
ssh box2.com << EOF
if [[ ! -f /home/rakesh/tomar.log ]]
then
echo "LOG file not found"
else
echo " LOG file present"
export server_node2= `cat /home/rakesh/tomar.log`
fi
EOF
but I am not getting value of "server_node1" and "server_node2" on local machine.
any help would be appreciated.
Just like bash -c 'export foo=bar' cannot declare a variable in the calling shell where you typed this, an ssh command cannot declare a variable in the calling shell. You will have to refactor so that the calling shell receives the information and knows what to do with it.
I agree with the comment that storing a log file in a variable is probably not a sane, or at least elegant, thing to do, but the easy way to do what you are attempting is to put the ssh inside the assignment.
server_node1=$(ssh box1.com cat tomar.log)
server_node2=$(ssh box2.com cat tomar.log)
A few notes and amplifications:
The remote shell will run in your home directory, so I took it out (on the assumption that /home/rt9419 is your home directory, obviously).
In case of an error in the cat command, the exit code of ssh will be the error code from cat, and the error message on standard error will be visible on your standard error, so the echo seemed quite superfluous. (If you want a custom message, variable=$(ssh whatever) || echo "Custom message" >&2 would do that. Note the redirection to standard error; it doesn't seem to matter here, but it's good form.)
If you really wanted to, you could run an arbitrarily complex command in the ssh; as outlined above, it didn't seem necessary here, but you could do assigment=$(ssh remote 'if [[ things ]]; then for variable in $(complex commands to drive a loop); do : etc etc; done; fi; more </dev/null; exit "$variable"') or whatever.
As further comments on your original attempt,
The backticks in the here document in your attempt would be evaluated by your local shell before the ssh command even ran. There are separate questions about how to fix that; see e.g. How have both local and remote variable inside an SSH command. but in short, unless you absolutely require the local shell to be able to modify the commands you send, probably put them in single quotes, like I did in the silly complex ssh example above.
The function of export is to make variables visible to child processes. There is no way to affect the environment of a parent process (short of having it cooperate and/or coordinate the change, as in the code above). As an example to illustrate the difference, if you set PERL5LIB to a directory with Perl libraries, but fail to export it, the Perl process you start will not see the variable; it is only visible to the current shell. When you export it, any Perl process you start as a child of this shell will also see this variable and the value you assigned. In other words, you export variables which are not private to the current shell (and don't export private ones; aside from making sure they are private, this saves the amount of memory which needs to be copied between processes), but that still only makes them visible to children, by the design of the U*x process architecture.
You should get back the file from box1and box2 with an scp:
scp box1.com:/home/rt9419/tomar.log ~/tomar1.log
#then you can cat!
export server_node1=`cat ~/tomar1.log`
idem with box2
scp box2.com:/home/rt9419/tomar.log ~/tomar2.log
#then you can cat!
export server_node2=`cat ~/tomar2.log`
There are several possibilities. In your case, you could on the remote system create a file (in bash syntax), containing the assignments of these variables, for example
echo "export server_node2='$(</home/rt9419/tomar.log)'" >>export_settings
(which makes me wonder why you want the whole content of your logfile be stored into a variable, but this is another question), then transfer this file to your host (for example with scp) and source it from within your bash script.

Pass a variable in a shell script

I'm new to Unix...I have a shell script that calls sqlplus. I have some variables that are defined within the code. However, I do not feel comfortable having the password displayed within the script. I would appreciate if someone could show me ways on how to hide my password.
One approach I know of is to omit the password and sqlplus will
prompt you for the password.
An approach that I will very much be interested in is a linux
command whose output can be passed into the password variable. That
way, I can replace easily replace "test" with some parameter.
Any other approach.
Thanks
#This is test.sh It executes sqlplus
#!/bin/sh
export user=TestUser
export password=test
# Other variables have been ommited
echo ----------------------------------------
echo Starting ...
echo ----------------------------------------
echo
sqlplus $user/$password
echo
echo ----------------------------------------
echo finish ...
echo ----------------------------------------
You can pipe the password to the sqlplus command:
echo ${password} | sqlplus ${user}
tl;dr: passwords on the command line are prone to exposure to hostile code and users. don't do it. you have better options.
the command line is accessible using $0 (the command itself) through ${!#} ($# is the number of arguments and ${!name} dereferences the value of $name, in this case $#).
you may simply provide the password as a positional argument (say, first, or $1), or use getopts(1), but the thing is passwords in the arguments array is a bad idea. Consider the case of ps auxww (displays full command lines of all processes, including those of other users).
prefer getting the password interactively (stdin) or from a configuration file. these solutions have different strengths and weaknesses, so choose according to the constraints of your situation. make sure the config file is not readable by unauthorized users if you go that way. it's not enough to make the file hard to find btw.
the interactive thing can be done with the shell builtin command read.
its description in the Shell Builtin Commands section in bash(1) includes
-s Silent mode. If input is coming from a terminal, characters are not echoed.
#!/usr/bin/env bash
INTERACTIVE=$([[ -t 0 ]] && echo yes)
if ! IFS= read -rs ${INTERACTIVE+-p 'Enter password: '} password; then
echo 'received ^D, quitting.'
exit 1
fi
echo password="'$password'"
read the bash manual for explanations of other constructs used in the snippet.
configuration files for shell scripts are extremely easy, just source ~/.mystuffrc in your script. the configuration file is a normal shell script, and if you limit yourself to setting variables there, it will be very simple.
for the description of source, again see Shell Builtin Commands.

How to write a bash script to set global environment variable?

Recently I wrote a script which sets an environment variable, take a look:
#!/bin/bash
echo "Pass a path:"
read path
echo $path
defaultPath=/home/$(whoami)/Desktop
if [ -n "$path" ]; then
export my_var=$path
else
echo "Path is empty! Exporting default path ..."
export my_var=$defaultPath
fi
echo "Exported path: $my_var"
It works just great but the problem is that my_var is available just locally, I mean in console window where I ran the script.
How to write a script which allow me to export global environment variable which can be seen everywhere?
Just run your shell script preceded by "." (dot space).
This causes the script to run the instructions in the original shell. Thus the variables still exist after the script finish
Ex:
cat setmyvar.sh
export myvar=exists
. ./setmyvar.sh
echo $myvar
exists
Each and every shell has its own environment. There's no Universal environment that will magically appear in all console windows. An environment variable created in one shell cannot be accessed in another shell.
It's even more restrictive. If one shell spawns a subshell, that subshell has access to the parent's environment variables, but if that subshell creates an environment variable, it's not accessible in the parent shell.
If all of your shells need access to the same set of variables, you can create a startup file that will set them for you. This is done in BASH via the $HOME/.bash_profile file (or through $HOME/.profile if $HOME/.bash_profile doesn't exist) or through $HOME/.bashrc. Other shells have their own set of startup files. One is used for logins, and one is used for shells spawned without logins (and, as with bash, a third for non-interactive shells). See the manpage to learn exactly what startup scripts are used and what order they're executed).
You can try using shared memory, but I believe that only works while processes are running, so even if you figured out a way to set a piece of shared memory, it would go away as soon as that command is finished. (I've rarely used shared memory except for named pipes). Otherwise, there's really no way to set an environment variable in one shell and have another shell automatically pick it up. You can try using named pipes or writing that environment variable to a file for other shells to pick it up.
Imagine the problems that could happen if someone could change the environment of one shell without my knowledge.
Actually I found an way to achieve this (which in my case was to use a bash script to set a number of security credentials)
I just call bash from inside the script and the spawned shell now has the export values
export API_USERNAME=abc
export API_PASSWORD=bbbb
bash
now calling the file using ~/.app-x-setup.sh will give me an interactive shell with those environment values setup
The following were extracted from 2nd paragraph from David W.'s answer: "If one shell spawns a subshell, that subshell has access to the parent's environment variables, but if that subshell creates an environment variable, it's not accessible in the parent shell."
In case a user need to let parent shell access your new environment variables, just issue the following command in parent shell:
source <your_subshell_script>
or using shortcut
. <your_subshell_script>
You got to add the variable in your .profile located in /home/$USER/.profile
Yo can do that with this command:
echo 'TEST="hi"' >> $HOME/.profile
Or by edit the file with emacs, for example.
If you want to set this variable for all users, you got to edit /etc/profile (root)
There is no global environment, really, in UNIX.
Each process has an environment, originally inherited from the parent, but it is local to the process after the initial creation.
You can only modify your own, unless you go digging around in the process using a debugger.
write it to a temporary file, lets say ~/.myglobalvar and read it from anywhere
echo "$myglobal" > ~/.myglobalvar
Environment variables are always "local" to process execution the export command allow to set environment variables for sub processes. You can look at .bashrc to set environment variables at the start of a bash shell. What you are trying to do seems not possible as a process cannot modify (or access ?) to environment variables of another process.
You can update the ~/.bashrc or ~/.bash_profile file which is used to initialize the environment.
Take a look at the loading behavior of your shell (explained in the manpage, usually referring to .XXXshrc or .profile). Some configuration files are loaded at login time of an interactive shell, some are loaded each time you run a shell. Placing your variable in the latter might result in the behavior you want, e.g. always having the variable set using that distinct shell (for example bash).
If you need to dynamically set and reference environment variables in shell scripts, there is a work around. Judge for yourself whether is worth doing, but here it is.
The strategy involves having a 'set' script which dynamically writes a 'load' script, which has code to set and export an environment variable. The 'load' script is then executed periodically by other scripts which need to reference the variable. BTW, the same strategy could be done by writing and reading a file instead of a variable.
Here's a quick example...
Set_Load_PROCESSING_SIGNAL.sh
#!/bin/bash
PROCESSING_SIGNAL_SCRIPT=./Load_PROCESSING_SIGNAL.sh
echo "#!/bin/bash" > $PROCESSING_SIGNAL_SCRIPT
echo "export PROCESSING_SIGNAL=$1" >> $PROCESSING_SIGNAL_SCRIPT
chmod ug+rwx $PROCESSING_SIGNAL_SCRIPT
Load_PROCESSING_SIGNAL.sh (this gets dynamically created when the above is run)
#!/bin/bash
export PROCESSING_SIGNAL=1
You can test this with
Test_PROCESSING_SIGNAL.sh
#!/bin/bash
PROCESSING_SIGNAL_SCRIPT=./Load_PROCESSING_SIGNAL.sh
N=1
LIM=100
while [ $N -le $LIM ]
do
# DO WHATEVER LOOP PROCESSING IS NEEDED
echo "N = $N"
sleep 5
N=$(( $N + 1 ))
# CHECK PROCESSING_SIGNAL
source $PROCESSING_SIGNAL_SCRIPT
if [[ $PROCESSING_SIGNAL -eq 0 ]]; then
# Write log info indicating that the signal to stop processing was detected
# Write out all relevent info
# Send an alert email of this too
# Then exit
echo "Detected PROCESSING_SIGNAL for all stop. Exiting..."
exit 1
fi
done
~/.bin/SOURCED/lazy script to save and load data as flat files for system.
[ ! -d ~/.megadata ] && mkdir ~/.megadata
function save_data {
[ -z "$1" -o -z "$2" ] && echo 'save_data [:id:] [:data:]' && return
local overwrite=${3-false}
[ "$overwrite" = 'true' ] && echo "$2" > ~/.megadata/$1 && return
[ ! -f ~/.megadata/$1 ] && echo "$2" > ~/.megadata/$1 || echo ID TAKEN set third param to true to overwrite
}
save_data computer engine
cat ~/.megadata/computer
save_data computer engine
save_data computer megaengine true
function get_data {
[ -z "$1" -o -f $1 ] && echo 'get_data [:id:]' && return
[ -f ~/.megadata/$1 ] && cat ~/.megadata/$1 || echo ID NOT FOUND
:
}
get_data computer
get_data computer
Maybe a little off topic, but when you really need it to set it temporarily to execute some script and ended up here looking for answers:
If you need to run a script with certain environment variables that you don't need to keep after execution you could do something like this:
#!/usr/bin/env sh
export XDEBUG_SESSION=$(hostname);echo "running with xdebug: $XDEBUG_SESSION";$#
In my example I just use XDEBUG_SESSION with a hostname, but you can use multiple variables. Keep them separated with a semi-colon. Execution as follows (assuming you called the script debug.sh and placed it in the same directory as your php script):
$ debug.sh php yourscript.php

Resources