Visitar URL original
C#/Go/Java/JS/Python/Ruby: Update the description and qhelp of the Zipslip query by atorralba · Pull Request #13475 · github/codeql · GitHub
The Wayback Machine - https://web.archive.org/web/20260616044022/https://github.com/github/codeql/pull/13475
Skip to content

C#/Go/Java/JS/Python/Ruby: Update the description and qhelp of the Zipslip query#13475

Merged
atorralba merged 5 commits into
github:mainfrom
atorralba:atorralba/many/zipslip-docs-update
Jun 19, 2023
Merged

C#/Go/Java/JS/Python/Ruby: Update the description and qhelp of the Zipslip query#13475
atorralba merged 5 commits into
github:mainfrom
atorralba:atorralba/many/zipslip-docs-update

Conversation

@atorralba

Copy link
Copy Markdown
Contributor

All filesystem operations, not just writes, with paths built from untrusted archive entry names are dangerous.

@atorralba atorralba requested review from a team as code owners June 16, 2023 06:51
@atorralba atorralba added the ready-for-doc-review This PR requires and is ready for review from the GitHub docs team. label Jun 16, 2023
@github-actions

github-actions Bot commented Jun 16, 2023 •

Copy link
Copy Markdown
Contributor

QHelp previews:

csharp/ql/src/Security Features/CWE-022/ZipSlip.qhelp

Arbitrary file access during archive extraction ("Zip Slip")

Extracting files from a malicious zip file, or similar type of archive, is at risk of directory traversal attacks if filenames from the archive are not properly validated.

Zip archives contain archive entries representing each file in the archive. These entries include a file path for the entry, but these file paths are not restricted and may contain unexpected special elements such as the directory traversal element (..). If these file paths are used to create a filesystem path, then a file operation may happen in an unexpected location. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.

For example, if a zip file contains a file entry ..\sneaky-file, and the zip file is extracted to the directory c:\output, then naively combining the paths would result in an output file path of c:\output\..\sneaky-file, which would cause the file to be written to c:\sneaky-file.

Recommendation

Ensure that output paths constructed from zip archive entries are validated to prevent writing files to unexpected locations.

The recommended way of writing an output file from a zip archive entry is to:

  1. Use Path.Combine(destinationDirectory, archiveEntry.FullName) to determine the raw output path.
  2. Use Path.GetFullPath(..) on the raw output path to resolve any directory traversal elements.
  3. Use Path.GetFullPath(destinationDirectory + Path.DirectorySeparatorChar) to determine the fully resolved path of the destination directory.
  4. Validate that the resolved output path StartsWith the resolved destination directory, aborting if this is not true.
    Another alternative is to validate archive entries against a whitelist of expected files.

Example

In this example, a file path taken from a zip archive item entry is combined with a destination directory. The result is used as the destination file path without verifying that the result is within the destination directory. If provided with a zip file containing an archive path like ..\sneaky-file, then this file would be written outside the destination directory.

using System.IO;
using System.IO.Compression;

class Bad
{
    public static void WriteToDirectory(ZipArchiveEntry entry,
                                        string destDirectory)
    {
        string destFileName = Path.Combine(destDirectory, entry.FullName);
        entry.ExtractToFile(destFileName);
    }
}

To fix this vulnerability, we need to make three changes. Firstly, we need to resolve any directory traversal or other special characters in the path by using Path.GetFullPath. Secondly, we need to identify the destination output directory, again using Path.GetFullPath, this time on the output directory. Finally, we need to ensure that the resolved output starts with the resolved destination directory, and throw an exception if this is not the case.

using System.IO;
using System.IO.Compression;

class Good
{
    public static void WriteToDirectory(ZipArchiveEntry entry,
                                        string destDirectory)
    {
        string destFileName = Path.GetFullPath(Path.Combine(destDirectory, entry.FullName));
        string fullDestDirPath = Path.GetFullPath(destDirectory + Path.DirectorySeparatorChar);
        if (!destFileName.StartsWith(fullDestDirPath)) {
            throw new System.InvalidOperationException("Entry is outside the target dir: " +
                                                                                 destFileName);
        }
        entry.ExtractToFile(destFileName);
    }
}

References

go/ql/src/Security/CWE-022/ZipSlip.qhelp

Arbitrary file access during archive extraction ("Zip Slip")

Extracting files from a malicious zip file, or similar type of archive, is at risk of directory traversal attacks if filenames from the archive are not properly validated. archive paths.

Zip archives contain archive entries representing each file in the archive. These entries include a file path for the entry, but these file paths are not restricted and may contain unexpected special elements such as the directory traversal element (..). If these file paths are used to create a filesystem path, then a file operation may happen in an unexpected location. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.

For example, if a zip file contains a file entry ..\sneaky-file, and the zip file is extracted to the directory c:\output, then naively combining the paths would result in an output file path of c:\output\..\sneaky-file, which would cause the file to be written to c:\sneaky-file.

Recommendation

Ensure that output paths constructed from zip archive entries are validated to prevent writing files to unexpected locations.

The recommended way of writing an output file from a zip archive entry is to check that ".." does not occur in the path.

Example

In this example an archive is extracted without validating file paths. If archive.zip contained relative paths (for instance, if it were created by something like zip archive.zip ../file.txt) then executing this code could write to locations outside the destination directory.

package main

import (
	"archive/zip"
	"io/ioutil"
	"path/filepath"
)

func unzip(f string) {
	r, _ := zip.OpenReader(f)
	for _, f := range r.File {
		p, _ := filepath.Abs(f.Name)
		// BAD: This could overwrite any file on the file system
		ioutil.WriteFile(p, []byte("present"), 0666)
	}
}

To fix this vulnerability, we need to check that the path does not contain any ".." elements in it.

package main

import (
	"archive/zip"
	"io/ioutil"
	"path/filepath"
	"strings"
)

func unzipGood(f string) {
	r, _ := zip.OpenReader(f)
	for _, f := range r.File {
		p, _ := filepath.Abs(f.Name)
		// GOOD: Check that path does not contain ".." before using it
		if !strings.Contains(f.Name, "..") {
			ioutil.WriteFile(p, []byte("present"), 0666)
		}
	}
}

References

java/ql/src/Security/CWE/CWE-022/ZipSlip.qhelp

Arbitrary file access during archive extraction ("Zip Slip")

Extracting files from a malicious zip file, or similar type of archive, is at risk of directory traversal attacks if filenames from the archive are not properly validated.

Zip archives contain archive entries representing each file in the archive. These entries include a file path for the entry, but these file paths are not restricted and may contain unexpected special elements such as the directory traversal element (..). If these file paths are used to create a filesystem path, then a file operation may happen in an unexpected location. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.

For example, if a zip file contains a file entry ..\sneaky-file, and the zip file is extracted to the directory c:\output, then naively combining the paths would result in an output file path of c:\output\..\sneaky-file, which would cause the file to be written to c:\sneaky-file.

Recommendation

Ensure that output paths constructed from zip archive entries are validated to prevent writing files to unexpected locations.

The recommended way of writing an output file from a zip archive entry is to verify that the normalized full path of the output file starts with a prefix that matches the destination directory. Path normalization can be done with either java.io.File.getCanonicalFile() or java.nio.file.Path.normalize(). Prefix checking can be done with String.startsWith(..), but it is better to use java.nio.file.Path.startsWith(..), as the latter works on complete path segments.

Another alternative is to validate archive entries against a whitelist of expected files.

Example

In this example, a file path taken from a zip archive item entry is combined with a destination directory. The result is used as the destination file path without verifying that the result is within the destination directory. If provided with a zip file containing an archive path like ..\sneaky-file, then this file would be written outside the destination directory.

void writeZipEntry(ZipEntry entry, File destinationDir) {
    File file = new File(destinationDir, entry.getName());
    FileOutputStream fos = new FileOutputStream(file); // BAD
    // ... write entry to fos ...
}

To fix this vulnerability, we need to verify that the normalized file still has destinationDir as its prefix, and throw an exception if this is not the case.

void writeZipEntry(ZipEntry entry, File destinationDir) {
    File file = new File(destinationDir, entry.getName());
    if (!file.toPath().normalize().startsWith(destinationDir.toPath()))
        throw new Exception("Bad zip entry");
    FileOutputStream fos = new FileOutputStream(file); // OK
    // ... write entry to fos ...
}

References

javascript/ql/src/Security/CWE-022/ZipSlip.qhelp

Arbitrary file access during archive extraction ("Zip Slip")

Extracting files from a malicious zip file, or similar type of archive, is at risk of directory traversal attacks if filenames from the archive are not properly validated. archive paths.

Zip archives contain archive entries representing each file in the archive. These entries include a file path for the entry, but these file paths are not restricted and may contain unexpected special elements such as the directory traversal element (..). If these file paths are used to create a filesystem path, then a file operation may happen in an unexpected location. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.

For example, if a zip file contains a file entry ..\sneaky-file, and the zip file is extracted to the directory c:\output, then naively combining the paths would result in an output file path of c:\output\..\sneaky-file, which would cause the file to be written to c:\sneaky-file.

Recommendation

Ensure that output paths constructed from zip archive entries are validated to prevent writing files to unexpected locations.

The recommended way of writing an output file from a zip archive entry is to check that ".." does not occur in the path.

Example

In this example an archive is extracted without validating file paths. If archive.zip contained relative paths (for instance, if it were created by something like zip archive.zip ../file.txt) then executing this code could write to locations outside the destination directory.

const fs = require('fs');
const unzip = require('unzip');

fs.createReadStream('archive.zip')
  .pipe(unzip.Parse())
  .on('entry', entry => {
    const fileName = entry.path;
    // BAD: This could write any file on the filesystem.
    entry.pipe(fs.createWriteStream(fileName));
  });

To fix this vulnerability, we need to check that the path does not contain any ".." elements in it.

const fs = require('fs');
const unzip = require('unzip');

fs.createReadStream('archive.zip')
  .pipe(unzip.Parse())
  .on('entry', entry => {
    const fileName = entry.path;
    // GOOD: ensures the path is safe to write to.
    if (fileName.indexOf('..') == -1) {
      entry.pipe(fs.createWriteStream(fileName));
    }
    else {
      console.log('skipping bad path', fileName);
    }
  });

References

python/ql/src/experimental/Security/CWE-022/ZipSlip.qhelp

Arbitrary file access during archive extraction ("Zip Slip")

Extracting files from a malicious zip file, or similar type of archive, is at risk of directory traversal attacks if filenames from the archive are not properly validated.

Zip archives contain archive entries representing each file in the archive. These entries include a file path for the entry, but these file paths are not restricted and may contain unexpected special elements such as the directory traversal element (..). If these file paths are used to create a filesystem path, then a file operation may happen in an unexpected location. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.

For example, if a Zip archive contains a file entry ..\sneaky-file, and the Zip archive is extracted to the directory c:\output, then naively combining the paths would result in an output file path of c:\output\..\sneaky-file, which would cause the file to be written to c:\sneaky-file.

Recommendation

Ensure that output paths constructed from Zip archive entries are validated to prevent writing files to unexpected locations.

The recommended way of writing an output file from a Zip archive entry is to call extract() or extractall().

Example

In this example an archive is extracted without validating file paths.

import zipfile
import shutil

def unzip(filename):
    with tarfile.open(filename) as zipf:
    #BAD : This could write any file on the filesystem.
        for entry in zipf:
            shutil.copyfile(entry, "/tmp/unpack/")
          
def unzip4(filename):
    zf = zipfile.ZipFile(filename)
    filelist = zf.namelist()
    for x in filelist:
        with zf.open(x) as srcf:
            shutil.copyfileobj(srcf, dstfile)

To fix this vulnerability, we need to call the function extractall().

import zipfile 

def unzip(filename, dir):
    zf = zipfile.ZipFile(filename)
    zf.extractall(dir)
    

def unzip1(filename, dir):
    zf = zipfile.ZipFile(filename)
    zf.extract(dir)

References

ruby/ql/src/experimental/cwe-022-zipslip/ZipSlip.qhelp

Arbitrary file access during archive extraction ("Zip Slip")

Extracting files from a malicious zip file, or similar type of archive, is at risk of directory traversal attacks if filenames from the archive are not properly validated.

Tar archives contain archive entries representing each file in the archive. These entries include a file path for the entry, but these file paths are not restricted and may contain unexpected special elements such as the directory traversal element (..). If these file paths are used to create a filesystem path, then a file operation may happen in an unexpected location. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.

For example, if a tar archive contains a file entry ..\sneaky-file, and the tar archive is extracted to the directory c:\output, then naively combining the paths would result in an output file path of c:\output\..\sneaky-file, which would cause the file to be written to c:\sneaky-file.

Recommendation

Ensure that output paths constructed from tar archive entries are validated to prevent writing files to unexpected locations.

The recommended way of writing an output file from a tar archive entry is to check that ".." does not occur in the path.

Example

In this example an archive is extracted without validating file paths. If archive.tar contained relative paths (for instance, if it were created by something like tar -cf archive.tar ../file.txt) then executing this code could write to locations outside the destination directory.

class FilesController < ActionController::Base
  def zipFileUnsafe
    path = params[:path]
    Zip::File.open(path).each do |entry|
      File.open(entry.name, "wb") do |os|
        entry.read
      end
    end
  end

  def tarReaderUnsafe
    path = params[:path]
    file_stream = IO.new(IO.sysopen(path))
    tarfile = Gem::Package::TarReader.new(file_stream)
    tarfile.each do |entry|
      ::File.open(entry.full_name, "wb") do |os|
        entry.read
      end
    end
  end  
end

To fix this vulnerability, we need to check that the path does not contain any ".." elements in it.

class FilesController < ActionController::Base
  def zipFileSafe
    path = params[:path]
    Zip::File.open(path).each do |entry|
      entry_path = entry.name
      next if !File.expand_path(entry_path).start_with?('/safepath/')
      File.open(entry_path, "wb") do |os|
        entry.read
      end
    end
  end

  def tarReaderSafe
    path = params[:path]
    file_stream = IO.new(IO.sysopen(path))
    tarfile = Gem::Package::TarReader.new(file_stream)
    tarfile.each do |entry|
      entry_path = entry.full_name
      raise ExtractFailed if entry_path != "/safepath"
      ::File.open(entry_path, "wb") do |os|
        entry.read
      end
    end
  end  
end

References

…ip query

All filesystem operations, not just writes, with paths built from untrusted archive entry names are dangerous
@atorralba atorralba force-pushed the atorralba/many/zipslip-docs-update branch from be4ca9b to 3e96fe6 Compare June 16, 2023 06:52
@atorralba atorralba changed the title Go/Java/JS/Python/Ruby: Update the description and qhelp of the Zipslip query C#/Go/Java/JS/Python/Ruby: Update the description and qhelp of the Zipslip query Jun 16, 2023
RasmusWL
RasmusWL previously approved these changes Jun 16, 2023

@RasmusWL RasmusWL left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python 👍

michaelnebel
michaelnebel previously approved these changes Jun 16, 2023

@michaelnebel michaelnebel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C# 👍

owen-mc
owen-mc previously approved these changes Jun 16, 2023

@owen-mc owen-mc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Go LGTM

Comment thread javascript/ql/src/Security/CWE-022/ZipSlip.qhelp Outdated
@mchammer01 mchammer01 self-requested a review June 19, 2023 07:12
@mchammer01

mchammer01 commented Jun 19, 2023 •

Copy link
Copy Markdown
Contributor

I'll review this on behalf of Docs.

mchammer01
mchammer01 previously approved these changes Jun 19, 2023

@mchammer01 mchammer01 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@atorralba - this LGTM ✨
A few minor editorial comments for your consideration. Feel free to ignore the comments you don't agree with.

Comment thread csharp/ql/src/Security Features/CWE-022/ZipSlip.qhelp Outdated
Comment thread csharp/ql/src/Security Features/CWE-022/ZipSlip.qhelp Outdated
Comment thread csharp/ql/src/Security Features/CWE-022/ZipSlip.qhelp Outdated
Comment thread csharp/ql/src/Security Features/CWE-022/ZipSlip.ql
Comment thread go/ql/src/Security/CWE-022/ZipSlip.qhelp Outdated
Comment thread go/ql/src/change-notes/2023-06-16-zipslip-rename.md Outdated
Comment thread java/ql/src/change-notes/2023-06-16-zipslip-rename.md Outdated
Comment thread javascript/ql/src/change-notes/2023-06-16-zipslip-rename.md Outdated
Comment thread python/ql/src/change-notes/2023-06-16-zipslip-rename.md Outdated
Comment thread ruby/ql/src/change-notes/2023-06-16-zipslip-rename.md Outdated
Co-authored-by: mc <42146119+mchammer01@users.noreply.github.com>
@atorralba atorralba dismissed stale reviews from mchammer01, owen-mc, and michaelnebel via 433fc68 June 19, 2023 08:17
Co-authored-by: Asger F <asgerf@github.com>
@atorralba atorralba force-pushed the atorralba/many/zipslip-docs-update branch from 109e2b1 to 3c4d938 Compare June 19, 2023 08:20
@atorralba

Copy link
Copy Markdown
Contributor Author

Thanks @asgerf and @mchammer01 for the suggestions! Let me know if anything else can still be improved.

@mchammer01 mchammer01 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@atorralba - thanks for addressing my comments, LGTM 🚀

@asgerf asgerf left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@atorralba atorralba merged commit 5cb451b into github:main Jun 19, 2023
@atorralba atorralba deleted the atorralba/many/zipslip-docs-update branch June 19, 2023 12:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

C# documentation Go Java JS Python ready-for-doc-review This PR requires and is ready for review from the GitHub docs team. Ruby

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants