MongoDb application security - mongodb

I'm checking with MongoDB application. There is application installed on my system, when I enter single quote(') in the input box it pop up the following error:
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
/usr/lib/cgi-bin/mongo/2.2.3/dbparse.py in ()
41 print "</th>"
42 if where:
=> 43 for record in collection.find(where):
44 print "<tr>"
45 print "<td align=\"center\">"+record["test"]+"</td>"
record undefined, collection = Collection(Database(MongoClient('localhost', 27017), u'test_d'), u'london_garages'), collection.find = <bound method Collection.find of Collection(Data...', 27017), u'test_d'), u'l_g')>, where = {'$where': "this.test== ''--'"}
What is the meaning of the error? If you have another pointer to check the security of this application please let me know.

If you look at the error and the following part:
where = {'$where': "this.test== ''--'"}
I assume the single quote goes to the where clause (some sort of search), so your code is probably something like the following:
where = {'$where': "this.test== '[YOUR TEXT BOX INPUT]--'"}
A single quote terminated your where clause prematurely. This is a good demonstration for a NoSQL injection.

Related

MongoDB find operation throws OperationFailure: Cannot update value

I have an application that uses MongoDB (on AWS DocumentDB) to stores documents with a large string in one of its fields which we call field X.
Few notes to start:
I'm using pymongo so the method names you might see here are taken from there
As of the nature of field X it is not being indexed
On field X we use MongoDB find method using a query with regex condition limiting it by both maxTimeMS and limit to a small amount of results.
When we get the results we iterate the cursor to fetch all the results to a list (inline loop).
Most of the times the query works properly but I'm starting to get more and more of the following error:
pymongo.errors.OperationFailure: Cannot update value (error code 14)
This is being thrown after the query return a cursor and we iterating the results and occurs after trying to _refresh the cursor connection by calling the next method and being thrown by _check_command_response at its last line meaning this is a default exception(?).
The query:
collection.find(condition).max_time_ms(MAX_QUERY_TIME_MS).sort(sort_order) \
.limit(RESULT_LIMIT)
results = [document for document in cursor] # <--- here we get the error
Stack trace:
pymongo/helpers.py in _check_command_response at line 155
pymongo/cursor.py in __send_message at line 982
pymongo/cursor.py in _refresh at line 1104
pymongo/cursor.py in next at line 1189
common/my_code.py in <listcomp> at line xxx
I'm trying to understand the origin of the exception to handle it correctly or use a different approach for handling the cursor.
what is being updated at the refresh method of the cursor that might
throw the above exception?
Thanks in advance.

"Insecure dependency error while running with -T switch" using cicindela2

I am applying the cicindela2 recommendation engine
It uses Apache mod_perl and the Perl DBI module.
Here is the rough flow of how it works
Data input by Record Handler
Data is passed through the filter chain for batch processing
Temporary tables are output from batch processing
Recommendation result is requested by accessing the Recommend Handler which trigger the action of Recommender
I configured an aggregation and ran the project batch script. I know that the batch processing succeeded because I saw the output of processing from DB. But when I tried to access the recommendation result with URL that triggers the Recommend Handler, I saw a blank white page and the log said
FATAL: Insecure dependency in parameter 1 of DBIx::ContextualFetch::db=HASH(0x7f2a76169e78)->prepare_cached method call while running with -T switch at /usr/local/share/perl5/Ima/DBI.pm line 398.
This is where the error was thrown from the
Ima::DBI
base module
/usr/local/share/perl5/Ima/DBI.pm.
sub _mk_sql_closure {
my ($class, $sql_name, $statement, $db_meth, $cache) = #_;
return sub {
my $class = shift;
my $dbh = $class->$db_meth();
# Everything must pass through sprintf, even if #_ is empty.
# This is to do proper '%%' translation.
my $sql = $class->transform_sql($statement => #_);
return $cache # Line 398
? $dbh->prepare_cached($sql)
: $dbh->prepare($sql);
};
}
It seems that the SQL query prepared by the program is insecure, right?
What is reason for this error?
Is it related to the function of cache management of DBI?
Would it be solved if I clear the cache regularly?
Also, I tried to log the SQL statement generated, but the output failed even when I placed something like $LOGGER->warn("123") in the handle subroutine of the Recommend Handler.
How come the log failed and how to log it correctly?
Insecure dependency... while running with -T switch is Perl's way of telling you that you're running with taint mode active and attempting to do something with tainted data which could be potentially unsafe. In this particular case, $sql is tainted, because some or all of its content came from sources external to the program - probably user input, although it could also have been read from a file.
To fix this, you need to think about where $sql came from, so that you can work out the appropriate way to clean it up.
In the most likely scenario, you've asked a user to supply search terms and then inserted those terms directly into your SQL string. This is a bad idea in general, as it opens you up to the possibility of SQL injection attacks. (Obligatory Bobby Tables link.) Revise your SQL handling to make use of SQL placeholders instead of inserting user input into the WHERE clause and this vulnerability should go away.
If tainted data is making its way into $sql in some other way, you need to clean up the tainted data by using a regular expression to validate it and capture the validated data, then assign the captured data to your variable. e.g.,
my $tainted = <STDIN>;
$tainted =~ /([A-Z]*)/; # Only allow uppercase characters
my $clean = $1; # No longer tainted because it came from $1
If you need to take this route, DO NOT use .* as your regex to untaint the data without serious, serious consideration, because, if you just blindly accept any and all data, you will be discarding any and all benefit provided by taint mode.

Crash with Lucene.NET when using Sort

I have a date field inserted in a Lucene database with the following code:
Document.Add(new NumericField("TimeStamp", Field.Store.YES, true).SetLongValue(Data.TimeStamp.ToBinary()));
And I have the following query:
var Sort = new Sort(new SortField("TimeStamp", SortField.LONG, true));
var ParsedQuery = ParseQuery(_Parser, SearchQuery);
var Filter = new QueryWrapperFilter(ParsedQuery);
var Hits = _Searcher.Search(ParsedQuery, Filter, Skip + Limit, Sort);
But it crashes when executing the search method with the following:
A first chance exception of type 'Lucene.Net.QueryParsers.QueryParser.LookaheadSuccess' occurred in Lucene.Net.dll
A first chance exception of type 'System.IO.IOException' occurred in Lucene.Net.dll
A first chance exception of type 'System.IO.IOException' occurred in Lucene.Net.dll
A first chance exception of type 'System.AccessViolationException' occurred in HDIndexing.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
If I replace the Sort variable with one of the constants, such as Sort.RELEVANCE then the search works properly.
The problem comes from my custom search.
Incidentally I noticed something else odd and I do not know if these is a connection: If I inspect my Lucene DB with the Luke tool, all my fields are reported to be strings:
http://i.stack.imgur.com/SnlSD.png
I do not know if this is a bug in Luke or something is wrong with how Lucene is set up on my end.
I tried to change the sort to a type 'string' to see what would happen, but it crashes the same way, so either way, the type of the field doesn't seem to have an impact.
Has anyone experienced that problem before?
It could be similar to someone else's post: lucene.net sort not working access violation

DBIx::Class undefined value exception when trying to use ->create()

I'm trying to create a new row using DBIx::Class from within Catalyst, with the following code:
$c->model('Session')->resultset('UserPreference')->create(
{
appname => 'rss_reader',
username => $username,
data => $data,
},
);
But, I hit this error every time:
Caught exception in App::Controller::rss->dbo "Can't call method "resolve" on an undefined value at /etg/source/Linux/pkg/perl-5.8.8/lib/site_perl/5.8.8/DBIx/Class/Row.pm line 1309."
I see a few mailing lists talking about this error being thrown as an incorrect blanket error when the query fails for whatever reason (perms, constraints,etc.), but it looks just fine AND even running with DBIC_TRACE=1, I don't even see the generated query in my console.
I should mention I don't think there's something bad with the permissions,etc. since using the database handle manually works:
my $stm=$c->model("Session")->storage->dbh->prepare("insert into user_preferences (username,appname,data) values ('mphillip','rss_reader','cookies')"); $stm->execute();
Have you tried update_or_create instead of create? If a row exists create will fail.

After querying DB I can't print data as well as text anymore to browser

I'm in a web scripting class, and honestly and unfortunately, it has come second to my networking and design and analysis classes. Because of this I find I encounter problems that may be mundane but can't find the solution to it easily.
I am writing a CGI form that is supposed to work with a MySQL DB. I can insert and delete into the DB just fine. My problem comes when querying the DB.
My code compiles fine and I don't get errors when trying to "display" the info in the DB through the browser but the data and text doesn't in fact display. The code in question is here:
print br, 'test';
my $dbh = DBI->connect("DBI:mysql:austinc4", "*******", "*******", {RaiseError => 1} );
my $usersstatement = "select * from users";
my $projstatment = "select * from projects";
# Get the handle
my $userinfo = $dbh->query($usersstatement);
my $projinfo = $dbh->query($projstatement);
# Fetch rows
while (#userrow = $userinfo->fetchrow()) {
print $userrow[0], br;
}
print 'end';
This code is in an if statement that is surrounded by the print header, start_html, form, /form, end_html. I was just trying to debug and find out what was happening and printed the statements test and end. It prints out test but doesn't print out end. It also doesn't print out the data in my DB, which happens to come before I print out end.
What I believe I am doing is:
Connecting to my DB
Forming a string the contains the command/request to the DB
Getting a handle for my query I perform on the DB
Fetching a row from my handle
Printing the first field in the row I fetched from my table
But I don't see why my data wouldn't print out as well as the end text. I looked in DB and it does in fact contain data in the DB and the table that I am trying to get data from.
This one has got me stumped, so I appreciate any help. Thanks again. =)
Solution:
I was using a that wasn't supported by the modules I was including. This leads me to another question. How can I detect errors like this? My program does in fact compile correctly and the webpage doesn't "break". Aside from me double checking that all the methods I do use are valid, do I just see something like text not being displayed and assume that an error like this occurred?
Upon reading the comments, the reason your program is broken is because query() does not execute an SQL query. Therefore you are probably calling an undefined subroutine unless this is a wrapper you have defined elsewhere.
Here is my original posting of helpful hints, which still apply:
I hope you have use CGI, use DBI, etc... and use CGI::Carp and use strict;
Look in /var/log/apache2/access.log or error.log for the bugs
Realize that the first thing a CGI script prints MUST be a valid header or the web server and browser become unhappy and often nothing else displays.
Because of #3 print the header first BEFORE you do anything, especially before you connect to the database where the script may die or print something else because otherwise the errors or other messages will be emitted before the header.
If you still don't see an error go back to #2.
CGIs that use CGI.pm can be run from a command line in a terminal session without going through the webserver. This is also a good way to debug.