void put(final URI uri, ArtifactData data) throws Exception {
   reporter.trace("put %s %s", uri, data);
   File tmp = createTempFile(repoDir, "mtp", ".whatever");
   tmp.deleteOnExit();
   try {
     copy(uri.toURL(), tmp);
     byte[] sha = SHA1.digest(tmp).digest();
     reporter.trace("SHA %s %s", uri, Hex.toHexString(sha));
     ArtifactData existing = get(sha);
     if (existing != null) {
       reporter.trace("existing");
       xcopy(existing, data);
       return;
     }
     File meta = new File(repoDir, Hex.toHexString(sha) + ".json");
     File file = new File(repoDir, Hex.toHexString(sha));
     rename(tmp, file);
     reporter.trace("file %s", file);
     data.file = file.getAbsolutePath();
     data.sha = sha;
     data.busy = false;
     CommandData cmddata = parseCommandData(data);
     if (cmddata.bsn != null) {
       data.name = cmddata.bsn + "-" + cmddata.version;
     } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri);
     codec.enc().to(meta).put(data);
     reporter.trace("TD = " + data);
   } finally {
     tmp.delete();
     reporter.trace("puted %s %s", uri, data);
   }
 }
Beispiel #2
0
    public void run() {
      try {
        URL url = new URL(protocol + "://localhost:" + port + "/test1/" + f);
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        if (urlc instanceof HttpsURLConnection) {
          HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
          urlcs.setHostnameVerifier(
              new HostnameVerifier() {
                public boolean verify(String s, SSLSession s1) {
                  return true;
                }
              });
          urlcs.setSSLSocketFactory(ctx.getSocketFactory());
        }
        byte[] buf = new byte[4096];

        if (fixedLen) {
          urlc.setRequestProperty("XFixed", "yes");
        }
        InputStream is = urlc.getInputStream();
        File temp = File.createTempFile("Test1", null);
        temp.deleteOnExit();
        OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp));
        int c, count = 0;
        while ((c = is.read(buf)) != -1) {
          count += c;
          fout.write(buf, 0, c);
        }
        is.close();
        fout.close();

        if (count != size) {
          throw new RuntimeException("wrong amount of data returned");
        }
        String orig = root + "/" + f;
        compare(new File(orig), temp);
        temp.delete();
      } catch (Exception e) {
        e.printStackTrace();
        fail = true;
      }
    }
  /**
   * Garbage collect repository
   *
   * @throws Exception
   */
  public void gc() throws Exception {
    HashSet<byte[]> deps = new HashSet<byte[]>();

    // deps.add(SERVICE_JAR_FILE);

    for (File cmd : commandDir.listFiles()) {
      CommandData data = getData(CommandData.class, cmd);
      addDependencies(deps, data);
    }

    for (File service : serviceDir.listFiles()) {
      File dataFile = new File(service, "data");
      ServiceData data = getData(ServiceData.class, dataFile);
      addDependencies(deps, data);
    }

    int count = 0;
    for (File f : repoDir.listFiles()) {
      String name = f.getName();
      if (!deps.contains(name)) {
        if (!name.endsWith(".json")
            || !deps.contains(name.substring(0, name.length() - ".json".length()))) { // Remove
          // json
          // files
          // only
          // if
          // the
          // bin
          // is
          // going
          // as
          // well
          f.delete();
          count++;
        } else {

        }
      }
    }
    System.out.format("Garbage collection done (%d file(s) removed)%n", count);
  }
Beispiel #4
0
  /** Runs a Solaris installer */
  public static boolean runSolarisInstaller(String installPath, File installFile) {

    /** Build temp. script file */
    File script = null;
    boolean success = false;
    try {
      script = SolarisInstaller.createTempShellScript();

      String[] args = new String[3];
      args[0] = installPath;
      args[1] = script.getAbsolutePath();
      args[2] = installFile.getAbsolutePath();
      String execString = getExecuteString(args);
      success = SolarisInstaller.execute(execString);
    } catch (IOException ioe) {
      Config.trace("Got ioe: " + ioe);
      return false;
    } finally {
      if (script != null) script.delete();
    }
    return success;
  }
  public boolean download(
      String sourceFile, String destFile, UserToken token, HashMap<String, ArrayList<Key>> keys) {
    try {
      destFile = "." + destFile;

      if (sourceFile.charAt(0) == '/') {
        sourceFile = sourceFile.substring(1);
      }

      File file = new File(destFile);

      if (!file.exists()) {
        file.createNewFile();

        FileOutputStream fos = new FileOutputStream(file);
        Envelope env = new Envelope("DOWNLOADF"); // Success
        env.addObject(sourceFile);
        env.addObject(token);
        String concat =
            sourceFile
                + token.toString()
                + "DOWNLOADF"
                + nonce; // concatinates all of the objects in envelope
        byte[] hasharray = concat.getBytes(); // turn the concat into a byte array
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(HMACkey);
        mac.update(hasharray);
        String stringhash =
            new String(mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision!
        env.addObject(stringhash);
        env.addObject(nonce);
        nonce++;

        byte[] envBytes = Envelope.toByteArray(env);

        // Encrypt envelope w/ AES
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, AESkey);
        byte[] cipherBytes = cipher.doFinal(envBytes);

        output.writeObject(cipherBytes); // here in download

        byte[] responseCipherBytes = (byte[]) input.readObject();

        // Decrypt response
        cipher.init(Cipher.DECRYPT_MODE, AESkey);
        byte[] responseBytes = cipher.doFinal(responseCipherBytes);

        env = Envelope.getEnvelopefromBytes(responseBytes);
        ShareFile sf = (ShareFile) env.getObjContents().get(2);
        int keyNum = sf.getKeyNum();
        ArrayList<Key> groupKeys = keys.get(sf.getGroup());
        Key key = groupKeys.get(keyNum);
        byte[] initialVector = sf.getIV();
        IvParameterSpec ivs = new IvParameterSpec(initialVector);
        byte[] decryptBuf = new byte[1024];

        while (env.getMessage().compareTo("CHUNK") == 0
            && (Integer) env.getObjContents().get(4) == nonce) {
          String hash = (String) env.getObjContents().get(3);
          concat =
              (Integer) env.getObjContents().get(1)
                  + env.getMessage()
                  + nonce; // reconstructs the hash
          System.out.println("Concat:" + concat);
          hasharray = concat.getBytes();
          mac = Mac.getInstance("HmacSHA1");
          File HASHfile = new File("FHASHKey.bin");
          FileInputStream fis = new FileInputStream(HASHfile);
          ObjectInputStream ois = new ObjectInputStream(fis);
          HMACkey = (Key) ois.readObject();
          mac.init(HMACkey);
          mac.update(hasharray);
          String newhash = new String(mac.doFinal(), "UTF8");
          nonce++;

          // check hashes for equality
          if (hash.equals(newhash) != true) {
            System.out.println("HASH EQUALITY FAIL1");
            disconnect();
            return false;
          } else {
            decryptBuf = new byte[1024];
            System.out.println("env.getMessage: " + env.getMessage());
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, key, ivs);
            decryptBuf = cipher.doFinal((byte[]) env.getObjContents().get(0));

            // Write encrypted file to disk
            fos.write(decryptBuf);
            System.out.printf(".");
            env = new Envelope("DOWNLOADF"); // Success
            concat = env.getMessage() + nonce; // concatinates all of the objects in envelope
            hasharray = concat.getBytes(); // turn the concat into a byte array
            mac = Mac.getInstance("HmacSHA1");
            mac.init(HMACkey);
            mac.update(hasharray);
            stringhash =
                new String(
                    mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision!
            env.addObject(stringhash);
            env.addObject(nonce);
            nonce++;

            envBytes = Envelope.toByteArray(env);

            // Encrypt envelope w/ AES
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, AESkey);
            cipherBytes = cipher.doFinal(envBytes);

            output.writeObject(cipherBytes);

            responseCipherBytes = (byte[]) input.readObject();

            // Decrypt response
            cipher.init(Cipher.DECRYPT_MODE, AESkey);
            responseBytes = cipher.doFinal(responseCipherBytes);

            env = Envelope.getEnvelopefromBytes(responseBytes);
          }
        }
        fos.close();
        if (env.getMessage().compareTo("EOF") == 0
            && (Integer) env.getObjContents().get(1) == nonce) {
          String hash = (String) env.getObjContents().get(0);
          concat = env.getMessage() + nonce; // reconstructs the hash
          hasharray = concat.getBytes();
          mac = Mac.getInstance("HmacSHA1");
          File HASHfile = new File("FHASHKey.bin");
          FileInputStream fis = new FileInputStream(HASHfile);
          ObjectInputStream ois = new ObjectInputStream(fis);
          HMACkey = (Key) ois.readObject();
          mac.init(HMACkey);
          mac.update(hasharray);
          String newhash = new String(mac.doFinal(), "UTF8");

          if (hash.equals(newhash) != true) // check hashes for equality
          {
            System.out.println("HASH EQUALITY FAIL2");
            disconnect();
          }

          fos.close();
          System.out.printf("\nTransfer successful file %s\n", sourceFile);
          nonce++;
          env = new Envelope("OK"); // Success
          concat = env.getMessage() + nonce; // concatinates all of the objects in envelope
          hasharray = concat.getBytes(); // turn the concat into a byte array
          mac = Mac.getInstance("HmacSHA1");
          mac.init(HMACkey);
          mac.update(hasharray);
          stringhash =
              new String(
                  mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision!
          env.addObject(stringhash);
          env.addObject(nonce);
          nonce++;

          envBytes = Envelope.toByteArray(env);

          // Encrypt envelope w/ AES
          cipher = Cipher.getInstance("AES");
          cipher.init(Cipher.ENCRYPT_MODE, AESkey);
          cipherBytes = cipher.doFinal(envBytes);

          output.writeObject(cipherBytes);

        } else if ((Integer) env.getObjContents().get(1) != nonce) {
          System.out.println("Nonce FAIL DOWNLOADF");
          disconnect();
          return false;
        } else {
          System.out.printf("Error reading file %s (%s)\n", sourceFile, env.getMessage());
          file.delete();
          return false;
        }
      } else {
        System.out.printf("Error couldn't create file %s\n", destFile);
        return false;
      }

    } catch (InvalidAlgorithmParameterException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(1);
    } catch (BadPaddingException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(2);
    } catch (InvalidKeyException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(3);
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(4);
    } catch (NoSuchPaddingException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(5);
    } catch (IOException e1) {

      System.out.printf("Error couldn't create file %s\n", destFile);
      return false;

    } catch (ClassNotFoundException e1) {
      e1.printStackTrace(System.err);
    }
    return true;
  }
Beispiel #6
0
 public static void deleteIfExists(File file) {
   if (file.exists()) file.delete();
 }
Beispiel #7
0
 public static void deleteDirectory(File f) throws IOException {
   if (f.isDirectory()) {
     for (File c : f.listFiles()) deleteDirectory(c);
   }
   if (!f.delete()) throw new FileNotFoundException("Failed to delete file: " + f);
 }
Beispiel #8
0
  /** Does install of JRE */
  public static void install() {

    // Hide the JNLP Clients installer window and show own
    Config.getInstallService().hideStatusWindow();
    showInstallerWindow();

    // Make sure the destination exists.
    String path = Config.getInstallService().getInstallPath();
    if (Config.isWindowsInstall()) {
      String defaultLocation = "C:\\Program Files\\Java\\j2re" + Config.getJavaVersion() + "\\";
      File defaultDir = new File(defaultLocation);
      if (!defaultDir.exists()) {
        defaultDir.mkdirs();
      }
      if (defaultDir.exists() && defaultDir.canWrite()) {
        path = defaultLocation; // use default if you can
      }
    }

    File installDir = new File(path);

    if (!installDir.exists()) {
      installDir.mkdirs();
      if (!installDir.exists()) {
        // The installFailed string is only for debugging. No localization needed
        installFailed("couldntCreateDirectory", null);
        return;
      }
    }

    // Show license if neccesary
    enableStep(STEP_LICENSE);
    if (!showLicensing()) {
      // The installFailed string is only for debugging. No localization needed
      installFailed("Licensing was not accepted", null);
    }
    ;

    // Make sure that the data JAR is downloaded
    enableStep(STEP_DOWNLOAD);
    if (!downloadInstallerComponent()) {
      // The installFailed string is only for debugging. No localization needed
      installFailed("Unable to download data component", null);
    }

    String nativeLibName = Config.getNativeLibName();
    File installerFile = null;

    try {
      // Load native library into process if found
      if (nativeLibName != null && !Config.isSolarisInstall()) {
        System.loadLibrary(nativeLibName);
      }

      // Unpack installer
      enableStep(STEP_UNPACK);
      String installResource = Config.getInstallerResource();
      Config.trace("Installer resource: " + installResource);
      installerFile = unpackInstaller(installResource);

      // To clean-up downloaded files
      Config.trace("Unpacked installer to: " + installerFile);
      if (installerFile == null) {
        // The installFailed string is only for debugging. No localization needed
        installFailed("Could not unpack installer components", null);
        return;
      }

      enableStep(STEP_INSTALL);
      setStepText(STEP_INSTALL, Config.getWindowStepWait(STEP_INSTALL));

      boolean success = false;
      if (Config.isSolarisInstall()) {
        success = runSolarisInstaller(path, installerFile);
      } else {
        success = runWindowsInstaller(path, installerFile);
      }

      if (!success) {
        // The installFailed string is only for debugging. No localization needed
        installFailed("Could not run installer", null);
        return;
      }
    } catch (UnsatisfiedLinkError ule) {
      // The installFailed string is only for debugging. No localization needed
      installFailed("Unable to load library: " + nativeLibName, null);
      return;
    } finally {
      if (installerFile != null) {
        installerFile.delete();
      }
    }

    setStepText(STEP_INSTALL, Config.getWindowStep(STEP_INSTALL));
    enableStep(STEP_DONE);

    String execPath = path + Config.getJavaPath();
    Config.trace(execPath);

    /** Remove installer JAR from cache */
    removeInstallerComponent();

    // If we're running anything after 1.0.1 or not on Windows, just call
    // finishedInstall.  Otherwise, deny ExitVM permission so that we can
    // return here and do a reboot.  We have to do this because we need to
    // call ExtensionInstallerService.finishedInstall(), which registers
    // that our extension (the JRE) is installed.  Unfortunately pre-1.2 it
    // also does not understand that we are requesting a reboot, and calls
    // System.exit().  So for pre 1.2 we want to deny the permission to
    // exit the VM so we can return here and perform a reboot.
    boolean ispre12 = false;
    String version = Config.getJavaWSVersion();
    // get first tuple
    String v = version.substring(version.indexOf('-') + 1);
    int i2 = v.indexOf('.');
    int v1 = Integer.parseInt(v.substring(0, i2));
    // get second tuple
    v = v.substring(i2 + 1);
    i2 = v.indexOf('.');
    if (i2 == -1) i2 = v.indexOf('-');
    if (i2 == -1) i2 = v.indexOf('[');
    if (i2 == -1) i2 = v.length();
    int v2 = Integer.parseInt(v.substring(0, i2));
    // are we pre 1.2?
    if (v1 < 1 || (v1 == 1 && v2 < 2)) ispre12 = true;

    if (Config.isWindowsInstall() && ispre12 && Config.isHopper()) {
      // deny ExitVM permission then call finishedInstall
      ProtectionDomain pd = (new Object()).getClass().getProtectionDomain();
      CodeSource cs = pd.getCodeSource();
      AllPermissionExceptExitVM perm = new AllPermissionExceptExitVM();
      PermissionCollection newpc = perm.newPermissionCollection();
      newpc.add(perm);

      // run finishedInstall within the new context which excluded
      // just the ExitVM permission
      ProtectionDomain newpd = new ProtectionDomain(cs, newpc);
      AccessControlContext newacc = new AccessControlContext(new ProtectionDomain[] {newpd});
      final String fExecPath = execPath;
      try {
        AccessController.doPrivileged(
            new PrivilegedExceptionAction() {
              public Object run() throws SecurityException {
                finishedInstall(fExecPath);
                return null;
              }
            },
            newacc);
      } catch (PrivilegedActionException pae) {
        // swallow the exception because we want ExitVM to fail silent
      } catch (SecurityException se) {
        // swallow the exception because we want ExitVM to fail silent
      }
    } else {
      // just call finished Install
      finishedInstall(execPath);
    }

    if (Config.isWindowsInstall() && WindowsInstaller.IsRebootNecessary()) {
      // reboot
      if (!WindowsInstaller.askUserForReboot()) System.exit(0);
    } else {
      System.exit(0);
    }
  }
Beispiel #9
0
  /** Runs a Windows installer */
  public static boolean runWindowsInstaller(String installPath, File installFile) {
    boolean deleteHopperKey = false;
    boolean deleteMerlinKey = false;
    // If Hopper, and JavaWS can update, ask the user if they want
    // to update.
    if (Config.isHopper()
        && !WinRegistry.doesSubKeyExist(WinRegistry.HKEY_LOCAL_MACHINE, JAVAWS_HOPPER_KEY)) {
      int res =
          JOptionPane.showConfirmDialog(
              _installerFrame,
              Config.getJavaWSConfirmMessage(),
              Config.getJavaWSConfirmTitle(),
              JOptionPane.YES_NO_OPTION);
      if (res == JOptionPane.NO_OPTION) {
        // create the registry key so that JavaWS will not install
        WinRegistry.setStringValue(WinRegistry.HKEY_LOCAL_MACHINE, JAVAWS_HOPPER_KEY, "Home", "");
        // flag to delete the key later
        deleteHopperKey = true;
      }
    }

    // If Merlin, never update JavaWS.  1.0.1_02 bundled with Merlin does
    // not have the ability to update while JavaWS is running.  So just
    // prevent the update by spoofing the registry key.
    if (Config.isMerlin()) {
      WinRegistry.setStringValue(WinRegistry.HKEY_LOCAL_MACHINE, JAVAWS_MERLIN_KEY, "Home", "");
      deleteMerlinKey = true;
    }

    /** Build temp. script file */
    boolean success = false;
    File iss = null;
    try {
      String[] args = new String[2];
      args[0] = installFile.getAbsolutePath();
      if (Config.getJavaVersion().startsWith("1.4.2")) {
        args[1] = "/s /v\"/qn WEBSTARTICON=1 INSTALLDIR=\\\"" + installPath + "\\\"\"";

      } else {
        iss = WindowsInstaller.createTempISSScript(installPath, Config.getJavaVersion());
        args[1] = iss.getAbsolutePath();
      }
      String execString = getExecuteString(args);
      success = WindowsInstaller.execute(execString);
    } catch (IOException ioe) {
      return false;
    } finally {
      if (iss != null) iss.delete();
    }

    // delete any spoofed keys we created earlier
    if (deleteHopperKey) {
      WinRegistry.deleteKey(WinRegistry.HKEY_LOCAL_MACHINE, JAVAWS_HOPPER_KEY);
    }
    if (deleteMerlinKey) {
      WinRegistry.deleteKey(WinRegistry.HKEY_LOCAL_MACHINE, JAVAWS_MERLIN_KEY);
    }

    // 4662215 cannot reboot here because the config hasn't been written
    // by JavaWS yet.  Reboot later, after installSucceeded has been
    // called.
    // WindowsInstaller.rebootIfNecessary();

    return success;
  }
  public boolean connect(String username, String weakSecret, final String server, final int port) {
    System.out.println("attempting to connect");

    try {
      sock = new Socket();
      sock.connect(new InetSocketAddress(server, port));
      output = new ObjectOutputStream(sock.getOutputStream());
      input = new ObjectInputStream(sock.getInputStream());
      output.writeObject(username);

      // do DH exchange and agree on starting message index
      try {
        if (weakSecret != null) // group server connect
        {
          HashMap<String, SecretKey> secretKeys =
              DHKeyExchange.generateSecretKeyWithWeakSecret(username, weakSecret, input, output);
          if (secretKeys == null) throw new Exception("Unable to verify server");
          encryptionKey = secretKeys.get("encryptionKey");
          signingKey = secretKeys.get("signingKey");
        } else // file server connect
        {
          PublicKey fileServerPublicKey = (PublicKey) input.readObject(); // read in public key

          File savedKeys = new File("savedkeys.bin");
          ArrayList<PublicKey> knownKeys = new ArrayList<PublicKey>();
          if (savedKeys.exists()) {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(savedKeys));
            knownKeys = (ArrayList<PublicKey>) in.readObject();
          }
          if (!knownKeys.contains(fileServerPublicKey)) // prompt the user to verify the key
          {
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            byte[] digest = sha.digest(fileServerPublicKey.getEncoded());
            System.out.println("RSA key fingerprint is " + getFingerprint(digest));
            System.out.println(
                "Please verify this is correct by contacting the file server owner.");
            System.out.println(
                "Do you want to add this key to your list of saved servers? (yes/no)");
            Scanner scanner = new Scanner(System.in);
            String answer = scanner.nextLine();
            if (answer.toLowerCase().equals("yes")) {
              knownKeys.add(fileServerPublicKey);
              savedKeys.delete();
              savedKeys.createNewFile();
              ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(savedKeys));
              out.writeObject(knownKeys);
              out.flush();
              out.close();
              output.writeObject("yes");
            } else {
              output.writeObject("no");
              System.out.println("Exiting");
              System.exit(0);
            }
          } else // accpet the key without prompt
          output.writeObject("yes");

          generateRSAKeypair();
          output.writeObject(publicKey);
          HashMap<String, SecretKey> secretKeys =
              DHKeyExchange.generateSecretKeySignedExchange(
                  input, output, privateKey, fileServerPublicKey);
          if (secretKeys == null) throw new Exception("Unable to verify server");
          encryptionKey = secretKeys.get("encryptionKey");
          signingKey = secretKeys.get("signingKey");
        }

        encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] key = sha.digest(encryptionKey.getEncoded());
        key = Arrays.copyOf(key, 16); // use only first 128 bit

        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes));
        decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes));

        BigInteger R = new BigInteger(128, new SecureRandom());
        output.writeObject(encryptCipher.doFinal(R.toByteArray()));
        BigInteger start = new BigInteger(decryptCipher.doFinal((byte[]) input.readObject()));
        if (start.compareTo(R) < 0) throw new Exception("Invalid message index from server");
        else messageIndex = start.add(BigInteger.ONE);
      } catch (Exception ex) {
        System.out.println("Failed to connect: " + ex.getMessage());
        // if anything fails, we are not connected
        sock = null;
        return false;
      }
    } catch (IOException ex) {
      return false;
    }

    return true;
  }