11

I'd like to have a file on my computer that stores a particular token (rather than having them just exported to the shell env). As such, I'd like that the token can only be read by sudo, so access to it requires authorisation. How can I write a file that can only be read by sudo?

balupton
  • 471
  • 2
    https://unix.stackexchange.com/questions/101263/what-are-the-different-ways-to-set-file-permissions-etc-on-gnu-linux (you need to learn about chmod, and chown) – ctrl-alt-delor Jul 13 '18 at 06:28

3 Answers3

28

Note that sudo is not synonymous with root/superuser. In fact, sudo command let you execute commands as virtually any user, as specified by the security policy:

$ sudo whoami
root
$ sudo -u bob whoami
bob

I assume you meant to create a file that only root user can read:

# Create the file
touch file

# Change permissions of the file
# '600' means only owner has read and write permissions
chmod 600 file

# Change owner of the file
sudo chown root:root file

When you need to edit the content of the file:

# Replace 'nano' with your prefered editor
sudo nano file

See how only root can read the file:

$ cat file
cat: file: Permission denied
$ sudo cat file
foo bar baz
nxnev
  • 3,654
3

Figured it out:

echo 'hello world' > test
sudo chown root test
sudo chmod 600 test
sudo cat test

In another terminal, if you do it without sudo:

> cat test
cat: test: Permission denied
balupton
  • 471
1

With tee

$ echo "some text" | sudo tee tmpfile
some text
$ sudo chmod 700 tmpfile 
$ cat tmpfile
cat: tmpfile: Permission non accordée
$ sudo cat tmpfile
some text

For append :

$ echo "text appened" | sudo tee -a tmpfile
$ sudo cat tmpfile
somme text
text appened
$ sudo rm tmpfile
alux
  • 36