From: Joachim Reichel <reichel@debian.org>
Description: Fix CVE-2022-41751
Origin: https://github.com/Matthias-Wandel/jhead/commit/ba1da7dce9e8f3269159b57b88ff9688624426d2,
        https://github.com/Matthias-Wandel/jhead/commit/76d11094d17380d51a7ad53da2287c9f53a72726,
        https://github.com/Matthias-Wandel/jhead/commit/2a237d866581b3774ebe63d6c312e76459bd0866
Bug: https://github.com/Matthias-Wandel/jhead/issues/57,
     https://github.com/Matthias-Wandel/jhead/issues/60,
     https://github.com/Matthias-Wandel/jhead/issues/65
Bug-Debian: https://bugs.debian.org/1022028

Index: jhead-3.04/jhead.c
===================================================================
--- jhead-3.04.orig/jhead.c
+++ jhead-3.04/jhead.c
@@ -165,6 +165,15 @@ static int FileEditComment(char * TempFi
         }
         if (strlen(Editor) > PATH_MAX) ErrFatal("env too long");
 
+        // Disallow characters in the editor or filename that could be used to execute arbitrary
+        // shell commands with system() below.
+        if (strpbrk(TempFileName, "\";'&|`$")) {
+            ErrFatal("Filename has invalid characters");
+        }
+        if (strpbrk(Editor, "\";'&|`$")) {
+            ErrFatal("Editor has invalid characters");
+        }
+
         sprintf(QuotedPath, "%s \"%s\"",Editor, TempFileName);
         a = system(QuotedPath);
     }
@@ -748,6 +757,14 @@ static int DoAutoRotate(const char * Fil
                 sprintf(RotateCommand,"jpegtran -trim -%s -outfile \"%s\" \"%s\"",
                     Argument, ThumbTempName_out, ThumbTempName_in);
 
+                // Disallow characters in the filenames that could be used to execute arbitrary
+                // shell commands with system() below.
+                if (strpbrk(FileName, "\";'&|`$")) {
+                    ErrNonfatal("Command has invalid characters.", 0, 0);
+                    unlink(ThumbTempName_in);
+                    return FALSE;
+                }
+
                 if (system(RotateCommand) == 0){
                     // Put the thumbnail back in the header
                     ReplaceThumbnail(ThumbTempName_out);
@@ -773,7 +790,15 @@ static int RegenerateThumbnail(const cha
         return FALSE;
     }
 
-    sprintf(ThumbnailGenCommand, "mogrify -thumbnail %dx%d -quality 80 \"%s\"", 
+    // Disallow characters in the filename that could be used to execute arbitrary
+    // shell commands with system() below.
+    if(strpbrk(FileName, "\";'&|`$")) {
+        ErrNonfatal("Filename has invalid characters.", 0, 0);
+        return FALSE;
+    }
+
+    snprintf(ThumbnailGenCommand, sizeof(ThumbnailGenCommand),
+        "mogrify -thumbnail %dx%d -quality 80 \"%s\"",
         RegenThumbnail, RegenThumbnail, FileName);
 
     if (system(ThumbnailGenCommand) == 0){
