正确关闭 SSLSocket [英] Properly closing SSLSocket

查看:46
本文介绍了正确关闭 SSLSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 Java 实现 SSL 代理.我基本上打开两个套接字 browser-proxy,proxy-server,并运行两个线程,这些线程将写入 proxy-server 他们从 proxy-server 读取的内容代码>浏览器代理,反之亦然.每个线程看起来像这样:

I want to implement an SSL proxy in Java. I basically open two sockets browser-proxy,proxy-server, and run two threads which would write to proxy-server what they read from browser-proxy, and vice versa. Each thread looks like this:

while (true) {
   nr = in.read(buffer);
   if (nr == -1) System.out.println(sockin.toString()+" EOF  "+nr);
   if (nr == -1) break;
   out.write(buffer, 0, nr);
}
sockin.shutdownInput();
sockout.shutdownOutput(); // now the second thread will receive -1 on read

每个线程只会关闭输入套接字,因此最终两个套接字都关闭.

Each thread will only close the input socket, so that eventually both sockets are closed.

但是如果我想使用 SSLSocket 该怎么办?那里似乎不支持 shutdownOutput/Input 方法.这是我得到的例外.

But what do I do if I want to use an SSLSocket? It seems that the shutdownOutput/Input methods are not supported there. Here's the exception I get.

Exception in thread "Thread-35" java.lang.UnsupportedOperationException: 
The method shutdownInput() is not supported in SSLSocket
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.shutdownInput(Unknown Source)

我想到的是:

try {
    while (true) {
       nr = in.read(buffer);
       if (nr == -1) System.out.println(sockin.toString()+" EOF  "+nr);
       if (nr == -1) break;
       out.write(buffer, 0, nr);
    }
    // possible race condition if by some mysterious way both threads would get EOF
    if (!sockin.isClosed()) sockin.close();
    if (!sockout.isClosed()) sockout.close();
} catch (SocketException e) {/*ignore expected "socket closed" exception, */}

每次套接字结束时,我都必须捕获并忽略套接字结束异常.

I must catch and ignore end of socket exception every time my socket ends.

我的问题是:

  1. 如果 shutdownInput() 不受支持,我怎么会从 SSLSocket 得到 -1 答案.
  2. 对于我的痛苦,有没有更好的解决方案?我不认为有任何理智,因为当另一个线程将他标记为我完成了"时,其中一个线程可能已经在阻塞 read 方法中.我认为将他踢出阻塞线程的唯一方法是关闭套接字并引发关闭的套接字"异常.

  1. If shutdownInput() is unsupported, how come I'm getting a -1 answer from an SSLSocket.
  2. Is there a better solution for my agony? I don't think there's anything sane, since one of the thread might be already in the blocking read method when the other thread marks him "I'm done". And the only way I see to kick him out of the blocking thread is by closing the socket and raising a "closed socket" exception.

(我猜你可以使用多线程消息传递和异步数据读取的一些邪恶组合来通知另一个线程你的工作已经完成,但这太可怕了,我担心 IntelliJ 的风格警察会来找我考虑一下...)

(You could I guess use some unholy combination of multithread message passing and asynchronous data reading in order to signal the other thread your work is done, but this is so horrible that I'm afraid IntelliJ's style cop will come after me just for thinking about it...)

澄清:我知道 shutdownInputshutdownOutput 没有意义,因为你不能有半双工 TLS 连接,每个规格但鉴于此,如何在 Java 中结束 TLS 连接而不出现异常?

Clarification: I know that shutdownInput and shutdownOutput doesn't make sense, since you cannot have a half-duplex TLS connection, per spec. But given that, how can I end a TLS connection in Java without getting an exception?

请不要告诉我 shutdownIput 对 TLS 没有意义.我知道,这不是我要问的.我在问我还能用什么来正确关闭 SSLSocket(因此标题为正确关闭 SSLSocket".

Please, don't tell me shutdownIput doesn't make sense for TLS. I know that, this is not what I'm asking. I'm asking what else can I use, in order to close SSLSocket properly (hence the title, "Properly closing SSLSocket".

推荐答案

这是我最初的(暂时删除的)答案,但显然不够好,因为它很快被-2...我想我应该添加更多解释.

无法关闭 SSL/TLS 套接字的一半连接以符合 TLS 协议,如 关闭警报部分.

It's not possible to close half of the connection for SSL/TLS sockets to comply with the TLS protocol, as specified in the section on closure alerts.

客户端和服务器必须共享连接是结束以避免截断攻击.任何一方均可发起交换关闭消息.

The client and the server must share knowledge that the connection is ending in order to avoid a truncation attack. Either party may initiate the exchange of closing messages.

close_notify 此消息通知收件人,发件人不会在此连接上发送更多消息.如果任何连接在没有级别等于警告的适当 close_notify 消息的情况下终止,会话将无法恢复.

close_notify This message notifies the recipient that the sender will not send any more messages on this connection. The session becomes unresumable if any connection is terminated without proper close_notify messages with level equal to warning.

任何一方都可以发起关闭通过发送 close_notify 警报.关闭后收到的任何数据警报被忽略.

Either party may initiate a close by sending a close_notify alert. Any data received after a closure alert is ignored.

每一方都需要发送一个关闭前 close_notify 警报连接的写入端.它要求对方以 close_notify 警报响应它自己的并关闭立即连接,丢弃任何待写.这不是必需的对于关闭的发起者等待对于响应 close_notify在关闭读取端之前发出警报连接.

Each party is required to send a close_notify alert before closing the write side of the connection. It is required that the other party respond with a close_notify alert of its own and close down the connection immediately, discarding any pending writes. It is not required for the initiator of the close to wait for the responding close_notify alert before closing the read side of the connection.

尽管您可能只想关闭一半的连接(通过 shutdownInput()/shutdownOutput() 输入或输出),但底层 TLS 层仍然需要发送这个close_notify数据包在真正关闭通信之前,否则将被视为截断攻击.

Although you may want to close only half of the connection (input or output via shutdownInput()/shutdownOutput()), the underlying TLS layer still needs to send this close_notify packet before really shutting down the communication, otherwise, it will be considered as a truncation attack.

修复非常简单:仅在 SSLSockets 上使用 close():它不只是像普通 TCP 套接字那样关闭连接,但它根据 SSL/TLS 规范干净利落地做到这一点.

The fix is quite simple: only use close() on SSLSockets: it doesn't just close the connection as it would for normal TCP sockets, but it does it cleanly according to the SSL/TLS specification.

编辑:附加说明.

简短的回答仍然是:使用 close(),您可能还需要从 SSL/TLS 之上的协议中找出何时适合这样做.

The short answer is still: use close(), you may also need to find out when it's appropriate to do so from the protocol on top of SSL/TLS.

(只是为了澄清,您正在尝试做的是有效的中间人"(MITM)代理.您需要将客户端配置为信任代理的证书,可能就好像如果这是透明的,它就是服务器证书.HTTPS 连接如何通过 HTTP 代理工作是一个不同的问题.)

(Just to clarify, what you're trying to do is effectively a "Man-In-The-Middle" (MITM) proxy. You would need the client to be configured to trust the proxy's certificate, possibly as if it was the server certificate if this is meant to happen transparently. How HTTPS connections work through an HTTP proxy is a different question.)

在您对 其他相关问题,我的印象是您认为不返回 -1 是破坏了 TLS 协议".这实际上不是关于协议,而是关于 API:向 TLS 堆栈的(程序员)用户提供编程结构(类、方法、函数等)的方式,以便能够使用 TLS.SSLSocket 只是 API 的一部分,它为程序员提供了以类似于普通 Socket 的方式使用 SSL/TLS 的能力.TLS 规范根本不讨论套接字.虽然 TLS(及其前身 SSL)旨在提供这种抽象,但归根结底 SSLSocket 只是:一种抽象.遵循OOP设计原则,SSLSocket继承了Socket,并尽量贴近Socket的行为.然而,由于 SSL/TLS 的工作方式(并且因为 SSLSocket 有效地位于普通 Socket 之上),不可能有所有功能的精确映射.

In some of your comments to your other related question, I got the impression that you thought that not returning -1 was "breaking the TLS protocol". This isn't really about the protocol, but about the API: the way programming structures (classes, methods, functions, ...) are provided to (programmer) user of the TLS stack to be able to use of TLS. SSLSocket is merely part of an API to provide programmers with the ability to use SSL/TLS in a way similar to plain Socket. The TLS specification doesn't talk about sockets at all. While TLS (and its precessor, SSL) were built with the aim to make it possible to provide this sort of abstraction, at the end of the day SSLSocket is just that: an abstraction. In line with the OOP design principles, SSLSocket inherits Socket and tries to stick as closely as possible to the behaviour of Socket. However, because of the way SSL/TLS works (and because an SSLSocket effectively sits on top of a normal Socket), there cannot be an exact mapping of all features.

特别是,从普通 TCP 套接字到 SSL/TLS 套接字的转换区域不能完全透明地建模.在设计 SSLSocket 类时,必须做出一些任意选择(例如握手的方式):这是在不 (a) 向 SSLSocket 用户暴露过多 TLS 的特殊性,(b) 使 TLS 机制工作和 (c) 将所有这些映射到由超类(Socket).这些选择不可避免地会对 SSLSocket 的功能产生一些影响,这就是为什么它的 Javadoc API 页面 有比较多的文字.SSLSocket.close(),在API方面,必须遵守Socket.close().从SSLSocket获取的InputStream/OutputStream与底层普通Socket获取的不一样,后者(除非您已明确转换它) 你可能看不到.

In particular, the area of transition from a normal TCP socket to an SSL/TLS socket can't quite be modelled transparently. Some arbitrary choices (e.g. how the handshake takes place) had to be made when designing the SSLSocket class: it's a compromise between not (a) exposing too much of the specificity of TLS to the SSLSocket user, (b) making the TLS mechanism work and (c) mapping all this to the existing interface provided by the superclass (Socket). These choices inevitably have some impact on the functionality of the SSLSocket, and that's why its Javadoc API page has a relatively large amount of text. SSLSocket.close(), in terms of API, has to abide by the description of Socket.close(). The InputStream/OutputStream obtained from the SSLSocket are not the same as the one from the underlying plain Socket,which (unless you've converted it explicitly) you might not see.

SSLSocket 被设计为尽可能接近地使用,就好像它是一个普通的 Socket,并且您获得的 InputStream 旨在行为尽可能接近基于文件的输入流.顺便说一下,这不是 Java 特有的.甚至 C 中的 Unix 套接字也与文件描述符和 read() 一起使用.只要您知道它们的局限性,这些抽象很方便并且在大多数情况下都可以使用.

SSLSocket is designed to be usable as closely as possibly as if it was a plain Socket, and the InputStream you get is designed to behave as closely as possibly to a file-based input stream. This isn't specific to Java, by the way. Even Unix sockets in C are used with a file descriptor and read(). These abstractions are convenient and work most of the time, so long as you know what their limitations are.

当涉及到 read() 时,即使在 C 中,EOF 的概念来自文件尾终止,但您实际上并没有处理与文件.TCP 套接字的问题在于,虽然您可以检测到远程方在发送 FIN 时选择关闭连接的时间,但如果它不发送,则无法检测到它没有任何事物.从套接字读取任何内容时,无法区分非活动连接和断开连接之间的区别.因此,当涉及到网络编程时,如果可以的话,依赖于从 InputStream 读取 -1,但你永远不要仅仅依赖于它,否则你最终可能会得到 unreleased,死连接.虽然它是礼貌"的一方正确关闭半 TCP 连接(以某种方式,例如远程方在其 InputStream 上读取 -1 或等效的东西,如 Java 中的有序与异常连接释放),处理这种情况是不够的.这就是为什么 TCP 之上的协议通常是 旨在指示他们何时完成发送数据:例如,SMTP 发送 QUIT(并具有特定的终止符),HTTP 1.1 使用 Content-Length 或分块编码.

When it comes to read(), even in C, the notion of EOF comes from an end-of-file termination, but you're not actually dealing with files. The problem with TCP sockets is that, while you can detect when the remote party has chosen to close the connection when it sends FIN, you can't detect it hasn't, if it doesn't send anything. When reading nothing from a socket, there is no way to tell the difference between an inactive and a broken connection. As such, when it comes to network programming, relying on reading -1 from the InputStream if fine, but you never rely solely on that, otherwise you may end up with unreleased, dead connections. While it's "polite" for a party to close the half TCP connection properly (in a way such as the remote party reads -1 on its InputStream or something equivalent, as described in Orderly Versus Abortive Connection Release in Java), handling this case isn't sufficient. This is why protocols on top of TCP are generally designed to give an indication as to when they're done sending data: for example, SMTP sends QUIT (and has specific terminators), HTTP 1.1 uses Content-Length or chunked encoding.

(顺便说一句,如果你对SSLSocket 提供的抽象不满意,可以尝试直接使用SSLEngine.它可能更难,它赢了不会改变 TLS 规范关于发送 close_notify 的内容.)

(By the way, if you're not satisfied with the abstraction provided by SSLSocket, try to use SSLEngine directly. It's likely to be harder, and it won't change what the TLS specification says about sending close_notify.)

一般使用 TCP,您应该知道,在应用程序协议级别,何时停止发送和接收数据(以避免未释放的连接和/或依赖超时错误).当涉及到 TLS 时,TLS 规范中的这句话使得这种通常良好的实践成为更强的要求:要求另一方使用自己的 close_notify 警报进行响应,并立即关闭连接并丢弃任何挂起的写入."您将不得不通过应用协议以某种方式进行同步,否则远程方可能仍然需要编写一些内容(尤其是在您允许流水线请求/响应的情况下).

In general with TCP, you should know, at the application protocol level, when to stop sending and receiving data (to avoid unreleased connections and/or relying on timeout errors). This sentence in the TLS specification makes this generally good practice a stronger requirement when it comes to TLS: "It is required that the other party respond with a close_notify alert of its own and close down the connection immediately discarding any pending writes." You will have to synchronize somehow, via the application protocol, or the remote party may still have something to write (especially if you're allowing pipelined requests/responses).

如果您编写的代理用于拦截 HTTPS 连接(作为 MITM),您可以查看请求的内容.即使 HTTP 请求是流水线化的,您也可以计算由目标服务器(并期望它们何时结束,通过 Content-Length 或块分隔符).

If the proxy you're writing is for intercepting HTTPS connections (as a MITM), you can look into the content of the requests. Even if the HTTP requests are pipelined, you can count the number of responses sent by the target server (and expect when they end, via Content-Length or chunks delimiters).

但是,您将无法拥有纯粹透明的通用 TLS拦截器".TLS 旨在保护两方之间的传输,而不是中间有一个.虽然实现这种保护(避免 MITM)的大部分机制是通过服务器证书完成的,但其他一些 TLS 机制也会受到阻碍(关闭警报就是其中之一).请记住,您正在有效地创建两个不同的 TLS 连接,考虑到 TLS 的目的,它们很难合并为一个这一事实不足为奇.

However, you won't be able to have a purely transparent, generic TLS "interceptor". TLS is designed to secure the transport between two parties and not to have one in the middle. While most of the mechanism to achieve that protection (avoiding a MITM) is done via the server certificate, some other TLS mechanisms will get in the way (closure alert is one of them). Remember that you're effectively creating two distinct TLS connections, the fact that they're hard to merge as one shouldn't be surprising, considering the purpose of TLS.

SSLSocket.close() 是关闭 SSLSocket 的正确方法,但应用程序协议也将帮助您确定何时适合这样做.

SSLSocket.close() is the right way to close an SSLSocket, but the application protocol will also help you determine when it's appropriate to do so.

这篇关于正确关闭 SSLSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆