narrowlink / ipstack

Asynchronous lightweight userspace implementation of TCP/IP stack for Tun device
Apache License 2.0
50 stars 11 forks source link

How to determine whether the stream is over `SSL/TLS`? #13

Closed xmh0511 closed 8 months ago

xmh0511 commented 8 months ago
IpStackStream::Tcp(mut tcp) =>{
      if ssl/tls over tcp{
         copy(tcp, "x.x.x.x:443")
      }else{
          copy(tcp, "x.x.x.x:8080")
       }
}

When a TCP stream is coming from tun, how to determine whether ssl/tls is used? For example, http://10.0.0.1:8080 and https://10.0.0.2:9090, such two request will both catched by IpStackStream::Tcp(mut tcp), but how correctly distinct whether it is ssl/tls?

planetoryd commented 8 months ago

SSL is a protocol run atop TCP. Thus it's your job to check the bytes of the stream to identify its protocol

xmh0511 commented 8 months ago

SSL is a protocol run atop TCP. Thus it's your job to check the bytes of the stream to identify its protocol

Assume the destination address is 2.2.2.2:443, and I have identified it as SSL/TLS, then I established a connection that

IpStackStream::Tcp(mut tcp) => {
   let socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;
   socket.connect(&SockAddr::from(SocketAddr::from(([2, 2, 2, 2],443,)))).unwrap();
   tokio::spawn(async move {
     tokio::io::copy_bidirectional(&mut tcp, &mut rhs).await.unwrap();
   });
}

However, this still does not work for me. When requesting, the client gives the error

OpenSSL: error:0A000438:SSL routines::tlsv1 alert internal error

How do I correctly establish SSL/TLS connection?

planetoryd commented 8 months ago

Try debugging it with wireshark.

You can refer to my code https://github.com/planetoryd/tun2socks5/tree/afe8157d4599d02a15cf47909053ed19a243bf71 for usage of ipstack. It's a functioning tool.

SajjadPourali commented 8 months ago

As mentioned by @planetoryd, this is not within the scope of ipstack. However, you can take a look at the following link to detect TLS Client Hello, which is useful for TLS connection detection.

https://github.com/narrowlink/narrowlink/blob/main/gateway/src/service/wss.rs#L76-L105