With GNU tar, it's simply
tar -xvf untrusted_file.tar
in an empty directory. GNU tar automatically strips a leading /
member names when extracting, unless explicitly not told otherwise with the --absolute-names
option. GNU tar also detects when the use of ../
would cause a file to be extracted outside of the toplevel directory and puts those files in the toplevel directory instead, e.g. a component foo/../../bar/qux
will be extracted as bar/qux
in the toplevel directory rather than bar/qux
in the parent of the toplevel directory. GNU tar also takes care of symbolic links pointing outside the toplevel directory, e.g. foo -> ../..
and foo/bar
will not cause bar
to be extracted outside the toplevel directory.
Note that this only applies to (sufficiently recent versions of) GNU tar (as well as some other implementations, e.g. *BSD tar and BusyBox tar). Some other implementations have no such protection.
Because of symbolic links, the protections you use wouldn't be enough: the archive could contain a symbolic link pointing to a directory outside the tree and extract files in that directory. There's no way to solve that problem based purely on the member names, you need to examine the target of symbolic links.
Note that if you're extracting into a directory that already contains symbolic links, the guarantee may no longer hold.
-t
option.