Skip to content

10DataService 10 of 13

Cloud SQLsecurity hardening

Harden Cloud SQL: private IP or PSC, no 0.0.0.0/0 authorized networks, SSL mode, Auth Proxy, IAM database auth, engine flags, pgAudit, backups and CMEK.

Baseline
12 controls
Category
Data
Updated
Reading
9 min read

Cloud SQL runs managed MySQL, PostgreSQL and SQL Server instances. Google patches the engine and the host, but the exposure decisions are yours, and the defaults are permissive. A new instance gets a public IP unless you say otherwise, 0.0.0.0/0 is one click away in the authorized networks field (often added to "just get the app connected"), unencrypted connections are accepted, and the database password for the built-in postgres or root user ends up in a config file or environment variable. Internet scanners find exposed PostgreSQL and MySQL ports within hours, and credential stuffing against them is routine. The other common failure is quieter: an instance deleted by a misconfigured Terraform run or a compromised account, with backups that were deleted along with it. This page covers network exposure, connection security, authentication, engine flags, auditing, and recovery.

Baseline controls

Apply these to every instance; the CIS IDs refer to section 6 of the CIS GCP Foundations Benchmark v5.0.1.

ControlWhyHow to checkCIS / SCC
Never authorize 0.0.0.0/0Exposes the database to the internetsettings.ipConfiguration.authorizedNetworksCIS 6.5, PUBLIC_SQL_INSTANCE
Use private IP or PSC, no public IPRemoves the internet pathipAddresses[].type in describeCIS 6.7, SQL_PUBLIC_IP
Require SSL/TLSStops plaintext credentialssettings.ipConfiguration.sslModeCIS 6.4, SSL_NOT_ENFORCED
Enable IAM database authenticationNo static database passwordscloudsql.iam_authentication flagCIS 6.6
Enable automated backups and PITRRecover from deletion or corruptionsettings.backupConfigurationCIS 6.8, AUTO_BACKUP_DISABLED
Enable deletion protectionBlocks accidental or malicious deletesettings.deletionProtectionEnabledCIS 6.9
Enable pgAudit on PostgreSQLRecords who ran which statementcloudsql.enable_pgaudit flagCIS 6.2.8
Log PostgreSQL connectionsDetect brute force and odd clientslog_connections, log_disconnectionsCIS 6.2.2, CIS 6.2.3, SQL_LOG_CONNECTIONS_DISABLED
Turn off MySQL local_infileBlocks client file readslocal_infile flagCIS 6.1.3, SQL_LOCAL_INFILE
Turn off SQL Server external scripts enabledBlocks code execution in the engineexternal scripts enabled flagCIS 6.3.1, SQL_EXTERNAL_SCRIPTS_ENABLED
Encrypt with CMEK for sensitive dataYou control and can revoke the keydiskEncryptionConfigurationSQL_CMEK_DISABLED
Require Cloud SQL connectorsEvery connection is IAM-authorizedsettings.connectorEnforcementn/a

Network exposure: private IP, PSC and authorized networks

The best network setting is no public IP at all. Cloud SQL supports two private options:

  • Private IP (private services access): the instance gets an address in a range you allocate in your VPC, reached over VPC peering.
  • Private Service Connect (PSC): the instance is exposed through a PSC endpoint in each consumer VPC, with an explicit list of allowed projects. No peering, no overlapping range issues, and it works across organizations.

Create a PostgreSQL instance with private IP only:

gcloud sql instances create pg-prod \
  --project=prj-website-prod \
  --database-version=POSTGRES_16 \
  --region=europe-west1 \
  --tier=db-custom-2-8192 \
  --network=projects/prj-website-prod/global/networks/vpc-prod \
  --no-assign-ip \
  --ssl-mode=ENCRYPTED_ONLY \
  --deletion-protection \
  --backup-start-time=02:00 \
  --enable-point-in-time-recovery \
  --retained-backups-count=14 \
  --database-flags=cloudsql.iam_authentication=on,cloudsql.enable_pgaudit=on,log_connections=on,log_disconnections=on

Or with PSC:

gcloud sql instances create pg-prod \
  --project=prj-website-prod \
  --database-version=POSTGRES_16 \
  --region=europe-west1 \
  --tier=db-custom-2-8192 \
  --enable-private-service-connect \
  --allowed-psc-projects=prj-website-prod \
  --no-assign-ip

If an instance must keep a public IP (a legacy client outside Google Cloud), do not use authorized networks as the main control. Connect through the Cloud SQL Auth Proxy or a language connector, which authenticate with IAM and encrypt the connection without any authorized network entry. Find instances that authorize the whole internet:

gcloud sql instances list \
  --format="table(name,settings.ipConfiguration.ipv4Enabled,settings.ipConfiguration.authorizedNetworks[].value.list())" \
  --filter="settings.ipConfiguration.authorizedNetworks.value=0.0.0.0/0"

Remove them with gcloud sql instances patch INSTANCE --clear-authorized-networks, and remove the public IP with --no-assign-ip once a private path is in place.

Console: SQL > (instance) > Connections > Networking.

Enforce org-wide:

  • sql.managed.restrictPublicIp (legacy sql.restrictPublicIp): blocks public IP on new and updated instances.
  • sql.managed.restrictAuthorizedNetworks (legacy sql.restrictAuthorizedNetworks): blocks adding authorized networks.

Both are not retroactive: existing public IPs and authorized networks keep working until you remove them.

name: organizations/ORG_ID/policies/sql.managed.restrictPublicIp
spec:
  rules:
  - enforce: true
gcloud org-policies set-policy sql-restrict-public-ip.yaml

Connection security: SSL mode, Auth Proxy and connectors

The sslMode setting replaces the older requireSsl boolean (the --require-ssl flag still exists, but --ssl-mode is the current form). It has three values:

sslModeEffect
ALLOW_UNENCRYPTED_AND_ENCRYPTEDAccepts plaintext. Fails CIS 6.4.
ENCRYPTED_ONLYRequires TLS; client certificates not checked.
TRUSTED_CLIENT_CERTIFICATE_REQUIREDRequires TLS and a valid client certificate.
gcloud sql instances patch pg-prod --ssl-mode=ENCRYPTED_ONLY

ENCRYPTED_ONLY is the practical baseline. Client certificates add a second credential to distribute and rotate; most teams get better results from the connectors below.

The Cloud SQL Auth Proxy (cloud-sql-proxy) and the language connectors (Java, Python, Go, Node.js) open a TLS 1.3 connection authorized by IAM: the caller needs roles/cloudsql.client on the project. Connections through the proxy are encrypted regardless of the database's own TLS configuration. To make the connector the only way in, set connector enforcement:

gcloud sql instances patch pg-prod --connector-enforcement=REQUIRED

With REQUIRED, direct connections are refused and all existing authorized networks stop working, so check client inventory first. Run the proxy with --private-ip or --psc to use the private path.

Authentication: IAM database users

Built-in database users have static passwords that end up in config files, CI variables and laptops. IAM database authentication lets users, service accounts and Google Groups log in with short-lived OAuth tokens instead (CIS 6.6).

Enable the flag (it is cloudsql.iam_authentication on PostgreSQL and cloudsql_iam_authentication on MySQL; SQL Server does not support it):

gcloud sql instances patch pg-prod \
  --database-flags=cloudsql.iam_authentication=on,cloudsql.enable_pgaudit=on,log_connections=on,log_disconnections=on

Create IAM users and groups, and grant the login permission:

gcloud sql users create app-dba@example.com \
  --instance=pg-prod --type=cloud_iam_group

gcloud sql users create sa-api@prj-website-prod.iam \
  --instance=pg-prod --type=cloud_iam_service_account

gcloud projects add-iam-policy-binding prj-website-prod \
  --member="group:app-dba@example.com" \
  --role="roles/cloudsql.instanceUser"

For PostgreSQL service accounts, the database user name drops the .gserviceaccount.com suffix. IAM only lets the principal log in; grant database privileges with GRANT as usual. Applications connect with cloud-sql-proxy --auto-iam-authn INSTANCE_CONNECTION_NAME or the connector's automatic IAM option.

Keep the built-in superuser for break-glass only: set a long random password, store it in Secret Manager, and on MySQL make sure no user can connect as root from any host (CIS 6.1.1). Enable a password validation policy for any remaining built-in users with --password-policy-min-length and related flags.

Database flags per engine

Flags are set with --database-flags, and that flag replaces the whole list: any flag you omit is reset to its default. Always read the current list first:

gcloud sql instances describe pg-prod --format="json(settings.databaseFlags)"

Some flag changes restart the instance (including cloudsql.enable_pgaudit), so schedule them.

PostgreSQL (CIS 6.2):

FlagValueCIS
log_connectionson6.2.2
log_disconnectionson6.2.3
log_statementddl6.2.4
log_min_messageswarning or stricter6.2.5
log_min_error_statementerror or stricter6.2.6
log_min_duration_statement-16.2.7
cloudsql.enable_pgauditon6.2.8

MySQL (CIS 6.1): local_infile=off (6.1.3) stops LOAD DATA LOCAL from reading client files, and skip_show_database=on (6.1.2) hides database names from users without the privilege.

SQL Server (CIS 6.3): external scripts enabled=off, cross db ownership chaining=off, remote access=off, contained database authentication=off, trace flag 3625=on (masks some error details from non-admin users), and leave user connections and user options at their defaults.

Enforce flags with a custom organization policy constraint on sqladmin.googleapis.com/Instance, which can read resource.settings.databaseFlags. The same mechanism enforces deletion protection and SSL mode, shown in the next section.

pgAudit and MySQL database auditing

pgAudit records statement-level activity (who read or changed what) in Cloud Logging Data Access audit logs. After setting cloudsql.enable_pgaudit=on, create the extension and choose what to log:

CREATE EXTENSION IF NOT EXISTS pgaudit;
ALTER DATABASE app SET pgaudit.log = 'ddl, role, write';

You can also set pgaudit.log as an instance flag. Logging read on a busy database is expensive; start with ddl, role and write, and use object-level auditing (pgaudit.role) for the tables that hold personal or payment data.

For MySQL, set cloudsql_mysql_audit=ON and define audit rules with the mysql.cloudsql_create_audit_rule stored procedure. For SQL Server, configure SQL Server Audit to write to a Cloud Storage bucket (--audit-bucket-path).

Data Access audit logs must be enabled for cloudsql.googleapis.com for these entries to be stored. See Cloud Audit Logs and Cloud Logging.

Backups, PITR and deletion protection

Enable automated backups and point-in-time recovery (on PostgreSQL --enable-point-in-time-recovery, on MySQL --enable-bin-log), and keep enough retention to cover the time it takes you to notice a problem:

gcloud sql instances patch pg-prod \
  --backup-start-time=02:00 \
  --retained-backups-count=14 \
  --enable-point-in-time-recovery \
  --retained-transaction-log-days=7 \
  --deletion-protection \
  --retain-backups-on-delete \
  --final-backup --final-backup-retention-days=30

Deletion protection (CIS 6.9) blocks instances.delete until someone removes the flag, which is itself an audited change. Retaining backups on delete and taking a final backup mean an instance deletion is no longer also a data deletion. For stronger isolation, enhanced backups through Backup and DR keep backups in a separate vault project.

Enforce with a custom constraint:

name: organizations/ORG_ID/customConstraints/custom.sqlRequireDeletionProtection
resourceTypes:
- sqladmin.googleapis.com/Instance
methodTypes:
- CREATE
- UPDATE
condition: "resource.settings.deletionProtectionEnabled == true && resource.settings.ipConfiguration.sslMode != 'ALLOW_UNENCRYPTED_AND_ENCRYPTED'"
actionType: ALLOW
displayName: Require deletion protection and SSL on Cloud SQL
gcloud org-policies set-custom-constraint sql-deletion-protection.yaml

Then enforce custom.sqlRequireDeletionProtection with a policy file as above.

Encryption with CMEK

Cloud SQL encrypts data at rest by default. For regulated data, use a Cloud KMS key in the same region as the instance. CMEK can only be set at creation:

gcloud beta services identity create --service=sqladmin.googleapis.com --project=prj-website-prod

gcloud kms keys add-iam-policy-binding k-sql-prod \
  --keyring=kr-sql --location=europe-west1 --project=prj-kms-prod \
  --member="serviceAccount:service-PROJECT_NUMBER@gcp-sa-cloud-sql.iam.gserviceaccount.com" \
  --role="roles/cloudkms.cryptoKeyEncrypterDecrypter"

gcloud sql instances create pg-sensitive \
  --database-version=POSTGRES_16 --region=europe-west1 --tier=db-custom-2-8192 \
  --network=projects/prj-website-prod/global/networks/vpc-prod --no-assign-ip \
  --disk-encryption-key=projects/prj-kms-prod/locations/europe-west1/keyRings/kr-sql/cryptoKeys/k-sql-prod

Backups, replicas and clones use the same key. Disabling or destroying the key version makes the instance unavailable, which is the point, so protect the key with the same care as the data. Require CMEK with gcp.restrictNonCmekServices listing sqladmin.googleapis.com.

Logging and detection

Admin Activity logs record every configuration change. Alert on changes that weaken exposure or recovery:

  • cloudsql.instances.update (authorized networks, public IP, SSL mode, flags, deletion protection)
  • cloudsql.instances.delete, cloudsql.backupRuns.delete
  • cloudsql.instances.export and cloudsql.instances.clone (bulk data leaving the instance)
  • cloudsql.users.create and cloudsql.users.update (new logins, password changes)

A log-based metric filter:

resource.type="cloudsql_database"
logName:"cloudaudit.googleapis.com%2Factivity"
protoPayload.methodName=("cloudsql.instances.update" OR "cloudsql.instances.delete" OR "cloudsql.instances.export" OR "cloudsql.users.update" OR "cloudsql.backupRuns.delete")

pgAudit entries for a project:

resource.type="cloudsql_database"
logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Fdata_access"
protoPayload.request.@type="type.googleapis.com/google.cloud.sql.audit.v1.PgAuditEntry"

Engine logs (cloudsql.googleapis.com/postgres.log, mysql.err) carry failed logins from log_connections; a spike of authentication failures from one source is worth an alert. In Security Command Center, Security Health Analytics reports the findings in the baseline table, and Event Threat Detection reports Cloud SQL exfiltration and privilege grant patterns.

Common mistakes

  • Adding 0.0.0.0/0 to authorized networks to connect from a laptop or a serverless runtime, instead of using the Auth Proxy.
  • Running gcloud sql instances patch --database-flags with only the new flag, which silently resets every other flag, including logging and pgAudit.
  • Setting sslMode to ENCRYPTED_ONLY while clients still connect with sslmode=disable, then reverting under pressure. Move clients to connectors first.
  • Enabling the IAM authentication flag but leaving the application on a built-in user with a password in an environment variable.
  • Relying on automated backups alone: without --retain-backups-on-delete, deleting the instance deletes its automated backups too.
  • Enabling pgAudit without enabling Data Access logs for Cloud SQL, so nothing is stored.

References

About the author

Security engineer writing practical, benchmark-aligned guides to hardening Google Cloud organizations, projects and workloads.

Related services

All services