Using sudo cd problem and workarounds

Pre-requisites

  1. Root access to your server or have access to an account that has sudo powers on your servers – Instructions here to see how to give a linux user sudo powers.

Setup

Login as a non-priveleged user (non-root). Let’s make a directory that only root can enter:

[ahmed@amayem ~]$ sudo mkdir test
[ahmed@amayem ~]$ ls -l
total 4
drwxr-xr-x 2 root root 4096 Apr 16 00:46 test

Not good enough, we need root to be the only one able to read, write or enter it.

[ahmed@amayem ~]$ sudo chmod 700 test/
[ahmed@amayem ~]$ ls -l
total 4
drwx------ 2 root root 4096 Apr 16 00:46 test

Much better.

The issue

Now let’s try to enter it:

[ahmed@amayem ~]$ cd test
-bash: cd: test: Permission denied

Just as expected we can’t get in. Let’s try a sudo

[ahmed@amayem ~]$ sudo cd test
sudo: cd: command not found

We are denied again, but the reason is different. It seems that cd is not a command that sudo knows. We can test this by checking

[ahmed@amayem test]$ ls /usr/bin | grep cd

Nope, it’s not there. How can we get in.

Workaround

You have two options:

  1. Turn into root
  2. Change the directory permission.

Turning into root.

This is accomplished with the following command:

[ahmed@amayem ~]$ sudo su
[root@amayem ahmed]# cd test

If you exit from the root shell you will be moved out to the directory above:

[root@amayem test]# exit
exit
[ahmed@amayem ~]$ ls

It worked. The same thing can also be done with the command sudo -s instead of sudo su. If you use sudo -i it will do as the others but also change the directory to the home directory of root.

Change the directory permission

This is probably not a good idea, as the permissions were probably set for a reason.

[ahmed@amayem ~]$ sudo chmod o+x test/

We gave the x permission to other than root and the group root. x means to execute. When applied to directories it means the permission to go through the directory. Let’s test now:

[ahmed@amayem ~]$ ls -l
total 4
drwx-----x 2 root root 4096 Apr 16 00:52 test
[ahmed@amayem ~]$ cd test/
[ahmed@amayem test]$

Looks good. But what can we do inside:

[ahmed@amayem test]$ ls
ls: cannot open directory .: Permission denied

But at least here we can use sudo as usual:

[ahmed@amayem test]$ sudo ls
test.txt

Clean up

Now that we know how to do it. Let’s clean up.

[ahmed@amayem ~]$ sudo rm -rf test/

Done.

References

  1. Warren Hill‘s, charlie‘s and Basharat Sial‘s answers to this askubuntu question.
  2. Siranjeevi’s answer here

Ahmed Amayem has written 90 articles

A Web Application Developer Entrepreneur.