Can my users inject my dynamic sql? - vb.net

I'm a desktop developer writing for internal users, so I'm not worried about malicious hackers, but I would like to know if there's anything they could enter when updating a value that would execute sql on the server.
The business defines their content schema and I have a CRUD application for them that doesn't have to be changed when their schema changes because the validation details are table-driven and the updates are with dynamic SQL. I have to support single quotes in their data entry, so when they enter them, I double them before the SQL is executed on the server. From what I've read, however, this shouldn't be enough to stop an injection.
So my question is, what text could they enter in a free-form text field that could change something on the server instead of being stored as a literal value?
Basically, I'm building an SQL statement at runtime that follows the pattern:
update table set field = value where pkField = pkVal
with this VB.NET code:
Friend Function updateVal(ByVal newVal As String) As Integer
Dim params As Collection
Dim SQL As String
Dim ret As Integer
SQL = _updateSQL(newVal)
params = New Collection
params.Add(SQLClientAccess.instance.sqlParam("#SQL", DbType.String, 0, SQL))
Try
ret = SQLClientAccess.instance.execSP("usp_execSQL", params)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
Return ret
End Function
Private Function _updateSQL(ByVal newVal As String) As String
Dim SQL As String
Dim useDelimiter As Boolean = (_formatType = DisplaySet.formatTypes.text)
Dim position As Integer = InStr(newVal, "'")
Do Until position = 0
newVal = Left(newVal, position) + Mid(newVal, position) ' double embedded single quotes '
position = InStr(position + 2, newVal, "'")
Loop
If _formatType = DisplaySet.formatTypes.memo Then
SQL = "declare #ptrval binary(16)"
SQL = SQL & " select #ptrval = textptr(" & _fieldName & ")"
SQL = SQL & " from " & _updateTableName & _PKWhereClauses
SQL = SQL & " updatetext " & _updateTableName & "." & _fieldName & " #ptrval 0 null '" & newVal & "'"
Else
SQL = "Update " & _updateTableName & " set " & _fieldName & " = "
If useDelimiter Then
SQL = SQL & "'"
End If
SQL = SQL & newVal
If useDelimiter Then
SQL = SQL & "'"
End If
SQL = SQL & _PKWhereClauses
End If
Return SQL
End Function
when I update a text field to the value
Redmond'; drop table OrdersTable--
it generates:
Update caseFile set notes = 'Redmond''; drop table OrdersTable--' where guardianshipID = '001168-3'
and updates the value to the literal value they entered.
What else could they enter that would inject SQL?
Again, I'm not worried that someone wants to hack the server at their job, but would like to know how if they could accidentally paste text from somewhere else and break something.
Thanks.

Regardless of how you cleanse the user input increasing the attack surface is the real problem with what you're doing. If you look back at the history of SQL Injection you'll notice that new and even more creative ways to wreak havoc via them have emerged over time. While you may have avoided the known it's always what's lurking just around the corner that makes this type of code difficult to productionize. You'd be better to simply use a different approach.

You can also evaluate an alternative solution. Dynamic generation of SQL with parameters. Something like this:
// snippet just for get the idea
var parameters = new Dictionary<string, object>();
GetParametersFromUI(parameters);
if (parameters.ContainsKey("#id")) {
whereBuilder.Append(" AND id = #id");
cmd.Parameters.AddWithValue("#id", parameters["#id"]);
}
...

Assuming you escape string literals (which from what you said you are doing), you should be safe. The only other thing I can think of is if you use a unicode-based character set to communicate with the database, make sure the strings you send are valid in that encoding.

As ugly as your doubling up code is (:p - Try String.Replace instead.) I'm pretty sure that will do the job.

The only safe assumption is that if you're not using parameterized queries (and you're not, exclusively, here, because you're concatenating the input string into your sql), then you're not safe.

You never never ever never want to build a SQL statement using user input that will be then directly executed. This leads to SQL injection attacks, as you've found. It would be trivial for someone to drop a table in your database, as you've described.
You want to use parameterized queries, where you build an SQL string using placeholders for the values, then pass the values in for those parameters.
Using VB you'd do something like:
'Define our sql query'
Dim sSQL As String = "SELECT FirstName, LastName, Title " & _
"FROM Employees " & _
"WHERE ((EmployeeID > ? AND HireDate > ?) AND Country = ?)"
'Populate Command Object'
Dim oCmd As New OledbCommand(sSQL, oCnn)
'Add up the parameter, associated it with its value'
oCmd.Parameters.Add("EmployeeID", sEmpId)
oCmd.Parameters.Add("HireDate", sHireDate)
oCmd.Parameters.Add("Country", sCountry)
(example taken from here) (also not I'm not a VB programmer so this might not be proper syntax, but it gets the point across)

Related

How to add a column in a SQL expression using a user defined function through VB net (odbc connesction)

I am new to VB.net and I would like to convert and display UnixStamp data in a new column.
Variant DatGridView = datasource is Dataset.
I can create empty columns within an SQL query (DataGridView_Dataset), unfortunately I can't use direct data conversion into new columns using my own function. Error see.SQL Error Code
The function works independently. see. Working UnixStampFunction
I got the result of 56,000 sentences in 7 seconds, without getting date and time values from UnixTimeStamp
Is there a solution for using udf in SQL Statement?
DataGridView variant - odbcExecuteRead Solution
Using the given code is not a problem to display eg 10 sentences (10 sentences result), but if the records are more than about 100 (around 50 thousand by month), an error like this will be displayed (Managed Debug Helper ContextSwitchDeadlock: The module CLR could not go out of context COM 0xb45680 to context 0xb455c8 for 60 seconds.).
Unchecking the ContextSwitchDeadlock option by
Debug > Windows > Exception Settings in VS 2019
I got the result of 56 000 record in awfull 228 seconds.
Is it possible to optimize the code or is it possible to use another solution?
Code:
Public Class Form1
Public strDateTime, strDate, strTime As String
Public x As Integer =0
Public y As Integer =0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim dgvDT As New DataGridView
Dim odbcConn As OdbcConnection
Dim odbcComm As OdbcCommand
Dim odbcAdapter As New Odbc.OdbcDataAdapter
Dim odbcDataset As New DataSet
Dim odbcDataTable As DataTable
Dim strConn, strSQL, strSQL1 As String
dgvDT.Location = New Point(382, 2)
dgvDT.Width = 360
dgvDT.Height = 600
Me.Controls.Add(dgvDT)
strConn = "Driver=Firebird/InterBase(r) driver;User=;Password=;DataSource=...." '
odbcConn = New OdbcConnection(strConn)
odbcConn.Open()
strSQL = "SELECT TEST.UNIXTIMESTAMP, " & "'dd.mm.yyyy" & "'" & "AS Date_ , " & "'hh:mm:ss" & "'" & "AS Time_ " _
& "From TEST " _
& "Where TEST.UNIXTIMESTAMP > 1646092800 " _ '1.3.2022
& "Order By TEST.ID "
strSQL1 = "SELECT TEST.UNIXTIMESTAMP, UnixTimestampToDateOrTime(TEST.UNIXTIMESTAMP,1) As Date_, " & "'hh:mm:ss" & "'" & "AS Time_ " _
& "From TEST " _
& "Where TEST.UNIXTIMESTAMP > 1646092800 " _ '1.3.2022
& "Order By TEST.ID "
odbcComm = New OdbcCommand(strSQL, odbcConn)
'odbcComm = New OdbcCommand(strSQL1, odbcConn)
odbcAdapter.SelectCommand() = odbcComm
odbcAdapter.Fill(odbcDataset, "TEST")
odbcDataTable = odbcDataset.Tables("TEST")
dgvDT.DataSource = odbcDataTable
dgvDT.Columns(0).HeaderText = "UnixTimeStamp"
dgvDT.Columns(1).HeaderText = "Date"
dgvDT.Columns(2).HeaderText = "Time"
dgvDT.Visible = True
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message, "Error")
End Try
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Try
Dim dgvDT1 As New DataGridView
Dim odbcConn1 As OdbcConnection
Dim odbcComm1 As OdbcCommand
Dim odbcDR As OdbcDataReader
Dim x As Integer = 0
Dim y As Integer = 0
Dim strConn1, strSQL, strSQL2 As String
dgvDT1.Location = New Point(382, 2)
dgvDT1.Width = 360
dgvDT1.Height = 600
For i As Integer = 0 To 2
Dim dgvNC As New DataGridViewTextBoxColumn
dgvNC.Name = "Column" & i.ToString
dgvDT1.Columns.Add(dgvNC)
Next
dgvDT1.Columns(0).HeaderText = "UnixTimeStamp"
dgvDT1.Columns(1).HeaderText = "Date"
dgvDT1.Columns(2).HeaderText = "Time"
dgvDT1.ReadOnly = True
dgvDT1.AllowUserToAddRows = False
dgvDT1.AllowUserToDeleteRows = False
strSQL2 = "SELECT TEST.UNIXTIMESTAMP " _
& "From TEST " _
& "Where TEST.UNIXTIMESTAMP > 1646092800 " _
& "Order By TEST.ID "
strConn1 = "Driver=Firebird/InterBase(r) driver;User=;Password=;DataSource="
odbcConn1 = New OdbcConnection(strConn1)
odbcConn1.Open()
odbcComm1 = New OdbcCommand(strSQL2, odbcConn1)
odbcDR = odbcComm1.ExecuteReader()
While (odbcDR.Read()) 'And y <= 10
dgvDT1.Rows.Add()
dgvDT1.Rows(y).Cells("Column0").Value = (odbcDR.GetValue(0).ToString())
dgvDT1.Rows(y).Cells("Column1").Value = (UnixTimestampToDateOrTime(odbcDR.GetValue(0), 1))
dgvDT1.Rows(y).Cells("Column2").Value = (UnixTimestampToDateOrTime(odbcDR.GetValue(0), 2))
y = y + 1
End While
Me.Controls.Add(dgvDT1)
dgvDT1.Visible = True
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message, "Error")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
MsgBox(UnixTimestampToDateOrTime(1646092800, 1) & vbNewLine & UnixTimestampToDateOrTime(1646092800, 2))
End Sub
Public Function UnixTimestampToDateOrTime(ByVal _UnixTimeStamp As Long, ByRef _Parameter As Integer) As String
strDateTime = New DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(_UnixTimeStamp).ToString()
strDate = strDateTime.Substring(0, strDateTime.IndexOf(" "))
strTime = strDateTime.Substring(strDateTime.IndexOf(" "), strDateTime.Length - strDateTime.IndexOf(" "))
If _Parameter = 1 Then
Return (strDate)
Else
Return (strTime)
End If
End Function
End Class
You write:
I would like to convert and display UnixStamp data in a new column.
Yes you can. But i do not believe that would make your applicatio nany faster.
However I would outline the strategy i personally would had used getting data conversion without UDF.
Removing UDF, i believe, would enhance your database in general. But would not fix performance problems. Due to amount of information i could not format it as mere comment.
So, about removing UDF from the query.
Link to Firebird 2.5 documentation: https://www.firebirdsql.org/file/documentation/html/en/refdocs/fblangref25/firebird-25-language-reference.html#fblangref25-psql-triggers
Link to Firebird 3 documentation:
https://www.firebirdsql.org/file/documentation/html/en/refdocs/fblangref30/firebird-30-language-reference.html
The key difference would be that FB3+ has "stored functions" and even DETERMINISTIC ones, and FB2 - only "stored procedures".
I would avoid using UDFs here: they are declared obsolete, they make deployment more complex, and they would reduce your flexibiltiy (for example, you can not use Firebird for Linux/ARM if you only have UDF DLL for Win64)
So, the approach i speculate, you can use.
You would have to find an algorythm, how to "parse" UNIX date/time into separate values for day, month, etc.
You would have to implement that algorythm in Procedural SQL stored function (in FB3, make it DETERMINISTIC) or stored procedure (FB2, make it selectable by having SUSPEND command, after you set value for the output parameter and before exit) - see the Ch. 7 of the manual.
For assembling values of DATE or TIME or DATETIME types you would have to use integer to string (VARCHAR) to resulting type coersion, see Ch. 3.8 of the manual.
Example:
select
cast( 2010 || '-' || 2 || '-' || 11 AS DATE ),
cast( 23 || ':' || 2 || ':' || 11 AS TIME )
from rdb$database
CAST | CAST
:--------- | :-------
2010-02-11 | 23:02:11
db<>fiddle here
You would have add the converted columns to your table. Those columns qwould be read-only, but they would change "unix time" to Firebird native date and/or type.
Read Ch. 5.4.2. of the manual, about ALTER TABLE <name> ADD <column> command.
Read 5.4.1. CREATE TABLE of the manual about Calculated fields ( columns, declared using COMPUTED BY ( <expression> ) instead of actual datatype. Those columns you would have to creat, and here is where difference between FB3 and FB2 kicks in.
in FB3 i believe you would be able to directly use your PSQL Function as the expression.
in FB2 i believe you would have to use a rather specific trampoline, to coerce a stored procedure into expression:
ALTER TABLE {tablename}
ADD {columnname} COMPUTED BY
(
(
SELECT {sp_output_param_name} FROM {stored_proc_name}( {table_unixtime_column} )
)
)
In you Visual Basic application you would read those read-only converted columns instead of original value columns
Now, this would address the perfomance problem. Again, writing this aas an answer, because it is too large to fit as a comment.
No, while UDF has a number of problems - those are not about performance, but about being "old-school" and prone to low-level problems, such as memory leaks. UDFs can trigger problems if used in other places in query, by prohibiting SQL optimizer to use fast, indexed codepaths, but it is not your case. You only use your UDF in the result columns list of SELECT - and here should be no prerformance troubles.
Your application/database therefore should have other bottlenecks.
first of all, you use Where TEST.UNIXTIMESTAMP > 1646092800 and Order By TEST.ID in your query. The obvious question is if your table does have index on those columns. If not, you force the database server to do full natural scan to apply where condition, and then use external, temporary file sorting. THAT can be really slow, and can scale badly as the table grows.
Use your database design tool of choice to check query plan of your select.
Does Firebird use indexed or non indexed access paths.
There are articles online how to read Firebird's query. I don't instantly know English language ones though. Also, it would be specific to your database design tool, how to get it.
Sorry, there is no silver bullet. That is where learning about databases is required.
Read Data Definition Language / Create Index chapter of the documentation.
Link to Firebird 2.5 documentation: https://www.firebirdsql.org/file/documentation/html/en/refdocs/fblangref25/firebird-25-language-reference.html#fblangref25-psql-triggers
Link to Firebird 3 documentation: https://www.firebirdsql.org/file/documentation/html/en/refdocs/fblangref30/firebird-30-language-reference.html
Check your database structure, if UNIXTIMESTAMP and ID have index on them or not. In general, indices speed some (not all) reading queries and slow down (slightly) all writing queries.
You may decide you want to add those indices if they do not exist yet.
Again, it would be dependent upon your database design tool, how to check for existing of the indexes. It also would depend on your data and your applications which kind of indexes is needed or not. That is not what someone else can decide for you.
i also have a lot of suspicion about odbcAdapter.Fill(odbcDataset, "TEST") command. Basically, you try to read all the data in one go. And you do it via ODBC connection, that is not natural for C#.
Usually desktop application only read first 100 or so rows. People would rarely actually read anything after first page or two. Humans are not machines.
Try to somehow connect your visual grid to the select query without reading ALL the table. There should be way.
Additionally, there is free Firebird .Net Provider - this should work natively with VB.Net and should be your first choice, not ODBC.
There also is commercial IBProvider, based on native OLE DB technology it should be worse choice than .Net Provider, but it can work too and has some code examples for VB.Net, and i suppose it is still better mantained than ODBC driver.
you may also change Firebird configuration and allow it using more RAM for cache. This may somewhat relax problems of index-less selecting and sorting. But only somewhat relax and offset, not solve. You can find articles about it on www.ib-aid.com

Retrieving "Number" From Sql VB.NET System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.'

If I want to retrieve a value that is saved as a number in an access database.
Im using the following:
Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = '" & todaysdate & "'"
Using connection As New OleDbConnection(getconn)
Using command As New OleDbCommand(sql, connection)
connection.Open()
scorevalue = CDec(command.ExecuteScalar()) 'Data type mismatch in criteria expression.
connection.Close()
End Using
End Using
MsgBox(scorevalue)
getconn = connection string as a string
scorevalue = Nothing as decimal
The field ArithmeticScore is set to Number in the table.
The exact value in the cell right now is 50, but the program should allow for any decimal value.
The error im getting is "Data type mismatch in criteria expression".
The criteria expression mentioned in the error message does not refer to the ArithmeticScore output. It's talking about the WHERE clause. Whatever you have for todaysdate does not match what the database is expecting for the DateAscending column.
Since OleDb is a generic provider, we don't know exactly what kind of database you're talking to, but most databases have a way to get the current date value in SQL: getdate(), current_timestamp, etc. Using that mechanism will likely solve the conflict, and there's no need to use string concatenation for this in the first place.
Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = Date()"
The other way you can fix this is with proper parameterized queries, which you should doing anyway. It's NEVER okay to use string concatenation to substitute data into an SQL query, and if you find yourself needing to think about how to format a date or number string for use in an SQL command, you're almost always doing something very wrong.

Execute a SQL statement inside VBA Code

I am attempting to execute a SQL query inside of VBA Code. The query works in MS Access and asks the user to input a value for Customer_Name and Part_Number
What I have done is written the VBA Code in outlook so we can run the macro to execute the query from Outlook. The code I have currently works until the very bottom line on the DoCmd.RunSQL portion. I think I have this syntax incorrect. I need to tell it to run the string of SQL listed above:
Public Sub AppendAllTables()
Part_Number = InputBox("Enter Part Number")
Customer_Name = InputBox("Enter Customer Name")
Dim strsqlQuery As String
Dim Y As String
Y = "YES, Exact Match"
Dim P As String
P = "Possible Match - Base 6"
Dim X As String
X = "*"
strsqlQuery = "SELECT Append_All_Tables.Customer,
Append_All_Tables.CustomerCode, Append_All_Tables.PartNumber,
Append_All_Tables.Description, Append_All_Tables.Vehicle, SWITCH" &
Customer_Name & " = Append_All_Tables.PartNumber, " & Y & ", LEFT(" &
Part_Number & ",12) = LEFT(Append_All_Tables.PartNumber,12)," & Y & ",
LEFT(" & Part_Number & ",6) = LEFT(Append_All_Tables.PartNumber,6)," & P
& ") AS Interchangeability FROM Append_All_Tables WHERE" & Customer_Name
& "Like " & X & Customer_Name & X & "AND
LEFT(Append_All_Tables.PartNumber,6) = LEFT(" & Part_Number & ",6);"
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase "path.accdb"
appAccess.DoCmd.RunSQL "strsqlQuery"
End Sub
Please note, the path has been changed for privacy. The SQL code already works in Access. I am only needing the last line to be evaluated.
If you want to have a datasheet form view show these records you can use
DoCmd.OpenForm
First create a query with the data you want to see, then bind that to your form using the Record Source property, then when you call DoCmd.OpenForm pass in the filter you want.
I'm not following what you're trying to do with SWITCH in your query (is that supposed to be the switch() function? it has no parentheses). But you'll need to adjust that to join to use a Where statement instead.
I agree with a couple of the above posts.
You need to do a Debug.Print of the strsqlQuery variable BEFORE YOU DO ANYTHING! Then evaluate that statement. Does it look right? As Matt says, it doesn't look like you have line continuations, which would make your SQL statement incomplete (and thus, the computer doesn't think its a query at all).
My personal preference is to define the SQL like you have, then create the actual query using that SQL (create query def), and then call that query, because it will now be an actual object in the database. The QUERY can show up as a datasheet without any form requirement, but a pure SQL Statement cannot.
Michael
Remove the quotes.
appAccess.DoCmd.RunSQL "strsqlQuery" to appAccess.DoCmd.RunSQL strsqlQuery

Inserting Single/double type to DB using VBA in access

I need some help with an issue that is doing my head in.
I need to update a database in access and its been working fine operating with Long and Integers.
Look at this code.
sql = "UPDATE DBNAME SET Long_Field = " & Long_Variable & " WHERE ID = " & id
DoCmd.SetWarnings (False)
DoCmd.RunSQL sql
This code runs flawlessly, it takes a long variable and puts it into the correct field which is set as Long.
However, if I want to populate a single/double field (ive tried both)
sql = "UPDATE DBNAME SET Double_Field = " & double_Variable & " WHERE ID= " & id
DoCmd.SetWarnings (False)
DoCmd.RunSQL sql
I keep getting Run-Time error 3144: Syntax error in update statement.
I can literally just switch out the field name and the variable name and the code runs flawlessly, but as soon as i try to send a double value, for example (5,8), to a field in the table that is set to double, it gives me this error.
Anyone?
I assume that you want a dot as decimal separator in your string.
The conversion from double to string is done using the separator from the system locale settings so in your case a comma.
This means that
double_variable = 5.8
sql = "... " & double_variable & " ..."
will produce ... 5,8 ... in the sql variable.
The easiest way to fix that is to use
"..." & Replace(CStr(double_variable), ",", ".") & "..."
This will replace all , with .. I put the CStr there to make sure it gets converted to a string first. It will also work if the system locale changes since nothing will happen if there is no ,. The only caveat is that if for some reason the conversion inserts 1000s separators it will fail but that would only be relevant in other circumstances as I don't think CStr will ever do that.
The current answer is not the easiest, neither the simplest.
The universal method is to use Str as it always returns a dot as the decimal separator:
sql = "UPDATE DBNAME SET Double_Field = " & Str(double_Variable) & " WHERE ID = " & id & ""

Parameterized field name

I was thinking if this will work:
Dim query As String = "UPDATE tblPiglets SET #to=#todate, CurrentLocation=#to" & _
" WHERE Week=#week AND SowOrder=#so AND PigletNumber=#pig"
But I caught Cannot update #to field lol
The #to is a variable in which I thought would work the same its value though its worth a try. Its value is dependent on a user input, so, is there any other way to do that?
Or this? (not sure if this will work though):
Dim to As String = "foo"
Dim query As String = "UPDATE tblPiglets SET " & to & "=#todate, CurrentLocation=#to" & _
" WHERE Week=#week AND SowOrder=#so AND PigletNumber=#pig"
It is always preferable to use parameters to insert user input into SQL code but parameters can only be used for values, not identifiers. Think of SQL parameters the same as parameters in a VB method. You can't use a method parameter to specify a property or method to use and you can't use a SQL parameter to specify a column or table.
You have no choice but to use string concatenation but doing so opens you up to SQL injection, so make absolutely sure that the user cannot insert arbitrary SQL code. If it's a column name then they should have to select it from a list that you have retrieved from the database itself, so that you are guaranteed that it's a valid column.
I have used option 2 to make it work.
Dim to As String = "foo"
Dim query As String = "UPDATE tblPiglets SET " & to & "=#todate, CurrentLocation=#to" & _
" WHERE Week=#week AND SowOrder=#so AND PigletNumber=#pig"
But it would be nicer if I can get the same result if I will be using the first option. thanks