From 053234ee3cee2a79ff4d5f137b85e7e8b27f27f2 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Sun, 6 Dec 2020 21:42:22 -0800 Subject: [PATCH] Updated SC2024 (markdown) --- SC2024.md | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/SC2024.md b/SC2024.md index 88ac7b9..6e4a112 100644 --- a/SC2024.md +++ b/SC2024.md @@ -1,24 +1,38 @@ ## `sudo` doesn't affect redirects. Use `..| sudo tee file` +or "Use `sudo cat file | ..`" for input files. + ### Problematic code: ``` +# Write to a file sudo echo 'export FOO=bar' >> /etc/profile + +# Read from a file +sudo wc -l < /etc/shadow ``` ### Correct code: ``` +# Write to a file echo 'export FOO=bar' | sudo tee -a /etc/profile > /dev/null + +# Read from a file +sudo cat /etc/shadow | wc -l ``` ### Rationale: -Redirections are performed by the current shell before `sudo` is started. This means that it will use the current shell's user and permissions to open and write to the file. +Redirections are performed by the current shell before `sudo` is started. This means that it will use the current shell's user and permissions to open and read from or write to the file. -`tee` is a simple command that opens and writes to files without help from the shell, which means that it will use the permissions that `sudo` grants it. +* To *read* from a file that requires additional privileges, you can replace `sudo command < file` with `sudo cat file | command`. +* To *write* to a file that requires additional privileges, you can replace `sudo command > file` with `command | sudo tee file > /dev/null` +* If the file does *not* require special privileges but the command *does*, then you are already doing the right thing: please [[ignore]] the message. -There is nothing special about `tee`. It's just the simplest command that can both truncate and append to files without help from the shell. Here are equivalent alternatives: +Both substitutions work by having a command open the file for reading or writing, instead of relying on the current shell. Since the command is run with elevated privileges, it will have access to files that the current user does not. + +Note: there is nothing special about `tee`. It's just the simplest command that can both truncate and append to files without help from the shell. Here are equivalent alternatives: Truncating: @@ -36,4 +50,4 @@ echo 'data' | sudo sh -c 'cat >> file' ### Exceptions -If you want to run a command as root but redirect as the normal user, you can ignore this message. +If you want to run a command as root but redirect as the normal user, you can [[ignore]] this message.