Skip to content

Commit

Permalink
prevent invalid zip file from exracting files to arbitrary locations.
Browse files Browse the repository at this point in the history
  • Loading branch information
coreybutler committed Apr 27, 2023
1 parent be690ad commit c1a6337
Showing 1 changed file with 62 additions and 57 deletions.
119 changes: 62 additions & 57 deletions src/file/file.go
Original file line number Diff line number Diff line change
@@ -1,75 +1,80 @@
package file

import(
"archive/zip"
"bufio"
"log"
"io"
"os"
"path/filepath"
"strings"
import (
"archive/zip"
"bufio"
"io"
"log"
"os"
"path/filepath"
"strings"
)

// Function courtesy http://stackoverflow.com/users/1129149/swtdrgn
func Unzip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()

for _, f := range r.File {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
for _, f := range r.File {
if !strings.Contains(f.Name, "..") {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()

fpath := filepath.Join(dest, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(fpath, f.Mode())
} else {
var fdir string
if lastIndex := strings.LastIndex(fpath,string(os.PathSeparator)); lastIndex > -1 {
fdir = fpath[:lastIndex]
}
fpath := filepath.Join(dest, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(fpath, f.Mode())
} else {
var fdir string
if lastIndex := strings.LastIndex(fpath, string(os.PathSeparator)); lastIndex > -1 {
fdir = fpath[:lastIndex]
}

err = os.MkdirAll(fdir, f.Mode())
if err != nil {
log.Fatal(err)
return err
}
f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer f.Close()
err = os.MkdirAll(fdir, f.Mode())
if err != nil {
log.Fatal(err)
return err
}
f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer f.Close()

_, err = io.Copy(f, rc)
if err != nil {
return err
}
}
}
return nil
_, err = io.Copy(f, rc)
if err != nil {
return err
}
}
} else {
log.Printf("failed to extract file: %s (cannot validate)\n", f.Name)
}
}

return nil
}

func ReadLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()

var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}

func Exists(filename string) bool {
_, err := os.Stat(filename);
return err == nil
_, err := os.Stat(filename)
return err == nil
}

0 comments on commit c1a6337

Please sign in to comment.