Beispiel #1
0
  /**
   * Callback method from _scanKeychain. If a trusted certificate is found, this method will be
   * called.
   */
  private void createTrustedCertEntry(
      String alias, long keychainItemRef, long creationDate, byte[] derStream) {
    TrustedCertEntry tce = new TrustedCertEntry();

    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      InputStream input = new ByteArrayInputStream(derStream);
      X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
      input.close();
      tce.cert = cert;
      tce.certRef = keychainItemRef;

      // Make a creation date.
      if (creationDate != 0) tce.date = new Date(creationDate);
      else tce.date = new Date();

      int uniqueVal = 1;
      String originalAlias = alias;

      while (entries.containsKey(alias.toLowerCase())) {
        alias = originalAlias + " " + uniqueVal;
        uniqueVal++;
      }

      entries.put(alias.toLowerCase(), tce);
    } catch (Exception e) {
      // The certificate will be skipped.
      System.err.println("KeychainStore Ignored Exception: " + e);
    }
  }
Beispiel #2
0
 private static KeyStore readKeyStore(String name) throws Exception {
   File file = new File(PATH, name);
   InputStream in = new FileInputStream(file);
   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(in, passwd);
   in.close();
   return ks;
 }
  void doTest(SSLSocket sslSocket) throws Exception {
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    System.out.println("  Writing");
    sslOS.write(280);
    sslOS.flush();
    System.out.println("  Reading");
    sslIS.read();

    sslSocket.close();
  }
Beispiel #4
0
 void handleRequest(InputStream in, OutputStream out) throws IOException {
   boolean newline = false;
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       throw new EOFException();
     }
     sb.append((char) ch);
     if (ch == '\r') {
       // empty
     } else if (ch == '\n') {
       if (newline) {
         // 2nd newline in a row, end of request
         break;
       }
       newline = true;
     } else {
       newline = false;
     }
   }
   String request = sb.toString();
   if (request.startsWith("GET / HTTP/1.") == false) {
     throw new IOException("Invalid request: " + request);
   }
   out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes());
 }
Beispiel #5
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;
      }
    }
 private Class<?> getClassFromStream(
     final InputStream stream, final String classname, final File container)
     throws IOException, SecurityException {
   final ByteArrayOutputStream baos = new ByteArrayOutputStream();
   int bytesRead = -1;
   final byte[] buffer = new byte[8192];
   while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
     baos.write(buffer, 0, bytesRead);
   }
   final byte[] classData = baos.toByteArray();
   return this.defineClassFromData(container, classData, classname);
 }
 /**
  * Read from the stream until length bytes have been read or EOF has been reached. Return the
  * number of bytes actually read.
  */
 private static int readFully(InputStream in, ByteArrayOutputStream bout, int length)
     throws IOException {
   int read = 0;
   byte[] buffer = new byte[2048];
   while (length > 0) {
     int n = in.read(buffer, 0, length < 2048 ? length : 2048);
     if (n <= 0) {
       break;
     }
     bout.write(buffer, 0, n);
     read += n;
     length -= n;
   }
   return read;
 }
Beispiel #8
0
 void sendRequest(InputStream in, OutputStream out) throws IOException {
   out.write("GET / HTTP/1.0\r\n\r\n".getBytes());
   out.flush();
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       break;
     }
     sb.append((char) ch);
   }
   String response = sb.toString();
   if (response.startsWith("HTTP/1.0 200 ") == false) {
     throw new IOException("Invalid response: " + response);
   }
 }
  /**
   * readPEM: Read a PEM encoded base64 stream and decode it
   *
   * @param is Base64 PEM encoded stream
   * @param hdr Header delimeter (e.g. ----------CERTIFICATE---------)
   * @param ftr Footer delimeter (e.g. ----------END CERTIFICATE---------)
   * @return decoded DER bytes
   * @throws IOException if a read error occurs
   */
  public static byte[] readPEM(InputStream is, String hdr, String ftr) throws IOException {
    logger.debug("Reading PEM hdr:" + hdr + " ftr:" + ftr);
    is.reset();
    InputStreamReader irr = new InputStreamReader(is);
    BufferedReader r = new BufferedReader(irr);

    StringBuffer buff = new StringBuffer();
    String line;
    boolean read = false;

    while ((line = r.readLine()) != null) {
      if (line.equals(hdr)) {
        read = true;
        continue;
      }
      if (line.equals(ftr)) read = false;
      if (read) buff.append(line);
    }
    return Base64.decode(buff.toString().getBytes());
  }
Beispiel #10
0
  static void compare(File f1, File f2) throws IOException {
    InputStream i1 = new BufferedInputStream(new FileInputStream(f1));
    InputStream i2 = new BufferedInputStream(new FileInputStream(f2));

    int c1, c2;
    try {
      while ((c1 = i1.read()) != -1) {
        c2 = i2.read();
        if (c1 != c2) {
          throw new RuntimeException("file compare failed 1");
        }
      }
      if (i2.read() != -1) {
        throw new RuntimeException("file compare failed 2");
      }
    } finally {
      i1.close();
      i2.close();
    }
  }
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    com.sun.net.ssl.SSLContext ctx = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");

    ks.load(new FileInputStream(keyFilename), cpasswd);
    kmf.init(ks, cpasswd);

    com.sun.net.ssl.TrustManager[] tms =
        new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()};

    ctx.init(kmf.getKeyManagers(), tms, null);

    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) ctx.getServerSocketFactory();

    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    sslServerSocket.setNeedClientAuth(true);

    /*
     * Create using the other type.
     */
    SSLContext ctx1 = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf1 = KeyManagerFactory.getInstance("SunX509");

    TrustManager[] tms1 = new TrustManager[] {new MyJavaxX509TrustManager()};

    kmf1.init(ks, cpasswd);

    ctx1.init(kmf1.getKeyManagers(), tms1, null);

    sslssf = (SSLServerSocketFactory) ctx1.getServerSocketFactory();

    SSLServerSocket sslServerSocket1 = (SSLServerSocket) sslssf.createServerSocket(serverPort1);
    serverPort1 = sslServerSocket1.getLocalPort();
    sslServerSocket1.setNeedClientAuth(true);

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    sslServerSocket.close();
    serverReady = false;

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    sslSocket = (SSLSocket) sslServerSocket1.accept();
    sslIS = sslSocket.getInputStream();
    sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    System.out.println("Server exiting!");
    System.out.flush();
  }
Beispiel #12
0
  /**
   * Callback method from _scanKeychain. If an identity is found, this method will be called to
   * create Java certificate and private key objects from the keychain data.
   */
  private void createKeyEntry(
      String alias,
      long creationDate,
      long secKeyRef,
      long[] secCertificateRefs,
      byte[][] rawCertData)
      throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
    KeyEntry ke = new KeyEntry();

    // First, store off the private key information.  This is the easy part.
    ke.protectedPrivKey = null;
    ke.keyRef = secKeyRef;

    // Make a creation date.
    if (creationDate != 0) ke.date = new Date(creationDate);
    else ke.date = new Date();

    // Next, create X.509 Certificate objects from the raw data.  This is complicated
    // because a certificate's public key may be too long for Java's default encryption strength.
    List<CertKeychainItemPair> createdCerts = new ArrayList<>();

    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");

      for (int i = 0; i < rawCertData.length; i++) {
        try {
          InputStream input = new ByteArrayInputStream(rawCertData[i]);
          X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
          input.close();

          // We successfully created the certificate, so track it and its corresponding
          // SecCertificateRef.
          createdCerts.add(new CertKeychainItemPair(secCertificateRefs[i], cert));
        } catch (CertificateException e) {
          // The certificate will be skipped.
          System.err.println("KeychainStore Ignored Exception: " + e);
        }
      }
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace(); // How would this happen?
    }

    // We have our certificates in the List, so now extract them into an array of
    // Certificates and SecCertificateRefs.
    CertKeychainItemPair[] objArray = createdCerts.toArray(new CertKeychainItemPair[0]);
    Certificate[] certArray = new Certificate[objArray.length];
    long[] certRefArray = new long[objArray.length];

    for (int i = 0; i < objArray.length; i++) {
      CertKeychainItemPair addedItem = objArray[i];
      certArray[i] = addedItem.mCert;
      certRefArray[i] = addedItem.mCertificateRef;
    }

    ke.chain = certArray;
    ke.chainRefs = certRefArray;

    // If we don't have already have an item with this item's alias
    // create a new one for it.
    int uniqueVal = 1;
    String originalAlias = alias;

    while (entries.containsKey(alias.toLowerCase())) {
      alias = originalAlias + " " + uniqueVal;
      uniqueVal++;
    }

    entries.put(alias.toLowerCase(), ke);
  }
  /**
   * Read one BER data block. This method is aware of indefinite-length BER encoding and will read
   * all of the sub-sections in a recursive way
   *
   * @param is Read from this InputStream
   * @param bout Write into this OutputStream
   * @param tag Tag already read (-1 mean not read)
   * @returns The current tag, used to check EOC in indefinite-length BER
   * @throws IOException Any parsing error
   */
  private static int readBERInternal(InputStream is, ByteArrayOutputStream bout, int tag)
      throws IOException {

    if (tag == -1) { // Not read before the call, read now
      tag = is.read();
      if (tag == -1) {
        throw new IOException("BER/DER tag info absent");
      }
      if ((tag & 0x1f) == 0x1f) {
        throw new IOException("Multi octets tag not supported");
      }
      bout.write(tag);
    }

    int n = is.read();
    if (n == -1) {
      throw new IOException("BER/DER length info ansent");
    }
    bout.write(n);

    int length;

    if (n == 0x80) { // Indefinite-length encoding
      if ((tag & 0x20) != 0x20) {
        throw new IOException("Non constructed encoding must have definite length");
      }
      while (true) {
        int subTag = readBERInternal(is, bout, -1);
        if (subTag == 0) { // EOC, end of indefinite-length section
          break;
        }
      }
    } else {
      if (n < 0x80) {
        length = n;
      } else if (n == 0x81) {
        length = is.read();
        if (length == -1) {
          throw new IOException("Incomplete BER/DER length info");
        }
        bout.write(length);
      } else if (n == 0x82) {
        int highByte = is.read();
        int lowByte = is.read();
        if (lowByte == -1) {
          throw new IOException("Incomplete BER/DER length info");
        }
        bout.write(highByte);
        bout.write(lowByte);
        length = (highByte << 8) | lowByte;
      } else if (n == 0x83) {
        int highByte = is.read();
        int midByte = is.read();
        int lowByte = is.read();
        if (lowByte == -1) {
          throw new IOException("Incomplete BER/DER length info");
        }
        bout.write(highByte);
        bout.write(midByte);
        bout.write(lowByte);
        length = (highByte << 16) | (midByte << 8) | lowByte;
      } else if (n == 0x84) {
        int highByte = is.read();
        int nextByte = is.read();
        int midByte = is.read();
        int lowByte = is.read();
        if (lowByte == -1) {
          throw new IOException("Incomplete BER/DER length info");
        }
        if (highByte > 127) {
          throw new IOException("Invalid BER/DER data (a little huge?)");
        }
        bout.write(highByte);
        bout.write(nextByte);
        bout.write(midByte);
        bout.write(lowByte);
        length = (highByte << 24) | (nextByte << 16) | (midByte << 8) | lowByte;
      } else { // ignore longer length forms
        throw new IOException("Invalid BER/DER data (too huge?)");
      }
      if (readFully(is, bout, length) != length) {
        throw new IOException("Incomplete BER/DER data");
      }
    }
    return tag;
  }
  /**
   * Returns an ASN.1 SEQUENCE from a stream, which might be a BER-encoded binary block or a
   * PEM-style BASE64-encoded ASCII data. In the latter case, it's de-BASE64'ed before return.
   *
   * <p>After the reading, the input stream pointer is after the BER block, or after the newline
   * character after the -----END SOMETHING----- line.
   *
   * @param is the InputStream
   * @returns byte block or null if end of stream
   * @throws IOException If any parsing error
   */
  private static byte[] readOneBlock(InputStream is) throws IOException {

    // The first character of a BLOCK.
    int c = is.read();
    if (c == -1) {
      return null;
    }
    if (c == DerValue.tag_Sequence) {
      ByteArrayOutputStream bout = new ByteArrayOutputStream(2048);
      bout.write(c);
      readBERInternal(is, bout, c);
      return bout.toByteArray();
    } else {
      // Read BASE64 encoded data, might skip info at the beginning
      char[] data = new char[2048];
      int pos = 0;

      // Step 1: Read until header is found
      int hyphen = (c == '-') ? 1 : 0; // count of consequent hyphens
      int last = (c == '-') ? -1 : c; // the char before hyphen
      while (true) {
        int next = is.read();
        if (next == -1) {
          // We accept useless data after the last block,
          // say, empty lines.
          return null;
        }
        if (next == '-') {
          hyphen++;
        } else {
          hyphen = 0;
          last = next;
        }
        if (hyphen == 5 && (last == -1 || last == '\r' || last == '\n')) {
          break;
        }
      }

      // Step 2: Read the rest of header, determine the line end
      int end;
      StringBuffer header = new StringBuffer("-----");
      while (true) {
        int next = is.read();
        if (next == -1) {
          throw new IOException("Incomplete data");
        }
        if (next == '\n') {
          end = '\n';
          break;
        }
        if (next == '\r') {
          next = is.read();
          if (next == -1) {
            throw new IOException("Incomplete data");
          }
          if (next == '\n') {
            end = '\n';
          } else {
            end = '\r';
            data[pos++] = (char) next;
          }
          break;
        }
        header.append((char) next);
      }

      // Step 3: Read the data
      while (true) {
        int next = is.read();
        if (next == -1) {
          throw new IOException("Incomplete data");
        }
        if (next != '-') {
          data[pos++] = (char) next;
          if (pos >= data.length) {
            data = Arrays.copyOf(data, data.length + 1024);
          }
        } else {
          break;
        }
      }

      // Step 4: Consume the footer
      StringBuffer footer = new StringBuffer("-");
      while (true) {
        int next = is.read();
        // Add next == '\n' for maximum safety, in case endline
        // is not consistent.
        if (next == -1 || next == end || next == '\n') {
          break;
        }
        if (next != '\r') footer.append((char) next);
      }

      checkHeaderFooter(header.toString(), footer.toString());

      return Base64.getMimeDecoder().decode(new String(data, 0, pos));
    }
  }