Files
sif/internal/scan/cloudstorage.go
TigahandGitHub a44cfb230f fix(store,logger,scan): concurrency-adjacent races and correctness fixes (#343)
* fix(logger): create log dirs and flatten url log filenames

CreateFile/Write kept the '/' from a target's url path when building the
log filename, so a target like http://host:port/ tried to open
<dir>/host:port/.log whose parent directory never existed. os.OpenFile
failed and scanTarget aborted the whole target before any scanning ran.

fold every '/' and '\\' run in the sanitized url into a single '_' via a
shared logPath helper so CreateFile and Write always resolve to the same
flat file, and mkdir the parent defensively in getWriter as a second line
of defense.

* fix(scan): route module status lines through the locking sink

subdomaintakeover, cloudstorage, and the next.js framework detector
printed their status/error lines with a bare fmt.Println straight to
os.Stdout, bypassing the output package's sink. under -concurrency>1
only the sink is lock-wrapped, so these lines could interleave or tear
against lines other targets write concurrently.

swap them for output.ScanStart / output.Error, matching every other
scanner in the package.

* fix(store): make snapshot filenames injective and writes atomic

sanitize() folds every separator run (and a literal '_') to one '_', so
distinct targets like https://a.com/x and https://a.com//x, or
host:8443/path and host_8443_path, sanitized to the identical string and
shared one snapshot file - the second target's Save silently clobbered
the first's baseline. Save's os.WriteFile also wasn't atomic, so two
targets racing on a collided path (or -concurrency>1 in general) could
interleave partial writes.

pathFor now appends 16 hex chars of the target's sha256 to the sanitized
name, so distinct targets never collide, and Save writes through a temp
file in the same dir followed by os.Rename so a reader always sees a
complete snapshot or the previous one, never a partial write.

this changes the on-disk snapshot filename scheme: existing users' -diff
baselines under the old sanitize()-only names won't be found and the
next run re-baselines from scratch (every finding reports as newly
added once). noting this as a deliberate tradeoff for a local hardening
pass rather than silently orphaning them.

* fix(store): check the deferred temp-file cleanup error

golangci-lint (errcheck) flagged the bare defer os.Remove(tmpPath) in
writeFileAtomic; wrap it so the discard is explicit.
2026-07-22 12:55:08 -07:00

173 lines
5.8 KiB
Go

/*
·━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━·
: :
: █▀ █ █▀▀ · Blazing-fast pentesting suite :
: ▄█ █ █▀ · BSD 3-Clause License :
: :
: (c) 2022-2026 vmfunc, xyzeva, :
: lunchcat alumni & contributors :
: :
·━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━·
*/
package scan
import (
"context"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/charmbracelet/log"
"github.com/vmfunc/sif/internal/httpx"
"github.com/vmfunc/sif/internal/logger"
"github.com/vmfunc/sif/internal/output"
"github.com/vmfunc/sif/internal/styles"
)
// maxBucketBodyReadBytes bounds how much of a bucket response we buffer to
// look for the listing markers below. an XML/JSON listing root or an error
// code always shows up well within this window; the rest is drained and
// discarded by httpx.DrainClose.
const maxBucketBodyReadBytes = 8 << 10
// s3ListingMarker is the root element of a real S3 ListBucketResult XML
// listing. its presence is what actually proves anonymous listing access;
// AccessDenied/NoSuchBucket/redirect bodies also come back with status 200
// and must not be mistaken for a listing.
const s3ListingMarker = "<ListBucketResult"
// s3DeniedMarkers are S3 error codes that can accompany a 200 (or that we
// check regardless of status) and rule out a listing even if the listing
// marker were somehow also present.
var s3DeniedMarkers = []string{"AccessDenied", "NoSuchBucket", "PermanentRedirect", "AllAccessDisabled"}
// s3EndpointFmt is a var so integration tests can repoint it at a fixture; the
// %s is the bucket name.
var s3EndpointFmt = "https://%s.s3.amazonaws.com"
type CloudStorageResult struct {
BucketName string `json:"bucket_name"`
// IsPublic means the bucket's listing was actually retrieved (the
// response body contains a ListBucketResult with no denial marker), not
// merely that the request returned 200.
IsPublic bool `json:"is_public"`
}
func CloudStorage(url string, timeout time.Duration, logdir string) ([]CloudStorageResult, error) {
output.ScanStart("Cloud Storage Misconfiguration Scan")
sanitizedURL := stripScheme(url)
if logdir != "" {
if err := logger.WriteHeader(sanitizedURL, logdir, "Cloud Storage Misconfiguration Scan"); err != nil {
log.Errorf("Error creating log file: %v", err)
return nil, err
}
}
cloudlog := log.NewWithOptions(os.Stderr, log.Options{
Prefix: "C3",
}).With("url", url)
client := httpx.Client(timeout)
potentialBuckets := extractPotentialBuckets(sanitizedURL)
var results []CloudStorageResult
for _, bucket := range potentialBuckets {
isPublic, err := checkS3Bucket(context.TODO(), bucket, client)
if err != nil {
cloudlog.Errorf("Error checking S3 bucket %s: %v", bucket, err)
continue
}
result := CloudStorageResult{
BucketName: bucket,
IsPublic: isPublic,
}
results = append(results, result)
if isPublic {
cloudlog.Warnf("Public S3 bucket found: %s", styles.Highlight.Render(bucket))
if logdir != "" {
_ = logger.Write(sanitizedURL, logdir, fmt.Sprintf("Public S3 bucket found: %s\n", bucket))
}
} else {
cloudlog.Infof("S3 bucket is not public/found: %s", bucket)
}
}
return results, nil
}
func extractPotentialBuckets(url string) []string {
labels := strings.Split(url, ".")
// drop the tld label so we don't waste guesses on it ("com", "com-s3", ...);
// a single-label host has no tld to strip.
if len(labels) > 1 {
labels = labels[:len(labels)-1]
}
var buckets []string
for _, label := range labels {
buckets = append(buckets, label, label+"-s3", "s3-"+label)
}
// combine every label with every other, not just adjacent ones, so a deep
// host like shop.cdn.example yields shop-example too.
for i, a := range labels {
for _, b := range labels[i+1:] {
buckets = append(buckets, a+"-"+b, b+"-"+a)
}
}
return buckets
}
func checkS3Bucket(ctx context.Context, bucket string, client *http.Client) (bool, error) {
url := fmt.Sprintf(s3EndpointFmt, bucket)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return false, err
}
resp, err := client.Do(req) //nolint:bodyclose // drained and closed via httpx.DrainClose
if err != nil {
return false, err
}
// any remainder past maxBucketBodyReadBytes is drained on close so the
// conn returns to the pool.
defer httpx.DrainClose(resp)
if resp.StatusCode != http.StatusOK {
return false, nil
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBucketBodyReadBytes))
if err != nil {
return false, err
}
return isListableBucketBody(body), nil
}
// isListableBucketBody reports whether body proves an S3 bucket is
// anonymously listable. a 200 status alone does not: AccessDenied pages,
// provider landing pages, and locked buckets can all return 200, so the
// listing root element must actually be present and no denial marker may
// be present alongside it.
func isListableBucketBody(body []byte) bool {
s := string(body)
if !strings.Contains(s, s3ListingMarker) {
return false
}
for _, marker := range s3DeniedMarkers {
if strings.Contains(s, marker) {
return false
}
}
return true
}