Executing code dynamically is security sensitive. It has led in the past to the following vulnerabilities:

* http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-9807[CVE-2017-9807]
* http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-9802[CVE-2017-9802]

Some APIs enable the execution of dynamic code by providing it as strings at runtime. These APIs might be useful in some very specific meta-programming use-cases. However most of the time their use is frowned upon as they also increase the risk of https://owasp.org/www-community/attacks/Code_Injection[Injected Code]. Such attacks can either run on the server or in the client (exemple: XSS attack) and have a huge impact on an application's security.


Both ``++EXECUTE( ... )++`` and ``++EXEC( ... )++`` execute as a command the string passed as an argument. They are safe only if the argument is composed of constant character string expressions. But if the command string is dynamically built using external parameters, then it is considered very dangerous because executing a random string allows the execution of arbitrary code.


This rule marks for review each occurrence of ``++EXEC++`` and ``++EXECUTE++``. This rule does not detect code injections. It only highlights the use of APIs which should be used sparingly and very carefully. The goal is to guide security code reviews.

include::../ask-yourself.adoc[]

== Recommended Secure Coding Practices

The best solution is to not run code provided by an untrusted source. If you really need to build a command string using external parameters, you should use ``++EXEC sp_executesql++`` instead.


Do not try to create a blacklist of dangerous code. It is impossible to cover all attacks that way.

== Sensitive Code Example

----
CREATE PROCEDURE USER_BY_EMAIL(@email VARCHAR(255)) AS
BEGIN
  EXEC('USE AuthDB; SELECT id FROM user WHERE email = ''' + @email + ''' ;'); -- Sensitive: could inject code using @email
END
----

== Compliant Solution

[source,sql]
----
CREATE PROCEDURE USER_BY_EMAIL(@email VARCHAR(255)) AS
BEGIN
  EXEC sp_executesql 'USE AuthDB; SELECT id FROM user WHERE email = @user_email;',
                     '@user_email VARCHAR(255)',
                      @user_email = @email;
END
----

include::../see.adoc[]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Use "sp_executesql" to execute this command string using dynamic parameters.


'''
== Comments And Links
(visible only on this page)

=== on 20 Jul 2017, 16:22:16 Pierre-Yves Nicolas wrote:
https://msdn.microsoft.com/en-us/library/ms175170(v=sql.105).aspx[Microsoft recommends using sp_executesql].

=== on 20 Jul 2017, 16:26:40 Pierre-Yves Nicolas wrote:
Maybe we should target both ``++EXECUTE(sql)++`` and ``++sp_executesql++`` where the executed string is the result of a concatenation which uses a parameter of the current procedure.

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
