Skip to content

Under Construction

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

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

Google Platform-Specific Phishing Techniques

Attack Methodology

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

  1. Google Groups Phishing
  2. Create Google Groups with legitimate-looking names
  3. Invite target users to join these groups
  4. Send emails from legitimate Google addresses
  5. Leverage group communication for payload delivery
  6. Exploit trust in Google's infrastructure

  7. Google Chat Phishing

  8. Initiate chat conversations with targets
  9. Create deceptive Spaces mimicking official support channels
  10. Send malicious links within chat conversations
  11. Exploit real-time nature for urgent action requests
  12. Use Google's legitimate notification system

  13. Google Calendar Phishing

  14. Create calendar invitations with embedded phishing links
  15. Configure events with short notice to create urgency
  16. Add malicious content in event descriptions and attachments
  17. Hide attendee lists to prevent cross-checking
  18. Disable email notifications to avoid scrutiny

  19. App Scripts Redirect Phishing

  20. Create malicious web apps on script.google.com
  21. Implement JavaScript redirects to phishing sites
  22. Leverage legitimate Google domains (script.google.com)
  23. Create URL parameters to customize phishing experience
  24. Evade URL filtering by using trusted Google domains

  25. OAuth App Phishing

  26. Create applications requesting excessive permissions
  27. Design convincing application names and descriptions
  28. Craft targeted permission requests based on victim role
  29. Exploit user tendency to authorize Google-hosted applications
  30. Obtain persistent access through authorized OAuth tokens

Defensive Countermeasures

  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

  6. Develop user training specific to Google platform phishing
  7. Create visual guides for Google-specific phishing indicators
  8. Implement simulated phishing using Google platforms
  9. Establish clear reporting procedures for suspicious activities

  10. 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)
    

1. OAuth-Based Attacks

Attack Methodology

Attackers frequently target Google Workspace through OAuth-based attacks:

  1. OAuth Phishing Campaigns
  2. Create malicious applications requesting extensive permissions
  3. Design convincing phishing emails with OAuth authorization links
  4. Persuade users to authorize deceptive applications

  5. Application Permission Abuse

  6. Request overly broad scopes (Gmail, Drive, Admin access)
  7. Exploit insufficient OAuth app verification requirements
  8. Use legitimate-looking application names and logos

  9. Token Theft and Abuse

  10. Target OAuth refresh tokens for long-term persistent access
  11. Use stolen tokens to access services without triggering login alerts
  12. Bypass MFA through pre-authenticated token usage

Defensive Countermeasures

  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

  4. Implement routine OAuth application reviews
  5. Develop OAuth risk scoring based on requested scopes
  6. Create user education focused on OAuth authorization risks

2. Email-Based Attack Vectors

Attack Methodology

Email remains a primary attack vector for Google Workspace:

  1. Lateral Phishing
  2. Compromise one account and use it to phish others in the organization
  3. Leverage existing trust relationships and conversation threads
  4. Target high-value accounts based on internal information

  5. Email Filter/Forwarding Abuse

  6. Create covert mail forwarding rules after account compromise
  7. Set up filters to hide specific messages from user view
  8. Establish persistent access to communications

  9. Mailbox Delegation Exploitation

  10. Add unauthorized delegates to compromised mailboxes
  11. Use delegation to maintain access even after password changes
  12. Access sensitive communications without generating alerts

Defensive Countermeasures

  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
    

3. Admin Account Targeting

Attack Methodology

Administrator accounts are primary targets due to their elevated privileges:

  1. Admin Role Privilege Escalation
  2. Target accounts with limited admin privileges
  3. Escalate permissions through role modification
  4. Create persistence through new admin accounts

  5. Super Admin Account Targeting

  6. Focus phishing and social engineering on super admin accounts
  7. Utilize session hijacking to access admin console
  8. Make subtle changes to avoid detection

  9. Recovery Email Manipulation

  10. Modify account recovery options for persistence
  11. Change recovery email to attacker-controlled address
  12. Use recovery process to regain access after remediation

Defensive Countermeasures

  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

  4. Implement strict separation of duties
  5. Require multi-party authorization for critical changes
  6. Create time-bound administrative access
  7. Implement enhanced logging for all admin actions

4. Persistence Mechanisms

Attack Methodology

Attackers use various persistence techniques to maintain access:

  1. Service Account Key Abuse
  2. Create or steal service account keys with elevated privileges
  3. Use keys for programmatic API access
  4. Maintain access independent of user credentials

  5. GCDS (Google Cloud Directory Sync) Exploitation

  6. Target directory synchronization configurations
  7. Modify sync rules to create or preserve access
  8. Leverage trusted synchronization channels

  9. Workspace Add-on Persistence

  10. Create malicious Workspace add-ons
  11. Deploy via compromised admin accounts
  12. Establish persistence through authorized applications

Defensive Countermeasures

  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
    

5. Data Exfiltration Techniques

Attack Methodology

Attackers use multiple methods to extract sensitive data:

  1. Google Takeout Exploitation
  2. Use Google Takeout to extract complete data archives
  3. Extract bulk data without triggering DLP alerts
  4. Obtain comprehensive data snapshots

  5. Drive Share Manipulation

  6. Share sensitive documents with external accounts
  7. Use sharing links with minimal visibility
  8. Create copies in personal accounts

  9. API-Based Exfiltration

  10. Use API access to extract data programmatically
  11. Stay under rate limits and detection thresholds
  12. Extract targeted data across multiple services

Defensive Countermeasures

  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

  4. Implement API access monitoring and limiting
  5. Create behavioral baselines for API usage
  6. Deploy anomaly detection for unusual data access patterns

Post-Exploitation Techniques

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

Data Exfiltration Methods

Attack Methodology

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

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

  6. Google Vault Extraction

  7. Leverage Google Vault (if enabled) to export user content
  8. Use eDiscovery capabilities to search across multiple users
  9. Extract content from multiple services in single operation
  10. Bypass service-specific export limitations

  11. Targeted Data Mining

  12. Use Google Cloud Search to find sensitive content across services
  13. Extract contacts from https://contacts.google.com
  14. Mine Google Chat for sensitive information or credentials
  15. Search Google Keep notes for recorded credentials or sensitive data

Defensive Countermeasures

  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
    

Group-Based Privilege Escalation

Attack Methodology

Attackers leverage Google Groups for privilege escalation:

  1. Group Membership Exploitation
  2. Search for groups with privileged access
  3. Identify groups with self-signup capabilities
  4. Join groups that provide elevated permissions
  5. Leverage transitive group memberships for access

  6. Group Settings Manipulation

  7. Modify group settings to allow external sharing
  8. Change group visibility to extend access
  9. Manipulate group permissions for persistence
  10. Exploit default settings that may be permissive

  11. Group-Based Resource Access

  12. Use group membership to access protected resources
  13. Leverage group-based sharing for sensitive documents
  14. Access applications with group-based authentication
  15. Exploit group-scoped API access

Defensive Countermeasures

  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

  4. Implement periodic group access reviews
  5. Create baseline for group security settings
  6. Document privileged groups and access requirements
  7. Develop automated group configuration validation

Google Apps Script Exploitation

Attack Methodology

Attackers leverage Google Apps Script for persistence and data access:

  1. Script Discovery and Modification
  2. Identify existing Apps Scripts in the environment
  3. Modify legitimate scripts to add malicious functionality
  4. Add persistence mechanisms through triggers
  5. Include data exfiltration capabilities

  6. Script Deployment Techniques

  7. Deploy scripts as web applications for external access
  8. Create time-driven triggers for scheduled execution
  9. Implement document-based triggers for user-initiated execution
  10. Configure cross-user deployment through sharing

  11. Sensitive Information Access

  12. Use script privileges to access user data
  13. Leverage authorization to read sensitive documents
  14. Extract email content through authorized access
  15. Access calendar and contact information

Defensive Countermeasures

  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

  3. Implement comprehensive audit of existing scripts
  4. Deploy monitoring for script creation and modification
  5. Create alerts for suspicious trigger creation
  6. Monitor for unusual script execution patterns

  7. Script Access Controls

  8. Restrict script deployment capabilities
  9. Implement approval process for web application deployment
  10. Control API access for scripts
  11. Restrict script sharing permissions

Advanced Persistence Techniques

Attack Methodology

Attackers employ multiple sophisticated persistence techniques:

  1. Gmail Filter and Forwarding Mechanisms
  2. Create mail filters to hide security notifications
  3. Set up automatic forwarding to attacker-controlled addresses
  4. Configure targeted filters to capture specific keywords or senders
  5. Implement filters to hide evidence of compromise

  6. App Password Exploitation

  7. Generate application-specific passwords for service access
  8. Use app passwords to bypass MFA requirements
  9. Maintain access even after password changes
  10. Create multiple app passwords for redundant access

  11. Account Delegation Abuse

  12. Configure mail delegation to attacker-controlled accounts
  13. Access victim's email through delegation relationship
  14. Maintain persistent access without additional authentication
  15. Use delegation to bypass password changes and MFA

  16. 2FA Manipulation

  17. Modify two-factor authentication settings
  18. Add attacker-controlled backup phone numbers
  19. Enroll new hardware security keys
  20. Change recovery email addresses to attacker-controlled accounts

Defensive Countermeasures

  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
  1. App Password Controls

    Admin Console > Security > Authentication > App passwords
    - Disable app password creation
    - Monitor for app password usage
    - Implement regular app password audits
    

  2. 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
  1. 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
    

Cross-Service Pivoting

Attack Methodology

Attackers exploit connections between Google services:

  1. GWS to GCP Pivoting
  2. Use Workspace credentials to access Google Cloud
  3. Leverage shared identity for cross-platform access
  4. Exploit integrated services between platforms
  5. Use IAM relationships between environments

  6. Service Integration Exploitation

  7. Leverage service account relationships
  8. Use federated identity mechanisms
  9. Exploit OAuth connections between services
  10. Target poorly configured service boundaries

Defensive Countermeasures

  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

  3. Implement monitoring across service boundaries
  4. Create alerts for unusual cross-service access
  5. Deploy logging for service-to-service authentication
  6. Develop cross-service correlation rules

Directory Synchronization Vulnerabilities

Attack Methodology

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

  1. Google Credential Provider for Windows (GCPW) Attacks
  2. Target Windows machines using GCPW for SSO
  3. Extract tokens stored in disk, memory, and registry
  4. Potentially obtain clear text passwords during synchronization
  5. Leverage compromised synchronization for persistent access

  6. Google Cloud Directory Sync (GCDS) Exploitation

  7. Target GCDS server components during AD to Workspace sync
  8. Access synchronization credentials with elevated privileges
  9. Extract Workspace super admin and privileged AD credentials
  10. Compromise synchronization rules to maintain persistence

  11. Google Password Sync (GPS) Attacks

  12. Target GPS components installed on domain controllers
  13. Access credentials during password synchronization processes
  14. Extract synchronized password data during transmission
  15. Modify synchronization behavior for credential harvesting

Defensive Countermeasures

  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
    
# 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
  1. 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
  1. 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
    

  2. 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
    

Advanced Penetration Testing Insights

Credential Access and Authentication Bypass

Attack Methodology

Sophisticated attackers target credential and authentication mechanisms:

  1. Password Spraying Techniques
  2. Use distributed login attempts to avoid lockouts
  3. Target account enumeration to identify valid accounts
  4. Utilize common password patterns specific to organizations

  5. Session Cookie Theft

  6. Target session cookies through XSS or client-side vulnerabilities
  7. Hijack authenticated sessions without credential theft
  8. Bypass MFA through authenticated session access

  9. OAuth Token Theft

  10. Target refresh tokens stored on client devices
  11. Extract tokens from application storage
  12. Use stolen tokens for persistent API access

Defensive Countermeasures

  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

  3. Implement secure and HTTP-only cookie flags
  4. Deploy anti-session hijacking mechanisms
  5. Configure appropriate session timeout values

  6. Token Security Framework

  7. Implement token revocation monitoring
  8. Create risk-based token lifetime policies
  9. Deploy device posture checks for token issuance

Cross-Service Attack Vectors

Attack Methodology

Attackers exploit interconnections between Google services:

  1. GCP-Workspace Pivoting
  2. Use Workspace compromise to access GCP resources
  3. Exploit shared authentication between services
  4. Leverage identity federation for privilege escalation

  5. Workspace-Chrome Exploitation

  6. Target Chrome Sync to extract credentials
  7. Use malicious extensions for data access
  8. Exploit managed Chrome deployments for persistence

  9. Google Meet/Chat Attack Surface

  10. Use meeting invitations for phishing
  11. Exploit chat functionality for malicious links
  12. Leverage file sharing for malware distribution

Defensive Countermeasures

  1. Cross-Service Security Boundaries
  2. Implement strict separation between environments
  3. Deploy service-specific access policies
  4. Create identity boundaries between services

  5. Chrome Security Hardening

    Admin Console > Devices > Chrome > Settings
    - Implement Chrome extension restrictions
    - Configure secure sync settings
    - Deploy enhanced safe browsing protection
    

  6. Collaboration Tool Security

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

Penetration Testing Methodologies

Reconnaissance Techniques

Understand common reconnaissance methods to strengthen defenses:

  1. Email Enumeration Countermeasures
  2. Implement anti-harvesting measures
  3. Deploy CAPTCHA for repeated lookup attempts
  4. Monitor for suspicious directory access patterns

  5. Public Document Exposure Control

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

  6. Digital Footprint Reduction

  7. Conduct regular exposure assessments
  8. Implement information exposure policies
  9. Monitor for organization information leakage

Advanced Social Engineering Defenses

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

  3. Implement targeted phishing simulations
  4. Deploy just-in-time security training
  5. Create contextual security awareness resources

  6. Communication Channel Verification

  7. Implement email authentication indicators
  8. Deploy external sender warnings
  9. Create secure communication verification procedures

Incident Response for Common Attack Scenarios

OAuth Phishing Attack Response

  1. Initial Assessment
  2. Identify compromised accounts and authorized applications
  3. Determine access scope and potential data exposure
  4. Review activity logs for suspicious actions

  5. Containment Actions

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

  6. Recovery Process

  7. Conduct thorough access review
  8. Implement enhanced monitoring for affected users
  9. Deploy additional authentication requirements

Admin Account Compromise Response

  1. Initial Assessment
  2. Identify scope of administrative access
  3. Review admin audit logs for unauthorized actions
  4. Determine extent of configuration changes

  5. Containment Actions

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

  6. Recovery Process

  7. Conduct comprehensive configuration review
  8. Restore from known-good configuration backups
  9. Implement enhanced logging and monitoring

Data Exfiltration Incident Response

  1. Initial Assessment
  2. Identify data access patterns and potentially exposed data
  3. Review sharing activity and external transfers
  4. Determine regulatory and compliance implications

  5. Containment Actions

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

  6. Recovery Process

  7. Implement enhanced DLP controls
  8. Conduct data exposure assessment
  9. Deploy additional monitoring for sensitive data

Continuous Security Improvement Framework

Penetration Testing Program

Establish an ongoing penetration testing program:

  1. Scope Definition
  2. Define clear testing boundaries
  3. Establish rules of engagement
  4. Create realistic attack scenarios

  5. Authorized Testing Procedures

  6. Develop Google Workspace-specific testing methodologies
  7. Implement safe testing practices
  8. Create realistic simulation capabilities

  9. Findings Remediation Process

  10. Establish severity classification system
  11. Implement remediation tracking
  12. Create verification testing procedures

Threat Intelligence Integration

Leverage threat intelligence to enhance defenses:

  1. Google Workspace Threat Feeds
  2. Subscribe to Google Cloud Threat Intelligence
  3. Implement industry-specific threat intelligence
  4. Create custom indicators for Google Workspace

  5. Attack Pattern Analysis

  6. Document common Google Workspace attack patterns
  7. Develop detection rules for known tactics
  8. Create proactive hunting procedures

  9. Security Control Validation

  10. Test defensive controls against known attack patterns
  11. Implement regular control validation
  12. Create continuous improvement framework

Resources for Security Testing


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.