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”Attack Methodology
Section titled “Attack Methodology”Attackers leverage Google’s own platforms to create sophisticated phishing campaigns:
-
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
-
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
-
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
-
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
-
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
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 -
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 -
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 -
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 -
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
-
Detection and Monitoring
# Python script to detect suspicious Google platform activitiesdef detect_google_platform_phishing(reports_service):"""Monitor for potentially suspicious Google platform activities"""# Check for suspicious group creationgroup_events = reports_service.activities().list(userKey='all',applicationName='groups',eventName='CREATE_GROUP',maxResults=1000).execute()suspicious_activities = []# Analyze groups creationfor event in group_events.get('items', []):# Extract group detailsparameters = event.get('events', [{}])[0].get('parameters', [])group_name = next((p.get('value') for p in parametersif p.get('name') == 'group_name'), '')# Check for suspicious group namessuspicious_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 eventscalendar_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 parametersif p.get('name') == 'event_title'), '')event_description = next((p.get('value') for p in parametersif p.get('name') == 'event_description'), '')# Check for suspicious calendar activityif 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_activitiesdef 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 URLsr'urgent',r'immediate.*action']return any(re.search(pattern, text.lower()) for pattern in suspicious_patterns)
1. OAuth-Based Attacks
Section titled “1. OAuth-Based Attacks”Attack Methodology
Section titled “Attack Methodology”Attackers frequently target Google Workspace through OAuth-based attacks:
-
OAuth Phishing Campaigns
- Create malicious applications requesting extensive permissions
- Design convincing phishing emails with OAuth authorization links
- Persuade users to authorize deceptive applications
-
Application Permission Abuse
- Request overly broad scopes (Gmail, Drive, Admin access)
- Exploit insufficient OAuth app verification requirements
- Use legitimate-looking application names and logos
-
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
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 -
Advanced Token Monitoring
# Python script for suspicious token activity monitoringdef detect_suspicious_token_activity(admin_sdk_service, reports_service):"""Monitor for suspicious OAuth token activity"""# Get token usage eventstoken_events = reports_service.activities().list(userKey='all',applicationName='token',maxResults=1000).execute()suspicious_activity = []for event in token_events.get('items', []):# Check for suspicious patternsif 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_activitydef is_suspicious_token_activity(event):"""Determine if token activity is suspicious based on various signals"""# Extract relevant dataevents = event.get('events', [{}])if not events:return Falseevent_data = events[0]# Check for sensitive scopesscopes = 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 parametersparameters = event_data.get('parameters', [])client_id = next((p.get('value') for p in parametersif p.get('name') == 'client_id'), None)# Check if client ID is not in our approved listapproved_clients = get_approved_client_ids()unknown_client = client_id not in approved_clients# Suspicious if sensitive scopes AND unknown clientreturn has_sensitive_scopes and unknown_clientdef 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 [] -
Advanced OAuth Governance
- Implement routine OAuth application reviews
- Develop OAuth risk scoring based on requested scopes
- Create user education focused on OAuth authorization risks
2. Email-Based Attack Vectors
Section titled “2. Email-Based Attack Vectors”Attack Methodology
Section titled “Attack Methodology”Email remains a primary attack vector for Google Workspace:
-
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
-
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
-
Mailbox Delegation Exploitation
- Add unauthorized delegates to compromised mailboxes
- Use delegation to maintain access even after password changes
- Access sensitive communications without generating alerts
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
Enhanced Email Monitoring
Admin Console > Reports > Audit > Email logs- Configure alerts for suspicious mail filter creation- Monitor for unusual delegation activity- Implement forwarding restrictions -
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 -
Mail Security Intelligence
# Python script for identifying suspicious email rulesdef detect_suspicious_email_rules(admin_sdk_service, reports_service):"""Detect suspicious email rules and filters"""# Get Gmail configuration eventsmail_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 detailsevent_name = event.get('events', [{}])[0].get('name')parameters = event.get('events', [{}])[0].get('parameters', [])# Check if this is a suspicious ruleif event_name == 'EMAIL_FORWARDING_CHANGE':forwarding_address = next((p.get('value') for p in parametersif p.get('name') == 'forwarding_address'), None)# Check if forwarding to external domainif 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 parametersif p.get('name') == 'filter_criteria'), None)filter_action = next((p.get('value') for p in parametersif p.get('name') == 'filter_action'), None)# Check for suspicious filter patternsif 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_rulesdef is_internal_domain(email_address):"""Check if the email belongs to an internal domain"""internal_domains = ['company.com', 'subsidiary.company.com'] # Your domainsfor domain in internal_domains:if email_address.endswith('@' + domain):return Truereturn Falsedef is_suspicious_filter(criteria, action):"""Determine if a filter is potentially suspicious"""suspicious_indicators = False# Suspicious if hiding emails from specific sendersif 'from:' in criteria and 'trash' in action.lower():suspicious_indicators = True# Suspicious if forwarding to external addressif 'forward' in action.lower() and not is_internal_domain(action.split(' ')[-1]):suspicious_indicators = True# Suspicious if archiving or marking as read security-related emailsif 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 = Truereturn suspicious_indicators
3. Admin Account Targeting
Section titled “3. Admin Account Targeting”Attack Methodology
Section titled “Attack Methodology”Administrator accounts are primary targets due to their elevated privileges:
-
Admin Role Privilege Escalation
- Target accounts with limited admin privileges
- Escalate permissions through role modification
- Create persistence through new admin accounts
-
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
-
Recovery Email Manipulation
- Modify account recovery options for persistence
- Change recovery email to attacker-controlled address
- Use recovery process to regain access after remediation
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 -
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 -
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
4. Persistence Mechanisms
Section titled “4. Persistence Mechanisms”Attack Methodology
Section titled “Attack Methodology”Attackers use various persistence techniques to maintain access:
-
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
-
GCDS (Google Cloud Directory Sync) Exploitation
- Target directory synchronization configurations
- Modify sync rules to create or preserve access
- Leverage trusted synchronization channels
-
Workspace Add-on Persistence
- Create malicious Workspace add-ons
- Deploy via compromised admin accounts
- Establish persistence through authorized applications
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 -
Synchronization Security
Admin Console > Directory > Directory settings- Implement secure GCDS configuration- Restrict synchronization permissions- Monitor synchronization logs for anomalies -
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
Section titled “5. Data Exfiltration Techniques”Attack Methodology
Section titled “Attack Methodology”Attackers use multiple methods to extract sensitive data:
-
Google Takeout Exploitation
- Use Google Takeout to extract complete data archives
- Extract bulk data without triggering DLP alerts
- Obtain comprehensive data snapshots
-
Drive Share Manipulation
- Share sensitive documents with external accounts
- Use sharing links with minimal visibility
- Create copies in personal accounts
-
API-Based Exfiltration
- Use API access to extract data programmatically
- Stay under rate limits and detection thresholds
- Extract targeted data across multiple services
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 -
Enhanced DLP Implementation
Admin Console > Security > Data protection- Configure comprehensive DLP policies- Implement content-aware access restrictions- Deploy sharing controls based on content classification -
API Access Monitoring
- Implement API access monitoring and limiting
- Create behavioral baselines for API usage
- Deploy anomaly detection for unusual data access patterns
Post-Exploitation Techniques
Section titled “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
Section titled “Data Exfiltration Methods”Attack Methodology
Section titled “Attack Methodology”Sophisticated attackers use several techniques to extract data from Google Workspace:
-
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
-
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
-
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
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 -
Enhanced Logging and Monitoring
# Python script to detect suspicious data export activitiesdef detect_suspicious_exports(reports_service):"""Monitor for suspicious data export activities"""# Get export eventsexport_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 datauser_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 exportif 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 activitiestakeout_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_exportsdef 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 hoursyesterday = (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 activitiesexport_count = len(events.get('items', []))# Threshold can be adjusted based on normal user behaviorreturn export_count > 50 # Arbitrary threshold -
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
Section titled “Group-Based Privilege Escalation”Attack Methodology
Section titled “Attack Methodology”Attackers leverage Google Groups for privilege escalation:
-
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
-
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
-
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
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 -
Group Audit and Monitoring
# Python script to monitor for suspicious group activitiesdef detect_suspicious_group_activities(admin_sdk_service, reports_service):"""Monitor for suspicious Google Groups activities"""# Get group membership change eventsgroup_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 detailsevent_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 parametersif p.get('name') == 'group_email'), None)# Check if this is a privileged groupif 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 parametersif p.get('name') == 'group_email'), None)setting_name = next((p.get('value') for p in parametersif p.get('name') == 'setting_name'), None)new_value = next((p.get('value') for p in parametersif p.get('name') == 'new_value'), None)# Check for suspicious setting changesif 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_activitiesdef 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 privilegesprivileged_groups = ['admins@domain.com', 'security@domain.com']return group_email in privileged_groupsdef 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] -
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
Google Apps Script Exploitation
Section titled “Google Apps Script Exploitation”Attack Methodology
Section titled “Attack Methodology”Attackers leverage Google Apps Script for persistence and data access:
-
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
-
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
-
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
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 -
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
-
Script Access Controls
- Restrict script deployment capabilities
- Implement approval process for web application deployment
- Control API access for scripts
- Restrict script sharing permissions
Advanced Persistence Techniques
Section titled “Advanced Persistence Techniques”Attack Methodology
Section titled “Attack Methodology”Attackers employ multiple sophisticated persistence techniques:
-
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
-
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
-
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
-
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
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 filtersdef detect_suspicious_mail_filters(reports_service):"""Detect suspicious mail filters and forwarding rules"""# Get mail filter eventsfilter_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 actionsparameters = event.get('events', [{}])[0].get('parameters', [])filter_criteria = next((p.get('value') for p in parametersif p.get('name') == 'filter_criteria'), '')filter_action = next((p.get('value') for p in parametersif p.get('name') == 'filter_action'), '')# Check for suspicious patternsis_suspicious = False# Check for security-related message filteringsecurity_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 forwardingif 'forward' in filter_action.lower():forward_address = filter_action.split(' ')[-1]if not is_internal_domain(forward_address):is_suspicious = Trueif 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 setupforwarding_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 parametersif 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 -
App Password Controls
Admin Console > Security > Authentication > App passwords- Disable app password creation- Monitor for app password usage- Implement regular app password audits -
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 delegationdef 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 settingsdelegates = 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 -
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
Section titled “Cross-Service Pivoting”Attack Methodology
Section titled “Attack Methodology”Attackers exploit connections between Google services:
-
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
-
Service Integration Exploitation
- Leverage service account relationships
- Use federated identity mechanisms
- Exploit OAuth connections between services
- Target poorly configured service boundaries
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 -
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
Directory Synchronization Vulnerabilities
Section titled “Directory Synchronization Vulnerabilities”Attack Methodology
Section titled “Attack Methodology”Attackers target directory synchronization components to access credentials and sensitive data:
-
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
-
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
-
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
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
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 devicesTerminal window # PowerShell script to detect and analyze GCPW installationsfunction Detect-GCPW {Write-Host "Checking for Google Credential Provider for Windows..."# Check for GCPW registry keys$gcpwKey = "HKLM:\SOFTWARE\Google\GCPW"$gcpwExists = Test-Path $gcpwKeyif ($gcpwExists) {Write-Host "GCPW detected! Analyzing configuration..." -ForegroundColor Yellow# Check domain configuration$domain = (Get-ItemProperty -Path $gcpwKey -Name "domain_name" -ErrorAction SilentlyContinue).domain_nameWrite-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 concernsif ($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 SilentlyContinueif ($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 -
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/bashecho "Auditing GCDS installation..."# Check for GCDS installation directoryif [ -d "/opt/GoogleCloudDirSync" ]; thenecho "[!] GCDS installation found!"# Check configuration file securityconfig_files=$(find /opt/GoogleCloudDirSync -name "*.xml")echo "Found $(echo "$config_files" | wc -l) configuration files"# Check file permissionsinsecure_files=$(find /opt/GoogleCloudDirSync -type f -name "*.xml" -perm /o+rw)if [ -n "$insecure_files" ]; thenecho "[!] WARNING: Found insecure file permissions on configuration files:"echo "$insecure_files"fi# Check for encrypted password storagefor config in $config_files; doif grep -q "encryptedPassword" "$config"; thenecho "[+] Using encrypted password storage in $config"elseecho "[!] WARNING: Unencrypted password storage detected in $config"fidoneelseecho "[+] GCDS not installed on this system"fi -
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 -
Synchronization Monitoring Framework
# Python script for monitoring directory synchronization activitiesdef monitor_directory_sync_activities(reports_service):"""Monitor for suspicious directory synchronization activities"""# Get admin directory sync eventssync_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 detailsevent_name = event.get('events', [{}])[0].get('name')parameters = event.get('events', [{}])[0].get('parameters', [])# Check for suspicious parametersif event_name == 'TOGGLE_SERVICE_ACCOUNT':service_account_status = next((p.get('value') for p in parametersif 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 parametersif 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
Section titled “Advanced Penetration Testing Insights”Credential Access and Authentication Bypass
Section titled “Credential Access and Authentication Bypass”Attack Methodology
Section titled “Attack Methodology”Sophisticated attackers target credential and authentication mechanisms:
-
Password Spraying Techniques
- Use distributed login attempts to avoid lockouts
- Target account enumeration to identify valid accounts
- Utilize common password patterns specific to organizations
-
Session Cookie Theft
- Target session cookies through XSS or client-side vulnerabilities
- Hijack authenticated sessions without credential theft
- Bypass MFA through authenticated session access
-
OAuth Token Theft
- Target refresh tokens stored on client devices
- Extract tokens from application storage
- Use stolen tokens for persistent API access
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
Advanced Authentication Hardening
Admin Console > Security > Authentication- Implement hardware key enforcement- Deploy risk-based authentication challenges- Enable strict session control policies -
Cookie Security Enhancement
- Implement secure and HTTP-only cookie flags
- Deploy anti-session hijacking mechanisms
- Configure appropriate session timeout values
-
Token Security Framework
- Implement token revocation monitoring
- Create risk-based token lifetime policies
- Deploy device posture checks for token issuance
Cross-Service Attack Vectors
Section titled “Cross-Service Attack Vectors”Attack Methodology
Section titled “Attack Methodology”Attackers exploit interconnections between Google services:
-
GCP-Workspace Pivoting
- Use Workspace compromise to access GCP resources
- Exploit shared authentication between services
- Leverage identity federation for privilege escalation
-
Workspace-Chrome Exploitation
- Target Chrome Sync to extract credentials
- Use malicious extensions for data access
- Exploit managed Chrome deployments for persistence
-
Google Meet/Chat Attack Surface
- Use meeting invitations for phishing
- Exploit chat functionality for malicious links
- Leverage file sharing for malware distribution
Defensive Countermeasures
Section titled “Defensive Countermeasures”-
Cross-Service Security Boundaries
- Implement strict separation between environments
- Deploy service-specific access policies
- Create identity boundaries between services
-
Chrome Security Hardening
Admin Console > Devices > Chrome > Settings- Implement Chrome extension restrictions- Configure secure sync settings- Deploy enhanced safe browsing protection -
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
Section titled “Penetration Testing Methodologies”Reconnaissance Techniques
Section titled “Reconnaissance Techniques”Understand common reconnaissance methods to strengthen defenses:
-
Email Enumeration Countermeasures
- Implement anti-harvesting measures
- Deploy CAPTCHA for repeated lookup attempts
- Monitor for suspicious directory access patterns
-
Public Document Exposure Control
Admin Console > Apps > Google Workspace > Drive and Docs- Audit publicly accessible documents- Implement default sharing restrictions- Deploy sensitive content controls -
Digital Footprint Reduction
- Conduct regular exposure assessments
- Implement information exposure policies
- Monitor for organization information leakage
Advanced Social Engineering Defenses
Section titled “Advanced Social Engineering Defenses”Counter sophisticated social engineering with enhanced controls:
-
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 -
User Awareness Enhancement
- Implement targeted phishing simulations
- Deploy just-in-time security training
- Create contextual security awareness resources
-
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”OAuth Phishing Attack Response
Section titled “OAuth Phishing Attack Response”-
Initial Assessment
- Identify compromised accounts and authorized applications
- Determine access scope and potential data exposure
- Review activity logs for suspicious actions
-
Containment Actions
Admin Console > Security > API Controls > App access control- Revoke suspicious application access- Block malicious client IDs- Reset passwords for affected users -
Recovery Process
- Conduct thorough access review
- Implement enhanced monitoring for affected users
- Deploy additional authentication requirements
Admin Account Compromise Response
Section titled “Admin Account Compromise Response”-
Initial Assessment
- Identify scope of administrative access
- Review admin audit logs for unauthorized actions
- Determine extent of configuration changes
-
Containment Actions
Admin Console > Account > Admin roles- Revoke compromised admin access- Reset super admin credentials- Implement IP restrictions for admin console -
Recovery Process
- Conduct comprehensive configuration review
- Restore from known-good configuration backups
- Implement enhanced logging and monitoring
Data Exfiltration Incident Response
Section titled “Data Exfiltration Incident Response”-
Initial Assessment
- Identify data access patterns and potentially exposed data
- Review sharing activity and external transfers
- Determine regulatory and compliance implications
-
Containment Actions
Admin Console > Security > Data protection- Block external sharing temporarily- Revoke suspicious sharing permissions- Disable data export capabilities -
Recovery Process
- Implement enhanced DLP controls
- Conduct data exposure assessment
- Deploy additional monitoring for sensitive data
Continuous Security Improvement Framework
Section titled “Continuous Security Improvement Framework”Penetration Testing Program
Section titled “Penetration Testing Program”Establish an ongoing penetration testing program:
-
Scope Definition
- Define clear testing boundaries
- Establish rules of engagement
- Create realistic attack scenarios
-
Authorized Testing Procedures
- Develop Google Workspace-specific testing methodologies
- Implement safe testing practices
- Create realistic simulation capabilities
-
Findings Remediation Process
- Establish severity classification system
- Implement remediation tracking
- Create verification testing procedures
Threat Intelligence Integration
Section titled “Threat Intelligence Integration”Leverage threat intelligence to enhance defenses:
-
Google Workspace Threat Feeds
- Subscribe to Google Cloud Threat Intelligence
- Implement industry-specific threat intelligence
- Create custom indicators for Google Workspace
-
Attack Pattern Analysis
- Document common Google Workspace attack patterns
- Develop detection rules for known tactics
- Create proactive hunting procedures
-
Security Control Validation
- Test defensive controls against known attack patterns
- Implement regular control validation
- Create continuous improvement framework
Resources for Security Testing
Section titled “Resources for Security Testing”- HackTricks Google Workspace Security Guide - Comprehensive pentesting information for Google Workspace
- HackTricks GWS Post-Exploitation Guide - Detailed post-exploitation techniques for Google Workspace
- HackTricks GWS Persistence Techniques - Advanced persistence methods for Google Workspace
- HackTricks Workspace Sync Attacks - Exploiting directory synchronization vulnerabilities
- HackTricks Google Platforms Phishing - Leveraging Google services for phishing attacks
- Google Workspace Security Configuration Validator
- Google Workspace Security Best Practices
- MITRE ATT&CK for Enterprise SaaS
- CISA Cloud Security Technical Reference Architecture
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.
Was this page useful?
Help us prioritize the next improvement.