Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Friday, November 16, 2018

Spoofing file extensions on HackerOne

While testing HackerOne, I observed an issue with the file upload functionality. It seems that on File upload, the uploader uses the content within the file for determining the content type of file instead of filetype .

Although this does not pose much of a risk since the changed extensions would be visible at download time but wanted to blog about this.

This raises below 2 scenario:

Scenario 1


  • Open the batch.cmd on the posted comment
  • Observe an image gets represented and their is no warning from HackerOne

  • User downloads the file, thinking of it as an image file 
  • if the user accidentally ignores the downloaded file extensions opens it then malicious batch file gets executed



Scenario 2 


  • Open the myFile.txt on the posted comment
  • You will see a warning from Hackerone, but since the file is txt file so user might just go ahead 

  • User downloads the file, thinking of it as an text file

  • if the user accidentally ignores the downloaded file extensions opens it then malicious HTML scripts execute


Reason:

  1. Content-Disposition: attachment; filename="" in response from hackerone-attachments.s3.amazonaws.com does not contain filename, forcing browser to decide the naming convention. 
  2. Since the Content type got decided on basis of file content header instead of extension by HackerOne so few browser would simply save it on user computer with incorrect extension, which caused the above Scenarios 1 and 2
HackerOne Report:
https://hackerone.com/reports/268123 (Closed as Informative)

Thursday, November 24, 2016

Unzip files using Java

We will unzip a zip file with Java using a third party library. But yes, you can also unzip the zip using pure Java without any third party library.

Language Used:
Java

Git Repo:
https://cooltrickshome.blogspot.in/2016/11/unzip-files-using-java.html

Reference:

Without using any third party: http://www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java

Using Third party library : http://stackoverflow.com/questions/10633595/java-zip-how-to-unzip-folder

POM Dependency:
 <!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j -->  
 <dependency>  
   <groupId>net.lingala.zip4j</groupId>  
   <artifactId>zip4j</artifactId>  
   <version>1.3.1</version>  
 </dependency>  

Program:

Main method:
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           Scanner s=new Scanner(System.in);  
           System.out.println("Please enter the zip file to be unzipped");  
           String zipFile=s.nextLine();  
           System.out.println("Please enter the password for zip file (type none if no password)");  
           String password=s.nextLine();  
           File f=new File(zipFile);  
           //Your password if any  
           unzipFile(zipFile, f.getParent(),password);  
           System.out.println("Extracted zip content at "+f.getParent());  
           s.close();  
      }  

How it works:
1) We make a scanner object to take user input
2) We ask user the file to be zipped
3) We ask password from user if needed
4) We call unzipFile method which unzip the file. It take 3 parameters.
5) First param defines the file to be unzipped
6) Second param defines the path where file will be extracted
7) Third param defines the password to be used for extracting zip file

unzipFile method:
      public static void unzipFile(String sourceZip, String destination, String password)  
      {  
           try {  
             ZipFile zipFile = new ZipFile(sourceZip);  
             if (zipFile.isEncrypted()) {  
               zipFile.setPassword(password);  
             }  
             zipFile.extractAll(destination);  
           } catch (ZipException e) {  
             e.printStackTrace();  
           }  
      }  

How it works:
1) We make an object of ZipFile pointing to the zip file to be unzipped
2) isEncrypted tell if the zip file require password for extraction
3) If password is needed we use setPassword to set the password for extraction
4) extractAll retreives the content of the zip file

Output:
 Please enter the zip file to be unzipped  
 C:\Users\anurag\Desktop\images.zip  
 Please enter the password for zip file (type none if no password)  
 Your password if any  
 Extracted zip content at C:\Users\anurag\Desktop  

Full Program:
 package com.cooltrickshome;  
 import java.io.File;  
 import java.util.Scanner;  
 import net.lingala.zip4j.core.ZipFile;  
 import net.lingala.zip4j.exception.ZipException;  
 public class UnzipFile {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           Scanner s=new Scanner(System.in);  
           System.out.println("Please enter the zip file to be unzipped");  
           String zipFile=s.nextLine();  
           System.out.println("Please enter the password for zip file (type none if no password)");  
           String password=s.nextLine();  
           File f=new File(zipFile);  
           //Your password if any  
           unzipFile(zipFile, f.getParent(),password);  
           System.out.println("Extracted zip content at "+f.getParent());  
           s.close();  
      }  
      public static void unzipFile(String sourceZip, String destination, String password)  
      {  
           try {  
             ZipFile zipFile = new ZipFile(sourceZip);  
             if (zipFile.isEncrypted()) {  
               zipFile.setPassword(password);  
             }  
             zipFile.extractAll(destination);  
           } catch (ZipException e) {  
             e.printStackTrace();  
           }  
      }  
 }  

Hope it helps :)

Wednesday, November 23, 2016

Zip Folder using Java

You can zip your folders/files using Java

Language Used:
Java

Git Repo:
https://github.com/csanuragjain/extra/tree/master/Compression/Zip%20Folder

Reference:

Without any third party library : http://www.java2s.com/Code/Java/File-Input-Output/UseJavacodetozipafolder.htm

Using third party library: http://howtodoinjava.com/core-java/io/how-to-create-password-protected-zip-files-in-java/

Program:

Main method:
      public static void main(String[] a) throws Exception {  
           Scanner s = new Scanner(System.in);  
           System.out.println("Enter the file/folder to be zipped");  
           String zipFile = s.nextLine();  
           File f = new File(zipFile);  
           String zipFileName = f.getName() + ".zip";  
           if (f.isDirectory()) {  
                zipFolder(zipFile, zipFileName);  
           } else {  
                zipFile(zipFile, zipFileName);  
           }  
           System.out.println(zipFileName + " has been generated at "  
                     + new File("").getAbsolutePath());  
           s.close();  
      }  

How it works:
1) First we ask user the folder or file to be zipped.
2) We check if the given is file or folder
3) If it is file we call zipFile method passing the file to be zipped
4) If it is directory we call zipFolder method passing the folder to be zipped

zipFile Method:
      static public void zipFile(String srcFile, String destZipFile)  
                throws Exception {  
           ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(destZipFile));  
           File folder = new File(srcFile);  
           byte[] buf = new byte[1024];  
           int len;  
           FileInputStream in = new FileInputStream(srcFile);  
           zip.putNextEntry(new ZipEntry(folder.getName()));  
           while ((len = in.read(buf)) > 0) {  
                zip.write(buf, 0, len);  
           }  
           zip.close();  
      }  

How it works:
1) We make a zipoutputstream object pointing to the destination zip file to be created
2) We make a File object pointing to the source file to be zipped
3) We start reading the source file using read method and write it in the zip object made in step1
4) Finally our file is zipped

zipFolder method:
      static public void zipFolder(String srcFolder, String destZipFile)  
                throws Exception {  
           ZipOutputStream zip = null;  
           FileOutputStream fileWriter = null;  
           fileWriter = new FileOutputStream(destZipFile);  
           zip = new ZipOutputStream(fileWriter);  
           addFolderToZip("", srcFolder, zip);  
           zip.flush();  
           zip.close();  
      }  

How it works:
1) We make an object of zipoutputstream pointing to the destination zip file to be written
2) We call addFolderToZip method passing 3 argument
3) First argument defines the parent. So for example if we want to zip a.txt which was present within folder abc then first argument will be abc. For the first time parent would be ""
4) Second argument defines the source folder to be zipped
5) Third argument is the object pointing to output zip file to be written.

addFolderToZip method:
      static private void addFolderToZip(String path, String srcFolder,  
                ZipOutputStream zip) throws Exception {  
           File folder = new File(srcFolder);  
           for (String fileName : folder.list()) {  
                if (path.equals("")) {  
                     addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);  
                } else {  
                     addFileToZip(path + "/" + folder.getName(), srcFolder + "/"  
                               + fileName, zip);  
                }  
           }  
      }  

How it works:
1) We iterate through each of files/folder present in the source folder to be zipped
2) For each of the file/folder scanned if it does not have parent then path is "" otherwise path has some value
3) To understand path, we take an example assume user gave c:\abc folder to be zipped. C:\abc has a folder named b and b folder has a file named c.txt. So when c.txt comes to this method then path will be b which is the parent. Similarly when b folder comes to zip the parent is null so path will be ""

addFileToZip method:
      static private void addFileToZip(String path, String srcFile,  
                ZipOutputStream zip) throws Exception {  
           File folder = new File(srcFile);  
           if (folder.isDirectory()) {  
                addFolderToZip(path, srcFile, zip);  
           } else {  
                byte[] buf = new byte[1024];  
                int len;  
                FileInputStream in = new FileInputStream(srcFile);  
                zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));  
                while ((len = in.read(buf)) > 0) {  
                     zip.write(buf, 0, len);  
                }  
           }  
      }  

How it works:
1) We make a file object pointing to the source file/folder to be zipped.
2) If its is directory we call addFolderToZip method to get entries within it
3)Otherwise if it is file then we write it in the zip

Output:
 Enter the file/folder to be zipped  
 C:\Users\anurag\Desktop\images  
 images.zip has been generated at C:\Users\anurag\Desktop\zipfolder

Full Program:
 package com.cooltrickshome;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.util.Scanner;  
 import java.util.zip.ZipEntry;  
 import java.util.zip.ZipOutputStream;  
 public class ZipFolder {  
      public static void main(String[] a) throws Exception {  
           Scanner s = new Scanner(System.in);  
           System.out.println("Enter the file/folder to be zipped");  
           String zipFile = s.nextLine();  
           File f = new File(zipFile);  
           String zipFileName = f.getName() + ".zip";  
           if (f.isDirectory()) {  
                zipFolder(zipFile, zipFileName);  
           } else {  
                zipFile(zipFile, zipFileName);  
           }  
           System.out.println(zipFileName + " has been generated at "  
                     + new File("").getAbsolutePath());  
           s.close();  
      }  
      static public void zipFile(String srcFile, String destZipFile)  
                throws Exception {  
           ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(destZipFile));  
           File folder = new File(srcFile);  
           byte[] buf = new byte[1024];  
           int len;  
           FileInputStream in = new FileInputStream(srcFile);  
           zip.putNextEntry(new ZipEntry(folder.getName()));  
           while ((len = in.read(buf)) > 0) {  
                zip.write(buf, 0, len);  
           }  
           zip.close();  
      }  
      static public void zipFolder(String srcFolder, String destZipFile)  
                throws Exception {  
           ZipOutputStream zip = null;  
           FileOutputStream fileWriter = null;  
           fileWriter = new FileOutputStream(destZipFile);  
           zip = new ZipOutputStream(fileWriter);  
           addFolderToZip("", srcFolder, zip);  
           zip.flush();  
           zip.close();  
      }  
      static private void addFileToZip(String path, String srcFile,  
                ZipOutputStream zip) throws Exception {  
           File folder = new File(srcFile);  
           if (folder.isDirectory()) {  
                addFolderToZip(path, srcFile, zip);  
           } else {  
                byte[] buf = new byte[1024];  
                int len;  
                FileInputStream in = new FileInputStream(srcFile);  
                zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));  
                while ((len = in.read(buf)) > 0) {  
                     zip.write(buf, 0, len);  
                }  
           }  
      }  
      static private void addFolderToZip(String path, String srcFolder,  
                ZipOutputStream zip) throws Exception {  
           File folder = new File(srcFolder);  
           for (String fileName : folder.list()) {  
                if (path.equals("")) {  
                     addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);  
                } else {  
                     addFileToZip(path + "/" + folder.getName(), srcFolder + "/"  
                               + fileName, zip);  
                }  
           }  
      }  
 }  

Hope it helps :)

Tuesday, November 8, 2016

Extract files & folder along with their sizes using Java

In this tutorial we will make use of File class to extract all files & folders within any directory on your computer. For this exercise we will extract the files and folders along with their sizes from Desktop.

Git Location:
https://github.com/csanuragjain/extra/tree/master/FileFolderExtractor

Program Explanation:

Main Method:
      public static void main(String[] args) {  
           String path=System.getProperty("user.home") + "/Desktop";  
           File f= new File(path);  
           File[] desktopProjects=f.listFiles();  
           for(File file:desktopProjects)  
           {  
                if(file.isDirectory())  
                {  
                     System.out.println("Directory: "+file.getName()+":"+(folderSize(file)/1000)+"KB");  
                }  
                else  
                {  
                     System.out.println("File: "+file.getName()+":"+(file.length()/1000)+"KB");  
                }  
           }  
      }  

How it works:

1) We call System.getProperty("user.home") which returns the current home for the logged in user. In this example we extract the files and folders from Desktop. Since desktop folder is inside the user home directory so we append Desktop with user home to get Desktop path
2) We point the File class to Desktop path
3) f.listFiles() returns all the files inside the Desktop path which gets stored in desktopProjects variable.
4) Now the values returned by listFiles function may be file or directory so we check this by calling the function isDirectory (return true if returned value is directory otherwise false).
5) For every file found we use file.getName to retrieve the name of file and file.length to retrieve the file length. Since the file length is returned in bytes so we convert this to KB by dividing by 1000
6) Now for every directory found we use getName to get the directory name. But for obtaining the folder size we cannot use file.length since it wont work so we made a new function for obtaining the folder length which is folderSize

folderSize function:
      public static long folderSize(File directory) {  
        long length = 0;  
        for (File file : directory.listFiles()) {  
          if (file.isFile())  
            length += file.length();  
          else  
            length += folderSize(file);  
        }  
        return length;  
      }  

How it works:

1) Since we cannot find length of folder so we iterate through each file in folder and extract size of all files within.
2) First we call listFiles to get all files within the directory.
3) If the returned from step2 is file then we update the length
4) If the returned from step2 is directory then we again recursively call this function so that the size of this subdirectory gets calculated.

Full Code:
 package com.cooltrickshome;  
 import java.io.File;  
 public class FileFolderExtractor {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String path=System.getProperty("user.home") + "/Desktop";  
           File f= new File(path);  
           File[] desktopProjects=f.listFiles();  
           for(File file:desktopProjects)  
           {  
                if(file.isDirectory())  
                {  
                     System.out.println("Directory: "+file.getName()+":"+(folderSize(file)/1000)+"KB");  
                }  
                else  
                {  
                     System.out.println("File: "+file.getName()+":"+(file.length()/1000)+"KB");  
                }  
           }  
      }  
      public static long folderSize(File directory) {  
        long length = 0;  
        for (File file : directory.listFiles()) {  
          if (file.isFile())  
            length += file.length();  
          else  
            length += folderSize(file);  
        }  
        return length;  
      }  
 }  

Hope this helps :)