STATE_DISCONNECTED_REMOTELY, iox); fireConnectionStateChanged(e);
private void dispatchMessage(TcpAddress incomingAddress, ByteBuffer byteBuffer, long bytesRead, Object sessionID, TransportStateReference tmStateReference) { byteBuffer.flip(); if (logger.isDebugEnabled()) { logger.debug("Received message from " + incomingAddress + " with length " + bytesRead + ": " + new OctetString(byteBuffer.array(), 0, (int) bytesRead).toHexString()); } ByteBuffer bis; if (isAsyncMsgProcessingSupported()) { byte[] bytes = new byte[(int) bytesRead]; System.arraycopy(byteBuffer.array(), 0, bytes, 0, (int) bytesRead); bis = ByteBuffer.wrap(bytes); } else { bis = ByteBuffer.wrap(byteBuffer.array(), 0, (int) bytesRead); } fireProcessMessage(incomingAddress, bis, tmStateReference); }
@Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { if (checkClientTrustedIntern(x509Certificates)) return; try { trustManager.checkClientTrusted(x509Certificates, s); } catch (CertificateException cex) { tlstm.getCounterSupport().fireIncrementCounter(new CounterEvent(this, SnmpConstants.snmpTlstmSessionOpenErrors)); tlstm.getCounterSupport().fireIncrementCounter(new CounterEvent(this, SnmpConstants.snmpTlstmSessionInvalidClientCertificates)); logger.warn("Client certificate validation failed for '"+x509Certificates[0]+"'"); throw cex; } }
public SocketEntry(TcpAddress address, Socket socket, boolean useClientMode, TransportStateReference tmStateReference) throws NoSuchAlgorithmException { super(address, socket); this.inAppBuffer = ByteBuffer.allocate(getMaxInboundMessageSize()); this.inNetBuffer = ByteBuffer.allocate(getMaxInboundMessageSize()); this.outNetBuffer = ByteBuffer.allocate(getMaxInboundMessageSize()); this.tmStateReference = tmStateReference; if (tmStateReference == null) { counterSupport.fireIncrementCounter(new CounterEvent(this, SnmpConstants.snmpTlstmSessionAccepts)); } SSLEngineConfigurator sslEngineConfigurator = ensureSslEngineConfigurator(); SSLContext sslContext = sslEngineConfigurator.getSSLContext(useClientMode, tmStateReference); this.sslEngine = sslContext.createSSLEngine(address.getInetAddress().getHostName(), address.getPort()); sslEngine.setUseClientMode(useClientMode); sslEngineConfigurator.configure(sslEngine); synchronized (TLSTM.this) { sessionID = nextSessionID++; } }
/** * Listen for incoming and outgoing requests. If the {@code serverEnabled} * member is {@code false} the server for incoming requests is not * started. This starts the internal server thread that processes messages. * @throws java.net.SocketException * when the transport is already listening for incoming/outgoing messages. * @throws java.io.IOException * if the listen port could not be bound to the server thread. */ public synchronized void listen() throws IOException { if (server != null) { throw new SocketException("Port already listening"); } try { serverThread = new ServerThread(); if (logger.isInfoEnabled()) { logger.info("TCP address "+getListenAddress()+" bound successfully"); } } catch (NoSuchAlgorithmException e) { throw new IOException("SSL not available: "+e.getMessage(), e); } server = SNMP4JSettings.getThreadFactory().createWorkerThread( "TLSTM_"+getAddress(), serverThread, true); if (connectionTimeout > 0) { // run as daemon socketCleaner = SNMP4JSettings.getTimerFactory().createTimer(); } server.run(); }
public ServerThread() throws IOException, NoSuchAlgorithmException { // Selector for incoming requests selector = Selector.open(); if (serverEnabled) { // Create a new server socket and set to non blocking mode ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); // Bind the server socket InetSocketAddress isa = new InetSocketAddress(tcpAddress.getInetAddress(), tcpAddress.getPort()); setSocketOptions(ssc.socket()); ssc.socket().bind(isa); // Register accepts on the server socket with the selector. This // step tells the selector that the socket wants to be put on the // ready list when accept operations occur, so allowing multiplexed // non-blocking I/O to take place. ssc.register(selector, SelectionKey.OP_ACCEPT); } }
/** * Sends a SNMP message to the supplied address. * @param address * an {@code TcpAddress}. A {@code ClassCastException} is thrown * if {@code address} is not a {@code TcpAddress} instance. * @param message byte[] * the message to sent. * @param tmStateReference * the (optional) transport model state reference as defined by * RFC 5590 section 6.1. * @throws java.io.IOException * if an IO exception occurs while trying to send the message. */ public void sendMessage(TcpAddress address, byte[] message, TransportStateReference tmStateReference) throws IOException { if (server == null) { listen(); } serverThread.sendMessage(address, message, tmStateReference); }
if (bindAddress == null) { if (target.getAddress() instanceof TlsAddress) { transport = new TLSTM(); } else if (target.getAddress() instanceof DtlsAddress) { transport = new DTLSTM(); transport = new TLSTM((TlsAddress)bindAddress); } else if (target.getAddress() instanceof DtlsAddress) { transport = new DTLSTM((DtlsAddress)bindAddress);
TLSTMTrustManagerFactory trustManagerFactory = (TLSTMTrustManagerFactory) c.newInstance(this); setTrustManagerFactory(trustManagerFactory);
public SocketEntry(TcpAddress address, Socket socket, boolean useClientMode, TransportStateReference tmStateReference) throws NoSuchAlgorithmException { this.inAppBuffer = ByteBuffer.allocate(getMaxInboundMessageSize()); this.inNetBuffer = ByteBuffer.allocate(getMaxInboundMessageSize()); this.outNetBuffer = ByteBuffer.allocate(getMaxInboundMessageSize()); this.peerAddress = address; this.tmStateReference = tmStateReference; this.socket = socket; this.lastUse = System.nanoTime(); if (tmStateReference == null) { counterSupport.fireIncrementCounter(new CounterEvent(this, SnmpConstants.snmpTlstmSessionAccepts)); } SSLContext sslContext = sslEngineConfigurator.getSSLContext(useClientMode, tmStateReference); this.sslEngine = sslContext.createSSLEngine(address.getInetAddress().getHostName(), address.getPort()); sslEngine.setUseClientMode(useClientMode); // sslEngineConfigurator.configure(SSLContext.getDefault(), useClientMode); sslEngineConfigurator.configure(sslEngine); synchronized (TLSTM.this) { sessionID = nextSessionID++; } }
/** * Listen for incoming and outgoing requests. If the {@code serverEnabled} * member is {@code false} the server for incoming requests is not * started. This starts the internal server thread that processes messages. * * @throws java.net.SocketException * when the transport is already listening for incoming/outgoing messages. * @throws java.io.IOException * if the listen port could not be bound to the server thread. */ public synchronized void listen() throws IOException { if (server != null) { throw new SocketException("Port already listening"); } try { serverThread = new ServerThread(); if (logger.isInfoEnabled()) { logger.info("TCP address " + tcpAddress + " bound successfully"); } } catch (NoSuchAlgorithmException e) { throw new IOException("SSL not available: " + e.getMessage(), e); } server = SNMP4JSettings.getThreadFactory().createWorkerThread( "TLSTM_" + getListenAddress(), serverThread, true); if (connectionTimeout > 0) { // run as daemon socketCleaner = SNMP4JSettings.getTimerFactory().createTimer(); } server.run(); }
public ServerThread() throws IOException, NoSuchAlgorithmException { super(TLSTM.this); // Selector for incoming requests if (serverEnabled) { // Create a new server socket and set to non blocking mode ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); // Bind the server socket InetSocketAddress isa = new InetSocketAddress(tcpAddress.getInetAddress(), tcpAddress.getPort()); setSocketOptions(ssc.socket()); ssc.socket().bind(isa); // Register accepts on the server socket with the selector. This // step tells the selector that the socket wants to be put on the // ready list when accept operations occur, so allowing multiplexed // non-blocking I/O to take place. ssc.register(selector, SelectionKey.OP_ACCEPT); } }
/** * Sends a SNMP message to the supplied address. * * @param address * an {@code TcpAddress}. A {@code ClassCastException} is thrown * if {@code address} is not a {@code TcpAddress} instance. * @param message * byte[] * the message to sent. * @param tmStateReference * the (optional) transport model state reference as defined by * RFC 5590 section 6.1. * @param timeoutMillis * maximum number of milli seconds the connection creation might take (if connection based). * @param maxRetries * maximum retries during connection creation. * * @throws java.io.IOException * if an IO exception occurs while trying to send the message. */ public void sendMessage(TcpAddress address, byte[] message, TransportStateReference tmStateReference, long timeoutMillis, int maxRetries) throws IOException { if (server == null) { listen(); } serverThread.sendMessage(address, message, tmStateReference); }
private Snmp createSnmpSession() throws IOException { AbstractTransportMapping<? extends Address> transport; if (address instanceof TlsAddress) { transport = new TLSTM(); } else if (address instanceof TcpAddress) { transport = new DefaultTcpTransportMapping(); } else { transport = new DefaultUdpTransportMapping(); } // Could save some CPU cycles: // transport.setAsyncMsgProcessingSupported(false); Snmp snmp = new Snmp(transport); MPv3 mpv3 = (MPv3)snmp.getMessageProcessingModel(MPv3.ID); mpv3.setLocalEngineID(localEngineID.getValue()); mpv3.setCurrentMsgID(MPv3.randomMsgID(engineBootCount)); if (version == SnmpConstants.version3) { USM usm = new USM(SecurityProtocols.getInstance(), localEngineID, engineBootCount); SecurityModels.getInstance().addSecurityModel(usm); addUsmUser(snmp); SecurityModels.getInstance().addSecurityModel( new TSM(localEngineID, false)); } return snmp; }
TLSTMTrustManagerFactory trustManagerFactory = (TLSTMTrustManagerFactory) c.newInstance(CounterSupport.getInstance(), securityCallback); setTrustManagerFactory(trustManagerFactory);
@Override protected TcpAddress writeData(SelectionKey sk, TcpAddress incomingAddress) { SocketEntry entry = (SocketEntry) sk.attachment(); try { SocketChannel sc = (SocketChannel) sk.channel(); incomingAddress = new TcpAddress(sc.socket().getInetAddress(), sc.socket().getPort()); if ((entry != null) && (!entry.hasMessage())) { synchronized (pending) { pending.remove(entry); entry.removeRegistration(selector, SelectionKey.OP_WRITE); } } if (entry != null) { writeMessage(entry, sc); } } catch (IOException iox) { logger.warn(iox); TransportStateEvent e = new TransportStateEvent(TLSTM.this, incomingAddress, TransportStateEvent. STATE_DISCONNECTED_REMOTELY, iox); fireConnectionStateChanged(e); // make sure channel is closed properly: closeChannel(sk.channel()); } return incomingAddress; }
private void dispatchMessage(TcpAddress incomingAddress, ByteBuffer byteBuffer, long bytesRead, Object sessionID, TransportStateReference tmStateReference) { byteBuffer.flip(); if (logger.isDebugEnabled()) { logger.debug("Received message from " + incomingAddress + " with length " + bytesRead + ": " + new OctetString(byteBuffer.array(), 0, (int)bytesRead).toHexString()); } ByteBuffer bis; if (isAsyncMsgProcessingSupported()) { byte[] bytes = new byte[(int)bytesRead]; System.arraycopy(byteBuffer.array(), 0, bytes, 0, (int)bytesRead); bis = ByteBuffer.wrap(bytes); } else { bis = ByteBuffer.wrap(byteBuffer.array(), 0, (int) bytesRead); } fireProcessMessage(incomingAddress, bis,tmStateReference); }
@Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { if (preCheckServerTrusted(x509Certificates)) return; try { trustManager.checkServerTrusted(x509Certificates, s); } catch (CertificateException cex) { tlstm.getCounterSupport().fireIncrementCounter(new CounterEvent(this, SnmpConstants.snmpTlstmSessionOpenErrors)); tlstm.getCounterSupport().fireIncrementCounter(new CounterEvent(this, SnmpConstants.snmpTlstmSessionUnknownServerCertificate)); logger.warn("Server certificate validation failed for '"+x509Certificates[0]+"'"); throw cex; } postCheckServerTrusted(x509Certificates); }
STATE_CONNECTED, null); fireConnectionStateChanged(e);
@Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException { logger.debug("checkClientTrusted with socket"); if (checkClientTrustedIntern(x509Certificates)) return; try { if (trustManager instanceof X509ExtendedTrustManager) { logger.debug("extended checkClientTrusted with socket"); ((X509ExtendedTrustManager)trustManager).checkClientTrusted(x509Certificates, s, socket); } else { trustManager.checkClientTrusted(x509Certificates, s); } } catch (CertificateException cex) { tlstm.getCounterSupport().fireIncrementCounter(new CounterEvent(this, SnmpConstants.snmpTlstmSessionOpenErrors)); tlstm.getCounterSupport().fireIncrementCounter(new CounterEvent(this, SnmpConstants.snmpTlstmSessionInvalidClientCertificates)); logger.warn("Client certificate validation failed for '"+x509Certificates[0]+"'"); throw cex; } }