Skip to content
Community previewValidate controls against current Google documentation.Report a gap

Google Workspace: Pentesting Insights and Defensive Countermeasures

This guide integrates adversarial perspectives into our security approach, drawing from pentesting techniques to strengthen Google Workspace security posture. Understanding attack methodologies is essential for implementing effective defenses.

Attribution: This guide incorporates insights and methodologies from the excellent HackTricks Google Workspace Security Guide, Google Workspace Post-Exploitation Guide, Google Workspace Persistence Techniques, Workspace Sync Attacks, and Google Platforms Phishing. We highly recommend reviewing the original resources for additional offensive security perspectives.

Common Attack Vectors and Defensive Strategies

Section titled “Common Attack Vectors and Defensive Strategies”

Google Platform-Specific Phishing Techniques

Section titled “Google Platform-Specific Phishing Techniques”

Attackers leverage Google’s own platforms to create sophisticated phishing campaigns:

  1. Google Groups Phishing

    • Create Google Groups with legitimate-looking names
    • Invite target users to join these groups
    • Send emails from legitimate Google addresses
    • Leverage group communication for payload delivery
    • Exploit trust in Google’s infrastructure
  2. Google Chat Phishing

    • Initiate chat conversations with targets
    • Create deceptive Spaces mimicking official support channels
    • Send malicious links within chat conversations
    • Exploit real-time nature for urgent action requests
    • Use Google’s legitimate notification system
  3. Google Calendar Phishing

    • Create calendar invitations with embedded phishing links
    • Configure events with short notice to create urgency
    • Add malicious content in event descriptions and attachments
    • Hide attendee lists to prevent cross-checking
    • Disable email notifications to avoid scrutiny
  4. App Scripts Redirect Phishing

    • Create malicious web apps on script.google.com
    • Implement JavaScript redirects to phishing sites
    • Leverage legitimate Google domains (script.google.com)
    • Create URL parameters to customize phishing experience
    • Evade URL filtering by using trusted Google domains
  5. OAuth App Phishing

    • Create applications requesting excessive permissions
    • Design convincing application names and descriptions
    • Craft targeted permission requests based on victim role
    • Exploit user tendency to authorize Google-hosted applications
    • Obtain persistent access through authorized OAuth tokens
  1. Google Groups Security Controls

    Admin Console > Groups > Groups settings
    - Configure "Who can create groups"
    - Set "Restrict group creation"
    - Implement group creation approval workflow
    - Configure external sharing restrictions
  2. Google Chat Security Settings

    Admin Console > Apps > Google Workspace > Google Chat
    - Configure "Chat with external users"
    - Set appropriate "External chat invites" settings
    - Implement URL scanning in chat messages
    - Configure appropriate Space creation permissions
  3. Calendar Security Controls

    Admin Console > Apps > Google Workspace > Calendar
    - Configure "Sharing options" to restrict external sharing
    - Set "External invitations" policy
    - Enable "Event scanning" for malicious content
    - Restrict automatic addition of external events
  4. App Scripts Security Management

    Admin Console > Security > API Controls > App Scripts
    - Configure "Google Cloud Platform (GCP) trust"
    - Restrict Apps Script application deployment
    - Implement appropriate Apps Script Marketplace controls
    - Configure allowlist for trusted scripts
  5. Cross-Platform Security Education

    • Develop user training specific to Google platform phishing
    • Create visual guides for Google-specific phishing indicators
    • Implement simulated phishing using Google platforms
    • Establish clear reporting procedures for suspicious activities
  6. Detection and Monitoring

    # Python script to detect suspicious Google platform activities
    def detect_google_platform_phishing(reports_service):
    """Monitor for potentially suspicious Google platform activities"""
    # Check for suspicious group creation
    group_events = reports_service.activities().list(
    userKey='all',
    applicationName='groups',
    eventName='CREATE_GROUP',
    maxResults=1000
    ).execute()
    suspicious_activities = []
    # Analyze groups creation
    for event in group_events.get('items', []):
    # Extract group details
    parameters = event.get('events', [{}])[0].get('parameters', [])
    group_name = next((p.get('value') for p in parameters
    if p.get('name') == 'group_name'), '')
    # Check for suspicious group names
    suspicious_terms = ['support', 'security', 'helpdesk', 'admin', 'it-team', 'password']
    if any(term in group_name.lower() for term in suspicious_terms):
    suspicious_activities.append({
    'user': event['actor']['email'],
    'activity': 'suspicious_group_creation',
    'details': f"Created potentially deceptive group: {group_name}",
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    # Check for suspicious calendar events
    calendar_events = reports_service.activities().list(
    userKey='all',
    applicationName='calendar',
    eventName='CREATE_EVENT',
    maxResults=1000
    ).execute()
    for event in calendar_events.get('items', []):
    parameters = event.get('events', [{}])[0].get('parameters', [])
    event_title = next((p.get('value') for p in parameters
    if p.get('name') == 'event_title'), '')
    event_description = next((p.get('value') for p in parameters
    if p.get('name') == 'event_description'), '')
    # Check for suspicious calendar activity
    if contains_suspicious_content(event_title) or contains_suspicious_content(event_description):
    suspicious_activities.append({
    'user': event['actor']['email'],
    'activity': 'suspicious_calendar_event',
    'details': f"Created potentially malicious calendar event: {event_title}",
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    return suspicious_activities
    def contains_suspicious_content(text):
    """Check if content contains suspicious patterns"""
    suspicious_patterns = [
    r'password.*reset',
    r'security.*alert',
    r'account.*verify',
    r'login.*required',
    r'unusual.*activity',
    r'http[s]?://(?!.*google\.com)[^\s]+', # Non-Google URLs
    r'urgent',
    r'immediate.*action'
    ]
    return any(re.search(pattern, text.lower()) for pattern in suspicious_patterns)

Attackers frequently target Google Workspace through OAuth-based attacks:

  1. OAuth Phishing Campaigns

    • Create malicious applications requesting extensive permissions
    • Design convincing phishing emails with OAuth authorization links
    • Persuade users to authorize deceptive applications
  2. Application Permission Abuse

    • Request overly broad scopes (Gmail, Drive, Admin access)
    • Exploit insufficient OAuth app verification requirements
    • Use legitimate-looking application names and logos
  3. Token Theft and Abuse

    • Target OAuth refresh tokens for long-term persistent access
    • Use stolen tokens to access services without triggering login alerts
    • Bypass MFA through pre-authenticated token usage
  1. OAuth Application Control

    Admin Console > Security > API Controls > App access control
    - Configure to "Only allow trusted applications"
    - Implement allowlisting for approved applications
    - Block applications requesting sensitive scopes
  2. Advanced Token Monitoring

    # Python script for suspicious token activity monitoring
    def detect_suspicious_token_activity(admin_sdk_service, reports_service):
    """Monitor for suspicious OAuth token activity"""
    # Get token usage events
    token_events = reports_service.activities().list(
    userKey='all',
    applicationName='token',
    maxResults=1000
    ).execute()
    suspicious_activity = []
    for event in token_events.get('items', []):
    # Check for suspicious patterns
    if is_suspicious_token_activity(event):
    suspicious_activity.append({
    'user': event['actor']['email'],
    'application': event.get('events', [{}])[0].get('name', 'Unknown'),
    'scopes': extract_scopes(event),
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    return suspicious_activity
    def is_suspicious_token_activity(event):
    """Determine if token activity is suspicious based on various signals"""
    # Extract relevant data
    events = event.get('events', [{}])
    if not events:
    return False
    event_data = events[0]
    # Check for sensitive scopes
    scopes = extract_scopes(event)
    sensitive_scope_indicators = ['mail', 'gmail', 'admin', 'directory']
    has_sensitive_scopes = any(indicator in str(scopes).lower()
    for indicator in sensitive_scope_indicators)
    # Check for suspicious parameters
    parameters = event_data.get('parameters', [])
    client_id = next((p.get('value') for p in parameters
    if p.get('name') == 'client_id'), None)
    # Check if client ID is not in our approved list
    approved_clients = get_approved_client_ids()
    unknown_client = client_id not in approved_clients
    # Suspicious if sensitive scopes AND unknown client
    return has_sensitive_scopes and unknown_client
    def extract_scopes(event):
    """Extract OAuth scopes from event data"""
    events = event.get('events', [{}])
    if not events:
    return []
    parameters = events[0].get('parameters', [])
    for param in parameters:
    if param.get('name') == 'scope':
    return param.get('value', '').split()
    return []
  3. Advanced OAuth Governance

    • Implement routine OAuth application reviews
    • Develop OAuth risk scoring based on requested scopes
    • Create user education focused on OAuth authorization risks

Email remains a primary attack vector for Google Workspace:

  1. Lateral Phishing

    • Compromise one account and use it to phish others in the organization
    • Leverage existing trust relationships and conversation threads
    • Target high-value accounts based on internal information
  2. Email Filter/Forwarding Abuse

    • Create covert mail forwarding rules after account compromise
    • Set up filters to hide specific messages from user view
    • Establish persistent access to communications
  3. Mailbox Delegation Exploitation

    • Add unauthorized delegates to compromised mailboxes
    • Use delegation to maintain access even after password changes
    • Access sensitive communications without generating alerts
  1. Enhanced Email Monitoring

    Admin Console > Reports > Audit > Email logs
    - Configure alerts for suspicious mail filter creation
    - Monitor for unusual delegation activity
    - Implement forwarding restrictions
  2. Mail Flow Rule Restrictions

    Admin Console > Apps > Google Workspace > Gmail > Routing
    - Restrict external auto-forwarding
    - Require administrator approval for mail delegation
    - Implement group-based restrictions for sensitive departments
  3. Mail Security Intelligence

    # Python script for identifying suspicious email rules
    def detect_suspicious_email_rules(admin_sdk_service, reports_service):
    """Detect suspicious email rules and filters"""
    # Get Gmail configuration events
    mail_events = reports_service.activities().list(
    userKey='all',
    applicationName='gmail',
    eventName='EMAIL_FORWARDING_CHANGE,EMAIL_FILTER_CREATION',
    maxResults=1000
    ).execute()
    suspicious_rules = []
    for event in mail_events.get('items', []):
    # Extract event details
    event_name = event.get('events', [{}])[0].get('name')
    parameters = event.get('events', [{}])[0].get('parameters', [])
    # Check if this is a suspicious rule
    if event_name == 'EMAIL_FORWARDING_CHANGE':
    forwarding_address = next((p.get('value') for p in parameters
    if p.get('name') == 'forwarding_address'), None)
    # Check if forwarding to external domain
    if forwarding_address and not is_internal_domain(forwarding_address):
    suspicious_rules.append({
    'user': event['actor']['email'],
    'type': 'forwarding',
    'destination': forwarding_address,
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    elif event_name == 'EMAIL_FILTER_CREATION':
    filter_criteria = next((p.get('value') for p in parameters
    if p.get('name') == 'filter_criteria'), None)
    filter_action = next((p.get('value') for p in parameters
    if p.get('name') == 'filter_action'), None)
    # Check for suspicious filter patterns
    if is_suspicious_filter(filter_criteria, filter_action):
    suspicious_rules.append({
    'user': event['actor']['email'],
    'type': 'filter',
    'criteria': filter_criteria,
    'action': filter_action,
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    return suspicious_rules
    def is_internal_domain(email_address):
    """Check if the email belongs to an internal domain"""
    internal_domains = ['company.com', 'subsidiary.company.com'] # Your domains
    for domain in internal_domains:
    if email_address.endswith('@' + domain):
    return True
    return False
    def is_suspicious_filter(criteria, action):
    """Determine if a filter is potentially suspicious"""
    suspicious_indicators = False
    # Suspicious if hiding emails from specific senders
    if 'from:' in criteria and 'trash' in action.lower():
    suspicious_indicators = True
    # Suspicious if forwarding to external address
    if 'forward' in action.lower() and not is_internal_domain(action.split(' ')[-1]):
    suspicious_indicators = True
    # Suspicious if archiving or marking as read security-related emails
    if any(term in criteria.lower() for term in ['security', 'password', 'verification']):
    if any(term in action.lower() for term in ['archive', 'mark_as_read']):
    suspicious_indicators = True
    return suspicious_indicators

Administrator accounts are primary targets due to their elevated privileges:

  1. Admin Role Privilege Escalation

    • Target accounts with limited admin privileges
    • Escalate permissions through role modification
    • Create persistence through new admin accounts
  2. Super Admin Account Targeting

    • Focus phishing and social engineering on super admin accounts
    • Utilize session hijacking to access admin console
    • Make subtle changes to avoid detection
  3. Recovery Email Manipulation

    • Modify account recovery options for persistence
    • Change recovery email to attacker-controlled address
    • Use recovery process to regain access after remediation
  1. Enhanced Admin Security

    Admin Console > Security > Authentication > Advanced Protection Program
    - Enroll all administrators in APP
    - Require hardware security keys
    - Implement IP-based restrictions for admin access
  2. Admin Activity Monitoring

    Admin Console > Reports > Audit > Admin
    - Create alerts for administrative role changes
    - Monitor account recovery modifications
    - Implement real-time alerting for critical setting changes
  3. Admin Access Control Framework

    • Implement strict separation of duties
    • Require multi-party authorization for critical changes
    • Create time-bound administrative access
    • Implement enhanced logging for all admin actions

Attackers use various persistence techniques to maintain access:

  1. Service Account Key Abuse

    • Create or steal service account keys with elevated privileges
    • Use keys for programmatic API access
    • Maintain access independent of user credentials
  2. GCDS (Google Cloud Directory Sync) Exploitation

    • Target directory synchronization configurations
    • Modify sync rules to create or preserve access
    • Leverage trusted synchronization channels
  3. Workspace Add-on Persistence

    • Create malicious Workspace add-ons
    • Deploy via compromised admin accounts
    • Establish persistence through authorized applications
  1. Service Account Security

    Admin Console > Security > API Controls > Domain-wide Delegation
    - Strictly limit service account permissions
    - Implement key rotation requirements
    - Conduct regular audits of delegated access
  2. Synchronization Security

    Admin Console > Directory > Directory settings
    - Implement secure GCDS configuration
    - Restrict synchronization permissions
    - Monitor synchronization logs for anomalies
  3. Add-on Security Controls

    Admin Console > Apps > Marketplace apps
    - Restrict add-on installation capabilities
    - Implement add-on allowlisting
    - Conduct security reviews for all add-ons

Attackers use multiple methods to extract sensitive data:

  1. Google Takeout Exploitation

    • Use Google Takeout to extract complete data archives
    • Extract bulk data without triggering DLP alerts
    • Obtain comprehensive data snapshots
  2. Drive Share Manipulation

    • Share sensitive documents with external accounts
    • Use sharing links with minimal visibility
    • Create copies in personal accounts
  3. API-Based Exfiltration

    • Use API access to extract data programmatically
    • Stay under rate limits and detection thresholds
    • Extract targeted data across multiple services
  1. Takeout Restrictions

    Admin Console > Apps > Google Workspace > Settings for data access
    - Restrict Google Takeout capabilities
    - Implement approval workflows for data exports
    - Enable alerts for bulk data downloads
  2. Enhanced DLP Implementation

    Admin Console > Security > Data protection
    - Configure comprehensive DLP policies
    - Implement content-aware access restrictions
    - Deploy sharing controls based on content classification
  3. API Access Monitoring

    • Implement API access monitoring and limiting
    • Create behavioral baselines for API usage
    • Deploy anomaly detection for unusual data access patterns

Understanding post-exploitation techniques is critical for effective defense. These methodologies highlight how attackers maintain access and extract data after initial compromise.

Sophisticated attackers use several techniques to extract data from Google Workspace:

  1. Google Takeout Exploitation

    • Navigate to https://takeout.google.com after account compromise
    • Extract complete account data archives across all services
    • Download bulk data without triggering traditional DLP alerts
    • Extract historical content that may not be visible in typical interfaces
  2. Google Vault Extraction

    • Leverage Google Vault (if enabled) to export user content
    • Use eDiscovery capabilities to search across multiple users
    • Extract content from multiple services in single operation
    • Bypass service-specific export limitations
  3. Targeted Data Mining

    • Use Google Cloud Search to find sensitive content across services
    • Extract contacts from https://contacts.google.com
    • Mine Google Chat for sensitive information or credentials
    • Search Google Keep notes for recorded credentials or sensitive data
  1. Takeout and Export Controls

    Admin Console > Apps > Google Workspace > Settings for Data Access
    - Restrict Google Takeout capabilities
    - Limit data download functionality
    - Apply export controls based on organizational unit
  2. Enhanced Logging and Monitoring

    # Python script to detect suspicious data export activities
    def detect_suspicious_exports(reports_service):
    """Monitor for suspicious data export activities"""
    # Get export events
    export_events = reports_service.activities().list(
    userKey='all',
    applicationName='drive',
    eventName='download,export_file',
    maxResults=1000
    ).execute()
    suspicious_exports = []
    for event in export_events.get('items', []):
    # Extract relevant data
    user_email = event['actor']['email']
    event_type = event.get('events', [{}])[0].get('name')
    document_id = next((p.get('value') for p in event.get('events', [{}])[0].get('parameters', [])
    if p.get('name') == 'doc_id'), None)
    # Check if this is a high-volume export
    if is_high_volume_export(reports_service, user_email):
    suspicious_exports.append({
    'user': user_email,
    'activity': 'high_volume_export',
    'details': f"Excessive {event_type} activity",
    'timestamp': event.get('id', {}).get('time')
    })
    # Check for Takeout activities
    takeout_events = reports_service.activities().list(
    userKey='all',
    applicationName='user_accounts',
    eventName='download_data',
    maxResults=1000
    ).execute()
    for event in takeout_events.get('items', []):
    suspicious_exports.append({
    'user': event['actor']['email'],
    'activity': 'takeout_export',
    'details': "Google Takeout data export",
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    return suspicious_exports
    def is_high_volume_export(reports_service, user_email):
    """Determine if a user is exporting high volumes of data"""
    # Get download/export count for last 24 hours
    yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
    events = reports_service.activities().list(
    userKey=user_email,
    applicationName='drive',
    eventName='download,export_file',
    startTime=yesterday,
    maxResults=1000
    ).execute()
    # Count export activities
    export_count = len(events.get('items', []))
    # Threshold can be adjusted based on normal user behavior
    return export_count > 50 # Arbitrary threshold
  3. Data Access Controls

    Admin Console > Security > Access and data control > Information rights management
    - Enable IRM for Google Drive
    - Restrict document download capabilities
    - Implement content-aware access restrictions

Attackers leverage Google Groups for privilege escalation:

  1. Group Membership Exploitation

    • Search for groups with privileged access
    • Identify groups with self-signup capabilities
    • Join groups that provide elevated permissions
    • Leverage transitive group memberships for access
  2. Group Settings Manipulation

    • Modify group settings to allow external sharing
    • Change group visibility to extend access
    • Manipulate group permissions for persistence
    • Exploit default settings that may be permissive
  3. Group-Based Resource Access

    • Use group membership to access protected resources
    • Leverage group-based sharing for sensitive documents
    • Access applications with group-based authentication
    • Exploit group-scoped API access
  1. Group Access Controls

    Admin Console > Directory > Groups
    - Configure "Who can join the group" to "Only invited users"
    - Disable "Allow members to join themselves"
    - Set appropriate visibility settings
    - Implement approval requirements for all groups
  2. Group Audit and Monitoring

    # Python script to monitor for suspicious group activities
    def detect_suspicious_group_activities(admin_sdk_service, reports_service):
    """Monitor for suspicious Google Groups activities"""
    # Get group membership change events
    group_events = reports_service.activities().list(
    userKey='all',
    applicationName='groups',
    eventName='add_to_group,change_group_setting',
    maxResults=1000
    ).execute()
    suspicious_activities = []
    for event in group_events.get('items', []):
    # Extract event details
    event_name = event.get('events', [{}])[0].get('name')
    parameters = event.get('events', [{}])[0].get('parameters', [])
    if event_name == 'add_to_group':
    group_email = next((p.get('value') for p in parameters
    if p.get('name') == 'group_email'), None)
    # Check if this is a privileged group
    if is_privileged_group(admin_sdk_service, group_email):
    suspicious_activities.append({
    'user': event['actor']['email'],
    'activity': 'joined_privileged_group',
    'group': group_email,
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    elif event_name == 'change_group_setting':
    group_email = next((p.get('value') for p in parameters
    if p.get('name') == 'group_email'), None)
    setting_name = next((p.get('value') for p in parameters
    if p.get('name') == 'setting_name'), None)
    new_value = next((p.get('value') for p in parameters
    if p.get('name') == 'new_value'), None)
    # Check for suspicious setting changes
    if is_sensitive_setting_change(setting_name, new_value):
    suspicious_activities.append({
    'user': event['actor']['email'],
    'activity': 'suspicious_group_setting_change',
    'group': group_email,
    'setting': f"{setting_name} changed to {new_value}",
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    return suspicious_activities
    def is_privileged_group(admin_sdk_service, group_email):
    """Determine if a group has privileged access"""
    # This would check against a list of known privileged groups
    # or check for groups with admin privileges
    privileged_groups = ['admins@domain.com', 'security@domain.com']
    return group_email in privileged_groups
    def is_sensitive_setting_change(setting_name, new_value):
    """Determine if a setting change is potentially dangerous"""
    sensitive_changes = {
    'WHO_CAN_JOIN': ['ALL_IN_DOMAIN_CAN_JOIN', 'ANYONE_CAN_JOIN'],
    'WHO_CAN_VIEW_MEMBERSHIP': ['ALL_IN_DOMAIN_CAN_VIEW', 'ANYONE_CAN_VIEW'],
    'WHO_CAN_VIEW_GROUP': ['ALL_IN_DOMAIN_CAN_VIEW', 'ANYONE_CAN_VIEW'],
    'ALLOW_EXTERNAL_MEMBERS': ['true']
    }
    return setting_name in sensitive_changes and new_value in sensitive_changes[setting_name]
  3. Group Security Framework

    • Implement periodic group access reviews
    • Create baseline for group security settings
    • Document privileged groups and access requirements
    • Develop automated group configuration validation

Attackers leverage Google Apps Script for persistence and data access:

  1. Script Discovery and Modification

    • Identify existing Apps Scripts in the environment
    • Modify legitimate scripts to add malicious functionality
    • Add persistence mechanisms through triggers
    • Include data exfiltration capabilities
  2. Script Deployment Techniques

    • Deploy scripts as web applications for external access
    • Create time-driven triggers for scheduled execution
    • Implement document-based triggers for user-initiated execution
    • Configure cross-user deployment through sharing
  3. Sensitive Information Access

    • Use script privileges to access user data
    • Leverage authorization to read sensitive documents
    • Extract email content through authorized access
    • Access calendar and contact information
  1. Apps Script Security Controls

    Admin Console > Security > API Controls > Apps Script
    - Configure "Google Cloud Platform (GCP) trust" appropriately
    - Restrict Apps Script creation capabilities
    - Implement appropriate Apps Script marketplace controls
  2. Script Monitoring Framework

    • Implement comprehensive audit of existing scripts
    • Deploy monitoring for script creation and modification
    • Create alerts for suspicious trigger creation
    • Monitor for unusual script execution patterns
  3. Script Access Controls

    • Restrict script deployment capabilities
    • Implement approval process for web application deployment
    • Control API access for scripts
    • Restrict script sharing permissions

Attackers employ multiple sophisticated persistence techniques:

  1. Gmail Filter and Forwarding Mechanisms

    • Create mail filters to hide security notifications
    • Set up automatic forwarding to attacker-controlled addresses
    • Configure targeted filters to capture specific keywords or senders
    • Implement filters to hide evidence of compromise
  2. App Password Exploitation

    • Generate application-specific passwords for service access
    • Use app passwords to bypass MFA requirements
    • Maintain access even after password changes
    • Create multiple app passwords for redundant access
  3. Account Delegation Abuse

    • Configure mail delegation to attacker-controlled accounts
    • Access victim’s email through delegation relationship
    • Maintain persistent access without additional authentication
    • Use delegation to bypass password changes and MFA
  4. 2FA Manipulation

    • Modify two-factor authentication settings
    • Add attacker-controlled backup phone numbers
    • Enroll new hardware security keys
    • Change recovery email addresses to attacker-controlled accounts
  1. Mail Filter Monitoring and Control

    Admin Console > Apps > Google Workspace > Gmail > Advanced settings
    - Restrict mail forwarding capabilities
    - Enable alerts for new forwarding rules
    - Monitor for suspicious filter creation
    # Python script for detecting suspicious mail filters
    def detect_suspicious_mail_filters(reports_service):
    """Detect suspicious mail filters and forwarding rules"""
    # Get mail filter events
    filter_events = reports_service.activities().list(
    userKey='all',
    applicationName='gmail',
    eventName='CREATE_FILTER',
    maxResults=1000
    ).execute()
    suspicious_filters = []
    for event in filter_events.get('items', []):
    # Extract filter criteria and actions
    parameters = event.get('events', [{}])[0].get('parameters', [])
    filter_criteria = next((p.get('value') for p in parameters
    if p.get('name') == 'filter_criteria'), '')
    filter_action = next((p.get('value') for p in parameters
    if p.get('name') == 'filter_action'), '')
    # Check for suspicious patterns
    is_suspicious = False
    # Check for security-related message filtering
    security_keywords = ['security', 'alert', 'warning', 'password', 'verify']
    if any(keyword in filter_criteria.lower() for keyword in security_keywords):
    if 'trash' in filter_action.lower() or 'archive' in filter_action.lower():
    is_suspicious = True
    # Check for external forwarding
    if 'forward' in filter_action.lower():
    forward_address = filter_action.split(' ')[-1]
    if not is_internal_domain(forward_address):
    is_suspicious = True
    if is_suspicious:
    suspicious_filters.append({
    'user': event['actor']['email'],
    'filter_criteria': filter_criteria,
    'filter_action': filter_action,
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    # Also check for forwarding setup
    forwarding_events = reports_service.activities().list(
    userKey='all',
    applicationName='gmail',
    eventName='FORWARDING_CHANGE',
    maxResults=1000
    ).execute()
    for event in forwarding_events.get('items', []):
    parameters = event.get('events', [{}])[0].get('parameters', [])
    forwarding_address = next((p.get('value') for p in parameters
    if p.get('name') == 'forwarding_address'), None)
    if forwarding_address and not is_internal_domain(forwarding_address):
    suspicious_filters.append({
    'user': event['actor']['email'],
    'type': 'forwarding',
    'forwarding_address': forwarding_address,
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    return suspicious_filters
  2. App Password Controls

    Admin Console > Security > Authentication > App passwords
    - Disable app password creation
    - Monitor for app password usage
    - Implement regular app password audits
  3. Delegation Monitoring and Restriction

    Admin Console > Apps > Google Workspace > Gmail > Advanced settings
    - Restrict mail delegation capabilities
    - Implement approval workflows for delegation
    - Monitor delegation relationships regularly
    # Python script for auditing mail delegation
    def audit_mail_delegation(admin_sdk_service):
    """Audit all mail delegation relationships"""
    users = admin_sdk_service.users().list(
    customer='my_customer',
    maxResults=100
    ).execute()
    delegation_relationships = []
    for user in users.get('users', []):
    user_email = user['primaryEmail']
    try:
    # Get delegation settings
    delegates = admin_sdk_service.users().settings().delegates().list(
    userId=user_email
    ).execute()
    for delegate in delegates.get('delegates', []):
    delegation_relationships.append({
    'user': user_email,
    'delegate': delegate.get('delegateEmail'),
    'verified': delegate.get('verificationStatus') == 'accepted'
    })
    except Exception as e:
    print(f"Error checking delegation for {user_email}: {str(e)}")
    return delegation_relationships
  4. 2FA Security Controls

    Admin Console > Security > Authentication > 2-Step Verification
    - Enforce 2FA for all users
    - Restrict 2FA enrollment options
    - Monitor 2FA configuration changes
    - Implement security key enforcement

Attackers exploit connections between Google services:

  1. GWS to GCP Pivoting

    • Use Workspace credentials to access Google Cloud
    • Leverage shared identity for cross-platform access
    • Exploit integrated services between platforms
    • Use IAM relationships between environments
  2. Service Integration Exploitation

    • Leverage service account relationships
    • Use federated identity mechanisms
    • Exploit OAuth connections between services
    • Target poorly configured service boundaries
  1. Identity Boundary Controls

    Admin Console > Security > Access and data control > API Controls
    - Configure appropriate service boundaries
    - Implement strict access controls between services
    - Enforce separation between environments
  2. Cross-Service Monitoring

    • Implement monitoring across service boundaries
    • Create alerts for unusual cross-service access
    • Deploy logging for service-to-service authentication
    • Develop cross-service correlation rules

Attackers target directory synchronization components to access credentials and sensitive data:

  1. Google Credential Provider for Windows (GCPW) Attacks

    • Target Windows machines using GCPW for SSO
    • Extract tokens stored in disk, memory, and registry
    • Potentially obtain clear text passwords during synchronization
    • Leverage compromised synchronization for persistent access
  2. Google Cloud Directory Sync (GCDS) Exploitation

    • Target GCDS server components during AD to Workspace sync
    • Access synchronization credentials with elevated privileges
    • Extract Workspace super admin and privileged AD credentials
    • Compromise synchronization rules to maintain persistence
  3. Google Password Sync (GPS) Attacks

    • Target GPS components installed on domain controllers
    • Access credentials during password synchronization processes
    • Extract synchronized password data during transmission
    • Modify synchronization behavior for credential harvesting
  1. GCPW Hardening

    Group Policy > Computer Configuration > Administrative Templates > Google > Google Credential Provider for Windows
    - Implement secure token storage settings
    - Configure appropriate session parameters
    - Restrict GCPW to managed devices
    Terminal window
    # PowerShell script to detect and analyze GCPW installations
    function Detect-GCPW {
    Write-Host "Checking for Google Credential Provider for Windows..."
    # Check for GCPW registry keys
    $gcpwKey = "HKLM:\SOFTWARE\Google\GCPW"
    $gcpwExists = Test-Path $gcpwKey
    if ($gcpwExists) {
    Write-Host "GCPW detected! Analyzing configuration..." -ForegroundColor Yellow
    # Check domain configuration
    $domain = (Get-ItemProperty -Path $gcpwKey -Name "domain_name" -ErrorAction SilentlyContinue).domain_name
    Write-Host "Configured domain: $domain"
    # Check security settings
    $enableSecurityKey = (Get-ItemProperty -Path $gcpwKey -Name "enable_security_key_sign_in" -ErrorAction SilentlyContinue).enable_security_key_sign_in
    $enablePasswordManagerAutofill = (Get-ItemProperty -Path $gcpwKey -Name "enable_password_manager_autofill" -ErrorAction SilentlyContinue).enable_password_manager_autofill
    $enableWatsonLogging = (Get-ItemProperty -Path $gcpwKey -Name "enable_watson_logging" -ErrorAction SilentlyContinue).enable_watson_logging
    # Report security concerns
    if ($enablePasswordManagerAutofill -eq 1) {
    Write-Host "WARNING: Password manager autofill is enabled - potential security risk" -ForegroundColor Red
    }
    if ($enableWatsonLogging -eq 1) {
    Write-Host "WARNING: Watson logging is enabled - may log sensitive data" -ForegroundColor Red
    }
    # Check token storage
    $tokenFiles = Get-ChildItem -Path "$env:LOCALAPPDATA\Google\GCPW" -Recurse -ErrorAction SilentlyContinue
    if ($tokenFiles) {
    Write-Host "Found $(($tokenFiles | Measure-Object).Count) GCPW token files" -ForegroundColor Yellow
    }
    }
    else {
    Write-Host "GCPW not detected on this system" -ForegroundColor Green
    }
    }
    Detect-GCPW
  2. GCDS Secure Configuration

    # GCDS Configuration Security Best Practices
    - Deploy GCDS on dedicated, hardened servers
    - Implement JCE unlimited strength cryptography
    - Use certificate-based authentication where possible
    - Configure secure credential storage
    # Bash script to audit GCDS installation
    #!/bin/bash
    echo "Auditing GCDS installation..."
    # Check for GCDS installation directory
    if [ -d "/opt/GoogleCloudDirSync" ]; then
    echo "[!] GCDS installation found!"
    # Check configuration file security
    config_files=$(find /opt/GoogleCloudDirSync -name "*.xml")
    echo "Found $(echo "$config_files" | wc -l) configuration files"
    # Check file permissions
    insecure_files=$(find /opt/GoogleCloudDirSync -type f -name "*.xml" -perm /o+rw)
    if [ -n "$insecure_files" ]; then
    echo "[!] WARNING: Found insecure file permissions on configuration files:"
    echo "$insecure_files"
    fi
    # Check for encrypted password storage
    for config in $config_files; do
    if grep -q "encryptedPassword" "$config"; then
    echo "[+] Using encrypted password storage in $config"
    else
    echo "[!] WARNING: Unencrypted password storage detected in $config"
    fi
    done
    else
    echo "[+] GCDS not installed on this system"
    fi
  3. GPS Hardening

    # GPS Configuration Security Best Practices
    - Deploy on dedicated, hardened domain controllers
    - Implement strict service account permissions
    - Configure encrypted password transmission
    - Implement monitoring of GPS components
  4. Synchronization Monitoring Framework

    # Python script for monitoring directory synchronization activities
    def monitor_directory_sync_activities(reports_service):
    """Monitor for suspicious directory synchronization activities"""
    # Get admin directory sync events
    sync_events = reports_service.activities().list(
    userKey='all',
    applicationName='admin',
    eventName='TOGGLE_SERVICE_ACCOUNT,ADD_SERVICE_ACCOUNT_PRIVILEGE',
    maxResults=1000
    ).execute()
    suspicious_activities = []
    for event in sync_events.get('items', []):
    # Extract event details
    event_name = event.get('events', [{}])[0].get('name')
    parameters = event.get('events', [{}])[0].get('parameters', [])
    # Check for suspicious parameters
    if event_name == 'TOGGLE_SERVICE_ACCOUNT':
    service_account_status = next((p.get('value') for p in parameters
    if p.get('name') == 'service_account_status'), None)
    if service_account_status == 'ON':
    suspicious_activities.append({
    'user': event['actor']['email'],
    'activity': 'service_account_enabled',
    'details': "Service account toggled on",
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    elif event_name == 'ADD_SERVICE_ACCOUNT_PRIVILEGE':
    privilege_name = next((p.get('value') for p in parameters
    if p.get('name') == 'privilege_name'), None)
    if privilege_name in ['ADMIN_DIRECTORY_GROUP', 'ADMIN_DIRECTORY_USER']:
    suspicious_activities.append({
    'user': event['actor']['email'],
    'activity': 'service_account_privilege_change',
    'details': f"Service account granted {privilege_name} privilege",
    'ip_address': event.get('ipAddress'),
    'timestamp': event.get('id', {}).get('time')
    })
    return suspicious_activities

Credential Access and Authentication Bypass

Section titled “Credential Access and Authentication Bypass”

Sophisticated attackers target credential and authentication mechanisms:

  1. Password Spraying Techniques

    • Use distributed login attempts to avoid lockouts
    • Target account enumeration to identify valid accounts
    • Utilize common password patterns specific to organizations
  2. Session Cookie Theft

    • Target session cookies through XSS or client-side vulnerabilities
    • Hijack authenticated sessions without credential theft
    • Bypass MFA through authenticated session access
  3. OAuth Token Theft

    • Target refresh tokens stored on client devices
    • Extract tokens from application storage
    • Use stolen tokens for persistent API access
  1. Advanced Authentication Hardening

    Admin Console > Security > Authentication
    - Implement hardware key enforcement
    - Deploy risk-based authentication challenges
    - Enable strict session control policies
  2. Cookie Security Enhancement

    • Implement secure and HTTP-only cookie flags
    • Deploy anti-session hijacking mechanisms
    • Configure appropriate session timeout values
  3. Token Security Framework

    • Implement token revocation monitoring
    • Create risk-based token lifetime policies
    • Deploy device posture checks for token issuance

Attackers exploit interconnections between Google services:

  1. GCP-Workspace Pivoting

    • Use Workspace compromise to access GCP resources
    • Exploit shared authentication between services
    • Leverage identity federation for privilege escalation
  2. Workspace-Chrome Exploitation

    • Target Chrome Sync to extract credentials
    • Use malicious extensions for data access
    • Exploit managed Chrome deployments for persistence
  3. Google Meet/Chat Attack Surface

    • Use meeting invitations for phishing
    • Exploit chat functionality for malicious links
    • Leverage file sharing for malware distribution
  1. Cross-Service Security Boundaries

    • Implement strict separation between environments
    • Deploy service-specific access policies
    • Create identity boundaries between services
  2. Chrome Security Hardening

    Admin Console > Devices > Chrome > Settings
    - Implement Chrome extension restrictions
    - Configure secure sync settings
    - Deploy enhanced safe browsing protection
  3. Collaboration Tool Security

    Admin Console > Apps > Google Workspace > Google Meet
    - Configure external participant restrictions
    - Implement file sharing controls
    - Deploy link scanning for chat messages

Understand common reconnaissance methods to strengthen defenses:

  1. Email Enumeration Countermeasures

    • Implement anti-harvesting measures
    • Deploy CAPTCHA for repeated lookup attempts
    • Monitor for suspicious directory access patterns
  2. Public Document Exposure Control

    Admin Console > Apps > Google Workspace > Drive and Docs
    - Audit publicly accessible documents
    - Implement default sharing restrictions
    - Deploy sensitive content controls
  3. Digital Footprint Reduction

    • Conduct regular exposure assessments
    • Implement information exposure policies
    • Monitor for organization information leakage

Counter sophisticated social engineering with enhanced controls:

  1. Business Email Compromise Protection

    Admin Console > Apps > Google Workspace > Gmail > Safety
    - Enable enhanced pre-delivery message scanning
    - Implement display name spoof protection
    - Deploy lookalike domain warnings
  2. User Awareness Enhancement

    • Implement targeted phishing simulations
    • Deploy just-in-time security training
    • Create contextual security awareness resources
  3. Communication Channel Verification

    • Implement email authentication indicators
    • Deploy external sender warnings
    • Create secure communication verification procedures

Incident Response for Common Attack Scenarios

Section titled “Incident Response for Common Attack Scenarios”
  1. Initial Assessment

    • Identify compromised accounts and authorized applications
    • Determine access scope and potential data exposure
    • Review activity logs for suspicious actions
  2. Containment Actions

    Admin Console > Security > API Controls > App access control
    - Revoke suspicious application access
    - Block malicious client IDs
    - Reset passwords for affected users
  3. Recovery Process

    • Conduct thorough access review
    • Implement enhanced monitoring for affected users
    • Deploy additional authentication requirements
  1. Initial Assessment

    • Identify scope of administrative access
    • Review admin audit logs for unauthorized actions
    • Determine extent of configuration changes
  2. Containment Actions

    Admin Console > Account > Admin roles
    - Revoke compromised admin access
    - Reset super admin credentials
    - Implement IP restrictions for admin console
  3. Recovery Process

    • Conduct comprehensive configuration review
    • Restore from known-good configuration backups
    • Implement enhanced logging and monitoring
  1. Initial Assessment

    • Identify data access patterns and potentially exposed data
    • Review sharing activity and external transfers
    • Determine regulatory and compliance implications
  2. Containment Actions

    Admin Console > Security > Data protection
    - Block external sharing temporarily
    - Revoke suspicious sharing permissions
    - Disable data export capabilities
  3. Recovery Process

    • Implement enhanced DLP controls
    • Conduct data exposure assessment
    • Deploy additional monitoring for sensitive data

Establish an ongoing penetration testing program:

  1. Scope Definition

    • Define clear testing boundaries
    • Establish rules of engagement
    • Create realistic attack scenarios
  2. Authorized Testing Procedures

    • Develop Google Workspace-specific testing methodologies
    • Implement safe testing practices
    • Create realistic simulation capabilities
  3. Findings Remediation Process

    • Establish severity classification system
    • Implement remediation tracking
    • Create verification testing procedures

Leverage threat intelligence to enhance defenses:

  1. Google Workspace Threat Feeds

    • Subscribe to Google Cloud Threat Intelligence
    • Implement industry-specific threat intelligence
    • Create custom indicators for Google Workspace
  2. Attack Pattern Analysis

    • Document common Google Workspace attack patterns
    • Develop detection rules for known tactics
    • Create proactive hunting procedures
  3. Security Control Validation

    • Test defensive controls against known attack patterns
    • Implement regular control validation
    • Create continuous improvement framework

Note: This guide integrates adversarial perspectives to strengthen your Google Workspace security posture. The techniques described should only be used in authorized security testing with proper approvals and controls.

Page provenance

Community-maintained guidance. Use the edit link below to propose a sourced correction.

Contributors

Was this page useful?

Help us prioritize the next improvement.