<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="162826" data-post-id="162826">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="why" src="/assets/icons/user-9f439610.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  why
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I hear the warnings around the dangers of like injection.</p>
<p>I figured out how to alternatively write the queries I need for these cases using Ecto fragments and PostgreSQL’s own string functions like position() and lower().</p>
<p>However, it would be nice to able to use like/ilike… Can anybody see any remaining risks if we sanitized the user input with the following function (using <a class="mention" href="/u/lostkobrakai" rel="nofollow">@LostKobrakai</a>’s proposed approach above, plus sanitizing for nil)?</p>
<p><code>sanitized_user_input = Regex.replace(~r/^$|([\%_])/, raw_user_input, "[\\1]")</code></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="162826" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-prevent-like-injections/22791/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-162826" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="162826"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #11"></div>
  </section>
</div>
    <div class="postbit" id="162933" data-post-id="162933">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="lukaszsamson" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/lukaszsamson/120/7671_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  lukaszsamson
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>ElixirLS Core Team</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>The regexes in this thread are still vulnerable. They fail to sanitise escape character <code>\</code>.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="162933" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-prevent-like-injections/22791/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-162933" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="162933"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="291738" data-post-id="291738">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="gcb" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/gcb/120/27227_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  gcb
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group quote-modified" data-username="lukaszsamson" data-post="13" data-topic="22791">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/lukaszsamson/48/7671_2.png" class="avatar"> lukaszsamson:</div>
<blockquote>
<p>The regexes in this thread are still vulnerable […]</p>
</blockquote>
</aside>
<p>So, everyone is cooking their own flawed escape code instead of centralizing this on ecto <img src="https://forum.elixirforum.com/images/emoji/apple/eyes.png?v=15" title=":eyes:" class="emoji" alt=":eyes:" loading="lazy" width="20" height="20"></p>
<p>For now i’m going with</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">String.contains?(user_query, ["\\", "%", "_"])
... raise Ecto.NoResultsError, queryable: "unsafe redacted"
</code></pre>
<p><img src="https://forum.elixirforum.com/images/emoji/apple/person_shrugging.png?v=15" title=":person_shrugging:" class="emoji" alt=":person_shrugging:" loading="lazy" width="20" height="20"> but mostly because I am just temporarily using ILIKE and will move to SIMILARITY soon.</p>
<p>in context:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">  def search(user_query) do
    case String.contains?(user_query, ["\\", "%", "_"]) do # TODO: move to app config in case you change db backend?
      true -&gt; raise Ecto.NoResultsError, queryable: "unsafe redacted"
      false -&gt;
        name_pattern = "#{user_query}%"
        Content
        |&gt; where(ilike("name", ^name_pattern))
        |&gt; limit(10)
        |&gt; Repo.all
    end
  end
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="291738" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-prevent-like-injections/22791/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-291738" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="291738"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #13"></div>
  </section>
</div>
    <div class="postbit" id="291745" data-post-id="291745">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="adamu" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/adamu/120/31482_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  adamu
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>This thread reminds me of a similar question I asked about Perl back in 2016 that never got a good answer. Quoting the comment from there</p>
<blockquote>
<p>A little surprised this is not supported out of the box. I’m wondering if there are driver-specific issues that make this difficult to do.</p>
</blockquote>
<aside class="onebox stackexchange" data-onebox-src="https://stackoverflow.com/questions/34760973/perl-dbi-escaping-a-like-prepared-statement">
  <header class="source">

      <a href="https://stackoverflow.com/questions/34760973/perl-dbi-escaping-a-like-prepared-statement" target="_blank" rel="noopener nofollow ugc">stackoverflow.com</a>
  </header>

  <article class="onebox-body">
      <a href="https://stackoverflow.com/users/1225617/adam-millerchip" target="_blank" rel="noopener nofollow ugc">
    <img alt="Adam Millerchip" src="https://www.gravatar.com/avatar/d5221312c38d547a0de3476fa0b8e49a?s=256&amp;d=identicon&amp;r=PG" class="thumbnail onebox-avatar" width="256" height="256">
  </a>

<h4>
  <a href="https://stackoverflow.com/questions/34760973/perl-dbi-escaping-a-like-prepared-statement" target="_blank" rel="noopener nofollow ugc">Perl DBI: Escaping a LIKE prepared statement</a>
</h4>

<div class="tags">
  <strong>sql, perl, dbi</strong>
</div>

<div class="date">
  asked by
  
  <a href="https://stackoverflow.com/users/1225617/adam-millerchip" target="_blank" rel="noopener nofollow ugc">
    Adam Millerchip
  </a>
  on <a href="https://stackoverflow.com/questions/34760973/perl-dbi-escaping-a-like-prepared-statement" target="_blank" rel="noopener nofollow ugc">07:42AM - 13 Jan 16 UTC</a>
</div>

  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>
 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="291745" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-prevent-like-injections/22791/15">Post #14</a>
	                </div>
	            </div>
              <div id="likers-container-291745" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="291745"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #14"></div>
  </section>
</div>
    <div class="postbit" id="299453" data-post-id="299453">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="felix-starman" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/felix-starman/120/18051_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  felix-starman
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>For something similar to the Rails approach would work like this:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">  @doc """
  This escapes the default SQL escape character `\\`, and any wildcard characters (`%` and `_`)
  so they can be used in a `LIKE` statement.

  This may not be perfect and is based off of the Rails implementation and the MySQL docs.

  - https://apidock.com/rails/v4.2.1/ActiveRecord/Sanitization/ClassMethods/sanitize_sql_like
  - https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html#operator_like
  """
  def sanitize_sql_like(string, escape_character \\ "\\") do
    {:ok, pattern} =
      [escape_character, "%", "_"]
      |&gt; Enum.map(&amp;Regex.escape/1)
      |&gt; Enum.join("|")
      |&gt; Regex.compile()

    String.replace(string, pattern, fn x -&gt; escape_character &lt;&gt; x end)
  end
</code></pre>
<p>There’s half a dozen other ways to do it, but this way should work fine, and supports the ability to pass a custom escape character so if you need to do that as part of your SQL query you can, which PostgreSQL and MySQL support (<code>string LIKE pattern [ESCAPE escape-character]</code>)</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="299453" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-prevent-like-injections/22791/16">Post #15</a>
	                </div>
	            </div>
              <div id="likers-container-299453" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="299453"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #15"></div>
  </section>
</div>
    <div class="postbit" id="299462" data-post-id="299462">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="smathy" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/smathy/120/20941_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  smathy
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group quote-modified" data-username="gcb" data-post="14" data-topic="22791">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/gcb/48/27227_2.png" class="avatar"> gcb:</div>
<blockquote>
<aside class="quote no-group quote-modified" data-username="lukaszsamson" data-post="13" data-topic="22791">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/lukaszsamson/48/7671_2.png" class="avatar"> lukaszsamson:</div>
<blockquote>
<p>The regexes in this thread are still vulnerable […]</p>
</blockquote>
</aside>
<p>So, everyone is cooking their own flawed escape code instead of centralizing this on ecto <img src="https://forum.elixirforum.com/images/emoji/apple/eyes.png?v=15" title=":eyes:" class="emoji" alt=":eyes:" loading="lazy" width="20" height="20"></p>
</blockquote>
</aside>
<p>It’s even worse than missing the fact that the backslash in the pattern wasn’t escaped (ie. doubled) so ends up just escaping the <code>%</code>, the backslashes in the replacement (<code>\\1</code> ) also needed to be escaped/doubled: as it stands the ruby (and elixir based on it) not only replaces just <code>%</code> and <code>_</code> but it replaces them with themselves <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<p><a class="mention" href="/u/felix-starman" rel="nofollow">@felix-starman</a> ftw here for accurately reproducing Rails’s version, shame we don’t have a <code>Regex.union</code></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="299462" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-prevent-like-injections/22791/17">Post #16</a>
	                </div>
	            </div>
              <div id="likers-container-299462" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="299462"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>