Quick question... I have to work with quite a bit of legacy ASP code that I am cleaning up, and it all uses queries that are vulnerable to SQL injection. I have a library that I put together to replace them with parameterized queries, and I'm wondering if there is a difference from a security standpoint between the following approaches.
Approach 1: This is the approach shown on most examples where parameter objects are individually built and added to the Command object. Here's an example from another question.
Approach 2: Use the Command.Execute method with an array of parameter values. Example:
Command.CommandText = "select foo, bar from baz where a = ? and b = ?"
Command.Execute , Array(1, "BBB")
Yes, the first parameter to Execute is ignored.
The first approach has each parameter built with its type, size, etc all specified, and it needs to match the database. But I've always had trouble with that approach, weird errors and the like if everything isn't "just" perfect. So I prefer the latter, and it in fact works with my coding style much better because I can encapsulate the DB logic into a class and pass around arrays as needed without having to litter my code with tons of DB calls.
Example of approach #2 using my wrapper DB.Query method:
set rs = DB.Query("select foo, bar from baz where a = ? and b = ?", Array(1, "BBB")
Or:
set rs = DB.Query("select foo, bar from baz", empty)
(passing keyword empty to denote the parameter is not used)
Given that, I'm wondering: Is approach #2 still safe from SQL injection attacks?
Thanks.
Edit The call to Execute was wrong and written from memory, it has been corrected.
From my sight: yes it is.
i wrote a quick example and then debugged it with Visual Studio. After the call to
Command.Execute , Array(1, "BBB")
the Parameters object of the ADODB.Command is properly filled with the given values from the Array. The datatype and length of the parameters is correctly set.
So in my opinion this approach is as safe as the approach #1 (with a manually created Parameters object).
Related
I tried to understand the new ways and possibilities with Codeigniter4.
I see a shorter way by the build in Crud-Model to do the simplest job with a bit less of code.
Do I insert new datas in the controller with this code, after I setup the myModel with the protected variables.?
$this->myModel->insert(['filed1' => 'value1,
'field2' =>$this->request->getPost('field')...
]));
So that works fine.
Now I want to make it a bit more secure and I want to insert only escaped values.
For that CodeIgniter has a lot of built-in functions/helpers. So I try to use "escape()" in this way
$this->myModel->insert(escape(['filed1' => 'value1,
'field2' =>$this->request->getPost('field')...
])));
but it failed with the error "Call to undefined function App\Controllers\escape()"
So how I can insert only escaped values into my db with the nicest/fastest code/Way may which is supported with the build-in basic Crud functions?
Thanks to teach/help me in this point!
escape doesn't work in a global context because that method is a member of the Database class (or rather, a parent class that implements the ConnectionInterface interface).
esc is a global function, which is why that works in a global context.
However, esc is designed to escape data that's going into web pages, not databases.
The good news is, if you're using Query Builder methods, then input is already escaped for you automatically:
It also allows for safer queries, since the values are escaped
automatically by the system.
If for some reason you still need to manually escape input (e.g. using basic queries), there are a few options, including the escape method you were trying to use earlier.
I find a first way with "esc()"
$this->myModel->insert(['filed1' => esc('value1'),
'field2' => esc($this->request->getPost('field'))...
]));
maybe there is a better way or someone has another sugeestion?
This question is with reference to the Cymbol code from the book (~ page 143) :
int t = ctx.type().start.getType(); // in DefPhase.enterFunctionDecl()
Symbol.Type type = CheckSymbols.getType(t);
What does each component return: "ctx.type()", "start", "getType()" ? The book does not contain any explanation about these names.
I can "kind of" understand that "ctx.type()" refers to the "type" rule, and "getType()" returns the number associated with it. But what exactly does the "start" do?
Also, to generalize this question: what is the mechanism to get the value/structure returned by a rule - especially in the context of usage in a listener?
I can see that for an ID, it is:
String name = ctx.ID().getText();
And as in above, for an enumeration of keywords it is via "start.getType()". Any other special kinds of access that I should be aware of?
Lets disassemble problem step by step. Obviously, ctx is instance of CymbolParser.FunctionDeclContext. On page 98-99 you can see how grammar and ParseTree are implemented (at least the feeling - for real implementation please see th .g4 file).
Take a look at the figure of AST on page 99 - you can see that node FunctionDeclContext has a several children, one labeled type. Intuitively you see that it somehow correspond with function return-type. This is the node you retrieve when calling CymbolParser.FunctionDeclContext::type. The return type is probably sth like TypeContext.
Note that methods without 'get' at the beginning are usually children-getters - e.g. you can access the block by calling CymbolParser.FunctionDeclContext::block.
So you got the type context of the method you got passed. You can call either begin or end on any context to get first of last Token defining the context. Simply start gets you "the first word". In this case, the first Token is of course the function return-type itsef, e.g. int.
And the last call - Token::getType returns integral representation of Token.
You can find more information at API reference webpages - Context, Token. But the best way of understanding the behavior is reading through the generated ANTLR classes such as <GrammarName>Parser etc. And to be complete, I attach a link to the book.
I've been a little surprised, because I have read before, that __gc metamethod is only called for userdata and never for tables. (LuaFAQ : Why don't the __gc and __len metamethods work on tables?)
But, recently, I have tried it and found it actually works! Try this code with Lua 5.2.1:
do
local b = setmetatable({a = 1}, {__gc = function(self) print(self.a); end});
end
collectgarbage();
But I can't find anywhere the changelog for this, so I'm little frustrated and afraid to use it.
Maybe, someone can prove my suggestion? Or it is an undocumented behaviour?
As for me it will be nice to have a regular way to create table destructor, and I will be glad if my observation is right.
The Lua 5.2 Reference Manual section 2.5.1 indicates that tables do support the __gc metamethod. Specifically, it says
For an object (table or userdata) to be finalized when collected, you must mark it for finalization. You mark an object for finalization when you set its metatable and the metatable has a field indexed by the string "__gc".
The similar documentation in the 5.1 Reference Manual says
Using the C API, you can set garbage-collector metamethods for userdata
It seems pretty clear that Lua 5.2 now explicitly supports the __gc metamethod for tables.
Some time recently, I heard someone espousing the fact that a domain model should not allow updating the domain objects via properties with a subsequent Save call. But rather all updates should be done through explicit methods. Example of how I understand what was said:
Bad Code (that seems pretty normal to me):
var x = _repository.GetCustomerByID(5);
x.Firstname = "Travis";
x.Lastname = "Laborde";
_respository.SaveCustomer(x);
The Code that I believe this person was pitching would look like:
var x = _repository.GetCustomerByID(5);
x.UpdateCustomerName("Travis", "Laborde");
_repository.SaveCustomer(x);
I'd like to learn more - is there a name to this pattern so that I can Google it on Bing?
I'm not aware of this pattern having a specific name, but from what you describe, there's a basic practical reason for this:
Writing x.Firstname = "Travis" does not let the x object know that the Firstname value was changed. This makes it hard to implement a SaveCustomer function that only uses UPDATE on the fields that were changed.
Of course, in a language that does support treating member assignment as a function call (like, say, C# does with its properties), this pattern becomes much less interesting.
I've implemented IDynamicObject in C# 4, return a custom MetaObject subclass that does simple property getter/setter dispatch to a Dictionary. Not rocket science.
If I do this:
dynamic foo = new DynamicFoo();
foo.Name = "Joe";
foo.Name = "Fred";
Console.WriteLine(foo.Name);
Then 'Joe' is printed to the console... the second call to the 'Name' setter is never invoked (never steps into my custom dispatcher code at all).
I know the DLR does callsite caching, but I assumed that wouldn't apply here. Anyone know what's going on?
Whatever MetaObject you're returning from (Bind)SetMember will be cached and re-used in this case. You have 2 dynamic sites doing sets. The 1st call will cache the result in an L2 cache which the 2nd site will pick up before asking you to produce a new rule.
So whatever MetaObject you're returning needs to include an expression tree that will update the value. For example it should do something like:
return new MetaObject(
Expression.AssignProperty(this.Expression, value.Expression),
Restrictions.TypeRestriction(this.Expression, this.Value.GetType());