public void bad() throws Throwable {

    String fn =
        ".\\src\\testcases\\CWE379_File_Creation_in_Insecure_Dir\\insecureDir"; /* may have to be changed depending on script */
    /* POSSIBLE FLAW: potentially insecure directory permissions */
    File dir = new File(fn);
    if (dir.exists()) {
      IO.writeLine("Directory already exists");
      if (dir.delete()) {
        IO.writeLine("Directory deleted");
      } else {
        return;
      }
    }
    if (!dir.getParentFile().canWrite()) {
      IO.writeLine("Cannot write to parent dir");
    }
    try {
      boolean success = dir.mkdir();
      if (success) {
        IO.writeLine("Directory created");
        File file = new File(dir.getAbsolutePath() + "\\newFile.txt");
        file.createNewFile();
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  private void good1() throws Throwable {

    String fn = ".\\src\\testcases\\CWE379_File_Creation_in_Insecure_Dir\\basic\\insecureDir";
    File dir = new File(fn);
    if (dir.exists()) {
      IO.writeLine("Directory already exists");
      if (dir.delete()) {
        IO.writeLine("Directory deleted");
      } else {
        return;
      }
    }
    if (!dir.getParentFile().canWrite()) {
      IO.writeLine("Cannot write to parent dir");
    }

    /* FIX: explicitly set directory permissions */
    dir.setExecutable(false, true);
    dir.setReadable(true);
    dir.setWritable(false, true);
    try {
      boolean success = dir.mkdir();
      if (success) {
        IO.writeLine("Directory created");
        File file = new File(dir.getAbsolutePath() + "\\newFile.txt");
        file.createNewFile();
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  public ReaderHandler(LowLevelDbAccess lowLevelDbAccess, String webDir) {

    loginInfoDb = new LoginInfo.DB(lowLevelDbAccess);
    userDb = new User.DB(lowLevelDbAccess);
    feedDb = new Feed.DB(lowLevelDbAccess);
    articleDb = new Article.DB(lowLevelDbAccess);
    readArticlesCollDb = new ReadArticlesColl.DB(lowLevelDbAccess);
    userHelpers = new UserHelpers(loginInfoDb, userDb);

    setContextPath("/");

    File warPath = new File(webDir);
    setWar(warPath.getAbsolutePath());

    if (isInJar) {
      for (Map.Entry<String, String> entry : PATH_MAPPING.entrySet()) {
        addPrebuiltJsp(entry.getKey(), "jsp." + entry.getValue().replaceAll("_", "_005f") + "_jsp");
      }
    } else {
      for (Map.Entry<String, String> entry : PATH_MAPPING.entrySet()) {
        addServlet(
            new ServletHolder(new RedirectServlet("/" + entry.getValue() + ".jsp")),
            entry.getKey());
      }
    }

    setErrorHandler(new ReaderErrorHandler());
  }
示例#4
0
  /**
   * return OutputStream of JasperReport object, this page could only be viewed from localhost for
   * security concern. parameter can be (id), or (table and type)
   *
   * @param id - report id, or
   * @param table - table name
   * @param type - reporttype "s","l","o", case insensitive
   * @param client(*) - client domain
   * @param version - version number, default to -1
   */
  public void process(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String clientName = request.getParameter("client");
    int objectId = ParamUtils.getIntAttributeOrParameter(request, "id", -1);
    if (objectId == -1) {
      // try using table and type
      objectId =
          getReportId(clientName, request.getParameter("table"), request.getParameter("type"));
    }
    if (objectId == -1) {
      logger.error("report not found, request is:" + Tools.toString(request));
      throw new NDSException("report not found");
    }
    int version = ParamUtils.getIntAttributeOrParameter(request, "version", -1);
    File reportXMLFile = new File(ReportTools.getReportFile(objectId, clientName));
    if (reportXMLFile.exists()) {
      // generate jasperreport if file not exists or not newer
      String reportName =
          reportXMLFile.getName().substring(0, reportXMLFile.getName().lastIndexOf("."));
      File reportJasperFile = new File(reportXMLFile.getParent(), reportName + ".jasper");
      if (!reportJasperFile.exists()
          || reportJasperFile.lastModified() < reportXMLFile.lastModified()) {
        JasperCompileManager.compileReportToFile(
            reportXMLFile.getAbsolutePath(), reportJasperFile.getAbsolutePath());
      }
      InputStream is = new FileInputStream(reportJasperFile);
      response.setContentType("application/octetstream;");
      response.setContentLength((int) reportJasperFile.length());

      // response.setHeader("Content-Disposition","inline;filename=\""+reportJasperFile.getName()+"\"");
      ServletOutputStream os = response.getOutputStream();

      byte[] b = new byte[8192];
      int bInt;
      while ((bInt = is.read(b, 0, b.length)) != -1) {
        os.write(b, 0, bInt);
      }
      is.close();
      os.flush();
      os.close();
    } else {
      throw new NDSException("Not found report template");
    }
  }
 // Fireup tomcat and register this servlet
 public static void main(String[] args) throws LifecycleException, SQLException {
   Tomcat tomcat = new Tomcat();
   tomcat.setPort(8080);
   File base = new File(System.getProperty("java.io.tmpdir"));
   Context rootCtx = tomcat.addContext("/", base.getAbsolutePath());
   Tomcat.addServlet(rootCtx, "log", new LogService());
   rootCtx.addServletMapping("/*", "log");
   tomcat.start();
   tomcat.getServer().await();
 }
  private Transformer buildTransformer(String name, File xslDir, TransformerFactory tf)
      throws Exception {

    Transformer tr =
        tf.newTransformer(
            new StreamSource(
                new FileReader(xslDir.getAbsolutePath() + File.separatorChar + name + ".xsl")));
    tr.setOutputProperty(OutputKeys.INDENT, "yes");
    tr.setOutputProperty(OutputKeys.METHOD, "html");
    tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");

    return tr;
  }
示例#7
0
  /**
   * Returns the adapter type for the given file. Will first use the adapter selector function if it
   * was specified in init.js, otherwise will use the static type (either set in _init file, as a
   * server-wide override in 10gen.properties, or default of DIRECT_10GEN)
   *
   * @param file to produce type for
   * @return adapter type for the specified file
   */
  public AdapterType getAdapterType(File file) {

    // Q : I think this is the right thing to do
    if (inScopeSetup()) {
      return AdapterType.DIRECT_10GEN;
    }

    /*
     * cheap hack - prevent any _init.* file from getting run as anythign but DIRECT_10GEN
     */

    if (file != null && file.getName().indexOf("_init.") != -1) {
      return AdapterType.DIRECT_10GEN;
    }

    if (_adapterSelector == null) {
      return _staticAdapterType;
    }

    /*
     *  only let the app select type if file is part of application (i.e.
     *  don't do it for corejs, core modules, etc...
     */

    String fp = file.getAbsolutePath();
    String fullRoot = _rootFile.getAbsolutePath(); // there must be a nicer way to do this?

    if (!fp.startsWith(fullRoot)) {
      return AdapterType.DIRECT_10GEN;
    }

    Object o = _adapterSelector.call(_initScope, new JSString(fp.substring(fullRoot.length())));

    if (o == null) {
      return _staticAdapterType;
    }

    if (!(o instanceof JSString)) {
      log("Error : adapter selector not returning string.  Ignoring and using static adapter type");
      return _staticAdapterType;
    }

    AdapterType t = getAdapterTypeFromString(o.toString());

    return (t == null ? _staticAdapterType : t);
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("utf-8");
    if (jjNumber.isDigit(jjTools.getParameter(request, "maxSize"))) {
      maxSize = Long.parseLong(jjTools.getParameter(request, "maxSize"));
    }

    response.setCharacterEncoding("utf-8");
    String name = request.getParameter("name");
    name = name == null ? "" : name;
    response.setContentType("text/plain");
    super.init(getServletConfig());
    //        response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    //        out.println();

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    //        fileItemFactory.setSizeThreshold(1024 * 1024); //1 MB

    try {
      ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
      List items = uploadHandler.parseRequest(request);
      Iterator itr = items.iterator();
      while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()) {
          /*
           * Field
           */
          //                    out.println("Field Name=" + item.getFieldName() + ", Value=" +
          // item.getString());
          data.put(item.getFieldName(), item.getString());
        } else {
          /*
           * File
           */
          File folderAddress =
              new File(request.getServletContext().getRealPath(Save_Folder_Name)); // "/" +
          String extension = "";
          String nameWithoutExtension = item.getName();
          if (item.getName().lastIndexOf(".") > -1) {
            extension = item.getName().substring(item.getName().lastIndexOf("."));
            nameWithoutExtension =
                item.getName()
                    .substring(
                        item.getName().lastIndexOf("\\") + 1, item.getName().lastIndexOf("."));
          }
          folderAddress.mkdirs();
          nameWithoutExtension = "P";
          File file =
              new File(
                  folderAddress
                      + "/"
                      + nameWithoutExtension.toLowerCase()
                      + jjNumber.getRandom(10)
                      + extension.toLowerCase());
          String i = "0000000000";
          while (file.exists()) {
            i = jjNumber.getRandom(10);
            file =
                new File(
                    folderAddress
                        + "/"
                        + nameWithoutExtension.toLowerCase()
                        + i
                        + extension.toLowerCase());
          }
          if (!name.equals("")) {
            file = new File(folderAddress + "/" + name);
          }
          //                    out.println("File Name=" + item.getName()
          //                            + ", Field Name=" + item.getFieldName()
          //                            + ", Content type=" + item.getContentType()
          //                            + ", File Size=" + item.getSize()
          //                            + ", Save Address=" + file);
          //                    out.println(file);
          //                    String urlPath =
          // request.getRequestURL().toString().replace("Upload2", "Upload") + "/" +
          // file.getName().replace("\\", "/");
          //                    out.println("<html><head><meta http-equiv='Content-Type'
          // content='text/html; charset=utf-8'></head><body><input type='text' name='T1' size='58'
          // value='" + urlPath + "'></body></html>");
          data.put(item.getFieldName(), file.getAbsolutePath());
          if (!file.getName().toLowerCase().endsWith(".exe")) {
            item.write(file);
          }
          long size = file.length();
          ServerLog.Print("?>>>>>>" + file + "   -    Size:" + size);
          if (size > maxSize) {
            file.delete();
            out.print("big");
          } else {
            out.print(
                file.getName()
                    .replace(" ", "%20")
                    .replace("<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">", ""));
            ServerLog.Print("Write pic in: " + file + " size:" + file.length());
            String name2 = file.getName().substring(0, file.getName().lastIndexOf("."));
            String extension2 =
                file.getName()
                    .substring(file.getName().lastIndexOf(".") + 1, file.getName().length());
            File file2 = new File(file.getParent() + "/" + name2 + "_small." + extension2);
            if (extension2.toLowerCase().equals("jpg")
                || extension2.toLowerCase().equals("png")
                || extension2.toLowerCase().equals("gif")) {
              jjPicture.doChangeSizeOfPic(file, file2, 250);
            }
          }
        }
      }
    } catch (Exception ex) {
      Server.ErrorHandler(ex);
    }
    out.flush();
    out.close();
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // set the response

    Shepherd myShepherd = new Shepherd();

    Vector rEncounters = new Vector();

    // setup data dir
    String rootWebappPath = getServletContext().getRealPath("/");
    File webappsDir = new File(rootWebappPath).getParentFile();
    File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName());
    // if(!shepherdDataDir.exists()){shepherdDataDir.mkdir();}
    File encountersDir = new File(shepherdDataDir.getAbsolutePath() + "/encounters");
    // if(!encountersDir.exists()){encountersDir.mkdir();}

    // set up the files
    String gisFilename = "geneGIS_export_" + request.getRemoteUser() + ".csv";
    File gisFile = new File(encountersDir.getAbsolutePath() + "/" + gisFilename);

    myShepherd.beginDBTransaction();

    try {

      // set up the output stream
      FileOutputStream fos = new FileOutputStream(gisFile);
      OutputStreamWriter outp = new OutputStreamWriter(fos);

      try {

        EncounterQueryResult queryResult =
            EncounterQueryProcessor.processQuery(
                myShepherd, request, "year descending, month descending, day descending");
        rEncounters = queryResult.getResult();

        int numMatchingEncounters = rEncounters.size();

        // build the CSV file header
        StringBuffer locusString = new StringBuffer("");
        int numLoci = 2; // most covered species will be loci
        try {
          numLoci = (new Integer(CommonConfiguration.getProperty("numLoci"))).intValue();
        } catch (Exception e) {
          System.out.println("numPloids configuration value did not resolve to an integer.");
          e.printStackTrace();
        }

        for (int j = 0; j < numLoci; j++) {
          locusString.append(",Locus" + (j + 1) + " A1,Locus" + (j + 1) + " A2");
        }
        // out.println("<html><body>");
        // out.println("Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub
        // Area,Sex,Haplotype"+locusString.toString());

        outp.write(
            "Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub Area,Sex,Haplotype"
                + locusString.toString()
                + "\n");

        for (int i = 0; i < numMatchingEncounters; i++) {

          Encounter enc = (Encounter) rEncounters.get(i);
          String assembledString = "";
          if (enc.getIndividualID() != null) {
            assembledString += enc.getIndividualID();
          }
          if (enc.getAlternateID() != null) {
            assembledString += "," + enc.getAlternateID();
          } else {
            assembledString += ",";
          }

          String dateString = ",";
          if (enc.getYear() > 0) {
            dateString += enc.getYear();
            if (enc.getMonth() > 0) {
              dateString += ("-" + enc.getMonth());
              if (enc.getDay() > 0) {
                dateString += ("-" + enc.getDay());
              }
            }
          }
          assembledString += dateString;

          String timeString = ",";
          if (enc.getHour() > -1) {
            timeString += enc.getHour() + ":" + enc.getMinutes();
          }
          assembledString += timeString;

          if ((enc.getDecimalLatitude() != null) && (enc.getDecimalLongitude() != null)) {
            assembledString += "," + enc.getDecimalLatitude();
            assembledString += "," + enc.getDecimalLongitude();
          } else {
            assembledString += ",,";
          }

          assembledString += "," + enc.getVerbatimLocality();
          assembledString += "," + enc.getLocationID();
          assembledString += "," + enc.getSex();

          // find and print the haplotype
          String haplotypeString = ",";
          if (enc.getHaplotype() != null) {
            haplotypeString += enc.getHaplotype();
          }

          // find and print the ms markers
          String msMarkerString = "";
          List<TissueSample> samples = enc.getTissueSamples();
          int numSamples = samples.size();
          boolean foundMsMarkers = false;
          for (int k = 0; k < numSamples; k++) {
            if (!foundMsMarkers) {
              TissueSample t = samples.get(k);
              List<GeneticAnalysis> analyses = t.getGeneticAnalyses();
              int aSize = analyses.size();
              for (int l = 0; l < aSize; l++) {
                GeneticAnalysis ga = analyses.get(l);
                if (ga.getAnalysisType().equals("MicrosatelliteMarkers")) {
                  foundMsMarkers = true;
                  MicrosatelliteMarkersAnalysis ga2 = (MicrosatelliteMarkersAnalysis) ga;
                  List<Locus> loci = ga2.getLoci();
                  int localLoci = loci.size();
                  for (int m = 0; m < localLoci; m++) {
                    Locus locus = loci.get(m);
                    if (locus.getAllele0() != null) {
                      msMarkerString += "," + locus.getAllele0();
                    } else {
                      msMarkerString += ",";
                    }
                    if (locus.getAllele1() != null) {
                      msMarkerString += "," + locus.getAllele1();
                    } else {
                      msMarkerString += ",";
                    }
                  }
                }
              }
            }
          }

          // out.println("<p>"+assembledString+haplotypeString+msMarkerString+"</p>");
          outp.write(assembledString + haplotypeString + msMarkerString + "\n");
        }
        outp.close();
        outp = null;

        // now write out the file
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment;filename=" + gisFilename);
        ServletContext ctx = getServletContext();
        // InputStream is = ctx.getResourceAsStream("/encounters/"+gisFilename);
        InputStream is = new FileInputStream(gisFile);

        int read = 0;
        byte[] bytes = new byte[BYTES_DOWNLOAD];
        OutputStream os = response.getOutputStream();

        while ((read = is.read(bytes)) != -1) {
          os.write(bytes, 0, read);
        }
        os.flush();
        os.close();

      } catch (Exception ioe) {
        ioe.printStackTrace();
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<html><body><p><strong>Error encountered</strong> with file writing. Check the relevant log.</p>");
        out.println(
            "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>");
        out.println(ServletUtilities.getFooter());
        out.close();
        outp.close();
        outp = null;
      }

    } catch (Exception e) {
      e.printStackTrace();
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println(ServletUtilities.getHeader(request));
      out.println("<html><body><p><strong>Error encountered</strong></p>");
      out.println(
          "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>");
      out.println(ServletUtilities.getFooter());
      out.close();
    }
    myShepherd.rollbackDBTransaction();
    myShepherd.closeDBTransaction();
  }