Introduction to Service Account Security
In the world of the GCP Professional Cloud Security Engineer (PSE), service accounts (SAs) are the most powerful and often the most vulnerable identities. Unlike human users, service accounts don't have eyes to see a phishing link or a voice to report a lost credential. They are the workhorses of automation, and if mismanaged, they become a silent backdoor for attackers.
Hardening service accounts requires a shift from "static credentials" (JSON keys) to "dynamic identity" (impersonation and short-lived tokens). This topic covers the lifecycle management, security pitfalls, and advanced hardening techniques for non-human identities.
白話文解釋(Plain English Explanation)
1. The Autonomous Delivery Drone (Service Account)
Imagine an autonomous drone that delivers packages. It doesn't have a pilot (human). It has a set of pre-programmed instructions and a digital ID that tells the warehouse it's allowed to pick up specific boxes. If the drone is stolen (compromised), it continues to perform its tasks until its ID is revoked.
2. The Valet Key (Service Account Impersonation)
When you give your car to a valet, you don't give them your master key which can open the trunk and glove box. You give them a "valet key" that only starts the car and moves it to the lot. Service Account Impersonation is like the car owner (User) temporarily using the valet key's identity to move the car, rather than carrying the key around physically.
3. The Self-Destructing Message (Short-lived Credentials)
Think of a mission-critical password that only works for 60 minutes and then automatically changes. Even if an attacker steals it at minute 59, they only have 60 seconds of access. This is the power of Short-lived Credentials over static JSON keys.
Types of Service Accounts
Understanding the difference between who manages the account is vital for security auditing.
User-Managed Service Accounts
Created by you within a project.
- Naming:
[email protected]. - Control: You manage the keys and IAM roles.
Google-Managed Service Accounts
Created and managed by Google to allow services to interact with each other.
- Naming:
[email protected]or service-specific like[email protected]. - Control: You cannot create keys for these; Google handles rotation.
A Service Account is a special type of Google account intended to represent a non-human user that needs to authenticate and be authorized to access data in Google APIs.
Managing and Rotating Service Account Keys
JSON keys are a major security risk. If you must use them, rotation is mandatory.
The Dangers of Static Keys
- No MFA: Keys bypass multi-factor authentication.
- Hard to Track: Once downloaded, you don't know where the key is stored (GitHub, Slack, local drive).
- Infinite Life: By default, keys are valid for 10 years.
Key Rotation Strategy
- Automate: Use Cloud Functions to rotate keys every 90 days.
- Overlap: Generate a new key, update the application, and then delete the old key after a cooling-off period.
The PSE recommendation is to eliminate keys entirely in favor of Workload Identity or Impersonation.
Service Account Impersonation
Impersonation allows a principal (User or another SA) to act as a target Service Account without needing a key.
How it Works
A user requests a short-lived OAuth 2.0 access token for the service account.
- Required Permission:
iam.serviceAccounts.getAccessToken. - Role:
roles/iam.serviceAccountTokenCreator.
Benefits
- No Secret Management: No JSON files to leak.
- Auditability: Logs show exactly who requested the token to impersonate the SA.
For on-premises or multi-cloud workloads, PSE scenarios expect Workload Identity Federation over downloaded JSON keys: the external workload presents an OIDC or SAML token, and the GCP Security Token Service (STS) exchanges it for a short-lived OAuth 2.0 access token bound to roles/iam.serviceAccountTokenCreator. Combined with the iam.disableServiceAccountKeyCreation org policy, this delivers a keyless architecture that the exam consistently picks over rotated JSON keys.
Hardening Service Account Permissions
Apply the Principle of Least Privilege (PoLP) rigorously.
Common Pitfalls
- Using Default SAs: The "Compute Engine Default Service Account" is granted the "Editor" role by default. This is a massive security hole.
- Over-Scoping: Granting
roles/storage.adminwhen the SA only needs to read one file.
Best Practices
- Disable Default SAs: Always create custom SAs for your VMs.
- Grant Resource-Level Access: Bind the SA role to a specific bucket or dataset, not the whole project.
Service Account User vs. Token Creator
These two roles are frequently confused on the PSE exam.
- Service Account User (
roles/iam.serviceAccountUser): Allows a user to attach a service account to a resource (like a VM or a Cloud Function). It does not allow them to generate tokens directly. - Service Account Token Creator (
roles/iam.serviceAccountTokenCreator): Allows a user to impersonate the account and generate tokens. This is a much higher-privilege role.
Granting serviceAccountUser to a developer allows them to run code as that SA on a VM, effectively giving them all the SA's permissions.
Disabling Service Account Key Creation
To enforce security, you can prevent users from creating keys at the Organization level.
Organization Policy Constraints
iam.disableServiceAccountKeyCreation: Prevents anyone from creating new JSON keys.iam.disableServiceAccountKeyUpload: Prevents users from uploading external keys to Google Cloud.
Enforce these constraints for all production projects to force developers to use Impersonation or Workload Identity.
Auditing Service Account Usage
Who is using the SA?
Enable Data Access Audit Logs for IAM. This will record every time a token is generated or a key is used.
The Service Account Recommender
Like the IAM Recommender, this tool identifies SAs that haven't been used in 90 days and suggests disabling or deleting them.
Cross-Project Service Account Access
SAs can be granted roles in projects other than the one where they were created.
- Centralized Identity: Create all SAs in a "Security-Hub" project and grant them roles in "Prod" projects.
- Trust Boundary: Be careful! A compromise in the "Security-Hub" could affect all projects.
Default Service Accounts and Their Risks
Compute Engine Default SA
- Role: Editor (by default).
- Risk: Any user with "Compute Instance Admin" can create a VM, attach this SA, and become an Editor of the whole project.
App Engine Default SA
- Role: Editor.
- Hardening: Switch to a custom SA with minimal permissions.
CLI Commands for Service Account Management
Creating a Service Account
gcloud iam service-accounts create my-hardened-sa \
--display-name="Production Web Server SA"
Granting Impersonation Access
gcloud iam service-accounts add-iam-policy-binding \
[email protected] \
--member="user:[email protected]" \
--role="roles/iam.serviceAccountTokenCreator"
Listing Keys (To find old ones)
gcloud iam service-accounts keys list \
[email protected]
The iam.serviceAccounts.actAs permission is part of the roles/iam.serviceAccountUser role and is required to deploy resources that use a service account.
Security Best Practices for PSE
- Delete Default SAs: If you can't delete them, strip their roles.
- Use Workload Identity for GKE: Never mount JSON keys into pods.
- Audit Monthly: Identify SAs with keys older than 90 days.
- Prefer Identity over Scopes: Don't rely on "Access Scopes" (the legacy method for VM permissions); use IAM roles.
Troubleshooting Scenarios
Scenario: A developer can't deploy a Cloud Function.
Diagnosis: The developer has "Cloud Functions Developer" but lacks iam.serviceAccounts.actAs on the runtime service account.
Fix: Grant the roles/iam.serviceAccountUser role to the developer for that specific service account.
Scenario: A Service Account key was found on a public GitHub repo.
Diagnosis: Immediate compromise. Fix:
- Delete the key in the Google Cloud Console.
- Revoke all active sessions.
- Audit the logs for any actions taken by that SA in the last 24 hours.
- Rotate any secrets the SA had access to (e.g., DB passwords).
PSE Exam Scenarios
Scenario 1: Keyless Architecture
"Your company wants to move to a zero-trust architecture where no static credentials are stored on disk. How do you authenticate on-premises servers to BigQuery?" Answer: Use Workload Identity Federation to exchange on-premises OIDC/SAML tokens for Google Cloud short-lived tokens.
Scenario 2: Restricting SA Creation
"How can you ensure that only the Security Team can create service accounts in the entire organization?"
Answer: Set an Organization Policy to restrict service account creation and remove the roles/iam.serviceAccountAdmin role from all other users.
FAQ
Q1: What is the maximum number of Service Accounts per project? A1: 100 by default (can be increased via quota request).
Q2: Can I recover a deleted Service Account key? A2: No. Once a key is deleted, it is gone forever. You must generate a new one.
Q3: Does a Service Account have a password? A3: No. It uses RSA key pairs (JSON keys) or tokens for authentication.
Summary Checklist
- List the risks of using Default Service Accounts.
- Explain the difference between
Service Account UserandToken Creator. - Describe the process of SA Impersonation.
- Identify two Organization Policies that help harden service accounts.
- Explain why short-lived credentials are superior to JSON keys.