예제 #1
0
  private final boolean checkHashed(String entry, String hostname) {
    if (entry.startsWith("|1|") == false) return false;

    int delim_idx = entry.indexOf('|', 3);

    if (delim_idx == -1) return false;

    String salt_base64 = entry.substring(3, delim_idx);
    String hash_base64 = entry.substring(delim_idx + 1);

    byte[] salt = null;
    byte[] hash = null;

    try {
      salt = Base64.decode(salt_base64.toCharArray());
      hash = Base64.decode(hash_base64.toCharArray());
    } catch (IOException e) {
      return false;
    }

    SHA1 sha1 = new SHA1();

    if (salt.length != sha1.getDigestLength()) return false;

    byte[] dig = hmacSha1Hash(salt, hostname);

    for (int i = 0; i < dig.length; i++) if (dig[i] != hash[i]) return false;

    return true;
  }
예제 #2
0
파일: XmlBuilder.java 프로젝트: mzhou/bVNC
  public XmlBuilder append(String field, Object data) {
    if (data == null) {
      sb.append(String.format("<%s/>", field));
    } else if (data instanceof String) {
      String input = (String) data;
      boolean binary = false;

      for (byte b : input.getBytes()) {
        if (b < 0x20 || b > 0x7e) {
          binary = true;
          break;
        }
      }

      sb.append(
          String.format(
              "<%s>%s</%s>",
              field, binary ? new String(Base64.encode(input.getBytes())) : input, field));
    } else if (data instanceof Integer) {
      sb.append(String.format("<%s>%d</%s>", field, data, field));
    } else if (data instanceof Long) {
      sb.append(String.format("<%s>%d</%s>", field, data, field));
    } else if (data instanceof byte[]) {
      sb.append(
          String.format("<%s>%s</%s>", field, new String(Base64.encode((byte[]) data)), field));
    } else if (data instanceof Boolean) {
      sb.append(String.format("<%s>%s</%s>", field, data, field));
    }

    return this;
  }
예제 #3
0
  /**
   * Generate the hashed representation of the given hostname. Useful for adding entries with hashed
   * hostnames to a known_hosts file. (see -H option of OpenSSH key-gen).
   *
   * @param hostname
   * @return the hashed representation, e.g.,
   *     "|1|cDhrv7zwEUV3k71CEPHnhHZezhA=|Xo+2y6rUXo2OIWRAYhBOIijbJMA="
   */
  public static final String createHashedHostname(String hostname) {
    SHA1 sha1 = new SHA1();

    byte[] salt = new byte[sha1.getDigestLength()];

    new SecureRandom().nextBytes(salt);

    byte[] hash = hmacSha1Hash(salt, hostname);

    String base64_salt = new String(Base64.encode(salt));
    String base64_hash = new String(Base64.encode(hash));

    return new String("|1|" + base64_salt + "|" + base64_hash);
  }
예제 #4
0
  private void initialize(char[] knownHostsData) throws IOException {
    BufferedReader br = new BufferedReader(new CharArrayReader(knownHostsData));

    while (true) {
      String line = br.readLine();

      if (line == null) break;

      line = line.trim();

      if (line.startsWith("#")) continue;

      String[] arr = line.split(" ");

      if (arr.length >= 3) {
        if ((arr[1].compareTo("ssh-rsa") == 0) || (arr[1].compareTo("ssh-dss") == 0)) {
          String[] hostnames = arr[0].split(",");

          byte[] msg = Base64.decode(arr[2].toCharArray());

          addHostkey(hostnames, arr[1], msg);
        }
      }
    }
  }
예제 #5
0
  public static String unmask(String secret) throws PhrescoException {
    if (StringUtils.isEmpty(secret)) {
      return StringUtils.EMPTY;
    }

    try {
      return new String(Base64.decode(secret.toCharArray()), "UTF-8");
    } catch (IOException e) {
      throw new PhrescoException(e);
    }
  }
예제 #6
0
  public static String mask(String password) throws PhrescoException {
    if (StringUtils.isEmpty(password)) {
      return StringUtils.EMPTY;
    }

    try {
      return new String(Base64.encode(password.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
      throw new PhrescoException(e);
    }
  }
예제 #7
0
    protected void check() throws IOException, ServletException {
      try {
        String v = request.getParameter("value");
        if (!allowWhitespace) {
          if (v.indexOf(' ') >= 0 || v.indexOf('\n') >= 0) {
            fail();
            return;
          }
        }
        v = v.trim();
        if (!allowEmpty && v.length() == 0) {
          fail();
          return;
        }

        com.trilead.ssh2.crypto.Base64.decode(v.toCharArray());
        ok();
      } catch (IOException e) {
        fail();
      }
    }
예제 #8
0
  /**
   * Adds a single public key entry to the a known_hosts file. This method is designed to be used in
   * a {@link ServerHostKeyVerifier}.
   *
   * @param knownHosts the file where the publickey entry will be appended.
   * @param hostnames a list of hostname patterns - at least one most be specified. Check out the
   *     OpenSSH sshd man page for a description of the pattern matching algorithm.
   * @param serverHostKeyAlgorithm as passed to the {@link ServerHostKeyVerifier}.
   * @param serverHostKey as passed to the {@link ServerHostKeyVerifier}.
   * @throws IOException
   */
  public static final void addHostkeyToFile(
      File knownHosts, String[] hostnames, String serverHostKeyAlgorithm, byte[] serverHostKey)
      throws IOException {
    if ((hostnames == null) || (hostnames.length == 0))
      throw new IllegalArgumentException("Need at least one hostname specification");

    if ((serverHostKeyAlgorithm == null) || (serverHostKey == null))
      throw new IllegalArgumentException();

    CharArrayWriter writer = new CharArrayWriter();

    for (int i = 0; i < hostnames.length; i++) {
      if (i != 0) writer.write(',');
      writer.write(hostnames[i]);
    }

    writer.write(' ');
    writer.write(serverHostKeyAlgorithm);
    writer.write(' ');
    writer.write(Base64.encode(serverHostKey));
    writer.write("\n");

    char[] entry = writer.toCharArray();

    RandomAccessFile raf = new RandomAccessFile(knownHosts, "rw");

    long len = raf.length();

    if (len > 0) {
      raf.seek(len - 1);
      int last = raf.read();
      if (last != '\n') raf.write('\n');
    }

    raf.write(new String(entry).getBytes("ISO-8859-1"));
    raf.close();
  }
예제 #9
0
  /** Gets the encrypted usage stat data to be sent to the Hudson server. */
  public String getStatData() throws IOException {
    Jenkins j = Jenkins.getInstance();

    JSONObject o = new JSONObject();
    o.put("stat", 1);
    o.put("install", j.getLegacyInstanceId());
    o.put("servletContainer", j.servletContext.getServerInfo());
    o.put("version", Jenkins.VERSION);

    List<JSONObject> nodes = new ArrayList<JSONObject>();
    for (Computer c : j.getComputers()) {
      JSONObject n = new JSONObject();
      if (c.getNode() == j) {
        n.put("master", true);
        n.put("jvm-vendor", System.getProperty("java.vm.vendor"));
        n.put("jvm-name", System.getProperty("java.vm.name"));
        n.put("jvm-version", System.getProperty("java.version"));
      }
      n.put("executors", c.getNumExecutors());
      DescriptorImpl descriptor = j.getDescriptorByType(DescriptorImpl.class);
      n.put("os", descriptor.get(c));
      nodes.add(n);
    }
    o.put("nodes", nodes);

    List<JSONObject> plugins = new ArrayList<JSONObject>();
    for (PluginWrapper pw : j.getPluginManager().getPlugins()) {
      if (!pw.isActive()) continue; // treat disabled plugins as if they are uninstalled
      JSONObject p = new JSONObject();
      p.put("name", pw.getShortName());
      p.put("version", pw.getVersion());
      plugins.add(p);
    }
    o.put("plugins", plugins);

    JSONObject jobs = new JSONObject();
    List<TopLevelItem> items = j.getAllItems(TopLevelItem.class);
    for (TopLevelItemDescriptor d : Items.all()) {
      int cnt = 0;
      for (TopLevelItem item : items) {
        if (item.getDescriptor() == d) cnt++;
      }
      jobs.put(d.getJsonSafeClassName(), cnt);
    }
    o.put("jobs", jobs);

    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      // json -> UTF-8 encode -> gzip -> encrypt -> base64 -> string
      OutputStreamWriter w =
          new OutputStreamWriter(
              new GZIPOutputStream(new CombinedCipherOutputStream(baos, getKey(), "AES")), "UTF-8");
      try {
        o.write(w);
      } finally {
        IOUtils.closeQuietly(w);
      }

      return new String(Base64.encode(baos.toByteArray()));
    } catch (GeneralSecurityException e) {
      throw new Error(e); // impossible
    }
  }
  public static Socket open(
      final String hostname, final int port, final ProxyData proxyData, final int connectTimeout)
      throws IOException {
    final Socket sock = new Socket();
    if (proxyData == null) {
      InetAddress addr = TransportManager.createInetAddress(hostname);
      sock.connect(new InetSocketAddress(addr, port), connectTimeout);
      sock.setSoTimeout(0);
      return sock;
    }

    if (proxyData instanceof SelfConnectionProxyData) {
      // already connected
      return ((SelfConnectionProxyData) proxyData).connect();
    }

    if (proxyData instanceof HTTPProxyData) {
      HTTPProxyData pd = (HTTPProxyData) proxyData;

      /* At the moment, we only support HTTP proxies */

      InetAddress addr = TransportManager.createInetAddress(pd.proxyHost);
      sock.connect(new InetSocketAddress(addr, pd.proxyPort), connectTimeout);
      sock.setSoTimeout(0);

      /* OK, now tell the proxy where we actually want to connect to */

      StringBuffer sb = new StringBuffer();

      sb.append("CONNECT ");
      sb.append(hostname);
      sb.append(':');
      sb.append(port);
      sb.append(" HTTP/1.0\r\n");

      if ((pd.proxyUser != null) && (pd.proxyPass != null)) {
        String credentials = pd.proxyUser + ":" + pd.proxyPass;
        char[] encoded = Base64.encode(credentials.getBytes("ISO-8859-1"));
        sb.append("Proxy-Authorization: Basic ");
        sb.append(encoded);
        sb.append("\r\n");
      }

      if (pd.requestHeaderLines != null) {
        for (int i = 0; i < pd.requestHeaderLines.length; i++) {
          if (pd.requestHeaderLines[i] != null) {
            sb.append(pd.requestHeaderLines[i]);
            sb.append("\r\n");
          }
        }
      }

      sb.append("\r\n");

      OutputStream out = sock.getOutputStream();

      out.write(sb.toString().getBytes("ISO-8859-1"));
      out.flush();

      /* Now parse the HTTP response */

      byte[] buffer = new byte[1024];
      InputStream in = sock.getInputStream();

      int len = ClientServerHello.readLineRN(in, buffer);

      String httpReponse = new String(buffer, 0, len, "ISO-8859-1");

      if (httpReponse.startsWith("HTTP/") == false)
        throw new IOException("The proxy did not send back a valid HTTP response.");

      /* "HTTP/1.X XYZ X" => 14 characters minimum */

      if ((httpReponse.length() < 14)
          || (httpReponse.charAt(8) != ' ')
          || (httpReponse.charAt(12) != ' '))
        throw new IOException("The proxy did not send back a valid HTTP response.");

      int errorCode = 0;

      try {
        errorCode = Integer.parseInt(httpReponse.substring(9, 12));
      } catch (NumberFormatException ignore) {
        throw new IOException("The proxy did not send back a valid HTTP response.");
      }

      if ((errorCode < 0) || (errorCode > 999))
        throw new IOException("The proxy did not send back a valid HTTP response.");

      if (errorCode != 200) {
        throw new HTTPProxyException(httpReponse.substring(13), errorCode);
      }

      /* OK, read until empty line */

      while (true) {
        len = ClientServerHello.readLineRN(in, buffer);
        if (len == 0) break;
      }
      return sock;
    }

    throw new IOException("Unsupported ProxyData");
  }