From dbd4c70346a858848a1815c915f86dc3fb395c20 Mon Sep 17 00:00:00 2001
From: Pompolic <pompolic@special-circumstanc.es>
Date: Tue, 27 Jul 2021 23:24:59 +0200
Subject: [PATCH] Fix UAF in gethash()

- Buffer returned by strtok() gets freed up by the next time it's called, so we need to strncpy() the contents out
- changed strcpy() to strncpy()
---
 pdf.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/pdf.c b/pdf.c
index aa6d6d3..390686a 100644
--- a/pdf.c
+++ b/pdf.c
@@ -2032,16 +2032,21 @@ gethash(const char *fn)
 	const char s[2] = "/";
     char *token, *res;
     char *tstr = malloc(sizeof(char)* (strlen(fn) + 1));
-    strcpy(tstr, fn);
+    strncpy(tstr, fn, strlen(fn)+1);
+    
+    // The filename/hash will be at most as long as the file path
+    res = malloc(sizeof(char)* (strlen(fn)+1));
 
 
     token = strtok(tstr, s);
-    res = token;
     while ( token != NULL ) {
-    	res = token;
-    	token = strtok(NULL, s);
+        free(res);
+        res = malloc(sizeof(char)*(strlen(token)+1));
+        strncpy(res, token, strlen(token)+1);
+        token = strtok(NULL, s);
     }
     free (tstr);
+    
     return res;
 }
 
-- 
GitLab