Is this Enough to Secure againts SQL Injections? - sql-server

I'm trying to secure a older classic asp web site (that has about 1,000 (.asp) pages) using MS SQL 2008 R2 (Express Edition).
I found a code (see below) on how to Parameterized Queries and the code looks to be the easiest for me to understand and use on all of the pages that need to be changed.
If I was to convert all of the ms sql queries (that will look something like the code below) will that be enough to protect against an ms sql injection attack ? or is there more that I will need to add/change ?
set objCommand = Server.CreateObject("ADODB.Command")
strSql = "SELECT * FROM users WHERE username=? AND password=?"
...
cmd1.Parameters(0) = Request.Form("login")
cmd1.Parameters(1) = Request.Form("password")
...

Its been a while since I've seen the old Adodb command syntax, but I think you would want something like:
set objCommand = Server.CreateObject("ADODB.Command")
strSql = "Select * From users where username=#username and password=#password"
objCommand.Parameters.Append.CreateParameter
("#username", adVarChar, adParamInput, 50, Request.Form("login"))
objCommand.Parameters.Append.CreateParameter
("#password", adVarChar, adParamInput, 50, Request.Form("password"))
As always, don't create dynamic sql statements without a type safe parameter encoding, I think even old school ADO provides this via CreateParameter.

Yes, the code you provided in your question is secured against Sql Injections.
However, as noted in this article on mitigating Sql Injection, your code will have "a minor performance issue because ADODB is going to have to made a round-trip to SQL to figure out the parameter type before it can execute the query."
You can resolve this by explicitly specifying the parameter type in your code using CreateParameter

Related

Query data from SQL to MS Access: Local Tables vs Pass-Through Tables

I've created an application that uses the following logic to query data from SQL to my MS Access App.
Using an ODBC connection I execute a stored procedure
Using This is assigned as a Pass-Through Query to pull the data locally.
It looks something like this:
strSQL = "EXEC StoredProcedure " & Variable & "
Call ChangeQueryDef("qryPassThrough", strSQL)
Call SQLPassThrough(strQDFName:="qryPassThrough", _
strSQL:=strSQL, strConnect:=gODBCConn)
Me.frmDataSheet.Form.RecordSource = "qryPassThrough"
But, recently we have upgraded our SQL Server to 2016 using a high availability failover system - hence our connection string has changed to connect to a listener like so:
gODBCConn = "ODBC;Driver= {SQL Server Native Client 11.0};Trusted_Connection=Yes;Regional=Yes;Database=" & varDB & ";MultiSubnetFailover=Yes;IntegratedSecurity=SSPI;Server=tcp:SERVER_LISTENER,1433;"
However, it looks like using SQL Server Native Client in the connection string is not the same as what we originally had which was SQL Server. Certain data types have changed and do not work in Access.
Is there a better way for me to query data from SQL and persist/display this data in access using ADO or an alternative method?
EDIT Based on Comment:
The issue I'm having is that I have tables in SQL using the data type: Decimal(12,2). With some testing and experimenting this seems to fail when using an ODBC pass-through query. But changing the data type to Float seems to work fine. Then there are other datatypes which seem to error too which I've not managed to find yet. It just seems there are a few difference which I'm not aware of and I'm keen to find a better way to load data into my Access App.
EDIT 2
This is the error message I get relating to the data type issue.
Sounds like you're not really interested in making the underlying data structure compatible with Access, so:
How to load an ADODB recordset into a datasheet form
Create the form
First, create a datasheet form. For this example, we're going to name our form frmDynDS. Populate the form with 256 text boxes, named Text0 to Text255. To populate the form with the text boxes, you can use the following helper function while the form is in design view:
Public Sub DynDsPopulateControls()
Dim i As Long
Dim myCtl As Control
For i = 0 To 255
Set myCtl = Application.CreateControl("frmDynDS", acTextBox, acDetail)
myCtl.NAME = "Text" & i
Next i
End Sub
VBA to bind a recordset to the form
First, we're going to allow the form to persist, by allowing it to reference itself:
(all on in the code module for frmDynDS)
Public Myself As Object
Then, we're going to add VBA to make it load a recordset. I'm using Object instead of ADODB.Recordset to allow it to both take DAO and ADODB recordsets.
Public Sub LoadRS(myRS As Object)
Dim i As Long
Dim myTextbox As textbox
Dim fld As Object
i = 0
With myRS
For Each fld In myRS.Fields
Set myTextbox = Me.Controls("Text" & i)
myTextbox.Properties("DatasheetCaption").Value = fld.NAME
myTextbox.ControlSource = fld.NAME
myTextbox.ColumnHidden = False
i = i + 1
Next fld
End With
For i = i To 255
Set myTextbox = Me.Controls("Text" & i)
myTextbox.ColumnHidden = True
Next i
Set Me.Recordset = myRS
End Sub
Use the form
(all in the module of the form using frmDynDS)
As an independent datasheet form
Dim frmDS As New Form_frmDynDS
frmDS.Caption = "My ADO Recordset"
frmDS.LoadRS MyAdoRS 'Where MyAdoRS is an open ADODB recordset
Set frmDS.Myself = frmDS
frmDS.Visible = True
frmDS.SetFocus
Note that you're allowed to have multiple instances of this form open, each bound to different recordsets.
As a subform (leave the subform control unbound)
Me.MySubformControl.SourceObject = "frmDynDS"
Me.MySubformControl.Form.LoadRS MyAdoRS 'Where MyAdoRS is an open ADODB recordset
Warning: Access uses the command text when sorting and filtering the datasheet form. If it contains a syntax error for Access (because it's T-SQL), you will get an error when trying to sort/filter. However, when the syntax is valid, but the SQL can't be executed (for example, because you're using parameters, which are no longer available), then Access will hard crash, losing any unsaved changes and possibly corrupting your database. Even if you disable sorting/filtering, you can still trigger the hard crash when attempting to sort. You can use comments in your SQL to invalidate the syntax, avoiding these crashes.
You previously used the pretty ancient, original ODBC Driver for SQL Server simply named SQL Server. You made the right decision to use a newer driver to support your failover cluster. But I would not recommend to use SQL Server Native Client. Microsoft says, It is not recommended to use this driver for new development.
Instead I would use the Microsoft ODBC Driver 13.1 for SQL Server. This is the most recent and recommended (by Microsoft) ODBC Driver for SQL Server.
Your main issue seems to be a translation issue between Access and SQL Server via the ODBC layer. So, using the more modern driver might very well make this problem go away. - I do not know if it solves your problem, but this is the very first thing I would try.

VBScript / ADODB Syntax Issue with adArray?

I'm hoping somebody could provide me with some fresh eyes on my vb script. The main purpose of this script is to execute a stored procedure using some parameters.
The error I get is
'Expected end of statement'
I haven't done much VB scripting but from what I have found so far - this error has been down to some kind of syntax issue. I've looked over this script for many hours and can't see anything obvious. I can only assume it's down to the declaration of adArray (which doesn't look right in my eyes but I haven't been able to find ANY examples of this being declared). This error has only been introduced when I started adding more parameters.
Code:
Const adVarChar = 200
Const adParamInput = 1
Const adArray = 0x2000
Dim cmd
Dim sp
Dim intCode
Dim addIn
Dim groupCode
Dim screens
Dim arrScreens
arrScreens=split(LF06,",")
Set cmd=CreateObject("ADODB.Command")
sp="vfile_dev.dbo.vfp_groupReorder"
Set intCode=CreateObject("ADODB.Parameter")
intCode.Direction=adParamInput
intCode.name="#p_intCode"
intCode.Size=100
intCode.Type=adVarChar
intCode.Value=LF03
Set addIn=CreateObject("ADODB.Parameter")
addIn.Direction=adParamInput
addIn.name="#p_addIn"
addIn.Size=100
addIn.Type=adVarChar
addIn.Value=LF04
Set groupCode=CreateObject("ADODB.Parameter")
groupCode.Direction=adParamInput
groupCode.name="#p_groupCode"
groupCode.Size=100
groupCode.Type=adVarChar
groupCode.Value=LF05
Set screens=CreateObject("ADODB.Parameter")
screens.Direction=adParamInput
screens.name="#p_screens"
screens.Size=100
screens.Type=adArray
screens.Value=arrScreens
With cmd
.ActiveCOnnection = "Provider='sqloledb';Data source='xxx';Integrated Security='SSPI';"
.CommandType = 4
.CommandText = sp
.Parameters.Append intCode
.Parameters.Append addIn
.Parameters.Append groupCode
.Parameters.Append screens
.Execute
End With
Set cmd = Nothing
Set sp = Nothing
Set intCode = Nothing
Set addIn = Nothing
Set groupCode = Nothing
Any help would be much appreciated. Thanks.
EDIT:
For those interested - my solution was to ditch adArray and pass my data through as a comma delimited varchar. I then handle this data in my stored procedure with a simple split function.
I'm fairly sure adArray although defined in the ADO constants is not supported by ADO and was added for future compatibility.
From MSDN - ADO API Reference - DataTypeEnum
A flag value, always combined with another data type constant, that indicates an array of the other data type. Does not apply to ADOX.
This definition suggests it should only be used with another ADO DataTypeEnum constant value to denote an Array of that Data Type.
Although there is some suggestion that ORing the value with another DataTypeEnum constant should work, I found this from the 12 years ago.
From the ADO public newsgroup (microsoft.public.ado)
Discussion: how to use AdArray data type with sql server 7 and stored procedures
Date: 2003-09-29 19:24:10 UTC
Hi David,
adArray is not supported in ADO and was created for future compatibility.
What do you need to achieve? Maybe we could help with another solution
--
Val Mazur
Microsoft MVP
Check Virus Alert, stay updated
http://www.microsoft.com/security/incident/blast.asp
Useful Links
How to use ADODB parameterized query with adArray data type in VBScript? - Suggestion that using adArray is possible.
Carl Prothman - Data Type Mapping - My go to resource for ADO data Type Mapping.

DSN-less Connection MS Access front end and SQL server backend

I don't normally program in MS Access VBA so forgive my question if it's stupid.
So I'm using MS Access 2010 as a front end and SQL Server 2014 as a backend. (I don't have a choice in frontend interface so please no suggestions on alternate options).
I'd like to programatically link SQL server's backend to my MS Access frontend. I read here at DJ Steele's DSN-less connection page that I can use the code he provided here to make a DSN-less connection to SQL server as a backend.
So I copied that into a VBA Access module and opened another module and ran this code to run the DJ Steele code in an attempt to connect to a small SQL Server database I made:
Option Compare Database
Sub runThis()
FixConnections "AServerNameHere", "MS_Access_BackEnd_Test"
End Sub
As far as I can tell from the VBA debugger it gets to
Set dbCurrent = DBEngine.Workspaces(0).Databases(0)
then that value seems to be empty. I'm not sure how else to proceed with this since as far as I was able to find this is one of the few full examples of a DSN-less connection I could find.
I'd like to not use the DSN method of linking a SQL server to a database since that would require me to go visit people and their computers in order to make the links. (And who'd want to to that? LOL)
I've also looked at similar questions that were linked to me while writing this question and this was close to what I wanted, but it kept giving me "Compile error: Constant expression required" for input of:
LinkTable "MS_Access_BackEnd_Test", "Table_1"
and
LinkTable "MS_Access_BackEnd_Test", "Table_1", , "AServerNameHere"
Again I'm not familiar with MS Access VBA so forgive the question if it's lame.
Looking at DJ Steele's code, I got it working apart from the line
' Unfortunately, I'm current unable to test this code,
' but I've been told trying this line of code is failing for most people...
' If it doesn't work for you, just leave it out.
tdfCurrent.Attributes = typNewTables(intLoop).Attributes
which I had to comment out.
Using Set dbCurrent = CurrentDb() does essentially the same thing as Set dbCurrent = DBEngine.Workspaces(0).Databases(0) but the latter is meant to be a lot faster ... which these days means it takes 10 microseconds instead of 100 :-o
You still need dbCurrent as a reference to the current Access front end which is where the linked table objects live, even if the data is coming from elsewhere.
Edit: working for me
I added a debug.print line to monitor what's going on
' Build a list of all of the connected TableDefs and
' the tables to which they're connected.
For Each tdfCurrent In dbCurrent.TableDefs
Debug.Print tdfCurrent.Name, tdfCurrent.Connect
If Len(tdfCurrent.Connect) > 0 Then
If UCase$(Left$(tdfCurrent.Connect, 5)) = "ODBC;" Then
...
and then
? currentdb().TableDefs("dbo_Person").Connect
ODBC;DSN=TacsData;APP=Microsoft Office 2003;WSID=TESTXP;DATABASE=TacsData;Trusted_Connection=Yes;QuotedId=No
FixConnections "TESTXP\SQLEXPRESS", "TacsData"
MSysAccessObjects
MSysAccessXML
...
MSysRelationships
Table1
dbo_Person ODBC;DSN=TacsData;APP=Microsoft Office 2003;WSID=TESTXP;DATABASE=TacsData;Trusted_Connection=Yes;QuotedId=No
? currentdb().TableDefs("dbo_Person").Connect
ODBC;DRIVER=sql server;SERVER=TESTXP\SQLEXPRESS;APP=Microsoft Office 2003;WSID=TESTXP;DATABASE=TacsData;Trusted_Connection=Yes

Unable to query nVarChar(Max) field in Access 2010

have used Stack Overflow as a resource hundreds of times, but my first time posting a question for some help!
I've got a table in SQL Server 2005 which contains 4 nVarChar(Max) fields.
I'm trying to pull out the data from an Access (2010) VBA Module using ADO 2.8
I'm connecting using SQL driver SQLNCLI10
(I can't use a linked table, as the 'table' I will ultimately be querying is a Table-Valued Function)
When I then print / use the recordset, the data is getting jumbled and concatenated with other fields in the same record - with a bunch of obscure characters thrown in.
The VBA: (various other methods were tried with the same result)
Sub TestWithoutCasting()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim i As Integer
cn.Open "Data Source=ART;DataTypeCompatibility=80;MARS Connection=True;"
Set rs = cn.Execute("SELECT * FROM JobDetail WHERE JobID = 2558 ORDER BY SeqNo ASC")
Do While Not rs.EOF
For i = 1 To rs.Fields.Count
Debug.Print rs.Fields(i).Name & ": " & rs.Fields(i).Value
Next i
rs.MoveNext
Loop
End Sub
Example Output:
SeqNo: 1
CommandID: 2
Parameter1: 2 Daily Report é [& some other chars not showing on here]
Parameter2: [Null]
Parameter3: [Null]
Parameter4: [Null]
Description: Daily Report
Active: False
Expected Output:
SeqNo: 1
CommandID: 2
Parameter1: SELECT Day_Number ,Day_Text ,Channel_Group_ID [...etc]
Parameter2: [Null]
Parameter3: [Null]
Parameter4: [Null]
Description: Daily Report
Active: False
So, it's grabbing bits of data from other fields instead of the correct data (in this case, it's an SQL statement)
I then tried casting the nvarchar(max) fields as text at source
View Created:
CREATE VIEW TestWithCast
AS
SELECT jd.JobID, jd.SeqNo, jd.CommandID
,cast(jd.Parameter1 as text) as Parameter1
,cast(jd.Parameter2 as text) as Parameter2
,cast(jd.Parameter3 as text) as Parameter3
,cast(jd.Parameter4 as text) as Parameter4
,jd.[Description]
,jd.Active
FROM JobDetail jd
Now, I initially had some luck here - using the same code as above does bring back data - but when I use this code in my main code (which jumps in & out of other procedures); as soon as I've queried the first result of the recordset, it appears to wipe the rest of the records / fields, setting them to Null. I also tried setting the value of each field to a variable whilst the rest of the vba runs before getting the next record - but this doesn't help either.
It almost feels like I need to dump the recordset into a local Access table, and query from there - which is a bazaar workaround for what is already a workaround (by casting as text).
I there something I'm completely missing here, or do I indeed need to cast as text and load to a local table?
Thanks for any help - it's driving me mad!
ps. Hope I've given the right level of detail / info - please let me know if I missed anything key.
EDIT:
Yikes, I think I've done it / found the issue...
I changed the driver to SQLSRV32 (v6.01) - and seems to work fine directly against the text casted field.
So... why would it work with an older driver but not the newer 'recommended' (by various sources I read) as the one to use.
And... will there be a significant drawback in using this over the native client?
EDIT 2:
Ok, I've tried a few drivers on a few machines, in each case with both the TEXT CASTING and Directly to VARCHAR MAX..
[On my windows 7 machine w/ SQLSMS 2008]
SQL Native Client 10.0 - Neither method works reliably with this driver
SQL Server 6.01 - BOTH methods appear to work reliably - further testing needed though
[On our production server w/ SQLS 2005]
SQL Native Client (v2005.90) - Does not work at all with varchar(max), but DOES work with text casting
SQL Server (v2008.86) - BOTH methods appear to work reliably - further testing needed though
This should make deployment interesting!
It's not a real answer, because I did not test it, but ... You are using a "DataTypeCompatibility=80" parameter in your connection. As far as I know, DataTypeCompatibility=80 refers to SQL Server 2000, where the nvarchar(max) field type was still not implemented.
I had the same problem, solved it by converting the field to an nvarchar(1000). Would be an easy, compatible solution for your problem if 1000 chars is enough.

Retrieving varbinary output from a query in sql server into classic ASP

I'm trying to retrieve a varbinary output value from a query running on SQL Server 2005 into Classic ASP. The ASP execution just fails when it comes to part of code that is simply taking a varbinary output into a string. So I guess we gotta handle it some other way.
Actually, I'm trying to set (sp_setapprole) and unset (sp_unsetapprole) application roles for a database connection. First I'd set the approle, then I'd run my required queries and finally unset the approle. During unsetting is when I need the cookie (varbinary) value in my ASP code so that I can create a query like 'exec sp_unsetapprole #cookie'. Well at this stage, I don't have the cookie (varbinary) value.
The reason I'm doing this is I used to get 'sp_setapprole was not invoked correctly' error when trying to set app roles. I've disabled pooling by appending 'OLE DB Services = -2;Pooling=False' into my connection string.
I know pooling helps performance wise but here I'm facing big problems.
Please help me out to retrieve a varbinary value into an classic ASP file or suggest a way to set & unset app roles. Either way solutions are appreciated.
Thanks,
Nandagopal
Maybe you could try casting your VARBINARY datatype to IMAGE, which is old enough that it might be able to be used by "Classic" ASP. Just a thought. Could be wrong.
The easiest way is to store the varbinary value from sp_setapprole in an ADO recordset and keep that value around, not worrying about the actual type (you should be able to store the value in an array of bytes, though).
Then, when you need to place that varbinary value in your final sp_setapprole, you can simply use the recordset value. Do this by invoking sp_setapprole using a ADODB.Command object:
'--untested, syntax could be slightly off'
Set myCommand = Server.CreateObject("ADODB.Command")
With myCommand
.ActiveConnection = myConnection
.CommandType = adCmdStoredProc
.CommandText = "sp_unsetapprole"
.Parameters.Append _
.CreateParameter("#Cookie", adLongVarBinary, adParamInput, fileSize)
.Parameters(str_ParamName).Attributes = adFldLong
.Parameters(str_ParamName).AppendChunk myRecordset.Fields("Cookie").Value
.Execute
End With
Perhaps you can also get some insights from this Stackoverflow question.

Resources