0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLインジェクション

Posted at

1. SQLインジェクション

データベースへの悪意あるリクエストにより、データベースの不正利用をまねくような脆弱性。

根本的解決その1: SQL文の組み立ては全てプレースホルダで実装する

下記はRailsアプリの検索フォーム用searchアクションです。Postモデルから指定文字列を含む投稿の配列を取得します。

posts_controller.rb

def search

  @posts = if params[:search].present?
             Post.where([
               'カラム名 LIKE ?', "%#{params[:search]}%"
             ])
           else
             Post.none
           end

# ダメなSQL → 'カラム名 LIKE "%#{params[:search]}%"'

end

?というSQLプレースホルダを用いて、まずSQL構文を決定した後に実際の値を機械的な処理で割り当てるというもの。
(※プレースホルダ・・・実際の内容を後から挿入するために、とりあえず仮に確保した場所のこと。)
直接、文字列連結処理によってSQL構文を組み立てる方法に比べて、このように機械的な処理でSQL構文を組み立てる方法を取ることでSQLインジェクションの脆弱性を解消できるとのこと。

参考文献

IPA - 安全なウェブサイトの作り方

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?