Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule which detects a potential path traversal when extracting zip archives #208

Merged
merged 3 commits into from
Jul 18, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Detect if any argument is derived from zip.File
  • Loading branch information
ccojocar committed Apr 30, 2018
commit 749c52708e1f1c3ef448b6ae22a80f73684df831
10 changes: 9 additions & 1 deletion rules/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,22 @@ func (a *archive) ID() string {
return a.MetaData.ID
}

// Match inspects AST nodes to determine if the filepath.Joins uses any argument derived from type zip.File
func (a *archive) Match(n ast.Node, c *gas.Context) (*gas.Issue, error) {
if node := a.calls.ContainsCallExpr(n, c); node != nil {
for _, arg := range node.Args {
var argType types.Type
if selector, ok := arg.(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
} else if ident, ok := arg.(*ast.Ident); ok {
argType = c.Info.TypeOf(ident)
if ident.Obj != nil && ident.Obj.Kind == ast.Var {
decl := ident.Obj.Decl
if assign, ok := decl.(*ast.AssignStmt); ok {
if selector, ok := assign.Rhs[0].(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
}
}
}
}

if argType != nil && argType.String() == a.argType {
Expand Down
46 changes: 46 additions & 0 deletions testutils/source.go
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,52 @@ func unzip(archive, target string) error {
}
}

return nil
}`, 1}, {`
package unzip

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

func unzip(archive, target string) error {
reader, err := zip.OpenReader(archive)
if err != nil {
return err
}

if err := os.MkdirAll(target, 0750); err != nil {
return err
}

for _, file := range reader.File {
archiveFile := file.Name
path := filepath.Join(target, archiveFile)
if file.FileInfo().IsDir() {
os.MkdirAll(path, file.Mode()) // #nosec
continue
}

fileReader, err := file.Open()
if err != nil {
return err
}
defer fileReader.Close()

targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if err != nil {
return err
}
defer targetFile.Close()

if _, err := io.Copy(targetFile, fileReader); err != nil {
return err
}
}

return nil
}`, 1}}

Expand Down