@Override
 public void logEvent(String message, int entityId, Class entityClass, Date date) {
   User user = (User) Utility.getAuthenticatedUser();
   try {
     auditLogRecordRepo.logEvent(
         user, PBEWithMD5AndDES.encrypt(message), entityId, entityClass, date);
   } catch (GeneralSecurityException e) {
     e.printStackTrace();
   }
 }
  /**
   * Creates the GenericStreamCipher or GenericBlockCipher data structure for specified data of
   * specified type.
   *
   * @throws AlertException if alert was occurred.
   */
  @Override
  protected byte[] encrypt(byte type, byte[] fragment, int offset, int len) {
    try {
      int content_mac_length = len + hash_size;
      int padding_length = is_block_cipher ? ((8 - (++content_mac_length & 0x07)) & 0x07) : 0;
      byte[] res = new byte[content_mac_length + padding_length];
      System.arraycopy(fragment, offset, res, 0, len);

      mac_material_header[0] = type;
      mac_material_header[3] = (byte) ((0x00FF00 & len) >> 8);
      mac_material_header[4] = (byte) (0x0000FF & len);

      encMac.update(write_seq_num);
      encMac.update(mac_material_header);
      encMac.update(fragment, offset, len);
      encMac.doFinal(res, len);

      // if (logger != null) {
      //    logger.println("MAC Material:");
      //    logger.print(write_seq_num);
      //    logger.print(mac_material_header);
      //    logger.print(fragment, offset, len);
      // }

      if (is_block_cipher) {
        // do padding:
        Arrays.fill(res, content_mac_length - 1, res.length, (byte) (padding_length));
      }
      if (logger != null) {
        logger.println(
            "SSLRecordProtocol.do_encryption: Generic"
                + (is_block_cipher
                    ? "BlockCipher with padding[" + padding_length + "]:"
                    : "StreamCipher:"));
        logger.print(res);
      }
      byte[] rez = new byte[encCipher.getOutputSize(res.length)];
      // We should not call just doFinal because it reinitialize
      // the cipher, but as says rfc 2246:
      // "For stream ciphers that do not use a synchronization
      // vector (such as RC4), the stream cipher state from the end
      // of one record is simply used on the subsequent packet."
      // and for block ciphers:
      // "The IV for subsequent records is the last ciphertext block from
      // the previous record."
      // i.e. we should keep the cipher state.
      encCipher.update(res, 0, res.length, rez);
      incSequenceNumber(write_seq_num);
      return rez;
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
      throw new AlertException(
          AlertProtocol.INTERNAL_ERROR, new SSLProtocolException("Error during the encryption"));
    }
  }
Example #3
0
  public static void crypt(String inFilename, String outFilename, int mode) {
    InputStream in = null;
    OutputStream out = null;
    ObjectInputStream keyin = null;
    try {
      in = new FileInputStream(inFilename);
      out = new FileOutputStream(outFilename);
      keyin = new ObjectInputStream(new FileInputStream(keyFilename));
      // 获取到密钥
      Key key = (Key) keyin.readObject();
      // 使用AES算法获取密码对象
      Cipher cipher = Cipher.getInstance("AES");
      // 通过设置模式和密钥来初始化
      cipher.init(mode, key);

      // 获取密码块大小,16
      int blockSize = cipher.getBlockSize();
      // 该密码块对应的输出缓存区大小,用于存放密码对象输出的数据块
      int outputSize = cipher.getOutputSize(blockSize);
      byte[] inBytes = new byte[blockSize];
      byte[] outBytes = new byte[outputSize];
      int length = 0;

      boolean more = true;
      while (more) {
        length = in.read(inBytes);
        // 如果能读到blockSize大小的块
        if (length == blockSize) {
          // 数据块存入outBytes
          int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
          out.write(outBytes, 0, outLength);
        } else {
          more = false;
        }
      }
      // 如果最后一个输入数据块的字节数小于blockSize,剩下的字节将会自动填充
      if (length > 0) {
        outBytes = cipher.doFinal(inBytes, 0, length);
      } else {
        outBytes = cipher.doFinal();
      }
      out.write(outBytes);

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
    } finally {
      Closer.close(in);
      Closer.close(out);
      Closer.close(keyin);
    }
  }
 public void run() {
   try {
     Subject server = subjectFactory.getSubjectForHost(getHostName(exchange));
     // The AcceptSecurityContext takes over responsibility for setting the result.
     Subject.doAs(server, new AcceptSecurityContext(result, exchange, challenge));
   } catch (GeneralSecurityException e) {
     e.printStackTrace();
     result.setResult(new AuthenticationResult(null, AuthenticationOutcome.NOT_AUTHENTICATED));
   } catch (PrivilegedActionException e) {
     e.printStackTrace();
     result.setResult(new AuthenticationResult(null, AuthenticationOutcome.NOT_AUTHENTICATED));
   }
 }
 static {
   try {
     KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
     X509EncodedKeySpec spec =
         new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(KEY_B64_ENCODED));
     key = factory.generatePublic(spec);
   } catch (GeneralSecurityException e) {
     key = null;
     // no log service available yet, so use syserr
     System.err.println(
         "Failed to initialize public key to verify extension certificates. Revoking permissions for all extensions!");
     e.printStackTrace();
   }
 }
Example #6
0
  /**
   * Decrypt a node.
   *
   * @param bytesToDecrypt Byte array to decrypt.
   * @param rawSKey Secret key for decryption.
   * @return Original byte array of node.
   */
  public static final synchronized byte[] decrypt(
      final byte[] bytesToDecrypt, final byte[] rawSKey) {

    // restore secret key from byte array
    final SecretKeySpec restoredSKey = new SecretKeySpec(rawSKey, ENCRYPTION_TYPE);

    final Cipher cipher;
    byte[] decrypted = null;
    final IvParameterSpec ivParams = new IvParameterSpec(rawSKey);

    try {
      cipher = Cipher.getInstance(ENCRYPTION_PADDING_TYPE);
      cipher.init(Cipher.DECRYPT_MODE, restoredSKey, ivParams);
      decrypted = cipher.doFinal(bytesToDecrypt);
    } catch (final GeneralSecurityException exc) {
      exc.printStackTrace();
    }
    return decrypted;
  }
 @Bean
 public JavaMailSender javaMailSender() {
   JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
   javaMailSender.setHost(host);
   javaMailSender.setPort(Integer.parseInt(port));
   javaMailSender.setUsername(username);
   javaMailSender.setPassword(password);
   Properties properties = new Properties();
   properties.put("mail.smtp.auth", "true");
   properties.put("mail.smtp.starttls.enable", "true");
   properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
   MailSSLSocketFactory sf = null;
   try {
     sf = new MailSSLSocketFactory();
     sf.setTrustAllHosts(true);
     properties.put("mail.smtp.ssl.socketFactory", sf);
   } catch (GeneralSecurityException e) {
     e.printStackTrace();
   }
   javaMailSender.setJavaMailProperties(properties);
   return javaMailSender;
 }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // first detect which language is in use
    ResourceBundle message = LiteUtility.detectLanguageInUse(req);

    HttpSession session = req.getSession();
    AccountService as = new AccountServiceImpl(LiteUtility.PARTNER_REF);
    LoginFrom loginFrom = null;
    if (req.getParameter("option") == null) { // sign in via form
      loginFrom = LoginFrom.FORM;
      String submit = req.getParameter("submit");
      if (submit == null) {
        req.getRequestDispatcher("/teacher_login.jsp").forward(req, resp);
        return;
      }
      String email = req.getParameter("email").toLowerCase();
      String password = req.getParameter("password");
      String usrPartnerRef = email;

      List<PartnerToAssistments> list;
      try {
        list = as.find(ColumnNames.PARTNER_EXTERNAL_REFERENCE, email);
        PartnerToAssistments user = list.get(0);
        if (user.getPartnerAccessToken().equals(LiteUtility.getHash(password))) {
          LoginInfo loginInfo =
              new LoginInfo(
                  user.getAssistmentsExternalRefernce(),
                  user.getAssistmentsAccessToken(),
                  email,
                  usrPartnerRef,
                  loginFrom);
          session.setAttribute(LiteUtility.LOGIN_INFO_ATTRIBUTE, loginInfo);
          resp.sendRedirect("/direct/teacher");
        } else { // Wrong password
          String msg = message.getString("teacher_login.incorrect_password");
          req.setAttribute("email", email);
          req.setAttribute("message", msg);
          req.getRequestDispatcher("/teacher_login.jsp").forward(req, resp);
          return;
        }
      } catch (ReferenceNotFoundException e) {
        // This should never happen
      }

    } else { // this request is sent via ajax
      String thirdPartyId = new String();
      String email = "";
      String from = new String();
      if ("facebook".equals(req.getParameter("option").toString())) {
        thirdPartyId = "facebook_" + req.getParameter("user_id");
        from = "Facebook";
        loginFrom = LoginFrom.FACEBOOK;
        email = req.getParameter("email");
      } else if ("google".equals(req.getParameter("option").toString())) {
        loginFrom = LoginFrom.GOOGLE;
        String idTokenString = req.getParameter("idtoken");
        from = "Google";
        HttpTransport transport = new NetHttpTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        GoogleIdTokenVerifier verifier =
            new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
                .setAudience(Arrays.asList(CLIENT_ID))
                .build();
        GoogleIdToken idToken = null;
        try {
          idToken = verifier.verify(idTokenString);
        } catch (GeneralSecurityException e) {
          e.printStackTrace();
          String msg = message.getString("teacher_login.failure_on_google");
          resp.getWriter().print(msg);
          resp.setStatus(203);
          return;
        }
        if (idToken != null) {
          Payload payload = idToken.getPayload();
          String userId = payload.getSubject();
          email = payload.getEmail();
          thirdPartyId = "google_" + userId;
        } else {
          String msg = message.getString("teacher_login.failure_on_google");
          resp.getWriter().print(msg);
          resp.setStatus(203);
          return;
        }
      }
      List<PartnerToAssistments> list;
      try {
        list = as.find(ColumnNames.PARTNER_EXTERNAL_REFERENCE, thirdPartyId);
        PartnerToAssistments user = list.get(0);

        LoginInfo loginInfo =
            new LoginInfo(
                user.getAssistmentsExternalRefernce(),
                user.getAssistmentsAccessToken(),
                email,
                thirdPartyId,
                loginFrom);
        session.setAttribute(LiteUtility.LOGIN_INFO_ATTRIBUTE, loginInfo);
        resp.getWriter().print(req.getContextPath() + "/teacher");
      } catch (ReferenceNotFoundException e) {
        String msg = String.format(message.getString("teacher_login.account_not_found"), from);
        resp.getWriter().print(msg);
        resp.setStatus(203);
        return;
      }
    }
  }
  public void changePassword(
      String env,
      String cspName,
      String cspPassword,
      String cloudNameString,
      String currentPassword,
      String newPassword) {
    // Step 0: Set up CSP

    CloudNumber cspCloudNumber = null;
    String cspRegistryURL = "";
    String cspUserURL = "";
    XDIDiscoveryClient discoveryClient = null;
    String registrationSvcURL = "";

    if (env.equalsIgnoreCase("prod")) {
      discoveryClient = XDIDiscoveryClient.NEUSTAR_PROD_DISCOVERY_CLIENT;
      cspRegistryURL = "https://mycloud.neustar.biz/" + cspName + "-registry";
      cspUserURL = "https://mycloud.neustar.biz/" + cspName + "-users/";
      registrationSvcURL = "https://registration.respectnetwork.net/registration";
    } else if (env.equalsIgnoreCase("ote")) {
      discoveryClient = XDIDiscoveryClient.NEUSTAR_OTE_DISCOVERY_CLIENT;
      cspRegistryURL = "https://mycloud-ote.neustar.biz/" + cspName + "-registry";
      cspUserURL = "https://mycloud-ote.neustar.biz/" + cspName + "-users/";
      registrationSvcURL = "https://registration-stage.respectnetwork.net/registration";
    } else if (env.equalsIgnoreCase("prod-au")) {
      discoveryClient = XDIDiscoveryClient.NEUSTAR_PROD_DISCOVERY_CLIENT;
      cspRegistryURL = "https://mycloud-au.neustar.biz/" + cspName + "-registry";
      ;
      cspUserURL = "https://mycloud-au.neustar.biz/" + cspName + "-users/";
      registrationSvcURL = "https://registration.respectnetwork.net/registration";
    }
    System.out.println("CSP Resistry URL:" + cspRegistryURL);
    System.out.println("CSP User URL:" + cspUserURL);
    System.out.println("Regn. svc. URL:" + registrationSvcURL);
    System.out.println("Discovery info:" + discoveryClient.toString());
    try {
      XDIDiscoveryResult discResult = discoveryClient.discover(XDIAddress.create("+" + cspName));

      cspCloudNumber = discResult.getCloudNumber();
      System.out.println("CSP Cloud Number : " + cspCloudNumber.toString());

    } catch (Xdi2ClientException e) {
      System.out.println("Xdi2ClientException: " + e.getMessage());
      e.printStackTrace();
    }
    BasicCSPInformation cspInformation =
        new BasicCSPInformation(
            cspCloudNumber,
            cspRegistryURL,
            cspUserURL,
            cspPassword,
            null,
            CloudNumber.create("[+]!:uuid:ca51aeb9-e09e-4305-89d7-87a944a1e1fa"),
            registrationSvcURL,
            XDIAddress.create("([+]!:uuid:ca51aeb9-e09e-4305-89d7-87a944a1e1fa/#registrar)$do"),
            null,
            discoveryClient);

    System.out.println("CSP Information:\n" + cspInformation.toString());
    cspInformation.setRnCspSecretToken(null);
    try {
      cspInformation.retrieveCspSignaturePrivateKey();
    } catch (Xdi2ClientException e2) {
      // TODO Auto-generated catch block
      e2.printStackTrace();
    } catch (GeneralSecurityException e2) {
      // TODO Auto-generated catch block
      e2.printStackTrace();
    }
    if (cspInformation.getCspSignaturePrivateKey() == null) {
      System.err.println("Invalid CSP Information.");
      System.exit(0);
    }

    cloudName = CloudName.create(cloudNameString);

    if (cloudName == null || !cloudNameString.startsWith("=")) {

      System.err.println("Invalid Cloud Name.");
      System.exit(0);
    }
    try {
      XDIDiscoveryResult discResult = discoveryClient.discover(XDIAddress.create(cloudNameString));

      cloudNumber = discResult.getCloudNumber();
      System.out.println("Cloud Number : " + cloudNumber.toString());

    } catch (Xdi2ClientException e) {
      System.out.println("Xdi2ClientException: " + e.getMessage());
      e.printStackTrace();
    }
    try {

      CSP csp = new BasicCSP(cspInformation);

      // Step 1: authenticate user

      try {
        csp.authenticateInCloud(cloudNumber, currentPassword);
      } catch (Xdi2ClientException badpass) {
        System.out.println("Cannot authenticate. Exiting ...");
        System.exit(0);
      }

      // Step 2: Change Secret Token

      csp.setCloudSecretTokenInCSP(cloudNumber, newPassword);

      // done

      System.out.println("Done Changing password for cloudname " + cloudNameString);
    } catch (RuntimeException ex1) {
      ex1.printStackTrace();
    } catch (Xdi2ClientException ex2) {
      ex2.printStackTrace();
    }
  }
Example #10
0
  public static void main(String[] args) {
    try {
      if (args[0].equals("-genkey")) {
        KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = new SecureRandom();
        pairgen.initialize(KEYSIZE, random);
        KeyPair keyPair = pairgen.generateKeyPair();
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
        out.writeObject(keyPair.getPublic());
        out.close();
        out = new ObjectOutputStream(new FileOutputStream(args[2]));
        out.writeObject(keyPair.getPrivate());
        out.close();
      } else if (args[0].equals("-encrypt")) {
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        SecretKey key = keygen.generateKey();

        // wrap with RSA public key
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key publicKey = (Key) keyIn.readObject();
        keyIn.close();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] wrappedKey = cipher.wrap(key);
        DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
        out.writeInt(wrappedKey.length);
        out.write(wrappedKey);

        InputStream in = new FileInputStream(args[1]);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        crypt(in, out, cipher);
        in.close();
        out.close();
      } else {
        DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
        int length = in.readInt();
        byte[] wrappedKey = new byte[length];
        in.read(wrappedKey, 0, length);

        // unwrap with RSA private key
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key privateKey = (Key) keyIn.readObject();
        keyIn.close();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.UNWRAP_MODE, privateKey);
        Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

        OutputStream out = new FileOutputStream(args[2]);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);

        crypt(in, out, cipher);
        in.close();
        out.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
  /*
   * This method performs a depth first search for a certification
   * path while building forward which meets the requirements set in
   * the parameters object.
   * It uses an adjacency list to store all certificates which were
   * tried (i.e. at one time added to the path - they may not end up in
   * the final path if backtracking occurs). This information can
   * be used later to debug or demo the build.
   *
   * See "Data Structure and Algorithms, by Aho, Hopcroft, and Ullman"
   * for an explanation of the DFS algorithm.
   *
   * @param dN the distinguished name being currently searched for certs
   * @param currentState the current PKIX validation state
   */
  private void depthFirstSearchForward(
      X500Principal dN,
      ForwardState currentState,
      ForwardBuilder builder,
      List<List<Vertex>> adjList,
      LinkedList<X509Certificate> cpList)
      throws GeneralSecurityException, IOException {
    if (debug != null) {
      debug.println(
          "SunCertPathBuilder.depthFirstSearchForward("
              + dN
              + ", "
              + currentState.toString()
              + ")");
    }

    /*
     * Find all the certificates issued to dN which
     * satisfy the PKIX certification path constraints.
     */
    Collection<X509Certificate> certs =
        builder.getMatchingCerts(currentState, buildParams.certStores());
    List<Vertex> vertices = addVertices(certs, adjList);
    if (debug != null) {
      debug.println(
          "SunCertPathBuilder.depthFirstSearchForward(): " + "certs.size=" + vertices.size());
    }

    /*
     * For each cert in the collection, verify anything
     * that hasn't been checked yet (signature, revocation, etc)
     * and check for loops. Call depthFirstSearchForward()
     * recursively for each good cert.
     */

    vertices:
    for (Vertex vertex : vertices) {
      /**
       * Restore state to currentState each time through the loop. This is important because some of
       * the user-defined checkers modify the state, which MUST be restored if the cert eventually
       * fails to lead to the target and the next matching cert is tried.
       */
      ForwardState nextState = (ForwardState) currentState.clone();
      X509Certificate cert = vertex.getCertificate();

      try {
        builder.verifyCert(cert, nextState, cpList);
      } catch (GeneralSecurityException gse) {
        if (debug != null) {
          debug.println(
              "SunCertPathBuilder.depthFirstSearchForward()" + ": validation failed: " + gse);
          gse.printStackTrace();
        }
        vertex.setThrowable(gse);
        continue;
      }

      /*
       * Certificate is good.
       * If cert completes the path,
       *    process userCheckers that don't support forward checking
       *    and process policies over whole path
       *    and backtrack appropriately if there is a failure
       * else if cert does not complete the path,
       *    add it to the path
       */
      if (builder.isPathCompleted(cert)) {

        if (debug != null)
          debug.println(
              "SunCertPathBuilder.depthFirstSearchForward()" + ": commencing final verification");

        List<X509Certificate> appendedCerts = new ArrayList<>(cpList);

        /*
         * if the trust anchor selected is specified as a trusted
         * public key rather than a trusted cert, then verify this
         * cert (which is signed by the trusted public key), but
         * don't add it yet to the cpList
         */
        if (builder.trustAnchor.getTrustedCert() == null) {
          appendedCerts.add(0, cert);
        }

        Set<String> initExpPolSet = Collections.singleton(PolicyChecker.ANY_POLICY);

        PolicyNodeImpl rootNode =
            new PolicyNodeImpl(null, PolicyChecker.ANY_POLICY, null, false, initExpPolSet, false);

        List<PKIXCertPathChecker> checkers = new ArrayList<>();
        PolicyChecker policyChecker =
            new PolicyChecker(
                buildParams.initialPolicies(),
                appendedCerts.size(),
                buildParams.explicitPolicyRequired(),
                buildParams.policyMappingInhibited(),
                buildParams.anyPolicyInhibited(),
                buildParams.policyQualifiersRejected(),
                rootNode);
        checkers.add(policyChecker);

        // add the algorithm checker
        checkers.add(new AlgorithmChecker(builder.trustAnchor));

        BasicChecker basicChecker = null;
        if (nextState.keyParamsNeeded()) {
          PublicKey rootKey = cert.getPublicKey();
          if (builder.trustAnchor.getTrustedCert() == null) {
            rootKey = builder.trustAnchor.getCAPublicKey();
            if (debug != null)
              debug.println(
                  "SunCertPathBuilder.depthFirstSearchForward "
                      + "using buildParams public key: "
                      + rootKey.toString());
          }
          TrustAnchor anchor = new TrustAnchor(cert.getSubjectX500Principal(), rootKey, null);

          // add the basic checker
          basicChecker =
              new BasicChecker(anchor, buildParams.date(), buildParams.sigProvider(), true);
          checkers.add(basicChecker);
        }

        buildParams.setCertPath(cf.generateCertPath(appendedCerts));

        boolean revCheckerAdded = false;
        List<PKIXCertPathChecker> ckrs = buildParams.certPathCheckers();
        for (PKIXCertPathChecker ckr : ckrs) {
          if (ckr instanceof PKIXRevocationChecker) {
            if (revCheckerAdded) {
              throw new CertPathValidatorException(
                  "Only one PKIXRevocationChecker can be specified");
            }
            revCheckerAdded = true;
            // if it's our own, initialize it
            if (ckr instanceof RevocationChecker) {
              ((RevocationChecker) ckr).init(builder.trustAnchor, buildParams);
            }
          }
        }
        // only add a RevocationChecker if revocation is enabled and
        // a PKIXRevocationChecker has not already been added
        if (buildParams.revocationEnabled() && !revCheckerAdded) {
          checkers.add(new RevocationChecker(builder.trustAnchor, buildParams));
        }

        checkers.addAll(ckrs);

        // Why we don't need BasicChecker and RevocationChecker
        // if nextState.keyParamsNeeded() is false?

        for (int i = 0; i < appendedCerts.size(); i++) {
          X509Certificate currCert = appendedCerts.get(i);
          if (debug != null)
            debug.println("current subject = " + currCert.getSubjectX500Principal());
          Set<String> unresCritExts = currCert.getCriticalExtensionOIDs();
          if (unresCritExts == null) {
            unresCritExts = Collections.<String>emptySet();
          }

          for (PKIXCertPathChecker currChecker : checkers) {
            if (!currChecker.isForwardCheckingSupported()) {
              if (i == 0) {
                currChecker.init(false);

                // The user specified
                // AlgorithmChecker may not be
                // able to set the trust anchor until now.
                if (currChecker instanceof AlgorithmChecker) {
                  ((AlgorithmChecker) currChecker).trySetTrustAnchor(builder.trustAnchor);
                }
              }

              try {
                currChecker.check(currCert, unresCritExts);
              } catch (CertPathValidatorException cpve) {
                if (debug != null)
                  debug.println(
                      "SunCertPathBuilder.depthFirstSearchForward(): "
                          + "final verification failed: "
                          + cpve);
                // If the target cert itself is revoked, we
                // cannot trust it. We can bail out here.
                if (buildParams.targetCertConstraints().match(currCert)
                    && cpve.getReason() == BasicReason.REVOKED) {
                  throw cpve;
                }
                vertex.setThrowable(cpve);
                continue vertices;
              }
            }
          }

          /*
           * Remove extensions from user checkers that support
           * forward checking. After this step, we will have
           * removed all extensions that all user checkers
           * are capable of processing.
           */
          for (PKIXCertPathChecker checker : buildParams.certPathCheckers()) {
            if (checker.isForwardCheckingSupported()) {
              Set<String> suppExts = checker.getSupportedExtensions();
              if (suppExts != null) {
                unresCritExts.removeAll(suppExts);
              }
            }
          }

          if (!unresCritExts.isEmpty()) {
            unresCritExts.remove(BasicConstraints_Id.toString());
            unresCritExts.remove(NameConstraints_Id.toString());
            unresCritExts.remove(CertificatePolicies_Id.toString());
            unresCritExts.remove(PolicyMappings_Id.toString());
            unresCritExts.remove(PolicyConstraints_Id.toString());
            unresCritExts.remove(InhibitAnyPolicy_Id.toString());
            unresCritExts.remove(SubjectAlternativeName_Id.toString());
            unresCritExts.remove(KeyUsage_Id.toString());
            unresCritExts.remove(ExtendedKeyUsage_Id.toString());

            if (!unresCritExts.isEmpty()) {
              throw new CertPathValidatorException(
                  "unrecognized critical extension(s)",
                  null,
                  null,
                  -1,
                  PKIXReason.UNRECOGNIZED_CRIT_EXT);
            }
          }
        }
        if (debug != null)
          debug.println(
              "SunCertPathBuilder.depthFirstSearchForward()"
                  + ": final verification succeeded - path completed!");
        pathCompleted = true;

        /*
         * if the user specified a trusted public key rather than
         * trusted certs, then add this cert (which is signed by
         * the trusted public key) to the cpList
         */
        if (builder.trustAnchor.getTrustedCert() == null) builder.addCertToPath(cert, cpList);
        // Save the trust anchor
        this.trustAnchor = builder.trustAnchor;

        /*
         * Extract and save the final target public key
         */
        if (basicChecker != null) {
          finalPublicKey = basicChecker.getPublicKey();
        } else {
          Certificate finalCert;
          if (cpList.isEmpty()) {
            finalCert = builder.trustAnchor.getTrustedCert();
          } else {
            finalCert = cpList.getLast();
          }
          finalPublicKey = finalCert.getPublicKey();
        }

        policyTreeResult = policyChecker.getPolicyTree();
        return;
      } else {
        builder.addCertToPath(cert, cpList);
      }

      /* Update the PKIX state */
      nextState.updateState(cert);

      /*
       * Append an entry for cert in adjacency list and
       * set index for current vertex.
       */
      adjList.add(new LinkedList<Vertex>());
      vertex.setIndex(adjList.size() - 1);

      /* recursively search for matching certs at next dN */
      depthFirstSearchForward(cert.getIssuerX500Principal(), nextState, builder, adjList, cpList);

      /*
       * If path has been completed, return ASAP!
       */
      if (pathCompleted) {
        return;
      } else {
        /*
         * If we get here, it means we have searched all possible
         * certs issued by the dN w/o finding any matching certs.
         * This means we have to backtrack to the previous cert in
         * the path and try some other paths.
         */
        if (debug != null)
          debug.println("SunCertPathBuilder.depthFirstSearchForward()" + ": backtracking");
        builder.removeFinalCertFromPath(cpList);
      }
    }
  }
Example #12
-5
  /*
   * Calculate the master secret from its various components.  This is
   * used for key exchange by all cipher suites.
   *
   * The master secret is the catenation of three MD5 hashes, each
   * consisting of the pre-master secret and a SHA1 hash.  Those three
   * SHA1 hashes are of (different) constant strings, the pre-master
   * secret, and the nonces provided by the client and the server.
   */
  private SecretKey calculateMasterSecret(
      SecretKey preMasterSecret, ProtocolVersion requestedVersion) {

    if (debug != null && Debug.isOn("keygen")) {
      HexDumpEncoder dump = new HexDumpEncoder();

      System.out.println("SESSION KEYGEN:");

      System.out.println("PreMaster Secret:");
      printHex(dump, preMasterSecret.getEncoded());

      // Nonces are dumped with connection keygen, no
      // benefit to doing it twice
    }

    // What algs/params do we need to use?
    String masterAlg;
    PRF prf;

    if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
      masterAlg = "SunTls12MasterSecret";
      prf = cipherSuite.prfAlg;
    } else {
      masterAlg = "SunTlsMasterSecret";
      prf = P_NONE;
    }

    String prfHashAlg = prf.getPRFHashAlg();
    int prfHashLength = prf.getPRFHashLength();
    int prfBlockSize = prf.getPRFBlockSize();

    TlsMasterSecretParameterSpec spec =
        new TlsMasterSecretParameterSpec(
            preMasterSecret,
            protocolVersion.major,
            protocolVersion.minor,
            clnt_random.random_bytes,
            svr_random.random_bytes,
            prfHashAlg,
            prfHashLength,
            prfBlockSize);

    SecretKey masterSecret;
    try {
      KeyGenerator kg = JsseJce.getKeyGenerator(masterAlg);
      kg.init(spec);
      masterSecret = kg.generateKey();
    } catch (GeneralSecurityException e) {
      // For RSA premaster secrets, do not signal a protocol error
      // due to the Bleichenbacher attack. See comments further down.
      if (!preMasterSecret.getAlgorithm().equals("TlsRsaPremasterSecret")) {
        throw new ProviderException(e);
      }

      if (debug != null && Debug.isOn("handshake")) {
        System.out.println("RSA master secret generation error:");
        e.printStackTrace(System.out);
        System.out.println("Generating new random premaster secret");
      }

      if (requestedVersion != null) {
        preMasterSecret = RSAClientKeyExchange.generateDummySecret(requestedVersion);
      } else {
        preMasterSecret = RSAClientKeyExchange.generateDummySecret(protocolVersion);
      }

      // recursive call with new premaster secret
      return calculateMasterSecret(preMasterSecret, null);
    }

    // if no version check requested (client side handshake), or version
    // information is not available (not an RSA premaster secret),
    // return master secret immediately.
    if ((requestedVersion == null) || !(masterSecret instanceof TlsMasterSecret)) {
      return masterSecret;
    }

    // we have checked the ClientKeyExchange message when reading TLS
    // record, the following check is necessary to ensure that
    // JCE provider does not ignore the checking, or the previous
    // checking process bypassed the premaster secret version checking.
    TlsMasterSecret tlsKey = (TlsMasterSecret) masterSecret;
    int major = tlsKey.getMajorVersion();
    int minor = tlsKey.getMinorVersion();
    if ((major < 0) || (minor < 0)) {
      return masterSecret;
    }

    // check if the premaster secret version is ok
    // the specification says that it must be the maximum version supported
    // by the client from its ClientHello message. However, many
    // implementations send the negotiated version, so accept both
    // for SSL v3.0 and TLS v1.0.
    // NOTE that we may be comparing two unsupported version numbers, which
    // is why we cannot use object reference equality in this special case.
    ProtocolVersion premasterVersion = ProtocolVersion.valueOf(major, minor);
    boolean versionMismatch = (premasterVersion.v != requestedVersion.v);

    /*
     * we never checked the client_version in server side
     * for TLS v1.0 and SSL v3.0. For compatibility, we
     * maintain this behavior.
     */
    if (versionMismatch && requestedVersion.v <= ProtocolVersion.TLS10.v) {
      versionMismatch = (premasterVersion.v != protocolVersion.v);
    }

    if (versionMismatch == false) {
      // check passed, return key
      return masterSecret;
    }

    // Due to the Bleichenbacher attack, do not signal a protocol error.
    // Generate a random premaster secret and continue with the handshake,
    // which will fail when verifying the finished messages.
    // For more information, see comments in PreMasterSecret.
    if (debug != null && Debug.isOn("handshake")) {
      System.out.println(
          "RSA PreMasterSecret version error: expected"
              + protocolVersion
              + " or "
              + requestedVersion
              + ", decrypted: "
              + premasterVersion);
      System.out.println("Generating new random premaster secret");
    }
    preMasterSecret = RSAClientKeyExchange.generateDummySecret(requestedVersion);

    // recursive call with new premaster secret
    return calculateMasterSecret(preMasterSecret, null);
  }