Ubuntu – ‘cat’: can’t open file: Permission denied

command linefilesfilesystempermissionssysfs

I am trying to copy the whole / directory to some other location. When doing cp recursively, it fails on some files like:-

/ # ls -lrt /sys/module/nf_conntrack_ipv4/uevent
--w-------    1 root     root          4096 Mar  7 06:29 /sys/module/nf_conntrack_ipv4/uevent
/ #
/ # cat /sys/module/nf_conntrack_ipv4/uevent
cat: can't open '/sys/module/nf_conntrack_ipv4/uevent': Permission denied
/ # cp /sys/module/nf_conntrack_ipv4/uevent /tmp
cp: can't open '/sys/module/nf_conntrack_ipv4/uevent': Permission denied

If I create some file with only w permissions and try to copy/cat it, I could see no problems there. However, for some files like the one mentioned above, I am unable to copy it or to cat it even though I am trying as root user. Also, the strange thing is that the size of the above mentioned file is mentioned to be as 4096 which is similar to the one we have for directory. Is this something special file?

I guess I am missing something here and need some input to know more about such files or such behaviors. Kindly do help me out in understanding why I am not allowed to cat contents of such files.

Best Answer

In a regular filesystem e.g. ext4, if you only have w permission in a file, you won't be able to read (cat) it, you need read (r) bit for that. Note that, root can read any file regardless of the permission bits.

Now, /sys is a mount point of special sysfs provided by Linux kernel which is actually a virtual filesystem and works differently than regular filesystems. /sys contains device related info of the system.

Modifying something in /sys would directly alter kernel's internal data structure so it depends on kernel what it would permit or deny.

For /sys/module/nf_conntrack_ipv4/uevent, you have only w bit set for owner (root), even if you add r bit for root (which is a very bad idea), while reading the file you would get I/O error because by design the kernel would not allow anyone to read the uevents for the nf_conntrack_ipv4 module.