From 646b383f959eff18d58081b1a574f0d777d353da Mon Sep 17 00:00:00 2001
From: Gail Badner <gbadner@redhat.com>
Date: Thu, 30 Apr 2020 16:26:56 -0700
Subject: [PATCH] HHH-14077 : CVE-2019-14900 SQL injection issue in Hibernate ORM

---
 .../expression/LiteralExpression.java         | 30 +++++++++++++++----
 1 file changed, 24 insertions(+), 6 deletions(-)

diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/criteria/expression/LiteralExpression.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/criteria/expression/LiteralExpression.java
index b2451e6..dc7cbc3 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/criteria/expression/LiteralExpression.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/criteria/expression/LiteralExpression.java
@@ -72,17 +72,35 @@ public class LiteralExpression<T> extends ExpressionImpl<T> implements Serializa
 		return ':' + parameterName;
 	}
 
+	/**
+	 * Inline String literal.
+	 *
+	 * @return escaped String
+	 */
+	private String inlineLiteral(String literal) {
+		return String.format( "\'%s\'", escapeLiteral( literal ) );
+	}
+
+	/**
+	 * Escape String literal.
+	 *
+	 * @return escaped String
+	 */
+	private String escapeLiteral(String literal) {
+		return literal.replace("'", "''");
+	}
+
 	@SuppressWarnings({ "unchecked" })
 	public String renderProjection(RenderingContext renderingContext) {
+		if ( ValueHandlerFactory.isCharacter( literal ) ) {
+			// In case literal is a Character, pass literal.toString() as the argument.
+			return inlineLiteral( literal.toString() );
+		}
+
 		// some drivers/servers do not like parameters in the select clause
 		final ValueHandlerFactory.ValueHandler handler =
 				ValueHandlerFactory.determineAppropriateHandler( literal.getClass() );
-		if ( ValueHandlerFactory.isCharacter( literal ) ) {
-			return '\'' + handler.render( literal ) + '\'';
-		}
-		else {
-			return handler.render( literal );
-		}
+		return handler.render( literal );
 	}
 
 	@Override
-- 
2.23.0

