From 396afe6f6aa90a31303c183e11b2b2d4b7956b35 Mon Sep 17 00:00:00 2001
From: drh <drh@noemail.net>
Date: Wed, 18 Dec 2019 20:51:58 +0000
Subject: [PATCH] Fix CVE-2019-19923
 Continue to back away from the LEFT JOIN optimization of
 check-in [41c27bc0ff1d3135] by disallowing query flattening if the outer
 query is DISTINCT.  Without this fix, if an index scan is run on the table
 within the view on the right-hand side of the LEFT JOIN, stale result
 registers might be accessed yielding incorrect results, and/or an
 OP_IfNullRow opcode might be invoked on the un-opened table, resulting in a
 NULL-pointer dereference.  This problem was found by the Yongheng and Rui
 fuzzer.

FossilOrigin-Name: 862974312edf00e9d1068115d1a39b7235b7db68b6d86b81d38a12f025a4748e

Change by Weifeng <suweifeng1@huawei.com>:
    Fit for version 3.24.0
---
 src/select.c   |  8 ++++++--
 test/join.test | 13 +++++++++++++
 2 files changed, 19 insertions(+), 2 deletions(-)

diff --git a/src/select.c b/src/select.c
index 529df0f..4510b77 100644
--- a/src/select.c
+++ b/src/select.c
@@ -3582,6 +3582,7 @@ static void substSelect(
 **        (3b) the FROM clause of the subquery may not contain a virtual
 **             table and
 **        (3c) the outer query may not be an aggregate.
+**        (3d) the outer query may not be DISTINCT.
 **
 **   (4)  The subquery can not be DISTINCT.
 **
@@ -3770,8 +3771,11 @@ static int flattenSubquery(
   */
   if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
     isLeftJoin = 1;
-    if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
-      /*  (3a)             (3c)     (3b) */
+    if( pSubSrc->nSrc>1                   /* (3a) */
+     || isAgg                             /* (3b) */
+     || IsVirtual(pSubSrc->a[0].pTab)     /* (3c) */
+     || (p->selFlags & SF_Distinct)!=0    /* (3d) */
+    ){
       return 0;
     }
   }
diff --git a/test/join.test b/test/join.test
index 8c6f463..8c6a53d 100644
--- a/test/join.test
+++ b/test/join.test
@@ -844,4 +844,17 @@ do_execsql_test join-15.110 {
    ORDER BY a1, a2, a3, a4, a5;
 } {1 {} {} {} {} 1 11 {} {} {} 1 12 {} {} {} 1 12 121 {} {} 1 13 {} {} {}}
 
+# 2019-12-18 problem with a LEFT JOIN where the RHS is a view.
+# Detected by Yongheng and Rui.
+# Follows from the optimization attempt of check-in 41c27bc0ff1d3135
+# on 2017-04-18
+#
+reset_db
+do_execsql_test join-22.10 {
+  CREATE TABLE t0(a, b);
+  CREATE INDEX t0a ON t0(a);
+  INSERT INTO t0 VALUES(10,10),(10,11),(10,12);
+  SELECT DISTINCT c FROM t0 LEFT JOIN (SELECT a+1 AS c FROM t0) ORDER BY c ;
+} {11}
+
 finish_test
-- 
2.19.1 
