473,405 Members | 2,310 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Regular Expression

164 Expert 100+
Hello all, could not find a regular expression forum, so I thought I would post it to my favorite of the forums.

I have a series of applications I've developed which all use a centralized function that creates a connection object and executes an SQL query, i.e. function Query().

I always sanitize my SQL statements to buffer all apostrophes with two apostrophes ala function Buffer().

However, I have long wondered if I could do away with Buffer(), and use a high-end regular expression to detect a string value in an SQL expression, and automatically replace any single apostrophes in the statement with doubles.

Psuedocode example:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. Query sSQL, rs
  4.  
  5. ....
  6.  
  7. (now inside Query())
  8.  
  9. ..
  10. ' create connection, or use already open connection
  11. ' create new recordset 
  12. ' regular expression analyzes SQL statement passed in thru arguments, detects the apostrophe in "o'toole" (but not the apostrophes surrounding "george o'toole") and VBScript replaces it with two apostrophes so that sSQL now looks like this:
  13.  
  14. sSQL = "select id from users where name = 'george o''toole'"
  15.  
  16. ' execute sql statement, return recordset to calling program
  17.  
  18.  
I already have most of the logic done, but I am CRAP at regular expressions. Anyone think they've got the gusto to work with me on this one? I've tried a couple of times to write it myself, but keep giving up in frustration.
Dec 7 '07 #1
8 1744
NeoPa
32,556 Expert Mod 16PB
I've done some playing with regular expressions (REs), but I can't see why any special handling would be required here. The apostrophe (') is not treated specially so surely a simple change of {'} to {''} (ignore the {} - I just used them to delineate the two strings) would work for you.
I should say I'm also no ASP user, but simply on the RE front I can't see why they would be required. If there's something I've overlooked I'm more than happy to lend what experience I have to try to help.
BTW If you're using VBScript then I would expect the following to work :
Expand|Select|Wrap|Line Numbers
  1. sSQL = "SELECT [ID] " & _
  2.        "FROM [Users] " & _
  3.        "WHERE [Name] = '" & Replace(sName, "'", "''") & "'"
Dec 11 '07 #2
Motoma
3,237 Expert 2GB
As my compatriot NeoPa has already stated, there is no reason to use regular expressions to deal with apostrophes. Regex's are typically orders of magnitude more expensive than a simple linear search, so the Replace() function is your best and quickest solution.
Dec 11 '07 #3
Nicodemas
164 Expert 100+
I'm afraid there is a little confusion as to my specific goal, as well as my specific situation.

I have a global function (i.e. accessible by any script in my application) named Query(). It accepts two arguments, an SQL statement, and any variant which comes back as a recordset, i.e.

Expand|Select|Wrap|Line Numbers
  1. dim rs      '// passed back to script by Query as a recordset.
  2. dim sSQL    '// a string
  3. dim sName   '// a user submitted value
  4.  
  5. sName = request.form("txtName")
  6.  
  7. '//----------------------------------------------------
  8. '// assume the user entered: O'Toole
  9. '//----------------------------------------------------
  10.  
  11. sSQL = "SELECT * FROM Administrators WHERE lastName = "& sName
  12.  
  13. if Query(sSQL, rs) then
  14.    'life goes on...
  15. else
  16.    'hang yourself
  17. end if
  18.  
As you can see, Query can accept any type of SQL statement as its first argument, e.g. SELECTs, UPDATEs, DELETEs, etc...

If I were to run the above SQL against a database, it would error because of the apostrophe in "O'Toole."

Until present, I have have used a custom function to perform inline replace statements on content concatenated onto SQL statements, e.g.

Expand|Select|Wrap|Line Numbers
  1. '//----------------------------------------------------
  2. '// function Buffer just does a replace
  3. '// replace(randomString, "'", "''")
  4. '//----------------------------------------------------
  5. sSQL = "SELECT * FROM Administrators WHERE lastName = "& Buffer(sName)
  6.  
It is my desire to no longer do this! I want to pass an unsanitized string into Query(), and have it sanitized by a Regular Expression, then executed against the database.

Such a Regular Expression would detect any apostrophes that were not a part of the SQL syntax, then it would replace just those apostrophes found with two apostrophes.

A few examples:

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM Administrators WHERE lastName = 'O'Toole';
  2. '// would be changed to:
  3. SELECT * FROM Administrators WHERE lastName = 'O''Toole';
  4.  
  5.  
  6. INSERT INTO Administrators (lastName, firstName, pword) VALUES ('O'Toole', 'Jacob', 'linux');
  7. '// would be changed to:
  8. INSERT INTO Administrators (lastName, firstName, pword) VALUES ('O''Toole', 'Jacob', 'linux');
  9.  
  10.  
  11. UPDATE Administrators SET lastName = 'O'Toole' WHERE adminID = 4;
  12. '// would be changed to:
  13. UPDATE Administrators SET lastName = 'O''Toole' WHERE adminID = 4;
  14.  
  15.  
  16. DELETE FROM Administrators WHERE lastName = 'O'Toole';
  17. '// would be changed to:
  18. DELETE FROM Administrators WHERE lastName = 'O''Toole';
  19.  
All of this would happen without me ever writing another inline replace statement, or using Buffer() ever again.
Dec 13 '07 #4
NeoPa
32,556 Expert Mod 16PB
That's fair enough Nicodemas, but you appear to be expecting us to design a full SQL parser here for you, rather than some code to handle replacement of YOUR defined understanding of what's required.
If you want to define what you understand to be the patterns to be recognised I can help. If you want me to look up all the syntax for you, and then build a routine, incorporating all possible situations, for you, then I'm afraid I won't do that.

** EDIT **
This sounds a little harsh maybe, and rereading the OP I see you are asking for someone to work with you on this. I'm happy to do it that way, but I think the defining the parsing part is the difficult bit.
Dec 13 '07 #5
NeoPa
32,556 Expert Mod 16PB
I should add that it's good security practice among designer / developers of database front-ends for each string taken from the operator to pass through a "security" function, which disallows single quotes (apostrophes) from being passed back as they stand. This is to protect against SQL Insertion attacks.

It may be appropriate for you to consider taking this (much more straightforward) approach instead.
This will not handle passing names taken from your database tables into any SQL though, so may not suit your needs fully.

I should also add that your first post was actually expressed admirably clearly. Sometimes it's just hard to take it all in without missing some important details though I'm afraid.
Dec 13 '07 #6
NeoPa
32,556 Expert Mod 16PB
As a final comment, I would just say that whatever algorithm is used here, I don't thing REs (per-se) can be. If a concept can be conceived (a fairly big ask), then this would have to be implemented in standard code. The concept may end up as something similar to what is found when working with REs, but I can see no way to utilise an RE system within this sort of situation.
The reason I mention this (it may seem obvious) is that it means RE experience is unlikely to be of help in this situation, although pattern matching skills may help to determine what the algorithm should be that we're looking for maybe.
Dec 13 '07 #7
Motoma
3,237 Expert 2GB
I'm afraid there is a little confusion as to my specific goal, as well as my specific situation.

I have a global function (i.e. accessible by any script in my application) named Query(). It accepts two arguments, an SQL statement, and any variant which comes back as a recordset, i.e.

Expand|Select|Wrap|Line Numbers
  1. dim rs      '// passed back to script by Query as a recordset.
  2. dim sSQL    '// a string
  3. dim sName   '// a user submitted value
  4.  
  5. sName = request.form("txtName")
  6.  
  7. '//----------------------------------------------------
  8. '// assume the user entered: O'Toole
  9. '//----------------------------------------------------
  10.  
  11. sSQL = "SELECT * FROM Administrators WHERE lastName = "& sName
  12.  
  13. if Query(sSQL, rs) then
  14.    'life goes on...
  15. else
  16.    'hang yourself
  17. end if
  18.  
As you can see, Query can accept any type of SQL statement as its first argument, e.g. SELECTs, UPDATEs, DELETEs, etc...

If I were to run the above SQL against a database, it would error because of the apostrophe in "O'Toole."

Until present, I have have used a custom function to perform inline replace statements on content concatenated onto SQL statements, e.g.

Expand|Select|Wrap|Line Numbers
  1. '//----------------------------------------------------
  2. '// function Buffer just does a replace
  3. '// replace(randomString, "'", "''")
  4. '//----------------------------------------------------
  5. sSQL = "SELECT * FROM Administrators WHERE lastName = "& Buffer(sName)
  6.  
It is my desire to no longer do this! I want to pass an unsanitized string into Query(), and have it sanitized by a Regular Expression, then executed against the database.

Such a Regular Expression would detect any apostrophes that were not a part of the SQL syntax, then it would replace just those apostrophes found with two apostrophes.

A few examples:

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM Administrators WHERE lastName = 'O'Toole';
  2. '// would be changed to:
  3. SELECT * FROM Administrators WHERE lastName = 'O''Toole';
  4.  
  5.  
  6. INSERT INTO Administrators (lastName, firstName, pword) VALUES ('O'Toole', 'Jacob', 'linux');
  7. '// would be changed to:
  8. INSERT INTO Administrators (lastName, firstName, pword) VALUES ('O''Toole', 'Jacob', 'linux');
  9.  
  10.  
  11. UPDATE Administrators SET lastName = 'O'Toole' WHERE adminID = 4;
  12. '// would be changed to:
  13. UPDATE Administrators SET lastName = 'O''Toole' WHERE adminID = 4;
  14.  
  15.  
  16. DELETE FROM Administrators WHERE lastName = 'O'Toole';
  17. '// would be changed to:
  18. DELETE FROM Administrators WHERE lastName = 'O''Toole';
  19.  
All of this would happen without me ever writing another inline replace statement, or using Buffer() ever again.
I am sorry Nicodemas, but this simply isn't how input sanitization works.
Take the following instances, how would these be properly quoted?
SELECT * FROM users WHERE username = 'Motoma'
SELECT * FROM users WHERE username = 'Motoma' AND password = 'nothing'

If you look at that and say "they are both correctly escaped" you could be wrong. While the first one is obviously correct, the second one could have have been correct, or it could have been the result of SQL injection with the input being "Motoma' AND password = 'nothing'"
The problem is, there is _no_reasonable_way_ to programmatically tell while keeping your Query function sufficiently powerful.
Dec 14 '07 #8
Nicodemas
164 Expert 100+
I concede. Exhaustive queries, searching, testing have rendered nothing. Thanks for your inputs.
Dec 14 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Kenneth McDonald | last post by:
I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make...
4
by: Buddy | last post by:
Can someone please show me how to create a regular expression to do the following My text is set to MyColumn{1, 100} Test I want a regular expression that sets the text to the following...
4
by: Neri | last post by:
Some document processing program I write has to deal with documents that have headers and footers that are unnecessary for the main processing part. Therefore, I'm using a regular expression to go...
11
by: Dimitris Georgakopuolos | last post by:
Hello, I have a text file that I load up to a string. The text includes certain expression like {firstName} or {userName} that I want to match and then replace with a new expression. However,...
3
by: James D. Marshall | last post by:
The issue at hand, I believe is my comprehension of using regular expression, specially to assist in replacing the expression with other text. using regular expression (\s*) my understanding is...
7
by: Billa | last post by:
Hi, I am replaceing a big string using different regular expressions (see some example at the end of the message). The problem is whenever I apply a "replace" it makes a new copy of string and I...
9
by: Pete Davis | last post by:
I'm using regular expressions to extract some data and some links from some web pages. I download the page and then I want to get a list of certain links. For building regular expressions, I use...
25
by: Mike | last post by:
I have a regular expression (^(.+)(?=\s*).*\1 ) that results in matches. I would like to get what the actual regular expression is. In other words, when I apply ^(.+)(?=\s*).*\1 to " HEART...
1
by: Allan Ebdrup | last post by:
I have a dynamic list of regular expressions, the expressions don't change very often but they can change. And I have a single string that I want to match the regular expressions against and find...
1
by: NvrBst | last post by:
I want to use the .replace() method with the regular expression /^ %VAR % =,($|&)/. The following DOESN'T replace the "^default.aspx=,($|&)" regular expression with "":...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.