From de7ccd88ef3d8e1ac52962b2b8dc1e5280f26171 Mon Sep 17 00:00:00 2001
From: mhasbini <mohammad.hasbini@gmail.com>
Date: Sat, 16 Sep 2017 20:43:38 +0300
Subject: [PATCH] Fix overflow in mangle_dupechar_last function

---
 OpenCL/inc_rp.cl       | 1 +
 docs/changes.txt       | 1 +
 src/rp_kernel_on_cpu.c | 1 +
 3 files changed, 3 insertions(+)

diff --git a/OpenCL/inc_rp.cl b/OpenCL/inc_rp.cl
index 69df5461d..85463fcb8 100644
--- a/OpenCL/inc_rp.cl
+++ b/OpenCL/inc_rp.cl
@@ -503,6 +503,7 @@ static int mangle_dupechar_last (MAYBE_UNUSED const u8 p0, MAYBE_UNUSED const u8
 {
   const int out_len = len + p0;
 
+  if (len     ==                0) return (len);
   if (out_len >= RP_PASSWORD_SIZE) return (len);
 
   const u8 c = buf[len - 1];
diff --git a/docs/changes.txt b/docs/changes.txt
index f27ab1f9d..8d6d74031 100644
--- a/docs/changes.txt
+++ b/docs/changes.txt
@@ -41,6 +41,7 @@
 - Fixed the output of --show when used together with the collider modes -m 9710, 9810 or 10410
 - Fixed the use of --veracrypt-pim option. It was completely ignored without showing an error
 - Fixed the version number used in the restore file header
+- Fixed overflow in mangle_dupechar_last function
 
 ##
 ## Improvements
diff --git a/src/rp_kernel_on_cpu.c b/src/rp_kernel_on_cpu.c
index 27927644e..d71c28ab3 100644
--- a/src/rp_kernel_on_cpu.c
+++ b/src/rp_kernel_on_cpu.c
@@ -528,6 +528,7 @@ static int mangle_dupechar_last (MAYBE_UNUSED const u8 p0, MAYBE_UNUSED const u8
 {
   const int out_len = len + p0;
 
+  if (len     ==                0) return (len);
   if (out_len >= RP_PASSWORD_SIZE) return (len);
 
   const u8 c = buf[len - 1];