parametrization in VBScript/ASP Classic and ADO - sql-server

I'm a bit confused here. Microsoft as far as I can tell claims that parametrization is the best way to protect your database from SQL injection attacks. But I find two conflicting sources of information here:
This page says to use the ADO command object. But this page says that the command object isn't safe for scripting. I seem to recall reading somewhere that the command object shouldn't be used in VBScript or JScript because of security vulnerabilities, but I can't seem to find that article.
Am I missing something here, or do those two articles seem to contradict each other?

I could be wrong here, but I think this just means that someone could use the Command object to do bad things. I.e. it's not to be trusted if someone else is scripting it.
See safe for scripting in this article. Every instance that talks about this phrase online, references it as if you are marking an ActiveX control saying "This control does no I/O or only talks back to the server that it came from" but the Command object doesn't do that. It can be used to do a lot of things which could be unsafe.
The "safe" they are talking about and the "safe" to prevent from SQL injection are two different things. The article about using the ADO Command object to parametrize your data is spot on. You should do that.
And, Microsoft further confirms this here:
http://msdn.microsoft.com/en-us/library/ms676585(v=VS.85).aspx

I think "safe for scripting" means "safe to be run from a webpage we just retrieved from some Nigerian prince". The command object should be safe to run on the server.
At work though, back in the day my colleagues didn't trust it so we had an in-house framework that basically did the same thing.

Related

Work with Database using Spock and Geb.

I hope someone have already faced an issue to verify that application shows correct data from database. I reviewd how groovy used SQL, but I have no idea where and how I should do that. I'm just starting to use gradle+Spock+Geb for testing application. I have a few files where I described a couple of pages from application, a couple of modules and a file with spock specification. Where and how I need to connect to Oracle DB, use SQL and compare result's data with application's ones?
P.S. I write everything in notepad++ and launch from command line writing 'gradlew firefoxTest'. Does exist any more comfortable way to work with gradle+spock+geb?
Thanks in advance.
Because there are no other answers, I wanted to provide a solution someone at my company thought of. This assumes you already have a project that uses some sort of JDBC. In our case it is JDBI.
The idea is to extend Classloader and then use that to directly access the data access object class via the JVM. That idea should work.
I have not tested it out because it doesn't completely fit our use-case. I'll admit that this does not completely apply to your use case, but technically you could just run the jar of an existing project, which can access the database.

DB Comparison tool that I can schedule

I'm after a DB Comparison tool for SQL Server that allows me to do the following:
Schedule a comparison to happen on a recurring schedule
Email me the results (in a nice readable format and not the generated script)
Allow me to exclude/include certain object names (for example exclude table names containing %test%. That's not a real example but there is a good reason why that would come in useful.)
As well as the obvious:
Have the usual options for ignoring things like comments, identity seeds etc
Options for selecting different types of objects
If it was free or at least didn't cost a forture that would be an extra bonus of course.
I have tried out RedGate's SQL Compare and also the built-in DB Comparison in Visual Studio but neither seem able to do the first 3 points above. I also looked at other tools recommended in various threads on here but again they don't mention in their features the 3 points above.
One option I found is RedGate's SQL Comparison SDK with which I think I could write something to do what I want.
I just wanted to investigate tools that might do all of the above out of the box.
Thank you!
SQL Compare Pro comes with a command line, which will be easier to set up than the SDK. If you call this via the Windows Scheduler or in an Agent Job you can achieve what you're looking for.
An example of how to invoke the command line from Powershell it can be found here:
http://www.simple-talk.com/sql/database-administration/auditing-ddl-changes-in-sql-server-databases/
This article also covers how to send an email in Powershell. SQL Compare can also be passed a filter using the /filter switch to exclude objects based on various rules.
http://www.red-gate.com/supportcenter/Content/SQL_Compare/help/10.0/sc_cl_Switches_in_the_cl
Do please email support#red-gate.com should you have trouble getting this working.
I don't think any tool would do all of this out of the box. Have you had a chance to look at
sp_CompareDB. I had a similar requirement and ended up writing my own routine based on the same.
http://www.sql-server-performance.com/2001/database-comparison-sp/

How can I execute code stored in a database?

How can I store, for example, the body of a method in a database and later run it? (I'm using Delphi XE2; maybe RTTI would help.)
RTTI is not a full language interpreter. Delphi is a compiled language. You write it, compile it, and distribute only your binaries. Unless you're Embarcadero, you don't have rights to distribute DCC32 (the command line compiler).
However, the JVCL includes a delphi-like language subset wrapped up in a very easy to use Component, called "JvInterpreter". You could write some code (as pascal) and place it in a database. You could then "run that code" (interpreted, not compiled) that you pull from the database. Typically these should be procedures that call methods in your code. YOu have to write some "wrappers" that expose the compiled APIs that you wish to expose to the interpreter (provide access to live data, or database connection objects, or table/query objects). You're thinking that this sounds perfect right? Well, it's a trap.
Beware of something called "the configuration complexity clock". YOu've just reached 9 o'clock, and that's where a lot of pain and suffering begins. Just like when you have a problem, and you solve it with regular expressions, and "now you have two problems", adding scripting and DSLs to your app has a way of solving one problem and creating several others.
While I think the "DLL stored in a database blob field" idea is evil, and absurd, I think that wanton addition of scripting and domain-specific languages to applications is also asking for a lot of pain. Ask yourself first if some other simpler solution could work. Then apply the YAGNI principle (You Ain't Gonna Need It) and KISS (keep-it-simple-smartguy).
Think twice before you implement anything like what you're asking about doing in your question.
Your best Option, IMHO, is using a scripting engine and storing scripts in the database.
Alternatively you could put the code in a dll and put that dll in the database. There is code for loading a dll from a resource into ram and processing it so it can be used as if it was loaded using LoadLibrary, e.g. in dzlib. I don't really know whether works with any dll and in which versions of Windows, but it does with the ones I tried.

SQL injection attempt on my server

I know a little about SQL injections and URL decode, but can someone who's more of an expert than me on this matter take a look at the following string and tell me what exactly it's trying to do?
Some kid from Beijing a couple weeks ago tried a number of injections like the one below.
%27%20and%20char(124)%2Buser%2Bchar(124)=0%20and%20%27%27=%27
It's making a guess about the sort of SQL statement that the form data is being substituted into, and assuming that it will be poorly sanitised at some step along the road. Consider a program talking to an SQL server (Cish code purely for example):
fprintf(sql_connection, "SELECT foo,bar FROM users WHERE user='%s';");
However, with the above string, the SQL server sees:
SELECT foo,bar FROM users WHERE user='' and char(124)+user+char(124)=0 and ''='';
Whoops! That wasn't what you intended. What happens next depends on the database back-end and whether or not you've got verbose error reporting turned on.
It's quite common for lazy web developers to enable verbose error reporting unconditionally for all clients and to not turn it off. (Moral: only enable detailed error reporting for a very tight trusted network, if at all.) Such an error report typically contains some useful information about the structure of the database which the attacker can use to figure out where to go next.
Now consider the username '; DESCRIBE TABLE users; SELECT 1 FROM users WHERE 'a'='. And so it goes on... There are a few different strategies here depending on exactly how the data comes out. SQL injection toolkits exist which can automate this process and attempt to automatically dump out the entire contents of a database via an unsecured web interface. Rafal Los's blog post contains a little more technical insight.
You're not limited to the theft of data, either; if you can insert arbitrary SQL, well, the obligatory xkcd reference illustrates it better than I can.
You'll find detailed info here:
http://blogs.technet.com/b/neilcar/archive/2008/03/15/anatomy-of-a-sql-injection-incident-part-2-meat.aspx
These lines are double-encoded -- the
first set of encoded characters, which
would be translated by IIS, are
denoted by %XX. For example, %20 is a
space. The second set aren't meant to
be translated until they get to the
SQL Server and they use the char(xxx)
function in SQL.
' and char(124)+user+char(124)=0 and ''='
that's strange..however, make sure you escape strings so there will be no sql injections
Other people have covered what's going on, so I'm going to take a moment to get on my high-horse and strongly suggest that if you're not already (I suspect not from a comment below) that you use parameterized queries. They literally make you immune to SQL injection because they cause parameters and the query to be transmitted completely separately. There's also potential performance benefits, yadda yadda, etc.
But seriously, do it.

VBScript/ASP Classic

I have a couple of questions regarding VBScript and ASP Classic:
What is the preferred way to access an MS SQL Server database in VBScript/ASP?
What are best practices in regards to separating model from view from controller?
Any other things I should know about either VBScript or ASP?
If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.
ADO is an excellent way to access a database in VBScript/Classic ASP.
Dim db: Set db = Server.CreateObject("ADODB.Connection")
db.Open "yourconnectionstring -> see connectionstrings.com"
Dim rs: Set rs = db.Execute("SELECT firstName from Employees")
While Not rs.EOF
Response.Write rs("firstName")
rs.MoveNext
Wend
rs.Close
More info here: http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/
One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query. Otherwise you will run into problems.
(Reference: http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html )
I had to walk away from my PC when I saw the first answer, and am still distressed that it has been approved by so many people. It's an appalling example of the very worst kind of ASP code, the kind that would ensure your site is SQL-injectable and, if you continue using this code across the site, hackable within an inch of its life.
This is NOT the kind of code you should be giving to someone new to ASP coding as they will think it is the professional way of coding in the language!
NEVER reveal a connection string in your code as it contains the username and password to your database. Use a UDL file instead, or at the very least a constant that can be declared elsewhere and used across the site.
There is no longer any good excuse for using inline SQL for any operation in a web environment. Use a stored procedure -- the security benefits cannot be stressed enough. If you really can't do that then look at inline parameters as a second-best option... Inline SQL will leave your site wide open to SQL injection, malware injection and the rest.
Late declaration of variables can lead to sloppy coding. Use "option explicit" and declare variables at the top of the function. This is best practice rather than a real WTF, but it's best to start as you mean to go on.
No hints to the database as to what type of connection this is -- is it for reading only, or will the user be updating records? The connection can be optimised and the database can handle locking very efficiently if effectively told what to expect.
The database connection is not closed after use, and the recordset object isn't fully destroyed.
ASP is still a strong language, despite many folks suggesting moving to .NET -- with good coding practices an ASP site can be written that is easy to maintain, scaleable and fast, but you HAVE to make sure you use every method available to make your code efficient, you HAVE to maintain good coding practices and a little forethought. A good editor will help too, my preference being for PrimalScript which I find more helpful to an ASP coder than any of the latest MS products which seem to be very .NET-centric.
Also, where is a "MEMO" field from? Is this Access nomenclature, or maybe MySQL? I ask as such fields have been called TEXT or NTEXT fields in MS-SQL for a decade.
Remember to program into the language rather than program in it. Just because you're using a limited tool set doesn't mean you have to program like it's 1999.
I agree with JasonS about classes. It's true you can't do things like inheritance but you can easily fake it
Class Dog
Private Parent
Private Sub Class_Initialize()
Set Parent = New Animal
End Sub
Public Function Walk()
Walk = Parent.Walk
End Function
Public Function Bark()
Response.Write("Woof! Woof!")
End Function
End Class
In my projects an ASP page will have the following:
INC-APP-CommonIncludes.asp - This includes stuff like my general libraries (Database Access, file functions, etc) and sets up security and includes any configuration files (like connection strings, directory locations, etc) and common classes (User, Permission, etc) and is included in every page.
Modules/ModuleName/page.vb.asp - Kind of like a code behind page. Includes page specific BO, BLL and DAL classes and sets up the data required for the page/receives submitted form data, etc
Modules/ModuleName/Display/INC-DIS-Page.asp - Displays the data set up in page.vb.asp.
Echoing some ideas and adding a few of my own:
1) Best way to access the database would to abstract that away into a COM component of some sort that you access from VBScript.
2) If you really wanted to you could write the controller in VBScript and then access that in the page. It would resemble a Page Controller pattern and not a Front Controller that you would see in ASP.NET MVC or MonoRail
3) Why are you doing this to yourself? Most of the tooling required to do this kind of work isn't even available anymore.
AXE - Asp Xtreme Evolution is a MVC framework for ASP classic
There are some attempts at making test frameworks for asp:
aspUnit is good, but no longer maintained.
I saw a sample on how to make your own one a few months back.
The example used nUnit to call functions against the website for automatic testing.
I think i got it off here (my line is borked so I can't check)
On number 2, I think you have a few options...
1) You can use COM components developed in VB6 or the like to separate some of your business logic from your UI.
2) You can create classes in VBScript. There is no concept of inheritance and other more advanced features are missing from the implementation, but you can encapsulate logic in classes that helps reduce the spagehtti-ness of your app. Check out this: https://web.archive.org/web/20210505200200/http://www.4guysfromrolla.com/webtech/092399-1.shtml
I agree with #Cirieno, that the selected answer would not be wise to use in production code, for all of the reasons he mentions. That said, if you have just a little experience, this answer is a good starting point as to the basics.
In my ASP experience, I preferred to write my database access layer using VB, compiling down to a DLL and referencing the DLL via VBScript. Tough to debug directly through ASP, but it was a nice way to encapsulate all data access code away from the ASP code.
way way back in the day when VBScript/ASP were still ok
I worked in a utility company with a very mixed DB envrionment, I used to swear by this website: http://www.connectionstrings.com/
#michealpryor got it right
I've been stuck building on ASP, and I feel your pain.
1) The best way to query against SQL Server is with parameterized queries; this will help prevent against SQL injection attacks.
Tutorial (not my blog):
http://www.nomadpete.com/2007/03/23/classic-asp-which-is-still-alive-and-parametised-queries/
2) I haven't seen anything regarding MVC specifically geared towards ASP, but I'm definitely interested because it's something I'm having a tough time wrapping my head around. I generally try to at least contain things which are view-like and things which are controller-like in separate functions. I suppose you could possibly write code in separate files and then use server side includes to join them all back together.
3) You're probably coming from a language which has more functionality built in. At first, some things may appear to be missing, but it's often just a matter of writing a lot more lines of code than you're used to.
Also for database access I have a set of functions - GetSingleRecord, GetRecordset and UpdateDatabase which has similar function to what Michael mentions above

Resources