From 29894a11168c1d1c58c8eb6e24cc50feda7ef145 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Petr=20P=C3=ADsa=C5=99?= <ppisar@redhat.com>
Date: Fri, 8 Jun 2018 11:45:40 +0100
Subject: Remove existing files before overwriting them

Archive should extract only the latest same-named entry.
Extracted regular file should not be writtent into existing block
device (or any other one).

[with t/porting/customized.dat updated for Debian]

Signed-off-by: Chris 'BinGOs' Williams <chris@bingosnet.co.uk>
Bug: https://rt.cpan.org/Ticket/Display.html?id=125523
Bug-Debian: https://bugs.debian.org/900834
Origin: upstream, https://github.com/jib/archive-tar-new/commit/ae65651eab053fc6dc4590dbb863a268215c1fc5
Patch-Name: fixes/CVE-2018-12015-Archive-Tar-directory-traversal.diff
---
 cpan/Archive-Tar/lib/Archive/Tar.pm | 14 ++++++++++++++
 t/porting/customized.dat            |  1 +
 2 files changed, 15 insertions(+)

diff --git a/cpan/Archive-Tar/lib/Archive/Tar.pm b/cpan/Archive-Tar/lib/Archive/Tar.pm
index 50afbb334b..dffcbe19f3 100644
--- a/cpan/Archive-Tar/lib/Archive/Tar.pm
+++ b/cpan/Archive-Tar/lib/Archive/Tar.pm
@@ -843,6 +843,20 @@ sub _extract_file {
         return;
     }
 
+    ### If a file system already contains a block device with the same name as
+    ### the being extracted regular file, we would write the file's content
+    ### to the block device. So remove the existing file (block device) now.
+    ### If an archive contains multiple same-named entries, the last one
+    ### should replace the previous ones. So remove the old file now.
+    ### If the old entry is a symlink to a file outside of the CWD, the new
+    ### entry would create a file there. This is CVE-2018-12015
+    ### <https://rt.cpan.org/Ticket/Display.html?id=125523>.
+    if (-l $full || -e _) {
+	if (!unlink $full) {
+	    $self->_error( qq[Could not remove old file '$full': $!] );
+	    return;
+	}
+    }
     if( length $entry->type && $entry->is_file ) {
         my $fh = IO::File->new;
         $fh->open( '>' . $full ) or (
diff --git a/t/porting/customized.dat b/t/porting/customized.dat
index 464a0f50ac..a87e70614c 100644
--- a/t/porting/customized.dat
+++ b/t/porting/customized.dat
@@ -1,3 +1,4 @@
+Archive::Tar cpan/Archive-Tar/lib/Archive/Tar.pm b027f0eefe1288590301daa21aec5a158d4fe203
 CPAN cpan/CPAN/lib/CPAN/Author.pm 792d7c8fbe6ed45e1244e589a8b712878c5dd2a5
 CPAN cpan/CPAN/lib/CPAN/CacheMgr.pm 132adb7f96014ec7ded45457044ed925d3181475
 CPAN cpan/CPAN/lib/CPAN/FTP.pm 3f0d5fc572c8749a566d73ca892c6c89ce3fb676
