Neohapsis is currently accepting applications for employment. For more information, please visit our website www.neohapsis.com or email hr@neohapsis.com
Re: gzip TOCTOU file-permissions vulnerability

From: Dmitry Yu. Bolkhovityanov (bolkhovsky.inp.nsk.su)
Date: Sat Apr 16 2005 - 07:06:14 CDT

On Thu, 14 Apr 2005 devnullRodents.Montreal.QC.CA wrote:

> >> The open() call is at fault here. If instead of being called with a
> >> mode of RW_USER, it is called with the final intended access mode,
> >> there is no need to later call chmod(), and the problem is averted.

        Doing open(,,RW_USER) is not a solution: the resulting file's mode
will be (mode & ~umask), but NOT just `mode'.

        So, either fchmod(,RW_USER) just after open()/creat() is required
(which seems to be the best practice), or some umask trickery will be

> > One wrinkle - if the file is not intended to have user write
> > permission on it, and gzip (unzip/cpio/pax...) initially created it
> > with the intended permissions, there would be no way to then write
> > the file.
> This is not how most Unix variants work: provided you have an
> open-for-write descriptor on a file, you can write to it as long as the
> descriptor survives even if the file's permissions deny you write
> access.
> In particular, creating a file for write with a mode forbidding writing
> is not at all impossible.
> Now, if you're not on a Unix variant, or for all I know even some of
> the more variant Unix variants, this may not be true. But it certainly
> is common for this to work fine. Indeed, it's arguably better because
> it helps prevent others from writing to the file by mistake even during
> a brief time between open()ing and fchmod()ing.

        Yes, writing to a just-created file with permissions 000 WILL work
under most Unices. But think about NFS -- since NFS doesn't have
"sessions"/"states"/"open descriptors", the checks will (or at least can,
at least in some versions of NFS) be performed upon each write. Thus,
write() may fail.

          Dmitry Yu. Bolkhovityanov
          The Budker Institute of Nuclear Physics
          Novosibirsk, Russia