classification
Title: `mode` security concern
Type: Stage: resolved
Components: IO Versions:
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: YoSTEALTH, serhiy.storchaka
Priority: normal Keywords:

Created on 2020-07-23 15:07 by YoSTEALTH, last changed 2020-07-23 18:01 by serhiy.storchaka. This issue is now closed.

Messages (3)
msg374138 - (view) Author: (YoSTEALTH) * Date: 2020-07-23 15:07
import os
import stat
import os.path


def problem(tmp_path):
    # result:
    # -------
    # check: False
    # mode: 416

    # create temp file
    fd = os.open(tmp_path, os.O_CREAT, 0o660)
    os.close(fd)

    # Directory is effected as well
    # os.mkdir(tmp_path, 0o660)


def solution(tmp_path):
    # result:
    # -------
    # check: True
    # mode: 432

    old_umask = os.umask(0)

    # create temp file
    fd = os.open(tmp_path, os.O_CREAT, 0o660)
    os.close(fd)

    # create temp dir
    # os.mkdir(tmp_path, 0o660)

    os.umask(old_umask)


def main():
    tmp_path = '_testing-chmod'

    problem(tmp_path)
    # solution(tmp_path)

    try:
        s = os.stat(tmp_path)
        mode = stat.S_IMODE(s.st_mode)
        print('check:', mode == 0o660)
        print('mode:', mode)  # this should be: 432
    finally:
        # delete temp file
        try:
            os.unlink(tmp_path)
        except IsADirectoryError:
            os.rmdir(tmp_path)


if __name__ == '__main__':
    main()


This result is not same for all os and distro, on multiple linux system for example the results will be different. I think Python should account for such behavior by default as it can lead to file/dir creation with security issues.
msg374142 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2020-07-23 15:48
It is expected behavior on Posix system. See https://pubs.opengroup.org/onlinepubs/9699919799/functions/umask.html

What is the problem?
msg374144 - (view) Author: (YoSTEALTH) * Date: 2020-07-23 16:34
I am closing this as its not a issue anymore... I was trying to solve a problem that has become a core feature!
History
Date User Action Args
2020-07-23 18:01:05serhiy.storchakasetresolution: not a bug
2020-07-23 16:34:25YoSTEALTHsetstatus: open -> closed

messages: + msg374144
stage: resolved
2020-07-23 15:48:14serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg374142
2020-07-23 15:07:20YoSTEALTHcreate