Bro_IDKU
Bro_IDKU

Reputation: 21

Python os.access() reads file no matter what

I have a script that checks a file for vulnerabilities. If the file path exists, the script then checks to see if the file can be read. However, when I set the file's permissions, os.access() is able to read the file no matter what. In windows I have denied all permissions and in Linux, I have tried chmod 000 on the file and got the same output on both machines.Here is the code:

import sys
import os

if len(sys.argv) == 2:
    filename = sys.argv[1]
    if not os.path.isfile(filename):
        print '[-] ' + filename + ' does not exist.'
        exit(0)
    if not os.access(filename, os.R_OK):
        print '[-] ' + filename + ': access denied.'
        exit(0)

    print '[+] Reading Vulnerabilities From: ' + filename

Whenever I pass an incorrect file name or path, os.path.isFile() works fine, however os.access() doesn't. I'm fairly new to python as well, all help will be appreciated

UPDATED:

When I run the script I use the command:

python scriptName.py vuln_banners.txt

after I have already ran

chmod 000 vuln_banners.txt

The only output I get is:

'[+] Reading Vulnerabilities From: vuln_banners.txt

I ran

ls -la vuln_banners.txt

and got the output:

---------- 1 root root 397 Dec 31 22:32 vuln_banners.txt

Upvotes: 2

Views: 2405

Answers (1)

Digisec
Digisec

Reputation: 710

It seems from your last comment that you are running the script as root which is a no no in Linux unless you REALLY know what you're doing.

os.access() will return True if you're running in root as you will have access to read the file even if its permissions are 000.

I was able to reproduce your issue when I tried running your script under root privileges. Try running it under a normal user and it should behave as expected then.

Also, if the script fails, you don't want it to return a 0, you want to return another value. The value 0 represents exiting with no error. Your script should look something similar to this where the return value of the exit is meaningful to you.

import sys
import os

if len(sys.argv) == 2:
    filename = sys.argv[1]
    if not os.path.isfile(filename):
        print '[-] ' + filename + ' does not exist.'
        rvalue = 1
    elif not os.access(filename, os.R_OK):
        print '[-] ' + filename + ': access denied.'
        rvalue = 2
    else:
        print '[+] Reading Vulnerabilities From: ' + filenam
        rvalue = 0

exit(rvalue)

Upvotes: 3

Related Questions