| 1 | + | // Copyright 2021 Security Scorecard Authors |
| 2 | + | // |
| 3 | + | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + | // you may not use this file except in compliance with the License. |
| 5 | + | // You may obtain a copy of the License at |
| 6 | + | // |
| 7 | + | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + | // |
| 9 | + | // Unless required by applicable law or agreed to in writing, software |
| 10 | + | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + | // See the License for the specific language governing permissions and |
| 13 | + | // limitations under the License. |
| 14 | + | |
| 15 | + | package gitlabrepo |
| 16 | + | |
| 17 | + | import ( |
| 18 | + | "archive/tar" |
| 19 | + | "compress/gzip" |
| 20 | + | "context" |
| 21 | + | "errors" |
| 22 | + | "fmt" |
| 23 | + | "io" |
| 24 | + | "log" |
| 25 | + | "net/http" |
| 26 | + | "os" |
| 27 | + | "path/filepath" |
| 28 | + | "strings" |
| 29 | + | "sync" |
| 30 | + | |
| 31 | + | "github.com/xanzy/go-gitlab" |
| 32 | + | |
| 33 | + | sce "github.com/ossf/scorecard/v4/errors" |
| 34 | + | ) |
| 35 | + | |
| 36 | + | const ( |
| 37 | + | repoDir = "project*" |
| 38 | + | repoFilename = "gitlabproject*.tar.gz" |
| 39 | + | ) |
| 40 | + | |
| 41 | + | var ( |
| 42 | + | errTarballNotFound = errors.New("tarball not found") |
| 43 | + | errTarballCorrupted = errors.New("corrupted tarball") |
| 44 | + | errZipSlip = errors.New("ZipSlip path detected") |
| 45 | + | ) |
| 46 | + | |
| 47 | + | func extractAndValidateArchivePath(path, dest string) (string, error) { |
| 48 | + | const splitLength = 2 |
| 49 | + | // The tarball will have a top-level directory which contains all the repository files. |
| 50 | + | // Discard the directory and only keep the actual files. |
| 51 | + | names := strings.SplitN(path, "/", splitLength) |
| 52 | + | if len(names) < splitLength { |
| 53 | + | return dest, nil |
| 54 | + | } |
| 55 | + | if names[1] == "" { |
| 56 | + | return dest, nil |
| 57 | + | } |
| 58 | + | // Check for ZipSlip: https://snyk.io/research/zip-slip-vulnerability |
| 59 | + | cleanpath := filepath.Join(dest, names[1]) |
| 60 | + | if !strings.HasPrefix(cleanpath, filepath.Clean(dest)+string(os.PathSeparator)) { |
| 61 | + | return "", fmt.Errorf("%w: %s", errZipSlip, names[1]) |
| 62 | + | } |
| 63 | + | return cleanpath, nil |
| 64 | + | } |
| 65 | + | |
| 66 | + | type tarballHandler struct { |
| 67 | + | errSetup error |
| 68 | + | once *sync.Once |
| 69 | + | ctx context.Context |
| 70 | + | repo *gitlab.Project |
| 71 | + | repourl *repoURL |
| 72 | + | commitSHA string |
| 73 | + | tempDir string |
| 74 | + | tempTarFile string |
| 75 | + | files []string |
| 76 | + | } |
| 77 | + | |
| 78 | + | func (handler *tarballHandler) init(ctx context.Context, repourl *repoURL, repo *gitlab.Project, commitSHA string) { |
| 79 | + | handler.errSetup = nil |
| 80 | + | handler.once = new(sync.Once) |
| 81 | + | handler.ctx = ctx |
| 82 | + | handler.repo = repo |
| 83 | + | handler.repourl = repourl |
| 84 | + | handler.commitSHA = commitSHA |
| 85 | + | } |
| 86 | + | |
| 87 | + | func (handler *tarballHandler) setup() error { |
| 88 | + | handler.once.Do(func() { |
| 89 | + | // cleanup any previous state. |
| 90 | + | if err := handler.cleanup(); err != nil { |
| 91 | + | handler.errSetup = sce.WithMessage(sce.ErrScorecardInternal, err.Error()) |
| 92 | + | return |
| 93 | + | } |
| 94 | + | |
| 95 | + | // setup tem dir/files and download repo tarball. |
| 96 | + | if err := handler.getTarball(); errors.Is(err, errTarballNotFound) { |
| 97 | + | log.Printf("unable to get tarball %v. Skipping...", err) |
| 98 | + | return |
| 99 | + | } else if err != nil { |
| 100 | + | handler.errSetup = sce.WithMessage(sce.ErrScorecardInternal, err.Error()) |
| 101 | + | return |
| 102 | + | } |
| 103 | + | |
| 104 | + | // extract file names and content from tarball. |
| 105 | + | if err := handler.extractTarball(); errors.Is(err, errTarballCorrupted) { |
| 106 | + | log.Printf("unable to extract tarball %v. Skipping...", err) |
| 107 | + | } else if err != nil { |
| 108 | + | handler.errSetup = sce.WithMessage(sce.ErrScorecardInternal, err.Error()) |
| 109 | + | } |
| 110 | + | }) |
| 111 | + | return handler.errSetup |
| 112 | + | } |
| 113 | + | |
| 114 | + | func (handler *tarballHandler) getTarball() error { |
| 115 | + | url := fmt.Sprintf("%s/api/v4/projects/%d/repository/archive.tar.gz?sha=%s", |
| 116 | + | handler.repourl.Host(), handler.repo.ID, handler.commitSHA) |
| 117 | + | req, err := http.NewRequestWithContext(handler.ctx, http.MethodGet, url, nil) |
| 118 | + | if err != nil { |
| 119 | + | return fmt.Errorf("http.NewRequestWithContext: %w", err) |
| 120 | + | } |
| 121 | + | req.Header.Set("PRIVATE-TOKEN", os.Getenv("GITLAB_AUTH_TOKEN")) |
| 122 | + | resp, err := http.DefaultClient.Do(req) |
| 123 | + | if err != nil { |
| 124 | + | return fmt.Errorf("http.DefaultClient.Do: %w", err) |
| 125 | + | } |
| 126 | + | defer resp.Body.Close() |
| 127 | + | |
| 128 | + | // Handler 400/404 errors. |
| 129 | + | switch resp.StatusCode { |
| 130 | + | case http.StatusNotFound, http.StatusBadRequest: |
| 131 | + | return fmt.Errorf("%w: %s", errTarballNotFound, url) |
| 132 | + | } |
| 133 | + | |
| 134 | + | // Create a temp file. This automatically appends a random number to the name. |
| 135 | + | tempDir, err := os.MkdirTemp("", repoDir) |
| 136 | + | if err != nil { |
| 137 | + | return fmt.Errorf("os.MkdirTemp: %w", err) |
| 138 | + | } |
| 139 | + | repoFile, err := os.CreateTemp(tempDir, repoFilename) |
| 140 | + | if err != nil { |
| 141 | + | return fmt.Errorf("os.CreateTemp: %w", err) |
| 142 | + | } |
| 143 | + | defer repoFile.Close() |
| 144 | + | if _, err := io.Copy(repoFile, resp.Body); err != nil { |
| 145 | + | // If the incomming tarball is corrupted or the server times out. |
| 146 | + | return fmt.Errorf("%w io.Copy: %v", errTarballNotFound, err) |
| 147 | + | } |
| 148 | + | |
| 149 | + | handler.tempDir = tempDir |
| 150 | + | handler.tempTarFile = repoFile.Name() |
| 151 | + | return nil |
| 152 | + | } |
| 153 | + | |
| 154 | + | // nolint: gocognit |
| 155 | + | func (handler *tarballHandler) extractTarball() error { |
| 156 | + | in, err := os.OpenFile(handler.tempTarFile, os.O_RDONLY, 0o644) |
| 157 | + | if err != nil { |
| 158 | + | return fmt.Errorf("os.OpenFile: %w", err) |
| 159 | + | } |
| 160 | + | gz, err := gzip.NewReader(in) |
| 161 | + | if err != nil { |
| 162 | + | return fmt.Errorf("%w: gzip.NewReader %v %v", errTarballCorrupted, handler.tempTarFile, err) |
| 163 | + | } |
| 164 | + | tr := tar.NewReader(gz) |
| 165 | + | for { |
| 166 | + | header, err := tr.Next() |
| 167 | + | if errors.Is(err, io.EOF) { |
| 168 | + | break |
| 169 | + | } |
| 170 | + | if err != nil { |
| 171 | + | return fmt.Errorf("%w tarReader.Next: %v", errTarballCorrupted, err) |
| 172 | + | } |
| 173 | + | |
| 174 | + | switch header.Typeflag { |
| 175 | + | case tar.TypeDir: |
| 176 | + | dirpath, err := extractAndValidateArchivePath(header.Name, handler.tempDir) |
| 177 | + | if err != nil { |
| 178 | + | return err |
| 179 | + | } |
| 180 | + | if dirpath == filepath.Clean(handler.tempDir) { |
| 181 | + | continue |
| 182 | + | } |
| 183 | + | |
| 184 | + | if err := os.Mkdir(dirpath, 0o755); err != nil { |
| 185 | + | return fmt.Errorf("error during os.Mkdir: %w", err) |
| 186 | + | } |
| 187 | + | case tar.TypeReg: |
| 188 | + | if header.Size <= 0 { |
| 189 | + | continue |
| 190 | + | } |
| 191 | + | filenamepath, err := extractAndValidateArchivePath(header.Name, handler.tempDir) |
| 192 | + | if err != nil { |
| 193 | + | return err |
| 194 | + | } |
| 195 | + | |
| 196 | + | if _, err := os.Stat(filepath.Dir(filenamepath)); os.IsNotExist(err) { |
| 197 | + | if err := os.Mkdir(filepath.Dir(filenamepath), 0o755); err != nil { |
| 198 | + | return fmt.Errorf("os.Mkdir: %w", err) |
| 199 | + | } |
| 200 | + | } |
| 201 | + | outFile, err := os.Create(filenamepath) |
| 202 | + | if err != nil { |
| 203 | + | return fmt.Errorf("os.Create: %w", err) |
| 204 | + | } |
| 205 | + | |
| 206 | + | //nolint: gosec |
| 207 | + | // Potential for DoS vulnerability via decompression bomb. |
| 208 | + | // Since such an attack will only impact a single shard, ignoring this for now. |
| 209 | + | if _, err := io.Copy(outFile, tr); err != nil { |
| 210 | + | return fmt.Errorf("%w io.Copy: %v", errTarballCorrupted, err) |
| 211 | + | } |
| 212 | + | outFile.Close() |
| 213 | + | handler.files = append(handler.files, |
| 214 | + | strings.TrimPrefix(filenamepath, filepath.Clean(handler.tempDir)+string(os.PathSeparator))) |
| 215 | + | case tar.TypeXGlobalHeader, tar.TypeSymlink: |
| 216 | + | continue |
| 217 | + | default: |
| 218 | + | log.Printf("Unknown file type %s: '%s'", header.Name, string(header.Typeflag)) |
| 219 | + | continue |
| 220 | + | } |
| 221 | + | } |
| 222 | + | return nil |
| 223 | + | } |
| 224 | + | |
| 225 | + | func (handler *tarballHandler) listFiles(predicate func(string) (bool, error)) ([]string, error) { |
| 226 | + | if err := handler.setup(); err != nil { |
| 227 | + | return nil, fmt.Errorf("error during tarballHandler.setup: %w", err) |
| 228 | + | } |
| 229 | + | ret := make([]string, 0) |
| 230 | + | for _, file := range handler.files { |
| 231 | + | matches, err := predicate(file) |
| 232 | + | if err != nil { |
| 233 | + | return nil, err |
| 234 | + | } |
| 235 | + | if matches { |
| 236 | + | ret = append(ret, file) |
| 237 | + | } |
| 238 | + | } |
| 239 | + | return ret, nil |
| 240 | + | } |
| 241 | + | |
| 242 | + | func (handler *tarballHandler) getFileContent(filename string) ([]byte, error) { |
| 243 | + | if err := handler.setup(); err != nil { |
| 244 | + | fmt.Printf("err: %v\n", err) |
| 245 | + | return nil, fmt.Errorf("error during tarballHandler.setup: %w", err) |
| 246 | + | } |
| 247 | + | fmt.Printf("handler.tempDir: %v\n", handler.tempDir) |
| 248 | + | fmt.Printf("filename: %v\n", filename) |
| 249 | + | content, err := os.ReadFile(filepath.Join(handler.tempDir, filename)) |
| 250 | + | if err != nil { |
| 251 | + | return content, fmt.Errorf("os.ReadFile: %w", err) |
| 252 | + | } |
| 253 | + | return content, nil |
| 254 | + | } |
| 255 | + | |
| 256 | + | func (handler *tarballHandler) cleanup() error { |
| 257 | + | if err := os.RemoveAll(handler.tempDir); err != nil && !os.IsNotExist(err) { |
| 258 | + | return fmt.Errorf("os.Remove: %w", err) |
| 259 | + | } |
| 260 | + | |
| 261 | + | // Remove old file so we don't iterate through them. |
| 262 | + | handler.files = nil |
| 263 | + | return nil |
| 264 | + | } |
| 265 | + | |