Esempio n. 1
0
 public DHG(Factory<Digest> digestFactory, BigInteger pValue, BigInteger gValue) throws Exception {
   myKpairGen = SecurityUtils.getKeyPairGenerator("DH");
   myKeyAgree = SecurityUtils.getKeyAgreement("DH");
   factory = digestFactory;
   p = pValue;
   g = gValue;
 }
Esempio n. 2
0
  @Override
  public void start() throws ServiceException {
    sshServer = SshServer.setUpDefaultServer();
    sshServer.setPort(port);
    sshServer.setHost(bind);

    final String basePath = SystemInstance.get().getBase().getDirectory().getAbsolutePath();
    if (SecurityUtils.isBouncyCastleRegistered()) {
      sshServer.setKeyPairProvider(
          new PEMGeneratorHostKeyProvider(new File(basePath, KEY_NAME + ".pem").getPath()));
    } else {
      sshServer.setKeyPairProvider(
          new SimpleGeneratorHostKeyProvider(new File(basePath, KEY_NAME + ".ser").getPath()));
    }

    final OpenEJBShellFactory sf = new OpenEJBShellFactory(bind, port);
    sshServer.setShellFactory(sf);

    final JaasPasswordAuthenticator authenticator = new OpenEJBJaasPasswordAuthenticator();
    authenticator.setDomain(domain);
    sshServer.setPasswordAuthenticator(authenticator);

    try {
      sshServer.start();
    } catch (IOException e) {
      // no-op
    }
  }
 /** {@inheritDoc} */
 public void addIdentity(String privateKey, final String passphrase, String comment)
     throws IOException {
   if (!SecurityUtils.isBouncyCastleRegistered()) {
     throw new IllegalStateException("BouncyCastle must be registered as a JCE provider");
   }
   try {
     PEMReader r =
         new PEMReader(
             new StringReader(privateKey),
             passphrase == null
                 ? null
                 : new PasswordFinder() {
                   public char[] getPassword() {
                     return passphrase.toCharArray();
                   }
                 });
     try {
       Object o = r.readObject();
       if (o instanceof KeyPair) {
         agent.getAgent().addIdentity((KeyPair) o, comment);
       }
     } finally {
       r.close();
     }
   } catch (Exception e) {
     listener.getLogger().println(Messages.SSHAgentBuildWrapper_UnableToReadKey(e.getMessage()));
     e.printStackTrace(listener.getLogger());
   }
 }
Esempio n. 4
0
 @Override
 protected byte[] calculateK() throws Exception {
   KeyFactory myKeyFac = SecurityUtils.getKeyFactory("DH");
   DHPublicKeySpec keySpec = new DHPublicKeySpec(f, p, g);
   PublicKey yourPubKey = myKeyFac.generatePublic(keySpec);
   myKeyAgree.doPhase(yourPubKey, true);
   return stripLeadingZeroes(myKeyAgree.generateSecret());
 }
Esempio n. 5
0
  @Test
  public void testLoadClientIdentities() throws Exception {
    Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered());

    Path resFolder = getClassResourcesFolder(TEST_SUBFOLDER, getClass()).toPath();
    LinkOption[] options = IoUtils.getLinkOptions(false);
    Collection<BuiltinIdentities> expected = EnumSet.noneOf(BuiltinIdentities.class);
    for (BuiltinIdentities type : BuiltinIdentities.VALUES) {
      String fileName = ClientIdentity.getIdentityFileName(type);
      Path file = resFolder.resolve(fileName);
      if (!Files.exists(file, options)) {
        System.out.println("Skip non-existing identity file " + file);
        continue;
      }

      if (!type.isSupported()) {
        System.out.println("Skip unsupported identity file " + file);
        continue;
      }

      expected.add(type);
    }

    Map<String, KeyPair> ids =
        ClientIdentity.loadDefaultIdentities(
            resFolder, false, // don't be strict
            null, // none of the files is password protected
            options);
    assertEquals(
        "Mismatched loaded ids count", GenericUtils.size(expected), GenericUtils.size(ids));

    Collection<KeyPair> pairs = new ArrayList<KeyPair>(ids.size());
    for (BuiltinIdentities type : BuiltinIdentities.VALUES) {
      if (expected.contains(type)) {
        KeyPair kp = ids.get(type.getName());
        assertNotNull("No key pair loaded for " + type, kp);
        pairs.add(kp);
      }
    }

    KeyPairProvider provider = IdentityUtils.createKeyPairProvider(ids, true /* supported only */);
    assertNotNull("No provider generated", provider);

    Iterable<KeyPair> keys = provider.loadKeys();
    for (KeyPair kp : keys) {
      assertTrue("Unexpected loaded key: " + kp, pairs.remove(kp));
    }

    assertEquals("Not all pairs listed", 0, pairs.size());
  }
Esempio n. 6
0
  @Override
  public Iterable<KeyPair> loadKeys() {
    if (!SecurityUtils.isBouncyCastleRegistered()) {
      throw new IllegalStateException("BouncyCastle must be registered as a JCE provider");
    }
    return new Iterable<KeyPair>() {
      @Override
      public Iterator<KeyPair> iterator() {
        return new Iterator<KeyPair>() {
          private final Iterator<String> iterator = Arrays.asList(files).iterator();
          private KeyPair nextKeyPair;
          private boolean nextKeyPairSet = false;

          @Override
          public boolean hasNext() {
            return nextKeyPairSet || setNextObject();
          }

          @Override
          public KeyPair next() {
            if (!nextKeyPairSet) {
              if (!setNextObject()) {
                throw new NoSuchElementException();
              }
            }
            nextKeyPairSet = false;
            return nextKeyPair;
          }

          @Override
          public void remove() {
            throw new UnsupportedOperationException();
          }

          private boolean setNextObject() {
            while (iterator.hasNext()) {
              String file = iterator.next();
              nextKeyPair = doLoadKey(file);
              if (nextKeyPair != null) {
                nextKeyPairSet = true;
                return true;
              }
            }
            return false;
          }
        };
      }
    };
  }
Esempio n. 7
0
  @Inject
  public Server(final Context ctx, CommandFactory factory) {
    port = ctx.configuration().getSshPort();
    sshd = SshServer.setUpDefaultServer();

    if (SecurityUtils.isBouncyCastleRegistered()) {
      sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider("key.pem"));
    } else {
      sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("key.ser"));
    }

    PublickeyAuthenticator auth = null;
    if (ctx.configuration().getAuthentication() == Configuration.Authentication.SSH_PUBLIC_KEYS) {
      auth = ctx.getInjector().getInstance(PublickeyAuthenticator.class);
    }
    setupUserAuth(auth);

    sshd.setCommandFactory(factory);

    if (!ctx.configuration().isRemoteAllowed()) {
      sshd.setSessionFactory(new LocalOnlySessionFactory());
    }

    sshd.setForwardingFilter(
        new ForwardingFilter() {
          public boolean canForwardAgent(ServerSession session) {
            return false;
          }

          public boolean canForwardX11(ServerSession session) {
            return false;
          }

          public boolean canListen(InetSocketAddress address, ServerSession session) {
            return false;
          }

          public boolean canConnect(InetSocketAddress address, ServerSession session) {
            return false;
          }
        });
  }
Esempio n. 8
0
  @Override
  public KeyPairProvider get() {
    Path objKey = site.ssh_key;
    Path rsaKey = site.ssh_rsa;
    Path dsaKey = site.ssh_dsa;

    final List<String> stdKeys = new ArrayList<>(2);
    if (Files.exists(rsaKey)) {
      stdKeys.add(rsaKey.toAbsolutePath().toString());
    }
    if (Files.exists(dsaKey)) {
      stdKeys.add(dsaKey.toAbsolutePath().toString());
    }

    if (Files.exists(objKey)) {
      if (stdKeys.isEmpty()) {
        SimpleGeneratorHostKeyProvider p = new SimpleGeneratorHostKeyProvider();
        p.setPath(objKey.toAbsolutePath().toString());
        return p;

      } else {
        // Both formats of host key exist, we don't know which format
        // should be authoritative. Complain and abort.
        //
        stdKeys.add(objKey.toAbsolutePath().toString());
        throw new ProvisionException("Multiple host keys exist: " + stdKeys);
      }

    } else {
      if (stdKeys.isEmpty()) {
        throw new ProvisionException("No SSH keys under " + site.etc_dir);
      }
      if (!SecurityUtils.isBouncyCastleRegistered()) {
        throw new ProvisionException(
            "Bouncy Castle Crypto not installed;"
                + " needed to read server host keys: "
                + stdKeys
                + "");
      }
      return new FileKeyPairProvider(stdKeys.toArray(new String[stdKeys.size()]));
    }
  }
Esempio n. 9
0
 @Override
 protected KeyPair[] loadKeys() {
   if (!SecurityUtils.isBouncyCastleRegistered()) {
     throw new IllegalStateException("BouncyCastle must be registered as a JCE provider");
   }
   List<KeyPair> keys = new ArrayList<KeyPair>();
   if (key != null) {
     try {
       PEMReader r =
           new PEMReader(new InputStreamReader(new ByteArrayInputStream(key.getContent())));
       try {
         Object o = r.readObject();
         if (o instanceof KeyPair) {
           keys.add((KeyPair) o);
         }
       } finally {
         r.close();
       }
     } catch (Exception e) {
       LOG.info("Unable to read key {}: {}", key, e);
     }
   }
   return keys.toArray(new KeyPair[keys.size()]);
 }