/* goodG2B1() - use goodsource and badsink by changing privateTrue to privateFalse */
  private void goodG2B1() throws Throwable {
    String data;
    if (privateFalse) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process process = Runtime.getRuntime().exec(osCommand + data);
    process.waitFor();
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in if */
  private void goodG2B2() throws Throwable {
    String data;
    if (IO.static_returns_t()) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Logger log_bad = Logger.getLogger("local-logger");

      data = ""; /* init data */

      File f = new File("C:\\data.txt");
      BufferedReader buffread = null;
      FileReader fread = null;
      try {
        /* read string from file into data */
        fread = new FileReader(f);
        buffread = new BufferedReader(fread);

        data = buffread.readLine(); // This will be reading the first "line" of the file, which
        // could be very long if there are little or no newlines in the file\
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } catch (NumberFormatException nfe) {
        log_bad.warning("Error with number parsing");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (fread != null) {
              fread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing fread");
          }
        }
      }
    }

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process p = Runtime.getRuntime().exec(osCommand + data);
    p.waitFor();
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;
    if (privateTrue) {
      /* get system property user.home */
      /* POTENTIAL FLAW: Read data from a system property */
      data = System.getProperty("user.home");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process process = Runtime.getRuntime().exec(osCommand + data);
    process.waitFor();
  }
Esempio n. 4
0
    private void setSysTime(long ctrTime) throws IOException {
    	DateFormat dateTimeFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String dt = dateTimeFmt.format(new Date(ctrTime))
    	String[] cmd = {"date", "-s", dt};
    	String osType = System.getProperty("os.name").toLowerCase();
    	if (osType.contains("linux")) {
    		LOGGER.debug("setting system time {} as {} on driver {}", ctrTime, dt, driver.getDriverInfo().getName());
    		Runtime.getRuntime().exec(cmd);
		} else {
			LOGGER.warn("os type on driver {} is {}!", 
					driver.getDriverInfo().getName(), osType);
		}
	}
  public void action(String data) throws Throwable {

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process process = Runtime.getRuntime().exec(osCommand + data);
    process.waitFor();
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink() throws Throwable {
    String data = CWE78_OS_Command_Injection__console_readLine_68a.data;

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process p = Runtime.getRuntime().exec(osCommand + data);
    p.waitFor();
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B() throws Throwable {
    String data = (new CWE78_OS_Command_Injection__fromDB_61b()).goodG2B_source();

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process p = Runtime.getRuntime().exec(osCommand + data);
    p.waitFor();
  }
  /* uses badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (true) {
      /* POTENTIAL FLAW: Read data from a querystring using getParameter */
      data = request.getParameter("name");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process process = Runtime.getRuntime().exec(osCommand + data);
    process.waitFor();
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;
    if (private_t) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      Connection conn = null;
      PreparedStatement statement = null;
      ResultSet rs = null;
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        /* setup the connection */
        conn = IO.getDBConnection();
        /* prepare the query */
        statement = conn.prepareStatement("select name from users where id=?");
        /* get user input for the userid */
        IO.writeLine("Enter a userid to login as (number): ");
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        int num = Integer.parseInt(buffread.readLine());
        statement.setInt(1, num);
        rs = statement.executeQuery();
        data = rs.getString(1);
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }

        /* clean up database objects */
        try {
          if (rs != null) {
            rs.close();
          }
        } catch (SQLException se) {
          log_bad.warning("Error closing rs");
        } finally {
          try {
            if (statement != null) {
              statement.close();
            }
          } catch (SQLException se) {
            log_bad.warning("Error closing statement");
          } finally {
            try {
              if (conn != null) {
                conn.close();
              }
            } catch (SQLException se) {
              log_bad.warning("Error closing conn");
            }
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process p = Runtime.getRuntime().exec(osCommand + data);
    p.waitFor();
  }
Esempio n. 10
0
 /**
  * The execute method on the Suspend command. This method is executed in the ejb command target.
  *
  * @throws CommandException necessary to fullfill abstract method signature
  * @throws EPlatformException thrown when the remote instance of the Controller can not be
  *     created.
  */
 public void execute()
     throws ie.ucd.srg.logica.eplatform.command.CommandException, EPlatformException {
   LogHelper.log(LogHelper.INFO, "[SuspendCommand.exeute] execute ");
   boolean bBackupFailed = false;
   try {
     /* init the variabeles */
     Hashtable htProps = new Hashtable();
     htProps.put(
         Context.INITIAL_CONTEXT_FACTORY,
         JNDIProperties.getProperty(JNDIProperties.CONTROLLER_CONTEXT_FACTORY));
     htProps.put(
         Context.PROVIDER_URL, JNDIProperties.getProperty(JNDIProperties.CONTROLLER_PROVIDER));
     /* init the context */
     InitialContext icContext = new InitialContext(htProps);
     /* lookup the controller */
     Object obj = icContext.lookup(JNDIProperties.getProperty(JNDIProperties.CONTROLLER_NAME));
     /* create the controller */
     ControllerHome xControllerHome =
         (ControllerHome) PortableRemoteObject.narrow(obj, ControllerHome.class);
     Controller xController = xControllerHome.create();
     // Verify pincodes. If validated then continue with change of state
     g_crCallResult = xController.checkPinCode(sPincode1, sPincode2);
     if (g_crCallResult.getResult() == CallResult.RESULT_OK) {
       // change state to suspended
       g_crCallResult = xController.suspend();
       try {
         /* Call script to backup database to removable medium */
         String sBackupPath = TechnicalProps.getProperty(TechnicalProps.BACKUP_SCRIPT);
         LogHelper.log(LogHelper.INFO, "[SuspendCommand.exeute] Start creating backup...");
         if (sBackupPath != null) {
           Process xProcess = Runtime.getRuntime().exec(sBackupPath);
           int iProcessRes = xProcess.waitFor();
           if (iProcessRes != 0) {
             bBackupFailed = true;
             KOALogHelper.log(
                 KOALogHelper.ERROR,
                 "Error executing script for backup to fs (suspend state) code = " + iProcessRes);
           } else {
             bBackupFailed = false;
             String sMessage =
                 ie.ucd.srg.logica.eplatform.error.ErrorMessageFactory.getErrorMessageFactory()
                     .getErrorMessage(ErrorConstants.CREATE_BACKUP_OK, null);
             KOALogHelper.audit(
                 KOALogHelper.INFO,
                 AuditEventListener.STATE_CHANGE,
                 "SuspendElection",
                 g_sUser,
                 sMessage);
             // set callresult for backup
             g_crCallResult.setBackupResult(sMessage);
             LogHelper.log(LogHelper.INFO, "[SuspendCommand.exeute] backup created OK...");
           }
         }
       } catch (java.lang.InterruptedException xInterruptedExc) {
         bBackupFailed = true;
         KOALogHelper.logErrorCode(
             "SuspendCommand.execute",
             ErrorConstants.UNABLE_TO_START_BACKUP_SCRIPT,
             null,
             xInterruptedExc);
       } catch (java.io.IOException xioExc) {
         bBackupFailed = true;
         String[] params = {"backupscript"};
         KOALogHelper.logErrorCode(
             "SuspendCommand.execute", ErrorConstants.ERR_IO, params, xioExc);
       }
     }
   } catch (NamingException ne) {
     String[] params = {"Controller"};
     KOALogHelper.logErrorCode("SuspendCommand.execute", ErrorConstants.ERR_NAMING, params, ne);
     throw new KOAException(ErrorConstants.COMMAND_SUSPEND_EXEC, ne);
   } catch (RemoteException re) {
     String[] params = {"Controller"};
     KOALogHelper.logErrorCode("SuspendCommand.execute", ErrorConstants.ERR_REMOTE, params, re);
     throw new KOAException(ErrorConstants.COMMAND_SUSPEND_EXEC, re);
   } catch (CreateException ce) {
     String[] params = {"Controller"};
     KOALogHelper.logErrorCode("SuspendCommand.execute", ErrorConstants.ERR_CREATE, params, ce);
     throw new KOAException(ErrorConstants.COMMAND_SUSPEND_EXEC, ce);
   } catch (KOAException koae) {
     KOALogHelper.logError("SuspendCommand.execute", "KOAException", koae);
     throw koae;
   }
   // Always perform the following code, to check if the backup was successful
   finally {
     if (bBackupFailed) {
       try {
         String sMessage =
             ie.ucd.srg.logica.eplatform.error.ErrorMessageFactory.getErrorMessageFactory()
                 .getErrorMessage(ErrorConstants.CREATE_BACKUP_ERROR, null);
         KOALogHelper.audit(
             KOALogHelper.ERROR,
             AuditEventListener.STATE_CHANGE,
             "SuspendElection",
             g_sUser,
             sMessage);
         g_crCallResult.setBackupResult(sMessage);
         LogHelper.log(
             LogHelper.ERROR,
             "[SuspendCommand.exeute] Error occured with result that back up is not created...");
       } catch (java.io.IOException ioe) {
         String[] params = {"Error message factory"};
         KOALogHelper.logErrorCode("SuspendCommand.execute", ErrorConstants.ERR_IO, params, ioe);
       }
     }
   }
 }
Esempio n. 11
0
  /**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      res.setContentType("text/html");

      ServletOutputStream out = res.getOutputStream();
      hitCount++;
      long totalMemory = Runtime.getRuntime().totalMemory();

      long maxMemoryBeforeGC = Runtime.getRuntime().maxMemory();
      long freeMemoryBeforeGC = Runtime.getRuntime().freeMemory();
      long startTime = System.currentTimeMillis();

      System.gc(); // Invoke the GC.

      long endTime = System.currentTimeMillis();
      long maxMemoryAfterGC = Runtime.getRuntime().maxMemory();
      long freeMemoryAfterGC = Runtime.getRuntime().freeMemory();

      out.println(
          "<html><head><title>ExplicitGC</title></head>"
              + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Explicit Garbage Collection<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : "
              + initTime
              + "<BR><BR></FONT>  <B>Hit Count: "
              + hitCount
              + "<br>"
              + "<table border=\"0\"><tr>"
              + "<td align=\"right\">Total Memory</td><td align=\"right\">"
              + totalMemory
              + "</td>"
              + "</tr></table>"
              + "<table width=\"350\"><tr><td colspan=\"2\" align=\"left\">"
              + "Statistics before GC</td></tr>"
              + "<tr><td align=\"right\">"
              + "Max Memory</td><td align=\"right\">"
              + maxMemoryBeforeGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Free Memory</td><td align=\"right\">"
              + freeMemoryBeforeGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Used Memory</td><td align=\"right\">"
              + (totalMemory - freeMemoryBeforeGC)
              + "</td></tr>"
              + "<tr><td colspan=\"2\" align=\"left\">Statistics after GC</td></tr>"
              + "<tr><td align=\"right\">"
              + "Max Memory</td><td align=\"right\">"
              + maxMemoryAfterGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Free Memory</td><td align=\"right\">"
              + freeMemoryAfterGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Used Memory</td><td align=\"right\">"
              + (totalMemory - freeMemoryAfterGC)
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Total Time in GC</td><td align=\"right\">"
              + Float.toString((endTime - startTime) / 1000)
              + "s</td></tr>"
              + "</table>"
              + "</body></html>");
    } catch (Exception e) {
      Log.error(e, "ExplicitGC.doGet(...): general exception caught");
      res.sendError(500, e.toString());
    }
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;
    if (IO.STATIC_FINAL_TRUE) {
      data = ""; /* Initialize data */
      /* Read data from a database */
      {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
          /* setup the connection */
          connection = IO.getDBConnection();
          /* prepare and execute a (hardcoded) query */
          preparedStatement = connection.prepareStatement("select name from users where id=0");
          resultSet = preparedStatement.executeQuery();
          /* POTENTIAL FLAW: Read data from a database query resultset */
          data = resultSet.getString(1);
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql);
        } finally {
          /* Close database objects */
          try {
            if (resultSet != null) {
              resultSet.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
          }

          try {
            if (preparedStatement != null) {
              preparedStatement.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
          }

          try {
            if (connection != null) {
              connection.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    String osCommand;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
    } else {
      /* running on non-Windows */
      osCommand = "/bin/ls ";
    }

    /* POTENTIAL FLAW: command injection */
    Process process = Runtime.getRuntime().exec(osCommand + data);
    process.waitFor();
  }