-1

I'm experiencing this really weird issue which I just can't understand why it is happening. When I execute following command from my shell manually it works.

sudo -u some-user echo "$SSH_KEY" | /home/some-user/.ssh/authorized_keys

however from a bash script it fails with a message we don't have any permissions.

#!/bin/bash
sudo -u some-user echo "$SSH_KEY" | /home/some-user/.ssh/authorized_keys

Is there any bash option to configure, or can someone explain this behavior? It looks a bit like a bash security thingy for non interactive terminals or something like that, but I lost my creativity to google for the solution.

I'm running Ubuntu 16.04.

Marco
  • 4,817
  • 5
  • 34
  • 75
  • 2
    What is the *exact text* of the message when run from a bash script? How do you run the bash script? And perhaps most importantly, why does `some-user` have an executable program as their authorized keys file? – Daniel H Oct 20 '17 at 15:43
  • You must have copied the command wrong into the question. Maybe you also made the same error when copying into the script. – Barmar Oct 20 '17 at 15:44
  • `authorized_keys` is a data file, not a command you can run, with or without `sudo`. – Barmar Oct 20 '17 at 15:44
  • Indeed forgot to type the ‘echo “sshkey” | ‘ in front of authorized_key file. Last Quick thing i wanted to do before weekend – Marco Oct 22 '17 at 21:05
  • That said, your `sudo` only applies to the `echo`. Since `echo` doesn't require *any* permissions to run, it's completely useless. `sudo foo | bar` only escalates `foo`, not `bar`; and `sudo foo >> bar` runs `foo` with escalated permissions, but **doesn't** use those escalated permissions to open `bar` as a file: The file is opened by the shell before `sudo` is even started. – Charles Duffy Oct 22 '17 at 21:25
  • Which is to say, once you fix the immediate bug, you're likely to run into [permission denied when trying to append to a root-owned file with sudo](https://stackoverflow.com/questions/13778857/permission-denied-when-trying-to-append-a-file-to-a-root-owned-file-with-sudo). (Yes, it's "user-owned" vs root-owned in present scenario, but the concept and constraints hold). – Charles Duffy Oct 22 '17 at 21:27
  • Also, if you use `|` to pipe the data, it *still* tries to run `authorized_keys` as a file. Please copy your actual command from the shell and from the script, and only redact from that what’s necessary (e.g., `some-user`’s actual username), instead of re-typing everything. – Daniel H Oct 23 '17 at 21:21

1 Answers1

0

After hours of investigation it seems sudo commands where not executed because of the password prompt which does not occur from the script.

The solution was to first run a sudo command before runnning the script or just runnning the whole script as sudo so you can enter the password one time and the other sudo commands are running without password prompts.

Marco
  • 4,817
  • 5
  • 34
  • 75