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.
| Control | Why | How to check | CIS / SCC |
|---|---|---|---|
| Never authorize 0.0.0.0/0 | Exposes the database to the internet | settings.ipConfiguration.authorizedNetworks | CIS 6.5, PUBLIC_SQL_INSTANCE |
| Use private IP or PSC, no public IP | Removes the internet path | ipAddresses[].type in describe | CIS 6.7, SQL_PUBLIC_IP |
| Require SSL/TLS | Stops plaintext credentials | settings.ipConfiguration.sslMode | CIS 6.4, SSL_NOT_ENFORCED |
| Enable IAM database authentication | No static database passwords | cloudsql.iam_authentication flag | CIS 6.6 |
| Enable automated backups and PITR | Recover from deletion or corruption | settings.backupConfiguration | CIS 6.8, AUTO_BACKUP_DISABLED |
| Enable deletion protection | Blocks accidental or malicious delete | settings.deletionProtectionEnabled | CIS 6.9 |
| Enable pgAudit on PostgreSQL | Records who ran which statement | cloudsql.enable_pgaudit flag | CIS 6.2.8 |
| Log PostgreSQL connections | Detect brute force and odd clients | log_connections, log_disconnections | CIS 6.2.2, CIS 6.2.3, SQL_LOG_CONNECTIONS_DISABLED |
Turn off MySQL local_infile | Blocks client file reads | local_infile flag | CIS 6.1.3, SQL_LOCAL_INFILE |
Turn off SQL Server external scripts enabled | Blocks code execution in the engine | external scripts enabled flag | CIS 6.3.1, SQL_EXTERNAL_SCRIPTS_ENABLED |
| Encrypt with CMEK for sensitive data | You control and can revoke the key | diskEncryptionConfiguration | SQL_CMEK_DISABLED |
| Require Cloud SQL connectors | Every connection is IAM-authorized | settings.connectorEnforcement | n/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(legacysql.restrictPublicIp): blocks public IP on new and updated instances.sql.managed.restrictAuthorizedNetworks(legacysql.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:
sslMode | Effect |
|---|---|
ALLOW_UNENCRYPTED_AND_ENCRYPTED | Accepts plaintext. Fails CIS 6.4. |
ENCRYPTED_ONLY | Requires TLS; client certificates not checked. |
TRUSTED_CLIENT_CERTIFICATE_REQUIRED | Requires 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):
| Flag | Value | CIS |
|---|---|---|
log_connections | on | 6.2.2 |
log_disconnections | on | 6.2.3 |
log_statement | ddl | 6.2.4 |
log_min_messages | warning or stricter | 6.2.5 |
log_min_error_statement | error or stricter | 6.2.6 |
log_min_duration_statement | -1 | 6.2.7 |
cloudsql.enable_pgaudit | on | 6.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.deletecloudsql.instances.exportandcloudsql.instances.clone(bulk data leaving the instance)cloudsql.users.createandcloudsql.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/0to authorized networks to connect from a laptop or a serverless runtime, instead of using the Auth Proxy. - Running
gcloud sql instances patch --database-flagswith only the new flag, which silently resets every other flag, including logging and pgAudit. - Setting
sslModetoENCRYPTED_ONLYwhile clients still connect withsslmode=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
- Configure private IP, Google Cloud documentation
- Configure SSL/TLS certificates, Google Cloud documentation
- Connect using the Cloud SQL Auth Proxy, Google Cloud documentation
- IAM authentication, Google Cloud documentation
- Audit PostgreSQL using pgAudit, Google Cloud documentation
- Prevent deletion of an instance, Google Cloud documentation
- Add predefined organization policies, Google Cloud documentation
- CIS Google Cloud Platform Foundation Benchmark, Center for Internet Security
- pgAudit, pgAudit project
- The pg_hba.conf file, PostgreSQL documentation
About the author
Florian AmetteSecurity engineer writing practical, benchmark-aligned guides to hardening Google Cloud organizations, projects and workloads.