Regain access to SQL Server via inject service

One way to regain access to SQL Server is to use a simple inject technique which overrides the current Image Path for the SQL Writer service.

#http://jongurgul.com/blog/regain-access-sql-server-inject-service
If(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
$You = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name;
$ImagePath = $(Get-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\SQLWriter" -Name ImagePath).ImagePath;
#"C:\Program Files\Microsoft SQL Server\90\Shared\sqlwriter.exe";
$SQLCMDPaths = $(Get-ChildItem -Path "C:\Program Files\Microsoft SQL Server\" -include SQLCMD.exe -Recurse | Select-Object FullName,Directory,@{Name="Version";Expression={$_.Directory.ToString().Split("\")[-3]}} | Sort-Object Version -Descending);
$SQLCMDPath = $SQLCMDPaths[0].FullName;
$SQLCMDPath;

If(Test-Path $SQLCMDPath){
$InjectedImagePath = "$SQLCMDPath -S . -E -Q `"CREATE LOGIN [$You] FROM WINDOWS;EXECUTE sp_addsrvrolemember @loginame = '$You', @rolename = 'sysadmin'`"";

#Stop SQLWriter
Get-Service -Name SQLWriter | Stop-Service -ea SilentlyContinue;

#Inject
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\SQLWriter" -Name ImagePath -Value $InjectedImagePath;
Write-Host $(Get-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\SQLWriter" -Name ImagePath).ImagePath;
Get-Service -Name SQLWriter | Start-Service -ea SilentlyContinue;

#Restore
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\SQLWriter" -Name ImagePath -Value $ImagePath;
Write-Host $(Get-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\SQLWriter" -Name ImagePath).ImagePath;

#Restart SQLWriter
Get-Service -Name SQLWriter | Start-Service -ea SilentlyContinue;
}Else{"Check SQLCMDPath";}

}Else{"Not Administrator"};

 

PsExec can alternatively be used to access SQL Server as shown in the post below. This relies on the NT AUTHORITY\SYSTEM account having been granted system administrator on the instance. This will be true for anything before SQL Server 2012.

Running as local system to allow administrators in to SQL Server

Additional notes:

 

“In SQL Server 2008 and later, the local Windows Group BUILTIN\Administrator is no longer provisioned as a login in the SQL Server sysadmin fixed server role by default at SQL Server setup install.
As a result, box administrators cannot login to the new SQL Server 2008 and SQL Server 2008 R2 instance by default.”

https://support.microsoft.com/en-gb/help/2184138/guidelines-on-granting-sql-server-sysadmin-privileges

 

 

In SQL Server 2012: “BUILTIN\administrators and Local System (NT AUTHORITY\SYSTEM) are not automatically provisioned in the sysadmin fixed server role.”

https://technet.microsoft.com/en-us/library/bb500459(v=sql.110).aspx

 

Leave a Reply