Skip to content

Prepared Statements and Security #1608

Closed

Description

@noah-goodrich

According to #998, the issue of prepared statements and parameter binding through the native mysql driver was considered and rejected previously.

I would like to reopen the issue as a security concern for queries being run against the server.

Frameworks in other languages use bound parameters natively because it is inherently more secure than doing the escaping in the framework and passing pure strings to the mysql server to process.

Can you explain the justification for not using prepared statements by default in Sequelize for security purposes?

Activity

  1. mickhansen commented on Apr 8, 2014

    @mickhansen
    Contributor

    The justifications are in the original issue i believe, one of them being that the drivers didn't support it - Not sure if that is the case anymore?

    Can you point to any reading material on bound parameters being inheritently more secure than framework escaping?

  2. noah-goodrich commented on Apr 8, 2014

    @noah-goodrich
    Author

    For a fairly decent treatment of the topic: http://stackoverflow.com/questions/8263371/how-prepared-statements-can-protect-from-sql-injection-attacks

    This node library implements prepared statement support: https://github.com/sidorares/node-mysql2

    The main gist here is that you are passing a 'template' to the server first and then you are passing the parameters to be used within the template separately. As a result, there is 0% chance of the server (assuming it is handling its arguments correctly) misinterpreting a value in a bound parameter as an instruction that should be executed as part of the template. Any library that implements parameter escaping instead is inherently less secure as it is possible that malicious 'instructions' could be inserted into the string that is ultimately passed to the server.

  3. mickhansen commented on Apr 8, 2014

    @mickhansen
    Contributor

    We use node-mysql though, plus we have support for sqlite and postgres aswell.
    I see your point, it still probably won't be a priority for a while - Lots of other stuff to look at.
    I've tagged this issue as a feature request, and others will be able to flag their support.

  4. mickhansen commented on Apr 8, 2014

    @mickhansen
    Contributor

    The link you provided seems to cover general SQL injection protection - I was hoping for resources digging into framework vs database. But as i said, i see your point ;) In any case the server is most likely implemented "better" than any framework.

  5. bill-myers commented on Sep 25, 2014

    @bill-myers

    Wait, are you seriously resending the whole SQL for EVERY CRUD OPERATION?

    Do you realize that this means that the server will have to PARSE SQL on every operation, which is ridiculous and totally unnecessary?

    Not to mention the overhead to escape things and so on.

    It's unfortunate that Node.js ORM software is such a joke.

    Please fix yesterday.

  6. mickhansen commented on Sep 25, 2014

    @mickhansen
    Contributor

    @bill-myers Awaiting your PR.
    Edit: Would love to see some resources on prepared statement performance actually.

  7. calvintwr commented on Mar 31, 2015

    @calvintwr
    Contributor

    @mickhanson if it still interests you.

    http://security.stackexchange.com/questions/3611/sql-injection-why-isnt-escape-quotes-safe-anymore

    From a theoratical point of view, prepare statements would prepare the access plans awaiting the parameters to be passed in, hence shouldn't be slow, as compared to javascript escaping the queries.

    And plus, it was viewed that it's never possible to cover the myriad of possibilities to inject given all possible permutations of sql constructs. Though general escaping would reduce such possibilities to near zero.

    Prepare statement is a solution that attacks the fundaments in a very common sense way. That is, if the thing that you were intending to do has changed so much after the parameters have been passed in, the third party must have passed in something that changed what you have intended. Thats quite rock solid.

  8. efuquen commented on Apr 8, 2015

    @efuquen

    @mickhansen pg and sqlite3 both have support for prepared statements. node-mysql2 is suppose to be API compatible with node-mysql, meaning you should just be able to drop it in and get the benefits of prepared statements without breaking anything. Obviously it should be tested.

    Overall I'm disappointed this is not considered a priority over other issues or features. The security benefits are well documented, personally I would think that would trump most if not all other issues outside of bugs breaking basic functionality. And then there are the performance benefits you get as a bonus.

    I get this is an open source project and if I really needed this I could submit a PR myself (which I don't, since I'm not using sequelize). But there is a difference between "we as maintainers don't have the time to implement new features like this" vs "we as maintainers have time to do some stuff, but we've decided this isn't important enough". I consider something that would improve security greatly and make the web a safer place of critical importance, so if other features are being prioritized over this it really bums me out.

  9. mickhansen commented on Apr 9, 2015

    @mickhansen
    Contributor

    @efuquen I understand your sentiment. Can you quantify the exact security benefits? So far the single security vulnerability in sequelize has been from an injection into the column name, which prepared statenents wouldn't have done much again.

    As for performance benefits, i'm still actively looking for some documentation or benchmarks on that (other than that i'm apparently an idiot for not obviously accepting that fact). (also say switching to node-mysql2 rather than node-mysql might take a performance hit)

    I don't doubt that security would improve from a theoretical point of view, however from a practical point the effects are probably minimal.

    It's still a priority for us but this change is more a bottom-up refactor than a 2-3 hour bugfix/feature.

    "Important enough" is a dangerous term to use, there's a factor of 10 more people who think that getting polymorphic associations or JSONB implementated is more important than prepared statements. (although i guess in fairness they might not be running penetration tests on their codebase).

    @efuquen Your comment was appreciated while highly negative and doesn't really seem to take into account the resources needed to run a project of sort-of-decent size - But i've put investigating the effort needed to implement this for postgres, sqlite, mysql and mssql on my list: #3495 and am hopefully able to do a review soon.

    @mbroadst Does the MSSQL driver support prepared statements?

  10. mbroadst commented on Apr 9, 2015

    @mbroadst
    Contributor

    @mickhansen sure does! I'll definitely take over migrating that over if you end up choosing a pattern for the other dialects. http://pekim.github.io/tedious/parameters.html for reference.

  11. mdarveau commented on Apr 10, 2015

    @mdarveau
    Contributor

    I also believe that prepared statements can improved performance if used
    right
    . If a prepared statement can be reused, the DBMS can skip some plan
    preparation and you save some (probably neglectable) bandwidth between the
    application and the database.

    However, the key here is "if prepared statement can be reused". This
    implies that there is some sort of caching of prepared statement so that
    (1) in the same transaction/session/connection it can be reused and (2) the
    same prepared statement can be used by multiple connections.

    If this can't be achieved, it could actually decrease performance a lot.
    Imagine that for each query, the prepared statement need to be sent and
    then the query executed using the prepared statement. This double the
    number of round-trips to the DBMS for each query. Even if the driver
    supports (1), you would only get the benefit of prepared statements if you
    execute the same query (excluding parameters) multiple times in the same
    transaction/connection but you would get the a performance hit for all
    other queries.

    The MySQL 2 driver supports 1 but not 2 (
    https://www.npmjs.com/package/mysql2#automatic-creation-cached-and-re-used-by-connection).
    If connections are pooled, it is likely that at some points all prepared
    statements would be cached. This could lead to memory issues down the road.
    If you look at how complex the prepared statement caching options are
    complex in c3p0 (java connection pooling), you will see that this cache
    management is far from easy.

    The Postgres driver (
    https://github.com/brianc/node-postgres/wiki/Prepared-Statements) supports
    prepared statement, but it says "the prepared statement is attached to the
    session". I have never used the driver directly so I'm not sure what is the
    life cycle of the session.

    For what it's worth, I think that prepared statements support could be
    added to Sequelize at some point, but you guys are doing an incredibly good
    job at improving the API, functionality and stability of this project. I
    don't think you should defocus solely because of the security argument. The
    most used ORM in Java (Hibernate) does the SQL injection escaping by itself
    and no one complains about the potential security flaws. It does support
    prepared statement if needed (via JDBC) but does not claim it's required to
    guarantee security.

    Again, you are doing great work with sequelize. I follow and use quite a
    few open source projects and you are one of the best when it comes to
    responsiveness, PR acceptance, bug fixing and product improvements. Please
    don't be affected too much by negative comments.

    Cheers,

    Manuel

    On 9 April 2015 at 01:26, Mick Hansen [email protected] wrote:

    @efuquen https://github.com/efuquen I understand your sentiment. Can
    you quantify the exact security benefits? So far the single security
    vulnerability in sequelize has been from an injection into the column name,
    which prepared statenents wouldn't have done much again.

    As for performance benefits, i'm still actively looking for some
    documentation or benchmarks on that (other than that i'm apparently an
    idiot for not obviously accepting that fact). (also say switching to
    node-mysql2 rather than node-mysql might take a performance hit)

    I don't doubt that security would improve from a theoretical point of
    view, however from a practical point the effects are probably minimal.

    It's still a priority for us but this change is more a bottom-up refactor
    than a 2-3 hour bugfix/feature.

    "Important enough" is a dangerous term to use, there's a factor of 10 more
    people who think that getting polymorphic associations or JSONB
    implementated is more important than prepared statements. (although i guess
    in fairness they might not be running penetration tests on their codebase).

    @efuquen https://github.com/efuquen Your comment was appreciated while
    highly negative and doesn't really seem to take into account the resources
    needed to run a project of sort-of-decent size - But i've put investigating
    the effort needed to implement this for postgres, sqlite, mysql and mssql
    on my list: #3495 #3495
    and am hopefully able to do a review soon.

    @mbroadst https://github.com/mbroadst Does the MSSQL driver support
    prepared statements?

    —
    Reply to this email directly or view it on GitHub
    #1608 (comment)
    .

  12. mickhansen commented on Apr 10, 2015

    @mickhansen
    Contributor

    @mdarveau Prepared statements (atleast in the case of PG) can only be cached per connection - And since we use pooling which will often release and create new connections it's hard to tell what impact this would have :)

  13. mickhansen commented on Apr 10, 2015

    @mickhansen
    Contributor

    And thanks for the kind words @mdarveau

  14. janmeier commented on Apr 12, 2015

    @janmeier
    Member

    I've been following this discussion on the sideline, but I feel I should give my input as well. First of all let me say that I am completely behind mick on this one. We appreciate that the issue has been brought up, but we have lots of other things to tend to - We are looking into it, but we are not going to fix it yesterday.

    I see the theoretical security benefit, but not much other than that.

    As for performance I doubt there is much to gain. I can't see how any DBMS would implemented prepared statements that support @mdarveau's 2nd point. If the prepared statement can be used by several connections, how will the DBMS know when to garbage collect the statement? Of course it could rely on the user to explicitly call unprepare when the statement is no longer needed, but I doubt that. Pg explicitly states that prepared statements are per connection http://www.postgresql.org/docs/9.4/static/sql-prepare.html and I'm pretty sure mysql and mssql are the same.

    And thanks for your words @mdarveau :)

  15. 23 remaining items

  16. dvlsg commented on Jun 15, 2016

    @dvlsg

    Trying to handle req.body.id of {$gt: 0} as a "sql injection" is out of scope, in my opinion. Or even working as intended, really. I'm not entirely sure how you could even determine when that type of request is "malicious", to be honest. If an end-user decides that they want to map a request body directly to a where statement without any sort of validation / permissions / ACL scoping, then they should probably be ready to accept a request body directly to their where statement. :)

    I have to admit, I was a bit surprised to find that sequelize doesn't use parameterized queries by default. I understand that could be a significant overhaul, though.

    Just to make sure I understand, when using raw queries with bind, the native driver bind / parameterization capabilities do get utilized, correct? But they aren't utilized when using standard Model methods?

  17. janmeier commented on Jun 16, 2016

    @janmeier
    Member

    Unexpected data in req.body is probably not something we can actually code against, but we can still advice our users to be careful.

    @dvlsg Correct - raw queries use bind in sqlite and postgres, sequelize metohods do not

  18. holm commented on Jul 20, 2016

    @holm
    Contributor

    To be honest I am extremely surprissed that bind/prepared statements is not used for a modern SQL framework. It is much much safer, and will in practice prevent catastrophic failures.

    I appreciate this project and the fact that it is open source, but leaving security to the developers when it can be handled at the framework level, is not going to be a sound strategy.

  19. mickhansen commented on Jul 20, 2016

    @mickhansen
    Contributor

    @holm I appreciate your feedback. It's simply just a massive refactor when it's not built-in from the ground up. But we've not forgotten it and are still thinking about how best to refactor.

  20. ciaranj commented on Jan 31, 2017

    @ciaranj

    Just a sidenote (in case it affects anyone else!) There is discussion above about whether or not this would affect performance at all.

    I've a confirmed use-case where the design decision not to use prepared statements/parameterised queries does have a dramatic affect on performance, which I'm documenting here so that someone else doesn't have to re-research this behaviour!

    On MSSQL (tedious), with a SQL table such as:

    CREATE TABLE [Artifacts](
     [art_id] [uniqueidentifier] NOT NULL,
     [content] [varbinary](max) NOT NULL)
    

    And a matching model such as:

    {
        id: {
          type: DataTypes.UUID,
          primaryKey: true,
          field: 'art_id'
        },
        content: {
          type: DataTypes.BLOB
        }
      }
    

    If I create an 'artifact' with a content field that is a Buffer which contains about 1.3MB of data, then it takes SQL server ~30seconds to round-trip.

    If I take the SQL sequelize generates to perform the create;

    INSERT INTO [Artifacts] ([art_id],[content]) VALUES (N'080abd3c-0dc4-469b-8c55-33532a4891e6',0x7babe34aasd34....')
    and write a small node test app to directly send this to tedious through the same mechanism as sequelize then the test app takes the same length of time to respond as the sequelize case (~30s).

    If however I re-write the sql used in my test app to be of the following form:

    INSERT INTO [Artifacts] ([art_id],[content]) VALUES (N'080abd3c-0dc4-469b-8c55-33532a4891e6',@data)

    and provide the tedious request with the 'data' parameter containing my Buffer, the result is instantaneous (or near enough!)

    We spent some time analysing the SQL server side of things and we think it is something to do with SQL Server trying to find an optimised plan by matching the query directly (all the wait is cpu-based) but we're not sure why this would be (as when we replicate the sequelize SQL from directly within the SQL enterprise manager we cannot replicate the delay!)

    I appreciate this isn't directly helping move this bug forward, but it may help someone else struggling with why the persistance of 'BLOB' types in MSSQL under Sequelize is so slow!

    If you really want to subvert sequelize but still interact with shared transactions (ymmv!) I used the following code.

        return Promise.using(tx.connection.lock(), function (connection) {
          return new Promise(function(resolve, reject) {
            var request = new connection.lib.Request("INSERT INTO ["+ this.db.Artifact.$schema + "].["+this.db.Artifact.tableName+"] ([art_id],[content]) VALUES (@art_id,@content)", function(err) {
              if (err) reject(err);
              else resolve();
            });
            request.addParameter('art_id', connection.lib.TYPES.UniqueIdentifier, artifactId);
            request.addParameter('content', connection.lib.TYPES.VarBinary, Buffer.from(deploymentInformation.content, "utf8"));
            connection.execSql(request);
           }.bind(this));
        }.bind(this));
    

    ... But you almost certainly shouldn't be doing this ;)

  21. DraconPern commented on Feb 6, 2017

    @DraconPern

    Very surprised there's no parameter support for mysql. So if anyone passes in say ';DELETE * from table;'. Then your data are all gone. I guess that's one way to get people to use postgres.. lol

  22. lassombra commented on Mar 15, 2017

    @lassombra

    I just wanted to pop in here and weigh in since I've been using this library for the last 2 days and this immediately got my attention the moment I noticed in console that full query strings were being emitted. I was naturally very concerned and end up here.

    I have since done a penetration test on my application, and while the lack of parameterized queries is a flag raised in said testing, all sql injection attempts fail. My sequelize layer is hidden behind a graphql layer, so I have already one library which is doing type safety and input control on my inputs. Sequelize protects against sql level injections by doing escape work on all parameters. Is this ideal? Probably not, but it is effective. Through the API gateway, I have no injection exposure. So, basically, sanely structure your queries, and if you are really nervous, sanitize all user input yourself to remove sql keywords.

    That said, I do hope that the security benefit of a second lock on the database door (prepared/parameterized statements) is realized soon by this library. This will not however stop me from using it in production.

  23. mickhansen commented on Mar 15, 2017

    @mickhansen
    Contributor

    @DraconPern Why would that be the case? Unless you're personally injecting raw statements into raw queries then sequelize won't allow bobby to drop tables.

    @lassombra Nobody is argueing that prepared/parameterized statements is a bad idea, it's mostly a matter of resources.

  24. noah-goodrich commented on Mar 15, 2017

    @noah-goodrich
    Author

    @mickhansen As the original poster of this issue, I never thought it would see this much continued activity.

    I see that now in v3, Postgres and Sqlite (I think) both support parameterized queries at least in the raw query documentation. Is the same true when using Sequelize Models?

    I also noticed that it looks like Sequelize has migrated to MySQL2 which supports bound parameters but according to the documentation for the latest release of v3, MySQL prepared statements are still not supported.

    Could you give me a short rundown on what still remains to be done so that we could have prepared statements and server bound parameters for MySQL? Professionally I've been working on other projects in other languages for the past while, but this might be something I could take a look at tackling if I understood the scope of the problem.

  25. lassombra commented on Mar 15, 2017

    @lassombra

    @mickhansen I think you misunderstood my statement perhaps.

    I am confident that the current implementation, when behind a service/api layer (as it is for me) and with sane service implementation is secure.

    I was simply throwing my voice in so as to voice support for prioritizing this whenever and however possible. I look forward to the conversion being complete. I know that it is no small matter to rebuild an entire query language system (having done so once myself in another language) so I accept that this isn't a fix yesterday thing, but I wanted to express that I still think it's a priority. That said, order/limit with includes is maybe a higher one?

  26. mickhansen commented on Mar 15, 2017

    @mickhansen
    Contributor

    @noah-goodrich It's had quite the attention. We supported parameterized raw queries but generated queries don't currently make use of this.

    Basically all query generation has to be rewritten to return a query and a set of values, rather than embed values themselves.

    @lassombra Re-reading your comment i might have, just wanted to clarify that no maintainer is against the idea.

  27. intellix commented on Aug 23, 2022

    @intellix

    Should this issue be re-opened? I see that INSERT support was added for bind but it's still missing from SELECT (I've noticed it from my own tests in UPDATE statements): #9431

    This would help with tooling to group queries that are the same (with different params) and to prevent leaking of data to external tooling like pganalyze.

    Edit: seems to be tracked in various other issues/PRs and looks like support is coming: #14524

  28. ephys commented on Sep 17, 2022

    @ephys
    Member

    We do support bind parameters everywhere nowadays, I think. Its support is even better in v7

    Prepared statements are also planned, but #3495 is the relevant issue for them. We have some draft design documents for them over here https://gist.github.com/ephys/50a6a05be7322c64645be716fea6186a#prepared-statements

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    staletype: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions