fmt.Sprintf in SQL

polaris · · 1357 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I had a question about the usage of fmt.Sprintf with SQL statements. I know that this is generally bad and that bindvars and prepared statements should be used for the builtin injection guards, but let&#39;s say that I have:</p> <p>fmt.Sprintf(&#34;select * from sometable where id=%d&#34; , someID)</p> <p>Is there anything that could go wrong or be abused here? Being that we&#39;re working with integers, I can&#39;t really see what could happen.</p> <hr/>**评论:**<br/><br/>shazow: <pre><pre><code>fmt.Sprintf(&#34;select * from sometable where id=%d&#34; , someID) </code></pre> <p>There might not be much that could go wrong with this particular line of code, but the problem is that it&#39;s a bad habit. Another developer might pick up the project, or even you yourself in a few months, and try to keep style consistent with an addition:</p> <pre><code>fmt.Sprintf(&#34;select * from sometable where name=%s&#34; , someName) </code></pre> <p>And you have yourself an SQL injection. This is how most vulnerabilities happen. The first bad code you write might be just fine, but over time it creates habits that infect all consequent additions and things get more and more broken over time.</p> <p>It&#39;s a good idea to build good habits early and often. :) Never know when it will save you in the future.</p></pre>dgryski: <pre><p>This particular instance is probably safe, but it&#39;s <em>very</em> easy to get wrong. It&#39;s just cleaner to <em>always</em> use prepared statements so that when requirements change, you don&#39;t tweak your Sprintf() to include a string var.</p></pre>FourSigma: <pre><p>Highly recommend this library if you need some flexibility in your SQL statements.</p> <p><a href="https://github.com/Masterminds/squirrel" rel="nofollow">https://github.com/Masterminds/squirrel</a></p></pre>ChrisAtWork_HARD: <pre><p>i would make sure that someID can never come directly from user input.</p></pre>weberc2: <pre><p>As long as <code>someID</code> is an int type, you should be okay AFAICT.</p></pre>mortonpe: <pre><p>Echoing the others who have replied you probably should avoid sprintf as it is vulnerable to SQL injection attacks. The safest thing to do would be to use prepared statements <a href="http://go-database-sql.org/retrieving.html" rel="nofollow">http://go-database-sql.org/retrieving.html</a> &lt;- see the first example on this page using the Query function.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1357 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传