Is the ability to debug stored procedures considered somehow frivolous? - sql-server

I am working on some stored procedures at a client site.
To debug stored procedures using SSMS, it seems you must be a member of the [sysadmin] group. However, they only have PROD and TEST database instances, and the DBA will not grant me these permissions.
According to him, using inline PRINT statements is considered to be just as good as the ability to debug. That doesn't seem quite right to me so I was thinking of escalating my request, but thought I'd first ask here, is this common sentiment in the industry (that the ability to debug is "not necessary")?

Though bit opinion based question but yes I have always used debug like that ... that is get the procedure body and run each code block separately to find where the problem is and fix accordingly.
You might also want to consider the execution plan of the procedure which will help in debugging.

In my experience, yes.
I once found the debugging functionality very useful when I was transitioning from being a ASP developer to a SQL developer, but as I've become more comfortable with SQL, I find that I can do all my debugging with PRINT statements.
Also in addition to being a sysadmin, did you know that you have to be running the debugger locally on the SQL server to use it? It's a lot more trouble than it's worth.

Related

SQL Server Profiler

I have been told that SQL Profiler makes changes to the MSDB when it is run. Is this true and if so what changes does it make?
MORE INFO
The reason I ask is that we have a DBA who wants us to range a change request when we run the profiler on a live server. Her argument is that it makes changes to the DB's which should be change controlled.
Starting a trace adds a row into msdb.sys.traces, stopping the trace removes the row. However msdb.sys.traces is a view over an internal table valued function and is not backed by any physical storage. To prove this, set msdb to read_only, start a trace, observer the new row in msdb.sys.traces, stop the trace, remember to turn msdb back read_write. Since a trace can be started in the Profiler event when msdb is read only it is clear that normally there is no write into msdb that can occur.
Now before you go and grin to your dba, she is actually right. Profiler traces can pose a significant stress on a live system because the traced events must block until they can generate the trace record. Live, busy, systems may experience blocking on resources of type SQLTRACE_BUFFER_FLUSH, SQLTRACE_LOCK, TRACEWRITE and other. Live traces (profiler) are usualy worse, file traces (sp_trace_create) are better, but still can cause issues. So starting new traces should definetly something that the DBa should be informed about and very carefully considered.
The only ones I know happen when you schedule a trace to gather periodic information - a job is added.
That's not the case as far as I'm aware (other than the trivial change noted by others).
What changes are you referring to?
Nothing I have ever read, heard, or seen says that SQL Profiler or anything it does or uses has any impact on the MSDB database. (SQL Profiler is, essentially, a GUI wrapped around the trace routines.) It is of course possible to configure a specific setup/implementation to do, well, anything, and perhaps that's what someone is thinking of.
This sounds like a kind of "urban legend". I recommend that you challenge it -- get the people who claim it to be true to provide proof.

SPROC hangs in SQL Server 2005

I get a problem with SQL Server 2005, where a stored procedure seems to randomly hang/lock, and never return any result.
What the stored procedure does is to call a function, which in turn makes a union of two different functions – returning the same type of data, but from different criteria. Nothing advanced. I don’t think it’s the functions hanging, because there are other SPROCs that call the same functions without a problem, even when the first one has locked up.
After the SPROC hangs, any further attempts to call it will result in a time out – not in the call itself, but the response time will be too great, as no result is returned the code will throw an exception.
It has happened at least three times in two months in a relatively low-load system. Restarting SQL Server solves the situation, but I don’t regard that as a “solution” to the problem.
I’ve looked for information, and found something about the query cache going corrupt. However, that was in regard to dynamic SQL strings, which my problem is not. I guess it could still be the query cache.
Has anyone had the same problem, and if so, what did you do about it (don’t say “restart SQL Server every morning” ;) )? Is there any way of debugging the issue to try and find exactly what and where things go wrong? I can’t recreate the problem, but when it appears again it would be good if I knew where to take a closer look.
I don't think it makes any difference, but just for the record, the SPROC is called from .NET 3.5 code, using the Entity Franework. I say it doesn't make a difference, because when I've tested to just execute the SPROC directly from SQL Server Management Studio, no result is returned either.
It's most likely parameter sniffing
Restarting SQL server clears the plan cache. If you rebuild statistics or indexes the problem will also go away "ALTER INDEX" and "sp_updatestats"
I suggest using "parameter masking" (not WITH RECOMPILE!) to get around it
SO answer already by me:
One
Two
Are your STATISTICS up to date? One of the common causes of an cached query plan that is incorrect, is out of date statistics.
Do you have a regularly scheduled index rebuild job?
Did you verify the SQL Server log..? Defenetly the cause for the problem is been logged.. atleast you can get some hint about that. pls check that.
This excellent MSDN Article SQL Server technical bulletin - How to resolve a deadlock
explains the steps needed to identify and resolve the deadlock issues in very detail.

Undocumented stored procedures in MS SQL, why?

I came to know about some uses of undocumented stored procedures (such as 'sp_MSforeachdb' ...etc) in MS SQL.
What are they? and Why they are 'undocumented'?
+1 on precipitous. These procs are generally used by replication or the management tools, they are undocumented as the dev team reserves the right to change them any time. Many have changed over the years, especially in SQL 2000 Sp3 and SQL 2005
My speculation would be because they are used internally and not supported, and might change. sp_who2 is another that I find very handy. Maybe management studio activity monitor uses that one - same output. Did I mention undocumented probably means unsupported? Don't depend on these to stick around or produce the same results next year.
sp_MSforeachdb and sp_MSforeachtable are unlikely to change.
Both can be used like this:
EXEC sp_MSforeachtable "print '?'; DBCC DBREINDEX ('?')"
where the question mark '?' is replaced by the tablename (or DB name in the other sp).
Undocumented means unsupported and that MS reserves the right to change or remove said commands at any time without any notice whatsoever.
Any documented features go through two deprecation stages before they are removed. An undocumented command can be removed, even in a service pack or hotfix, without any warning or any announcements.
It is most likely that one of the internal SQl Server developers needed these stored procedures to implement the functionality that they were working on, so they developed it and used it in their code. When working with the technical documentation people they covered the scope of their project, and included in the official documentation only the portion of their project that applied to the customer. Over time, people found the extra stored procedures (because you can't hide them) and started using them. While the internal SQl Server developers wouldn't want to change these undocumented procedures, I'm sure they would in two seconds if they had to to for their next project.
As others have said, they are unsupported features that are not intended for general consumption, although they can't stop you from having a go, and indeed, sometimes they can be very useful.
But as internal code, they might have unexpected side-effects or limitations, and may well be here one day and gone the next.
Use them carefully if you wish, but don't rely on them entirely.

Am I immune to SQL injections if I use stored procedures?

Lets say on MySQL database (if it matters).
No, you will not be completely safe. As others have mentioned, parameterized queries are always the way to go -- no matter how you're accessing the database.
It's a bit of an urban legend that with procs you're safe. I think the reason people are under this delusion is because most people assume that you'll call the procs with parameterized queries from your code. But if you don't, if for example you do something like the below, you're wide open:
SqlCommand cmd = new SqlCommand("exec #myProc " + paramValue, con);
cmd.ExecuteNonQuery();
Because you're using unfiltered content from the end user. Once again, all they have to do is terminate the line (";"), add their dangerous commands, and boom -- you're hosed.
(As an aside, if you're on the web, don't take unfiltered junk from the query string of the browser -- that makes it absurdly easy to do extremely bad things to your data.)
If you parameterize the queries, you're in much better shape. However, as others here have mentioned, if your proc is still generating dynamic SQL and executing that, there may still be issues.
I should note that I'm not anti-proc. Procs can be very helpful for solving certain problems with data access. But procs are not a "silver-bullet solution to SQL injections.
You are only immune to SQL injections if you consistenly use parameterized queries. You are nearly immune to SQL injections if you use proper escaping everywhere (but there can be, and has been, bugs in the escaping routines, so it's not as foolproof as parameters).
If you call a stored procedure, adding the arguments by concatenation, I can still add a random query at the end of one of the input fields - for example, if you have CALL CheckLogin #username='$username', #password='$password', with the $-things representing directly concatenated variables, nothing stops me from changing the $password variable to read "'; DROP DATABASE; --".
Obviously, if you clean up the input beforehand, this also contributes to preventing SQL injection, but this can potentially filter out data that shouldn't have been cleaned.
It depends what your stored procs do. If they dynamically generate SQL based on their parameters, and then execute that SQL, then you're still vulnerable. Otherwise, you're far more likely to be fine - but I hesitate to sound 100% confident!
nope. If you're constructing SQL that invokes a stored procedure you're still a target.
You should be creating parametized queries on the client side.
No, as you could still use D-SQL in your stored procedures... and validating and restricting your input is a good idea in any case.
Stored Procedures are not a guarantee, because what is actually vulnerable is any dynamic code, and that includes code inside stored procedures and dynamically generated calls to stored procedures.
Parameterized queries and stored procs called with parameters are both invulnerable to injection as long as they don't use arbitrary inputs to generate code. Note that there is plenty of dynamic code which is also not vulnerable to injection (for instance integer parameters in dynamic code).
The benefits of a largely (I'm not sure 100% is really possible) stored procs-based architecture, however, is that injection can even be somewhat defended against (but not perfectly) for dynamic code at the client side because:
Only EXEC permissions are granted to any user context the app is connecting under, so any SELECT, INSERT, UPDATE, DELETE queries will simply fail. Of course, DROP etc should not be allowed anyway. So any injection would have to be in the form of EXEC, so ultimately, only operations which you have defined in your SP layer will even be available (not arbitrary SQL) to inject against.
Amongst the many other benefits of defining your database services as a set of stored procedures (like any abstraction layer in software) are the ability to refactor your database underneath without affecting apps, the ability to better understand and monitor the usage patterns in your database with a profiler, and the ability to selectively optimize within the database without having to deploy new clients.
Additionally, consider using fine grained database access, (also called generally Role Based Access Control) The main user of your database should have exactly the permissions needed to do its job and nothing else. Don't need to create new tables after install? REVOKE that permission. Don't have a legitimate need to run as sysdba? Then don't! A sneaky injection instructing the user to "DROP DATABASE" will be stymied if the user has not been GRANTed that permission. Then all you need to worry about is data-leaking SELECT statements.

Usefulness of SQL Server "with encryption" statement

Recently a friend and I were talking about securing stored procedure code in a SQL server database.
From distant memory, I'm pretty certain that "with encryption" is incredibly easily broken in all versions of SQL Server, however he said it has been greatly improved in SQL 2005. As a result I have not seriously considered it as a security option in any systems I have ever worked on.
So in what scenarious could "with encryption" be used, and when should it be avoided at all costs?
It can be used to hide your code from casual observers, but as you say: it's easily circumvented.
It really can't be any other way, since the server needs to decrypt the code to execute it. It's DRM, basically, and fails for the same reason as all the other DRM does - you can't simultaneously hide the data, and allow it to be accessed.
#Blorgbeard
Good response, the MSDN documentation on "WITH ENCRYPTION" seems to agree with your point, now calling it "obfuscated" rather then encrypted.
I've met a few developers who were completely unaware of this point however. Hopefully this question/response will inform others too.
Yes, it's easily broken. I had a situation this past week where I had to decrypt several sprocs that a former developer had encrypted for a client of mine. After decrypting it, which took a moderate effort, I wouldn't rely on that for any means of protecting intellectual property, passwords, user ids. Anything really.

Resources