How UMASK is applied on SFTP uploads

Lee Painter

One of the less well understood areas of SFTP is how umasks are applied to files uploaded by the API. The SftpClient object supports a umask function that can be called to both enable the use of client side umask, and also to the the value.

umask 027

 

The behaviour of umask can be confusing for user if they fail to understand how this is applied. Firstly, when uploading a file via SFTP a set of permissions is provided to the server as part of the open file message. If the file already exists, no change in permissions is applied. If the file does not exist then the permissions MAY be applied depending on the configuration of the users account on the server.

 

The permissions that will be applied will be the most restrictive of:

a. The APIs umask value

or 

b. The users umask setting (as set by calling umask)

 

Effectivley what happens is that the users umask is always be applied to the permissions provided by the API. Therefore you cannot upload files and have default permissions set to anything more liberal than the users current umask setting.

You can see this by performing the following test. Create/Edit ~/.bashrc in the users home folder on the server you are uploading to and add the following line:

umask 027

 

Now upload a file without setting umask on file. The result is:

-rw-r-----    1 lee      staff        4400 Jun 11 12:05 upload.txt

 

Next tell API to use a umask, in this case we set it to more restrictive 044;

sftp.umask(0044);

 

And the upload results in 

-rw-------    1 lee      staff        4400 Jun 11 12:04 upload.txt

 

However if you now set umask to 022 which is less restrictive than the users default of 027 it results in the users setting applied and not the API setting

-rw-r-----    1 lee      staff        4400 Jun 11 12:07 upload.txt

 

Therefore if you need to apply liberal file permissions on files that you upload via the API, for example 666, then you should consider forcing a permissions change using the chmod function.

sftp.chmod(0666, "upload.txt");

 

Now after upload we can see we have the file permissions that we desired.

-rw-rw-rw-    1 lee      staff        4400 Jun 11 12:22 upload.txt