org.apache.sshd.common.util.ValidateUtils Java Examples

The following examples show how to use org.apache.sshd.common.util.ValidateUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Utils.java    From termd with Apache License 2.0 6 votes vote down vote up
public static KeyPairProvider createTestHostKeyProvider(Class<?> anchor) {
    KeyPairProvider provider = KEYPAIR_PROVIDER_HOLDER.get();
    if (provider != null) {
        return provider;
    }

    File targetFolder = ValidateUtils.checkNotNull(detectTargetFolder(anchor), "Failed to detect target folder");
    File file = new File(targetFolder, "hostkey." + DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM.toLowerCase());
    provider = createTestHostKeyProvider(file);

    KeyPairProvider prev = KEYPAIR_PROVIDER_HOLDER.getAndSet(provider);
    if (prev != null) { // check if somebody else beat us to it
        return prev;
    } else {
        return provider;
    }
}
 
Example #2
Source File: Utils.java    From termd with Apache License 2.0 6 votes vote down vote up
public static KeyPairProvider createTestHostKeyProvider(Class<?> anchor) {
    KeyPairProvider provider = KEYPAIR_PROVIDER_HOLDER.get();
    if (provider != null) {
        return provider;
    }

    File targetFolder = ValidateUtils.checkNotNull(detectTargetFolder(anchor), "Failed to detect target folder");
    File file = new File(targetFolder, "hostkey." + DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM.toLowerCase());
    provider = createTestHostKeyProvider(file);

    KeyPairProvider prev = KEYPAIR_PROVIDER_HOLDER.getAndSet(provider);
    if (prev != null) { // check if somebody else beat us to it
        return prev;
    } else {
        return provider;
    }
}
 
Example #3
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
private static <P extends KeyIdentityProvider> P validateKeyPairProvider(P provider) {
    ValidateUtils.checkNotNull(provider, "No provider");

    // get the I/O out of the way
    Iterable<KeyPair> keys = ValidateUtils.checkNotNull(provider.loadKeys(), "No keys loaded");
    if (keys instanceof Collection<?>) {
        ValidateUtils.checkNotNullAndNotEmpty((Collection<?>) keys, "Empty keys loaded");
    }

    return provider;
}
 
Example #4
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * @return The TEMP sub-folder {@link Path} of the Maven &quot;target&quot; folder
 * associated with the project - never {@code null}
 */
protected Path getTempTargetFolder() {
    synchronized (TEMP_SUBFOLDER_NAME) {
        if (tempFolder == null) {
            tempFolder = ValidateUtils.checkNotNull(detectTargetFolder(), "No target folder detected").resolve(TEMP_SUBFOLDER_NAME);
        }
    }

    return tempFolder;
}
 
Example #5
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to detect the location of the Maven &quot;target&quot; folder
 * associated with the project that contains the actual class extending this
 * base class
 *
 * @return The {@link File} representing the location of the &quot;target&quot; folder
 * @throws IllegalArgumentException If failed to detect the folder
 */
protected Path detectTargetFolder() throws IllegalArgumentException {
    synchronized (TEMP_SUBFOLDER_NAME) {
        if (targetFolder == null) {
            targetFolder = ValidateUtils.checkNotNull(Utils.detectTargetFolder(getClass()), "Failed to detect target folder").toPath();
        }
    }

    return targetFolder;
}
 
Example #6
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static KeyPair getFirstKeyPair(KeyIdentityProvider provider) {
    ValidateUtils.checkNotNull(provider, "No key pair provider");
    Iterable<? extends KeyPair> pairs = ValidateUtils.checkNotNull(provider.loadKeys(), "No loaded keys");
    Iterator<? extends KeyPair> iter = ValidateUtils.checkNotNull(pairs.iterator(), "No keys iterator");
    ValidateUtils.checkTrue(iter.hasNext(), "Empty loaded kyes iterator");
    return ValidateUtils.checkNotNull(iter.next(), "No key pair in iterator");
}
 
Example #7
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static KeyPair getFirstKeyPair(KeyIdentityProvider provider) {
    ValidateUtils.checkNotNull(provider, "No key pair provider");
    Iterable<? extends KeyPair> pairs = ValidateUtils.checkNotNull(provider.loadKeys(), "No loaded keys");
    Iterator<? extends KeyPair> iter = ValidateUtils.checkNotNull(pairs.iterator(), "No keys iterator");
    ValidateUtils.checkTrue(iter.hasNext(), "Empty loaded kyes iterator");
    return ValidateUtils.checkNotNull(iter.next(), "No key pair in iterator");
}
 
Example #8
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
private static <P extends KeyIdentityProvider> P validateKeyPairProvider(P provider) {
    ValidateUtils.checkNotNull(provider, "No provider");

    // get the I/O out of the way
    Iterable<KeyPair> keys = ValidateUtils.checkNotNull(provider.loadKeys(), "No keys loaded");
    if (keys instanceof Collection<?>) {
        ValidateUtils.checkNotNullAndNotEmpty((Collection<?>) keys, "Empty keys loaded");
    }

    return provider;
}
 
Example #9
Source File: AsyncUserAuthService.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
public AsyncUserAuthService(Session s) throws SshException {
    ValidateUtils.checkTrue(s instanceof ServerSession, "Server side service used on client side");
    if (s.isAuthenticated()) {
        throw new SshException("Session already authenticated");
    }

    this.session = (ServerSession) s;
    maxAuthRequests = session.getIntProperty(ServerFactoryManager.MAX_AUTH_REQUESTS, DEFAULT_MAX_AUTH_REQUESTS);

    ServerFactoryManager manager = getFactoryManager();
    userAuthFactories = new ArrayList<>(manager.getUserAuthFactories());
    // Get authentication methods
    authMethods = new ArrayList<>();

    String mths = FactoryManagerUtils.getString(manager, ServerFactoryManager.AUTH_METHODS);
    if (GenericUtils.isEmpty(mths)) {
        for (NamedFactory<UserAuth> uaf : manager.getUserAuthFactories()) {
            authMethods.add(new ArrayList<>(Collections.singletonList(uaf.getName())));
        }
    }
    else {
        for (String mthl : mths.split("\\s")) {
            authMethods.add(new ArrayList<>(Arrays.asList(mthl.split(","))));
        }
    }
    // Verify all required methods are supported
    for (List<String> l : authMethods) {
        for (String m : l) {
            NamedFactory<UserAuth> factory = NamedResource.Utils.findByName(m, String.CASE_INSENSITIVE_ORDER, userAuthFactories);
            if (factory == null) {
                throw new SshException("Configured method is not supported: " + m);
            }
        }
    }

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Authorized authentication methods: "+ NamedResource.Utils.getNames(userAuthFactories));
    }
}
 
Example #10
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to detect the location of the Maven &quot;target&quot; folder
 * associated with the project that contains the actual class extending this
 * base class
 *
 * @return The {@link File} representing the location of the &quot;target&quot; folder
 * @throws IllegalArgumentException If failed to detect the folder
 */
protected Path detectTargetFolder() throws IllegalArgumentException {
    synchronized (TEMP_SUBFOLDER_NAME) {
        if (targetFolder == null) {
            targetFolder = ValidateUtils.checkNotNull(Utils.detectTargetFolder(getClass()), "Failed to detect target folder").toPath();
        }
    }

    return targetFolder;
}
 
Example #11
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * @return The TEMP sub-folder {@link Path} of the Maven &quot;target&quot; folder
 * associated with the project - never {@code null}
 */
protected Path getTempTargetFolder() {
    synchronized (TEMP_SUBFOLDER_NAME) {
        if (tempFolder == null) {
            tempFolder = ValidateUtils.checkNotNull(detectTargetFolder(), "No target folder detected").resolve(TEMP_SUBFOLDER_NAME);
        }
    }

    return tempFolder;
}
 
Example #12
Source File: ESBJAVA3470.java    From product-ei with Apache License 2.0 4 votes vote down vote up
public static KeyPairProvider createTestHostKeyProvider(Path path) {
    SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider();
    keyProvider.setPath(ValidateUtils.checkNotNull(path, "No path"));
    keyProvider.setAlgorithm(DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM);
    return keyProvider;
}
 
Example #13
Source File: PortForwardingTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshd = setupTestServer();
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 2048);
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.MAX_PACKET_SIZE, 256);
    sshd.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
    sshd.start();

    if (!requestsQ.isEmpty()) {
        requestsQ.clear();
    }

    final TcpipForwarderFactory factory = ValidateUtils.checkNotNull(sshd.getTcpipForwarderFactory(), "No TcpipForwarderFactory");
    sshd.setTcpipForwarderFactory(new TcpipForwarderFactory() {
        private final Class<?>[] interfaces = {TcpipForwarder.class};
        private final Map<String, String> method2req = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) {
            private static final long serialVersionUID = 1L;    // we're not serializing it...

            {
                put("localPortForwardingRequested", TcpipForwardHandler.REQUEST);
                put("localPortForwardingCancelled", CancelTcpipForwardHandler.REQUEST);
            }
        };

        @Override
        public TcpipForwarder create(ConnectionService service) {
            Thread thread = Thread.currentThread();
            ClassLoader cl = thread.getContextClassLoader();

            final TcpipForwarder forwarder = factory.create(service);
            return (TcpipForwarder) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() {
                @SuppressWarnings("synthetic-access")
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = method.invoke(forwarder, args);
                    String name = method.getName();
                    String request = method2req.get(name);
                    if (GenericUtils.length(request) > 0) {
                        if (requestsQ.offer(request)) {
                            log.info("Signal " + request);
                        } else {
                            log.error("Failed to offer request=" + request);
                        }
                    }
                    return result;
                }
            });
        }
    });
    sshPort = sshd.getPort();

    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            IoBuffer recv = (IoBuffer) message;
            IoBuffer sent = IoBuffer.allocate(recv.remaining());
            sent.put(recv);
            sent.flip();
            session.write(sent);
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(0));
    echoPort = acceptor.getLocalAddress().getPort();
    this.acceptor = acceptor;
}
 
Example #14
Source File: Utils.java    From termd with Apache License 2.0 4 votes vote down vote up
public static KeyPair getFirstKeyPair(KeyPairProviderHolder holder) {
    return getFirstKeyPair(ValidateUtils.checkNotNull(holder, "No holder").getKeyPairProvider());
}
 
Example #15
Source File: Utils.java    From termd with Apache License 2.0 4 votes vote down vote up
public static KeyPairProvider createTestHostKeyProvider(Path path) {
    SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider();
    keyProvider.setPath(ValidateUtils.checkNotNull(path, "No path"));
    keyProvider.setAlgorithm(DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM);
    return validateKeyPairProvider(keyProvider);
}
 
Example #16
Source File: Utils.java    From termd with Apache License 2.0 4 votes vote down vote up
public static KeyPairProvider createTestHostKeyProvider(File file) {
    return createTestHostKeyProvider(ValidateUtils.checkNotNull(file, "No file").toPath());
}
 
Example #17
Source File: AbstractUserAuth.java    From termd with Apache License 2.0 4 votes vote down vote up
protected AbstractUserAuth(ClientSession session, String service) {
    this.session = ValidateUtils.checkNotNull(session, "No client session");
    this.service = service;
}
 
Example #18
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 4 votes vote down vote up
public AsyncUserAuthService(Session s) throws SshException {
  ValidateUtils.checkTrue(s instanceof ServerSession, "Server side service used on client side");
  if (s.isAuthenticated()) {
    throw new SshException("Session already authenticated");
  }

  serverSession = (ServerSession) s;
  maxAuthRequests = PropertyResolverUtils.getIntProperty(s, ServerAuthenticationManager.MAX_AUTH_REQUESTS, ServerAuthenticationManager.DEFAULT_MAX_AUTH_REQUESTS);

  List<NamedFactory<UserAuth>> factories = ValidateUtils.checkNotNullAndNotEmpty(
      serverSession.getUserAuthFactories(), "No user auth factories for %s", s);
  userAuthFactories = new ArrayList<>(factories);
  // Get authentication methods
  authMethods = new ArrayList<>();

  String mths = PropertyResolverUtils.getString(s, ServerFactoryManager.AUTH_METHODS);
  if (GenericUtils.isEmpty(mths)) {
    for (NamedFactory<UserAuth> uaf : factories) {
      authMethods.add(new ArrayList<>(Collections.singletonList(uaf.getName())));
    }
  } else {
    if (log.isDebugEnabled()) {
      log.debug("ServerUserAuthService({}) using configured methods={}", s, mths);
    }
    for (String mthl : mths.split("\\s")) {
      authMethods.add(new ArrayList<>(Arrays.asList(GenericUtils.split(mthl, ','))));
    }
  }
  // Verify all required methods are supported
  for (List<String> l : authMethods) {
    for (String m : l) {
      NamedFactory<UserAuth> factory = NamedResource.Utils.findByName(m, String.CASE_INSENSITIVE_ORDER, userAuthFactories);
      if (factory == null) {
        throw new SshException("Configured method is not supported: " + m);
      }
    }
  }

  if (log.isDebugEnabled()) {
    log.debug("ServerUserAuthService({}) authorized authentication methods: {}",
        s, NamedResource.Utils.getNames(userAuthFactories));
  }
}
 
Example #19
Source File: ESBJAVA3470.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
public static KeyPairProvider createTestHostKeyProvider(Path path) {
    SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider();
    keyProvider.setPath(ValidateUtils.checkNotNull(path, "No path"));
    keyProvider.setAlgorithm(DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM);
    return keyProvider;
}
 
Example #20
Source File: PortForwardingTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshd = setupTestServer();
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 2048);
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.MAX_PACKET_SIZE, 256);
    sshd.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
    sshd.start();

    if (!requestsQ.isEmpty()) {
        requestsQ.clear();
    }

    final TcpipForwarderFactory factory = ValidateUtils.checkNotNull(sshd.getTcpipForwarderFactory(), "No TcpipForwarderFactory");
    sshd.setTcpipForwarderFactory(new TcpipForwarderFactory() {
        private final Class<?>[] interfaces = {TcpipForwarder.class};
        private final Map<String, String> method2req = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) {
            private static final long serialVersionUID = 1L;    // we're not serializing it...

            {
                put("localPortForwardingRequested", TcpipForwardHandler.REQUEST);
                put("localPortForwardingCancelled", CancelTcpipForwardHandler.REQUEST);
            }
        };

        @Override
        public TcpipForwarder create(ConnectionService service) {
            Thread thread = Thread.currentThread();
            ClassLoader cl = thread.getContextClassLoader();

            final TcpipForwarder forwarder = factory.create(service);
            return (TcpipForwarder) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() {
                @SuppressWarnings("synthetic-access")
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = method.invoke(forwarder, args);
                    String name = method.getName();
                    String request = method2req.get(name);
                    if (GenericUtils.length(request) > 0) {
                        if (requestsQ.offer(request)) {
                            log.info("Signal " + request);
                        } else {
                            log.error("Failed to offer request=" + request);
                        }
                    }
                    return result;
                }
            });
        }
    });
    sshPort = sshd.getPort();

    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            IoBuffer recv = (IoBuffer) message;
            IoBuffer sent = IoBuffer.allocate(recv.remaining());
            sent.put(recv);
            sent.flip();
            session.write(sent);
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(0));
    echoPort = acceptor.getLocalAddress().getPort();
    this.acceptor = acceptor;
}
 
Example #21
Source File: Utils.java    From termd with Apache License 2.0 4 votes vote down vote up
public static KeyPair getFirstKeyPair(KeyPairProviderHolder holder) {
    return getFirstKeyPair(ValidateUtils.checkNotNull(holder, "No holder").getKeyPairProvider());
}
 
Example #22
Source File: Utils.java    From termd with Apache License 2.0 4 votes vote down vote up
public static KeyPairProvider createTestHostKeyProvider(Path path) {
    SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider();
    keyProvider.setPath(ValidateUtils.checkNotNull(path, "No path"));
    keyProvider.setAlgorithm(DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM);
    return validateKeyPairProvider(keyProvider);
}
 
Example #23
Source File: Utils.java    From termd with Apache License 2.0 4 votes vote down vote up
public static KeyPairProvider createTestHostKeyProvider(File file) {
    return createTestHostKeyProvider(ValidateUtils.checkNotNull(file, "No file").toPath());
}
 
Example #24
Source File: AbstractUserAuth.java    From termd with Apache License 2.0 4 votes vote down vote up
protected AbstractUserAuth(ClientSession session, String service) {
    this.session = ValidateUtils.checkNotNull(session, "No client session");
    this.service = service;
}
 
Example #25
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 4 votes vote down vote up
public AsyncUserAuthService(Session s) throws SshException {
  ValidateUtils.checkTrue(s instanceof ServerSession, "Server side service used on client side");
  if (s.isAuthenticated()) {
    throw new SshException("Session already authenticated");
  }

  serverSession = (ServerSession) s;
  maxAuthRequests = PropertyResolverUtils.getIntProperty(s, ServerAuthenticationManager.MAX_AUTH_REQUESTS, ServerAuthenticationManager.DEFAULT_MAX_AUTH_REQUESTS);

  List<NamedFactory<UserAuth>> factories = ValidateUtils.checkNotNullAndNotEmpty(
      serverSession.getUserAuthFactories(), "No user auth factories for %s", s);
  userAuthFactories = new ArrayList<NamedFactory<UserAuth>>(factories);
  // Get authentication methods
  authMethods = new ArrayList<List<String>>();

  String mths = PropertyResolverUtils.getString(s, ServerFactoryManager.AUTH_METHODS);
  if (GenericUtils.isEmpty(mths)) {
    for (NamedFactory<UserAuth> uaf : factories) {
      authMethods.add(new ArrayList<String>(Collections.singletonList(uaf.getName())));
    }
  } else {
    if (log.isDebugEnabled()) {
      log.debug("ServerUserAuthService({}) using configured methods={}", s, mths);
    }
    for (String mthl : mths.split("\\s")) {
      authMethods.add(new ArrayList<String>(Arrays.asList(GenericUtils.split(mthl, ','))));
    }
  }
  // Verify all required methods are supported
  for (List<String> l : authMethods) {
    for (String m : l) {
      NamedFactory<UserAuth> factory = NamedResource.Utils.findByName(m, String.CASE_INSENSITIVE_ORDER, userAuthFactories);
      if (factory == null) {
        throw new SshException("Configured method is not supported: " + m);
      }
    }
  }

  if (log.isDebugEnabled()) {
    log.debug("ServerUserAuthService({}) authorized authentication methods: {}",
        s, NamedResource.Utils.getNames(userAuthFactories));
  }
}