-
Notifications
You must be signed in to change notification settings - Fork 227
SqlReplication: Fix T-SQL string escaping #2445
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
6994487
SqlReplication: Add T-SQL string escaping functions
johlju e6b7ead
Fix formatting in ConvertTo-EscapedQueryString function and improve v…
johlju aa2197b
Update CHANGELOG to reflect added T-SQL string escaping functions and…
johlju d597e91
Fix output type formatting in ConvertTo-SqlString function documentation
johlju File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| <# | ||
| .SYNOPSIS | ||
| Formats a query string with escaped values to prevent SQL injection. | ||
|
|
||
| .DESCRIPTION | ||
| This function formats a query string with placeholders using provided | ||
| arguments. Each argument is escaped by doubling single quotes to prevent | ||
| SQL injection vulnerabilities. This is the standard escaping mechanism | ||
| for SQL Server string literals. | ||
|
|
||
| The function takes a format string with standard PowerShell format | ||
| placeholders (e.g., {0}, {1}) and an array of arguments to substitute | ||
| into those placeholders. Each argument is escaped before substitution. | ||
|
|
||
| .PARAMETER Query | ||
| Specifies the query string containing format placeholders (e.g., {0}, {1}). | ||
| The placeholders will be replaced with the escaped values from the | ||
| Argument parameter. | ||
|
|
||
| .PARAMETER Argument | ||
| Specifies an array of strings that will be used to format the query string. | ||
| Each string will have single quotes escaped by doubling them before being | ||
| substituted into the query. | ||
|
|
||
| .EXAMPLE | ||
| ConvertTo-EscapedQueryString -Query "SELECT * FROM Users WHERE Name = N'{0}'" -Argument "O'Brien" | ||
|
|
||
| Returns: SELECT * FROM Users WHERE Name = N'O''Brien' | ||
|
|
||
| .EXAMPLE | ||
| ConvertTo-EscapedQueryString -Query "EXECUTE sys.sp_adddistributor @distributor = N'{0}', @password = N'{1}';" -Argument 'Server1', "Pass'word;123" | ||
|
|
||
| Returns: EXECUTE sys.sp_adddistributor @distributor = N'Server1', @password = N'Pass''word;123'; | ||
|
|
||
| .INPUTS | ||
| None. | ||
|
|
||
| .OUTPUTS | ||
| `System.String` | ||
|
|
||
| Returns the formatted query string with escaped values. | ||
|
johlju marked this conversation as resolved.
|
||
|
|
||
| .NOTES | ||
| This function escapes single quotes by doubling them, which is the | ||
| standard SQL Server escaping mechanism for string literals. This helps | ||
| prevent SQL injection when embedding values in dynamic T-SQL queries. | ||
| #> | ||
| function ConvertTo-EscapedQueryString | ||
| { | ||
| [CmdletBinding()] | ||
| [OutputType([System.String])] | ||
| param | ||
| ( | ||
| [Parameter(Mandatory = $true)] | ||
| [System.String] | ||
| $Query, | ||
|
|
||
| [Parameter(Mandatory = $true)] | ||
| [AllowEmptyString()] | ||
| [System.String[]] | ||
| $Argument | ||
| ) | ||
|
|
||
| $escapedArguments = @() | ||
|
|
||
| foreach ($currentArgument in $Argument) | ||
| { | ||
| $escapedArguments += ConvertTo-SqlString -Text $currentArgument | ||
| } | ||
|
|
||
| $result = $Query -f $escapedArguments | ||
|
|
||
| return $result | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| <# | ||
| .SYNOPSIS | ||
| Escapes a string for use in a T-SQL string literal. | ||
|
|
||
| .DESCRIPTION | ||
| This function escapes a string for safe use in T-SQL string literals by | ||
| doubling single quotes. This is the standard SQL Server escaping mechanism | ||
| for preventing SQL injection when embedding values in dynamic T-SQL queries. | ||
|
|
||
| Use this function when you need to escape a value that will also be used | ||
| elsewhere (e.g., for redaction), ensuring the escaped value matches what | ||
| appears in the final query. | ||
|
|
||
| .PARAMETER Text | ||
| Specifies the text string to escape for T-SQL. | ||
|
|
||
| .EXAMPLE | ||
| ConvertTo-SqlString -Text "O'Brien" | ||
|
|
||
| Returns: O''Brien | ||
|
|
||
| .EXAMPLE | ||
| ConvertTo-SqlString -Text "Pass'word;123" | ||
|
|
||
| Returns: Pass''word;123 | ||
|
|
||
| .EXAMPLE | ||
| $escapedPassword = ConvertTo-SqlString -Text $password | ||
| $query = "EXECUTE sys.sp_adddistributor @password = N'$escapedPassword';" | ||
| Invoke-SqlDscQuery -Query $query -RedactText $escapedPassword | ||
|
|
||
| Escapes the password and uses the same escaped value for both the query | ||
| and the RedactText parameter to ensure proper redaction. | ||
|
|
||
| .INPUTS | ||
| None. | ||
|
|
||
| .OUTPUTS | ||
| `System.String` | ||
|
|
||
| Returns the escaped string with single quotes doubled. | ||
|
johlju marked this conversation as resolved.
|
||
|
|
||
| .NOTES | ||
| This function only escapes single quotes by doubling them. This is | ||
| sufficient for SQL Server string literals enclosed in single quotes. | ||
| #> | ||
| function ConvertTo-SqlString | ||
| { | ||
| [CmdletBinding()] | ||
| [OutputType([System.String])] | ||
| param | ||
| ( | ||
| [Parameter(Mandatory = $true)] | ||
| [AllowEmptyString()] | ||
| [System.String] | ||
| $Text | ||
| ) | ||
|
|
||
| $escapedText = $Text -replace "'", "''" | ||
|
|
||
| return $escapedText | ||
| } | ||
133 changes: 133 additions & 0 deletions
133
tests/Unit/Private/ConvertTo-EscapedQueryString.Tests.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] | ||
| param () | ||
|
|
||
| BeforeDiscovery { | ||
| try | ||
| { | ||
| if (-not (Get-Module -Name 'DscResource.Test')) | ||
| { | ||
| # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. | ||
| if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) | ||
| { | ||
| # Redirect all streams to $null, except the error stream (stream 2) | ||
| & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null | ||
| } | ||
|
|
||
| # If the dependencies have not been resolved, this will throw an error. | ||
| Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' | ||
| } | ||
| } | ||
| catch [System.IO.FileNotFoundException] | ||
| { | ||
| throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' | ||
| } | ||
| } | ||
|
|
||
| BeforeAll { | ||
| $script:moduleName = 'SqlServerDsc' | ||
|
|
||
| $env:SqlServerDscCI = $true | ||
|
|
||
| Import-Module -Name $script:moduleName -ErrorAction 'Stop' | ||
|
|
||
| $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName | ||
| $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName | ||
| $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName | ||
| } | ||
|
|
||
| AfterAll { | ||
| $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') | ||
| $PSDefaultParameterValues.Remove('Mock:ModuleName') | ||
| $PSDefaultParameterValues.Remove('Should:ModuleName') | ||
|
|
||
| Remove-Item -Path 'env:SqlServerDscCI' | ||
| } | ||
|
|
||
| Describe 'ConvertTo-EscapedQueryString' -Tag 'Private' { | ||
| Context 'When escaping single quotes in query arguments' { | ||
| It 'Should escape a single quote in an argument' { | ||
| InModuleScope -ScriptBlock { | ||
| Set-StrictMode -Version 1.0 | ||
|
|
||
| $result = ConvertTo-EscapedQueryString -Query "SELECT * FROM Users WHERE Name = N'{0}'" -Argument "O'Brien" | ||
|
|
||
| $result | Should -Be "SELECT * FROM Users WHERE Name = N'O''Brien'" | ||
| } | ||
| } | ||
|
|
||
| It 'Should escape multiple single quotes in an argument' { | ||
| InModuleScope -ScriptBlock { | ||
| Set-StrictMode -Version 1.0 | ||
|
|
||
| $result = ConvertTo-EscapedQueryString -Query "SELECT * FROM Users WHERE Name = N'{0}'" -Argument "O'Brien's" | ||
|
|
||
| $result | Should -Be "SELECT * FROM Users WHERE Name = N'O''Brien''s'" | ||
| } | ||
| } | ||
|
|
||
| It 'Should handle arguments without single quotes' { | ||
| InModuleScope -ScriptBlock { | ||
| Set-StrictMode -Version 1.0 | ||
|
|
||
| $result = ConvertTo-EscapedQueryString -Query "SELECT * FROM Users WHERE Name = N'{0}'" -Argument 'Smith' | ||
|
|
||
| $result | Should -Be "SELECT * FROM Users WHERE Name = N'Smith'" | ||
| } | ||
| } | ||
| } | ||
|
|
||
| Context 'When formatting a query with multiple arguments' { | ||
| It 'Should escape single quotes in all arguments' { | ||
| InModuleScope -ScriptBlock { | ||
| Set-StrictMode -Version 1.0 | ||
|
|
||
| $result = ConvertTo-EscapedQueryString -Query "EXECUTE sys.sp_adddistributor @distributor = N'{0}', @password = N'{1}';" -Argument 'Server1', "Pass'word;123" | ||
|
|
||
| $result | Should -Be "EXECUTE sys.sp_adddistributor @distributor = N'Server1', @password = N'Pass''word;123';" | ||
| } | ||
| } | ||
|
|
||
| It 'Should handle multiple arguments with single quotes' { | ||
| InModuleScope -ScriptBlock { | ||
| Set-StrictMode -Version 1.0 | ||
|
|
||
| $result = ConvertTo-EscapedQueryString -Query "INSERT INTO Users (FirstName, LastName) VALUES (N'{0}', N'{1}')" -Argument "Mary's", "O'Connor" | ||
|
|
||
| $result | Should -Be "INSERT INTO Users (FirstName, LastName) VALUES (N'Mary''s', N'O''Connor')" | ||
| } | ||
| } | ||
| } | ||
|
|
||
| Context 'When handling special characters that could be used for SQL injection' { | ||
| It 'Should escape single quotes in passwords with special characters' { | ||
| InModuleScope -ScriptBlock { | ||
| Set-StrictMode -Version 1.0 | ||
|
|
||
| # Password with single quote, semicolon, and dashes | ||
| $result = ConvertTo-EscapedQueryString -Query "EXECUTE sys.sp_adddistributor @password = N'{0}';" -Argument "Pass'word;--DROP TABLE Users" | ||
|
|
||
| $result | Should -Be "EXECUTE sys.sp_adddistributor @password = N'Pass''word;--DROP TABLE Users';" | ||
| } | ||
| } | ||
|
|
||
| It 'Should handle argument with only single quotes' { | ||
| InModuleScope -ScriptBlock { | ||
| Set-StrictMode -Version 1.0 | ||
|
|
||
| $result = ConvertTo-EscapedQueryString -Query "SELECT N'{0}'" -Argument "'''" | ||
|
|
||
| $result | Should -Be "SELECT N''''''''" | ||
| } | ||
| } | ||
|
|
||
| It 'Should handle empty string argument' { | ||
| InModuleScope -ScriptBlock { | ||
| Set-StrictMode -Version 1.0 | ||
|
|
||
| $result = ConvertTo-EscapedQueryString -Query "SELECT N'{0}'" -Argument '' | ||
|
|
||
| $result | Should -Be "SELECT N''" | ||
| } | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.