run gpg encryption command through cronjob - linux

I have a script which executes the gpg encryption command in a sh script throught cronjob.
This is a part of my script
do
gpg --batch --no-tty --yes --recipient $Key --output $Outputdir/${v}.pgp --encrypt ${v}
echo "$?"
if ["$?" -eq 0 ];
then
mv $Inputdir/${v} $Readydir/
echo "file moved"
else
echo "error in encryption"
fi
done
the echo $? gives value as 2.
tried the bellow command also
gpg --batch --home-dir dir --recipient $Key --output $Outputdir/${v}.pgp --encrypt ${v}
where dir=/usr/bin/gpg
My complete script
#set -x
PT=/gonm1_apps/xfb/ref/phoenix_drop
Inputdir=`grep Inputdir ${PT}/param.cfg | cut -d "=" -f2`
Outputdir=`grep Outputdir ${PT}/param.cfg | cut -d "=" -f2`
Key=`grep Key ${PT}/param.cfg | cut -d "=" -f2`
Readydir=`grep Readydir ${PT}/param.cfg | cut -d "=" -f2`
echo $USER
if [ "$(ls -la $Inputdir | grep -E 'S*.DAT')" ]; then
echo "Take action $Inputdir is not Empty"
cd $Inputdir
for v in `ls SID_090_*`
do
gpg --recipient $Key --output $Outputdir/${v}.pgp --encrypt ${v}
echo "$?"
if ["$?" -eq 0 ];
then
mv $Inputdir/${v} $Readydir/
echo "file moved"
else
echo "error in encryption"
fi
done
cd ${PT}
else
echo "$Inputdir is Empty"
fi

GnuPG manages individual keyrings and "GnuPG home directories" per user. A commmon problem when calling GnuPG from web services or cronjobs is executing them as another user.
This means that the other user's GnuPG does look up keys in the wrong key ring (home directory), and if that's fixed it should not have access permissions to the GnuPG home directory at all (not an issue when running a cron or web server as root, but that shouldn't be done for pretty much this reason first hand).
There are different ways to mitigate the issue:
Run the web server or cron job under another user. This might be a viable solution for cron jobs, but very likely not for web services. sudo or su might help at running GnuPG as another user.
Import the required (private/public) keys to the other user's GnuPG home directory, for example by switching to the www-data or root user (or whatever it's called on your machine).
Change GnuPG's behavior to use another user's home directory. You can do so with --home-dir /home/[username]/.gnupg or shorter --home-dir ~username/.gnupg if your shell resolves the short-hand. Better don't do this, as GnuPG is very strict at verifying access privileges and refuse to work if those are too relaxed. GnuPG doesn't like permissions allowing other users but the owner to access a GnuPG home directory at all, for good reasons.
Change GnuPG's behavior to use a completely unrelated folder as home directory, for example somewhere your application is storing data anyway. Usually, the best solution. Make sure to set the owner and access permissions appropriately. An example would be the option --home-dir /var/lib/foo-product/gnupg.

if
the echo $USER prints as root when executed on cronjob and as
username when executed manually
Then you need to login as the user and use a command such as "crontab -e" to add a cronjob for that user to run your script

Related

How can I make my bash script create an ssh key pair for a given user

I am new to bash scripting. I wrote a script that can create groups and users which works just fine, but my challenge now is how do I make the script create an ssh key pair for a particular user. From my script, it stopped working immediately after you switch to that user and it doesn't proceed to create the ssh key pair.
Below is my script.
for group in admin support engineering
do
sudo groupadd $group
sudo useradd -m -s /bin/bash achebeh_${group}
done
sudo passwd achebeh_admin
sudo su achebeh_admin
ssh-keygen -t rsa
So please how can I go about creating an ssh pair for the achebeh_admin user using this script. I am open to learn. Please this is my firs script after following a tutorial course.
#Achebe-peter If I got your requirements correctly from your short description, this will do the job for you.
Note:
Try this script in a test environment at your own risk!
This script best performs assuming that you don't have configured users and related files
#!/bin/bash
### Configuration Parameters Start ###
## The username that doesn't exist and you want to create.
user_name_prefix='testuser'
## The groups array that doesn't exist and you want to create and assign them to your user.
groups=(testadmin testsupport testengineering)
## SSH-key lenght
ssh_key_lenght='2048'
### Configuration Parameters End ###
for group in ${groups[#]} ;do
# Set username containing the prefix and group name
user="${user_name_prefix}_${group}"
# create such user if not exist
getent passwd ${user} &>/dev/null
if [ "$?" -ne 0 ] ;then
sudo useradd -m -s /bin/bash "${user}"
echo -e "\nType password for: ${user}"
sudo passwd ${user}
fi
# Create '.ssh' directory in user's home directory
if ! [ -d /home/${user}/.ssh ] ;then
sudo mkdir /home/${user}/.ssh
fi
# Generate ssh-key pair and move them to correspondig user's '.ssh/' dir.
ssh_file_name="./${user}_ssh"
(
echo "${ssh_file_name}"
echo ""
echo ""
) | ssh-keygen -t rsa -b ${ssh_key_lenght}
sudo mv -i "${ssh_file_name}" "${ssh_file_name}.pub" /home/${user}/.ssh/
sudo chown ${user}:${user} /home/${user}
# Create the groups (if does not exist)
getent group ${group} &>/dev/null
if [ "$?" -ne 0 ] ;then
sudo groupadd ${group}
fi
# Assign relevant group to the new user
sudo usermod -aG ${group} ${user}
done
exit 0
Tested in
GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
PS. Please vote up my answer and mark it as the correct answer if it satisfies your requirements.

Shell script to clone a GitHub Repo

I am trying to automate a process that contains a series of git commands.
I want the shell script to deal with some interactive commands, like passing the username and password to git clone url -v. I verified that if I just run git clone url -v it will show the following in order:
cloning into someRepo
asking for username
asking for password
I've tried:
echo -e 'username\n' | git clone url -v
echo -e 'username\npassword\n' | git clone url -v
git clone url -v <<< username\npassword\n
(sleep 5;echo -e 'username\n' | git clone url -v)
I thought that the first message cloning into repo will take some time. None of them is working, but all of them are showing the same message that Username for url:
Having spent lots of time in this, I know that
git clone https://$username:$password#enterpriseGithub.com/org/repo
is working, but it is UNSAFE to use since the log show the username and password explicitly.
Better practice would be to avoid user/password authentication at all (as by configuring agent-based auth, ideally backed by private keys stored on physical tokens), or set up credential storage in a keystore provided (and hopefully secured) by your operating system -- but if you just want to keep credentials off the command line, that can be done:
# Assume that we already know the credentials we want to store...
gitUsername="some"; gitPassword="values"
# Create a file containing the credentials readable only to the current user
mkdir -p "$HOME/.git-creds/https"
chmod 700 "$HOME/.git-creds"
cat >"$HOME/.git-creds/https/enterprise-github.com" <<EOF
username=$gitUsername
password=$gitPassword
EOF
# Generate a script that can retrieve stored credentials
mkdir -p -- "$HOME/bin"
cat >"$HOME/bin/git-retrieve-creds" <<'EOF'
#!/usr/bin/env bash
declare -A args=( )
while IFS= read -r line; do
case $line in
*..*) echo "ERROR: Invalid request" >&2; exit 1;;
*=*) args[${line%%=*}]=${line#*=} ;;
'') break ;;
esac
done
[[ ${args[protocol]} && ${args[host]} ]] || {
echo "Did not retrieve protocol and host" >&2; exit 1;
}
f="$HOME/.git-creds/${args[protocol]}/${args[host]}"
[[ -s $f ]] && cat -- "$f"
EOF
chmod +x "$HOME/bin/git-retrieve-creds"
# And configure git to use that
git config --global credential.helper "$HOME/bin/git-retrieve-creds"

ssh to different nodes using shell scripting

I am using below code to ssh to different nodes and find if an user exists or not. If the user doesn't exist it will create it.
The script works fine if I don't do ssh but it fails if I do ssh.
How can I go through different nodes using this script?
for node in `nodes.txt`
usr=root
ssh $usr#$node
do
if [ $(id -u) -eq 0 ]; then
read -p "Enter username : " username
read -s -p "Enter password : " password
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p $pass $username
[ $? -eq 0 ] && echo "User has been added to system!" || echo "F
ailed to add a user!"
fi
else
echo "Only root may add a user to the system"
exit 2
fi
done
Your script has grave syntax errors. I guess the for loop at the beginning is what you attempted to add but you totally broke the script in the process.
The syntax for looping over lines in a file is
while read -r line; do
.... # loop over "$line"
done <nodes.txt
(or marginally for line in $(cat nodes.txt); do ... but this has multiple issues; see http://mywiki.wooledge.org/DontReadLinesWithFor for details).
If the intent is to actually run the remainder of the script in the ssh you need to pass it to the ssh command. Something like this:
while read -r node; do
read -p "Enter user name: " username
read -p -s "Enter password: "
ssh root#"$node" "
# Note addition of -q option and trailing :
egrep -q '^$username:' /etc/passwd ||
useradd -m -p \"\$(perl -e 'print crypt(\$ARGV[0], \"password\")' \"$password\")" '$username'" </dev/null
done <nodes.txt
Granted, the command you pass to ssh can be arbitrarily complex, but you will want to avoid doing interactive I/O inside a root-privileged remote script, and generally make sure the remote command is as quiet and robust as possible.
The anti-pattern command; if [ $? -eq 0 ]; then ... is clumsy but very common. The purpose of if is to run a command and examine its result code, so this is better and more idiomatically written if command; then ... (which can be even more succinctly written command && ... or ! command || ... if you only need the then or the else part, respectively, of the full long-hand if/then/else structure).
Maybe you should only do the remote tasks via ssh. All the rest runs local.
ssh $user#$node egrep "^$username" /etc/passwd >/dev/null
and
ssh $user#$node useradd -m -p $pass $username
It might also be better to ask for username and password outside of the loop if you want to create the same user on all nodes.

How to correctly secure this Bash Script? (Sudo)

I wanted to make this Script kinda Secure, so it cannot be direct exploited.
I have a Bash file called Test.sh, I gave a User Sudo rights on it:
user ALL=(root) NOPASSWD: /home/user/Test.sh
So the User has full Sudo permission to this file.
Next Step was to ensure that the User cannot edit this file with:
chown root:root /home/user/Test.sh
chmod u=rwx,g=rwx,o=rx /home/user/Test.sh
The File for example contains this Command
if [ "$1" = "run" ]; then
sudo -u ${2} ${3};
fi
OR
`sudo cp -R /home/test/test/${2}/* /home/${3}/test/
useradd ${2} -r -d /home/${2} -s /bin/bash
userdel -r ${2}
Basically the User could even Login as root and fuck things up.
So my first thought was, lets check if the Home folder exists like that:
if [ -d "/home/$2" ] && [ "$2" != "" ]; then
Which would prevent such things like run crap as root and only let them log into th other users like i want. Or do i think wrong?
I would also check that the Command begins with /home/....
grep '^/home/....' $3
So, is that enought? or Not? I guess I should filter also ;

How to make a script run commands as root

I'm new to Ubuntu and bash scripts, but I just made runUpdates.sh and added this to my .profile to run it:
if [ -f "$HOME/bin/runUpdates.sh" ]; then
. "$HOME/bin/runUpdates.sh"
fi
The problem I'm having is, I want the script to run as if root is running it (because I don't want to type my sudo password)
I found a few places that I should be able to do sudo chown root.root <my script> and sudo chmod 4755 <my script> and when I run it, it should run as root. But it's not...
The script looks good to me. What am I missing? -rwxr-xr-x 1 root root 851 Mar 23 21:14 runUpdates.sh*
Can you please help me run the commands in this script as root? I don't really want to change the sudors file, I really just want to run the commands in this script at root (if possible).
#!/bin/sh
echo "user is ${USER}"
#check for updates
update=`cat /var/lib/update-notifier/updates-available | head -c 2 | tail -c 1`;
if [ "$update" = "0" ]; then
echo -e "No updates found.\n";
else
read -p "Do you wish to install updates? [yN] " yn
if [ "$yn" != "y" ] && [ "$yn" != "Y" ]; then
echo -e 'No\n';
else
echo "Please wait...";
echo `sudo apt-get update`;
echo `sudo apt-get upgrade`;
echo `sudo apt-get dist-upgrade`;
echo -e "Done!\n";
fi
fi
#check for restart
restartFile=`/usr/lib/update-notifier/update-motd-reboot-required`;
if [ ! -z "$restartFile" ]; then
echo "$restartFile";
read -p "Do you wish to REBOOT? [yN] " yn
if [ "$yn" != "y" ] && [ "$yn" != "Y" ]; then
echo -e 'No\n';
else
echo `sudo shutdown -r now`;
fi
fi
I added the user is to debug, it always outputs my user not root, and prompts for the sudo password (since I'm calling the commands with sudo) or tells me are you root? (if I remove sudo)
Also, is there a way to output the update commands stdout in real time, not just one block when they finish?
(I also tried with the shebang as #!/bin/bash)
setuid does not work on shell scripts for security reasons. If you want to run a script as root without a password, you can edit /etc/sudoers to allow it to be run with sudo without a password.
To "update in real time", you would run the command directly instead of using echo.
Its not safe to do, you should probably use sudoers but if you really need/want to, you can do it with something like this:
echo <root password> | sudo -S echo -n 2>/dev/random 1>/dev/random
sudo <command>
This works because sudo doesn't require a password for a brief window after successfully being used.
SUID root scripts were phased out many years ago if you really want to run scripts as root you need to wrap them in an executable, you can see an example on how to do this on my blog:
http://scriptsandoneliners.blogspot.com/2015/01/sanitizing-dangerous-yet-useful-commands.html
The example is how to change executable permissions and place a filter around other executables using a shell script but the concept of wrapping a shell script works for SUID as well, the resulting executable file from the shell script can be made SUID.
https://help.ubuntu.com/community/Sudoers

Resources