ENGINEERING NOTE / 14 SQL SERVERPRODUCTION FORENSICS
The Database Moved Hosts. Its Service Master Key Couldn't Follow.
An upgrade on RDS Custom moved a SQL Server to a new host. The databases came up, master came with them, and the key that protects every stored secret was still there. It just could not be opened any more, because what protected it had stayed behind on the old machine.
TABLE OF CONTENTS
This one comes from a multi-tenant SQL Server on Amazon RDS Custom: one
instance, a separate database per tenant, thousands of them. RDS Custom is
the variant of RDS that gives you the Windows host. You get remote access to
the operating system and to sysadmin, and AWS still runs backups,
monitoring and host replacement for you. That arrangement is the reason this
failure can happen at all.
During a production upgrade, RDS Custom replaced the host. Afterwards the
instance was available, every database was online and the application was
fine. The backup jobs were not.
What failed, and what it looked like§
There were two symptoms. Which one shows up depends on whether the backup credential still exists:
native backup to S3: Msg 33094 An error occurred during Service Master Key decryption maintenance backup jobs (every few minutes): The value for the parameter @Credential is not supported
The first means the credential is there but its secret cannot be decrypted. The second means the job refers to a credential that is not there, for example because it was dropped and recreation failed. Neither one says “your host changed”, and neither one is about S3.
The real damage was slower and quieter than either error. The log backups
were failing as well, and in the full recovery model a transaction log cannot
be truncated until it has been backed up. Across thousands of tenant
databases, sys.databases started reporting the same reason for keeping log:
SELECT log_reuse_wait_desc, COUNT(*) AS databases
FROM sys.databases
GROUP BY log_reuse_wait_desc
ORDER BY databases DESC;
-- LOG_BACKUP, for most of the instance
That is not an outage yet. It is log files growing on every database at once, on volumes that were sized for a working backup chain. It is also a recovery point that gets older every minute. The fix has a deadline, and the deadline is disk space.
What the Service Master Key is, exactly§
The fault only makes sense with the key hierarchy written out. SQL Server encrypts secrets in layers:
-
01 DPAPI
Windows Data Protection API. It protects the Service Master Key using the SQL Server service account credentials and the machine key of the host.
-
02 SMK
Service Master Key. One per instance, created on first start, stored in master. It encrypts server-level secrets: credential secrets, linked server passwords, and the copy of each database master key that lets the database open it without a password.
-
03 DMK
Database master key. One per database, optional. Always encrypted by a password; usually also encrypted by the SMK so it opens automatically.
-
04 SECRETS CONFIRMED
Database-scoped credentials, certificates and keys inside that database, protected by its DMK.
The detail that matters is where each layer is stored. The SMK lives in
master, so it travels with the data. What decrypts it does not travel:
DPAPI is tied to the Windows installation it runs on. The SMK is stored
twice, once protected with the service account’s credentials and once with
the local machine key, so that SQL Server can still open it if one of those
changes.
A host replacement on RDS Custom moves the volumes, master included, to a
new EC2 instance. That instance has a new DPAPI machine key. On this instance
neither protected copy could be opened on the new host. Msg 33094 is SQL
Server reporting exactly that: the key is present and cannot be decrypted.
Upgrades, host replacements and some failovers can all do this. On this system it was not a one-off. It is now documented as a recurring consequence of how the platform replaces hosts.
Proving it in ten seconds§
The S3 error points at backups, S3, IAM and networking before it points at encryption. The fastest way to remove all of those is a test that involves none of them. Creating a credential needs the SMK, because SQL Server has to encrypt the new secret with it. So create one and drop it:
CREATE CREDENTIAL smk_probe
WITH IDENTITY = N'probe', SECRET = N'not-a-secret';
DROP CREDENTIAL smk_probe;
If that succeeds, the SMK is fine and the problem is somewhere else. If it fails with a Service Master Key error, the key hierarchy is broken at the top, and fixing backups means fixing that first.
The fix that destroys things§
The repair is one statement:
ALTER SERVICE MASTER KEY FORCE REGENERATE;
REGENERATE without FORCE makes a new SMK, decrypts everything the old
one protected and re-encrypts it under the new one. That cannot work here,
because the old one cannot be decrypted, so it fails. FORCE generates the
new key anyway and accepts the loss. Anything that was encrypted only by the
old SMK becomes unreadable: credential secrets, linked server passwords, and
the SMK-protected copies of database master keys.
That last item is the one that can hurt. A DMK is always encrypted by a
password as well. If that password is known, the database can open its key
again and have it re-protected by the new SMK. If nobody knows it, the
SMK copy was the only way in. After FORCE, whatever that DMK protects is
gone.
So before running it, I listed everything that depended on the old key:
-- server-level secrets protected by the SMK
SELECT name, credential_identity FROM sys.credentials;
SELECT s.name, l.remote_name
FROM sys.linked_logins AS l
JOIN sys.servers AS s ON s.server_id = l.server_id
WHERE l.uses_self_credential = 0;
-- databases whose master key opens through the SMK
SELECT name
FROM sys.databases
WHERE is_master_key_encrypted_by_server = 1;
-- then, in each of those: SELECT * FROM sys.database_scoped_credentials;
The list was not empty. Roughly 420 tenant databases had a database master key and a database-scoped credential, both left over from an earlier migration onto this platform, for an audit-to-blob feature of the previous one. Nothing on the current platform used them. Losing the automatic opening of those DMKs cost nothing, but that was a conclusion I reached by checking each one, not something I assumed.
The order that worked§
-
01 SPACE
Check free disk and the log backlog first. LOG_BACKUP across the instance sets the deadline for everything else.
-
02 DEPENDENTS
List every credential, linked login and SMK-protected database master key. Confirm each one is recreatable or unused.
-
03 REGENERATE
ALTER SERVICE MASTER KEY FORCE REGENERATE.
-
04 RECREATE
Recreate the backup credential from the secrets store it is provisioned from. The secret never passes through a script or a ticket.
-
05 DRAIN CONFIRMED
Restart the log backup job and watch log_reuse_wait_desc move off LOG_BACKUP, database by database.
The last step is the one to watch, not to assume. The first log backup of each database after a long gap is the biggest, and thousands of them queued behind one job take time. The incident is over when the backlog has drained, not when the credential exists again.
The other thing the move broke§
The same host replacement also stopped SQL Server Agent from starting:
Failed to initialize SQL Agent log ... path not found
Agent keeps the path of its own error log as a setting, ErrorLogFile,
outside the databases. It still pointed to a folder that did not exist on
the new host. The fix was to point it at the engine’s current LOG folder
(msdb.dbo.sp_set_sqlagent_properties @errorlog_file = ... writes the same
setting) and start Agent again. It is a small fix, but on this instance the
Agent runs every backup job. While it was down, the backups would have
stayed stopped even after the key was fixed.
Both failures have the same cause. Something tied to the old machine was missing on the new one. In one case it was a DPAPI machine key, in the other a folder path.
What the pipeline should do instead§
The credential and the maintenance jobs are created by an infrastructure pipeline, and several improvements are still open:
- Fail loudly. A SQL step that cannot create the credential has to stop
the build. With
sqlcmd, that means-b; without it, an error is printed and the build carries on as if it had worked. - Find the right host on Multi-AZ. The lookup that finds the current primary has to be robust to the hosts having changed underneath it.
- Regenerate on the event, with guards. A host replacement is an event the platform reports. The response can be automated: run the probe, and only if it fails, check for dependents. Regenerate only if that check is clean, then recreate the credential. If it is not clean, stop and page a human.
The same platform, patched by hand§
The second lesson from this instance is also about the parts of the host that AWS does not manage for you.
RDS Custom engine images can be behind on Windows security updates. The current image had been built on an earlier Windows image and did not have that month’s updates. Patching it means doing what the platform would normally do, while making sure the platform does not interfere.
-
01 PREFLIGHT
Instance available, every database online, both hosts reachable, which named updates are missing. Take a snapshot.
-
02 PAUSE
Pause RDS Custom automation, with an automatic resume as a safety net.
-
03 STANDBY
Install only the named updates on the standby host, reboot it, prove it rebooted, verify the updates.
-
04 FAILOVER
Resume automation and force a failover. The patched host becomes primary; this is the only outage.
-
05 OLD PRIMARY CONFIRMED
Check SQL health on the new primary. Pause again, patch and reboot the old primary, now the standby. Resume.
That sounds routine. The details are where it goes wrong, and each one ended up as a check in the script that runs it.
Automation has to be paused, and staying paused is a process. A paused
instance reports automation-paused, never available, so the standard
“wait until available” call cannot be used while it is paused. The pause
also expires on its own. The automatic resume is a safety net, between
150 and 1,440 minutes, 180 by default. The floor of 150 exists because one
host can need about 30 minutes to scan, 90 to install and 30 to reboot and
verify. Before every long step, the script reads how much of the pause is
left and extends it if needed. Every prompt shown while automation is paused
times out after 15 minutes, so nobody can leave a production instance paused
by walking away from a terminal.
The backup window blocks the pause. Automation cannot be paused during
the backup window or while the instance is backing-up. The preflight
stops before changing anything if the status is anything other than
available, so a run started inside the window has to be started again
after it.
The failover is followed by a backup. After a forced failover, RDS
usually starts a backup straight away. On this instance it stayed in
backing-up for about 70 minutes, longer than the 30-minute limit of the
standard AWS waiter. So the script waits 30 minutes normally, and up to two
hours once it has seen backing-up. If that still runs out, it reports the
true state: the failover happened, the patched host is primary, and the old
primary is still unpatched. Running it again patches that host as the
standby, with no second failover.
Install exactly what was asked for. Only the named updates are installed, never “everything available”. Windows Update services that the image ships disabled are enabled for the run and put back as they were afterwards. If Windows Update declines an update on the standby, usually because a later cumulative update has superseded it, the primary runs the same build and will decline it too. A failover whose only purpose would be to retry that update is refused.
A reboot has to be proven. An EC2 instance stays running while it
reboots, so its state proves nothing. The script compares the Windows boot
time before and after, then reads the installed updates on the host.
A dry run is still a production action. The check-only mode changes nothing, but it still runs commands on the production hosts. So the DBA runs it, and an agent or a scheduler does not.
None of that is specific to patching. It is the same lesson as the Service Master Key: on RDS Custom, the host is yours, and so is everything the platform does not know you changed on it.
What carries over§
The general version of this is not about RDS Custom. Some state in a SQL
Server instance depends on the machine it runs on, and anything that moves a
database to new hardware without SQL Server’s involvement can break that
dependency. That includes restores of master, rebuilt VMs and managed
host replacements.
- Know which of your secrets depend on the SMK, and keep a list. The queries above are the list.
- Back up the Service Master Key where the platform allows it, so a
restore is an option and
FORCEis not the only one. - Keep DMK passwords for any database master key you want to keep. The SMK copy is a convenience, not a backup.
- Probe with a dummy credential after any host change, before the backup jobs find the problem for you.
- Watch
log_reuse_wait_desc, not just job outcomes. A failing log backup chain shows up there as log growth risk before it shows up as a full disk.
Failover protects the instance. It does not cover everything around it, which is also the theme of the note on CDC jobs after an Availability Group failover. The Service Master Key is another example. The data moved and was intact. The host-specific protection around its key did not move with it.