/*
** Creative Commons Attribution-ShareAlike 3.0 License -
** This work is licensed under the Creative Commons Attribution-Share Alike
** 3.0 License. To view a copy of this license,
** visit http://creativecommons.org/licenses/by-sa/3.0/legalcode;
** or, (b) send a letter to Creative Commons, 171 2nd Street, Suite 300, San
** Francisco, California, 94105, USA.
**
** Originally created : Mataru
**
** Comments : CWE 022 - Improper Limitation of a Pathname to a 
**	Restricted Directory ('Path Traversal')
**	http://cwe.mitre.org/data/definitions/22.html
*/
import java.io.*;

public class path_traversal
{
    public static void main(String[] argv)
    {
	// directory where profiles should be (relative to current working directory)
	final String PROFILES_DIR	= "chroot/usr/local/share/profiles/";
	// filename of the profile inside user profile dir
	final String PROFILE_FILENAME	= "profile";
	// from untrusted user input
	String		profile_name = null;	
	String		profile = null;
	String		line = null;
	// current working directory
	String		cur_wd = null;
	
	BufferedReader	profile_fd = null;
	
	if(argv.length != 1)
	{
	    System.err.println("Usage: path_traversal <profile_name>\n");
	    System.err.println("Read data from given user profile\n");
	    System.err.println("profile_name:\tname of the profile to read");

	    System.exit(1);
	}

	// retrieve the actual working directory
	cur_wd = new File(".").getAbsolutePath();

	profile = cur_wd + "/" + PROFILES_DIR + "/" + argv[0];

	try
	{
	    profile_fd = new BufferedReader(new FileReader(profile));

	    while((line = profile_fd.readLine()) != null)
	    {
		System.out.println(line);
	    }    
	}
	catch(FileNotFoundException e)
	{
	    System.err.println("[ERROR] file " + profile + " not found");
	    System.exit(2);
	}
	catch(IOException e)
	{
	    System.err.println("[ERROR] while reading file " + profile);
	    System.exit(3);
	}
	finally
	{
	    try
	    {
		profile_fd.close();
	    }
	    catch(IOException e)
	    {
		System.err.println("[ERROR] while closing the file " + profile);
		System.exit(4);
	    }
	       
	}
    }
}
