in reply to Cleaning up directory paths.
Doing a similar thing, I was disappointed to find that none of the File::* modules wouldn't rationlise a path containing relative elements,and came up with this.
#! perl -slw use strict; sub sanitizeDir { require Cwd; my( $path ) = @_; my( $cwd ) = Cwd::getcwd() =~ m[^(.*)$]; return unless do{ local %ENV; $path =~ s[^(.*)$][$1]; chdir $path; + }; my $sanitized = Cwd::getcwd(); chdir $cwd; return $sanitized =~ s[^$cwd][$cwd] ? $sanitized : (); } my $dubiousPath = $ARGV[0]; my $absPath = sanitizeDir( $dubiousPath ); if( defined $absPath ) { print 'Absolute path: ', $absPath; } else { print 'Invalid path: ', $dubiousPath; }
Some tests
P:\test>perl -T junk.pl8 . Absolute path: P:/test P:\test>perl -T junk.pl8 .. Invalid path: .. P:\test>perl -T junk.pl8 ./.. Invalid path: ./.. P:\test>perl -T junk.pl8 ./../. Invalid path: ./../. P:\test>perl -T junk.pl8 ./used Absolute path: P:/test/used P:\test>perl -T junk.pl8 ./used/.. Absolute path: P:/test P:\test>perl -T junk.pl8 ./used/../.. Invalid path: ./used/../.. P:\test>perl -T junk.pl8 ./used/././t/ Absolute path: P:/test/used/t P:\test>perl -T junk.pl8 ./used/././t/../ Absolute path: P:/test/used P:\test>perl -T junk.pl8 ./used/././t/../.. Absolute path: P:/test P:\test>perl -T junk.pl8 ./used/././t/../.././.. Invalid path: ./used/././t/../.././..
The basic idea is to use the OS to rationaise the path and convert it to an absolute path. You can then check that it starts with the root of the subtree you want to expose. In the example, it verifies that the path specified is in the subtree below the current working directory, but you could pass in the required cwd as a second argument to the sub.
It returns a fully rationalised and untainted, absolute path, or undef.
This hasn't been tested on a vunerable system, so you will need to verify it for yourself, but hopefully their are enough experienced eyes here to spot any weakness in the approach or implementation.
I believe it should be portable, but it has only neen tested under Win32.
|
|---|