diff --git a/ktls/src/ktls_stream.rs b/ktls/src/ktls_stream.rs index 388421a..113383d 100644 --- a/ktls/src/ktls_stream.rs +++ b/ktls/src/ktls_stream.rs @@ -76,7 +76,7 @@ where IO: AsRawFd + AsyncRead + AsyncReadReady, { fn poll_read( - self: Pin<&mut Self>, + mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &mut ReadBuf<'_>, ) -> task::Poll> { @@ -90,9 +90,8 @@ where return task::Poll::Ready(Ok(())); } - let mut this = self.project(); - - if let Some((drain_index, drained)) = this.drained.as_mut() { + let drained_slot = self.as_mut().project().drained; + if let Some((drain_index, drained)) = drained_slot.as_mut() { let drained = &drained[*drain_index..]; let len = std::cmp::min(buf.remaining(), drained.len()); @@ -102,197 +101,215 @@ where *drain_index += len; if *drain_index >= drained.len() { tracing::trace!("KtlsStream::poll_read, done draining"); - *this.drained = None; + *drained_slot = None; } - cx.waker().wake_by_ref(); tracing::trace!("KtlsStream::poll_read, returning after drain"); return task::Poll::Ready(Ok(())); } - let filled_before = buf.filled().len(); - let read_res = this.inner.as_mut().poll_read(cx, buf); - if let task::Poll::Ready(Err(e)) = &read_res { - // 5 is a generic "input/output error", it happens when - // using poll_read on a kTLS socket that just received - // a control message - if let Some(5) = e.raw_os_error() { - // could be a control message, let's check - let fd = this.inner.as_raw_fd(); - - // XXX: recvmsg wants a `&mut Vec` so it's able to resize it - // I guess? Or so there's a clear separation between uninitialized - // and initialized? We could probably get read of that heap alloc, idk. - - // let mut cmsgspace = - // [0u8; unsafe { libc::CMSG_SPACE(std::mem::size_of::() as _) as _ }]; - let mut cmsgspace = Vec::with_capacity(unsafe { - libc::CMSG_SPACE(std::mem::size_of::() as _) as _ - }); - - let mut iov = [IoSliceMut::new(buf.initialize_unfilled())]; - let flags = MsgFlags::empty(); - - let r = recvmsg::(fd, &mut iov, Some(&mut cmsgspace), flags); - let r = match r { - Ok(r) => r, - Err(Errno::EAGAIN) => { - unreachable!("expected a control message, got EAGAIN") - } - Err(e) => { - // ok I guess it really failed then - tracing::trace!(?e, "recvmsg failed"); - return Err(e.into()).into(); + loop { + let filled_before = buf.filled().len(); + match self + .as_mut() + .project() + .inner + .poll_read(cx, buf) + { + // A kTLS socket returns EIO from read() when the next record is + // a TLS control message rather than application data. + task::Poll::Ready(Err(e)) if e.raw_os_error() == Some(libc::EIO) => { + match self + .as_mut() + .handle_control_message(buf)? + { + ControlMessageOutcome::Continue => continue, + ControlMessageOutcome::Eof => return task::Poll::Ready(Ok(())), } - }; - let cmsg = r - .cmsgs()? - .next() - .expect("we should've received exactly one control message"); + } + task::Poll::Ready(Ok(())) if buf.filled().len() == filled_before => { + // A transport EOF before the peer's close_notify means the stream was + // truncated--possibly by an attacker, since a TCP FIN is not + // authenticated. Report it as an error. + return task::Poll::Ready(Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "peer closed connection without sending TLS close_notify", + ))); + } + res => return res, + } + } + } +} - let record_type = match cmsg { - ControlMessageOwned::TlsGetRecordType(t) => t, - _ => panic!("unexpected cmsg type: {cmsg:#?}"), - }; +enum ControlMessageOutcome { + /// Control message consumed; poll the inner IO again for more data or + /// another control message (or to register the waker). + Continue, + /// The peer ended the TLS session; report EOF. + Eof, +} - match record_type { - TlsGetRecordType::ChangeCipherSpec => { - panic!("change_cipher_spec isn't supported by the ktls crate") - } - TlsGetRecordType::Alert => { - // the alert level and description are in iovs - let iov = r - .iovs() - .next() - .expect("expected data in iovs"); - - let (level, description) = match iov { - [] => { - // we have an early return case for that - unreachable!(); - } - &[level] => { - // https://github.com/facebookincubator/fizz/blob/fff6d9d49d3c554ab66b58822d1e1fe93e8d80f2/fizz/experimental/ktls/AsyncKTLSSocket.cpp#L144 - // - // Since all alerts (even warning-level alerts) - // signal the abort of a TLS session, we do not - // need to worry about additional application - // data. - // - // If we only have half the alert (because the - // user passed a buffer of size 1), just assume - // it's a close_notify - ( - TlsAlertLevel::from_primitive(level), - TlsAlertDescription::CloseNotify, - ) - } - &[level, description] => ( - TlsAlertLevel::from_primitive(level), - TlsAlertDescription::from_primitive(description), - ), - _ => { - unreachable!( - "TLS alerts are exactly 2 bytes, your kTLS is misbehaving" - ); - } - }; - - match (level, description) { - // https://datatracker.ietf.org/doc/html/rfc5246#section-7.2 - // alerts we should handle are ones with fatal level or a - // close_notify - (_, TlsAlertDescription::CloseNotify) | (TlsAlertLevel::Fatal, _) => { - tracing::trace!(?level, ?description, "got TLS alert"); - *this.read_closed = true; - *this.write_closed = true; - if let Err(e) = send_close_notify(this.inner.as_raw_fd()) { - // This can fail in case of a full send buffer (EAGAIN), - // or a dead socket. Ignore the error, as replying with - // close_notify is best-effort. - tracing::trace!("failed to reply with close_notify: {e}"); - } - // the file descriptor will be closed when the stream is dropped, - // we already protect against writes-after-close_notify through - // the write_closed flag - return task::Poll::Ready(Ok(())); - } - _ => { - // we got something we probably can't handle - } - } - return task::Poll::Ready(Ok(())); - } - TlsGetRecordType::Handshake => { - // https://www.rfc-editor.org/info/rfc9846/#appendix-B.3 - const MSG_NEW_SESSION_TICKET: u8 = 4; - const MSG_KEY_UPDATE: u8 = 24; - let message_type = r - .iovs() - .next() - .and_then(|iov| iov.first()); - match message_type { - Some(&MSG_KEY_UPDATE) => { - // KeyUpdate is fatal: This crate cannot switch traffic - // keys, so every read after the peer rekeys would fail - // to decrypt. Recent kernels (6.14+) support rekeying, - // but it's not implemented here. - return task::Poll::Ready(Err(io::Error::new( - io::ErrorKind::Unsupported, - "peer sent a TLS 1.3 KeyUpdate, which is currently unsupported by the ktls crate", - ))); - } - Some(&MSG_NEW_SESSION_TICKET) => { - // NewSessionTicket is safe to ignore: A ticket only - // matters if you want to resume later. Dropping it - // doesn't affect the current connection. - tracing::trace!("ignoring NewSessionTicket"); - } - other => { - tracing::trace!(?other, "ignoring unexpected handshake message"); - } - } +impl KtlsStream +where + IO: AsRawFd, +{ + /// Receives and processes a pending TLS control message using `buf`'s + /// unfilled portion as scratch space without committing bytes to `buf`. + fn handle_control_message( + self: Pin<&mut Self>, + buf: &mut ReadBuf<'_>, + ) -> io::Result { + let this = self.project(); + let fd = this.inner.as_raw_fd(); + + // XXX: recvmsg wants a `&mut Vec` so it's able to resize it + // I guess? Or so there's a clear separation between uninitialized + // and initialized? We could probably get read of that heap alloc, idk. + + // let mut cmsgspace = + // [0u8; unsafe { libc::CMSG_SPACE(std::mem::size_of::() as _) as _ }]; + let mut cmsgspace = + Vec::with_capacity(unsafe { libc::CMSG_SPACE(std::mem::size_of::() as _) as _ }); + + let mut iov = [IoSliceMut::new(buf.initialize_unfilled())]; + let flags = MsgFlags::empty(); + + let r = recvmsg::(fd, &mut iov, Some(&mut cmsgspace), flags); + let r = match r { + Ok(r) => r, + Err(Errno::EAGAIN) => { + unreachable!("expected a control message, got EAGAIN") + } + Err(e) => { + // ok I guess it really failed then + tracing::trace!(?e, "recvmsg failed"); + return Err(e.into()); + } + }; + let cmsg = r + .cmsgs()? + .next() + .expect("we should've received exactly one control message"); + + let record_type = match cmsg { + ControlMessageOwned::TlsGetRecordType(t) => t, + _ => panic!("unexpected cmsg type: {cmsg:#?}"), + }; + + let outcome = match record_type { + TlsGetRecordType::ChangeCipherSpec => { + panic!("change_cipher_spec isn't supported by the ktls crate") + } + TlsGetRecordType::Alert => { + // the alert level and description are in iovs + let iov = r + .iovs() + .next() + .expect("expected data in iovs"); + + let (level, description) = match iov { + [] => { + // we have an early return case for that + unreachable!(); } - TlsGetRecordType::ApplicationData => { - unreachable!( - "received TLS application in recvmsg, this is supposed to happen in the poll_read codepath" + &[level] => { + // https://github.com/facebookincubator/fizz/blob/fff6d9d49d3c554ab66b58822d1e1fe93e8d80f2/fizz/experimental/ktls/AsyncKTLSSocket.cpp#L144 + // + // Since all alerts (even warning-level alerts) + // signal the abort of a TLS session, we do not + // need to worry about additional application + // data. + // + // If we only have half the alert (because the + // user passed a buffer of size 1), just assume + // it's a close_notify + ( + TlsAlertLevel::from_primitive(level), + TlsAlertDescription::CloseNotify, ) } - TlsGetRecordType::Unknown(t) => { - // just ignore the record? - tracing::trace!("received record_type {t:#?}"); - } + &[level, description] => ( + TlsAlertLevel::from_primitive(level), + TlsAlertDescription::from_primitive(description), + ), _ => { - tracing::trace!("received unsupported record type"); + unreachable!("TLS alerts are exactly 2 bytes, your kTLS is misbehaving"); } }; - // FIXME: this is hacky, but can we do better? - // after we handled (..ignored) the control message, we don't - // know whether the socket is still ready to be read or not. - // - // we could try looping (tricky code structure), but we can't, - // for example, just call `poll_read`, which might fail not - // with EAGAIN/EWOULDBLOCK, but because _another_ control - // message is available. - cx.waker().wake_by_ref(); - return task::Poll::Pending; - } - } + // https://datatracker.ietf.org/doc/html/rfc5246#section-7.2 + // alerts we should handle are ones with fatal level or a + // close_notify + if matches!( + (level, description), + (_, TlsAlertDescription::CloseNotify) | (TlsAlertLevel::Fatal, _) + ) { + tracing::trace!(?level, ?description, "got TLS alert"); + *this.read_closed = true; + *this.write_closed = true; + if let Err(e) = send_close_notify(fd) { + // This can fail in case of a full send buffer (EAGAIN), + // or a dead socket. Ignore the error, as replying with + // close_notify is best-effort. + tracing::trace!("failed to reply with close_notify: {e}"); + } + // the file descriptor will be closed when the stream is dropped, + // we already protect against writes-after-close_notify through + // the write_closed flag + } - if let task::Poll::Ready(Ok(())) = &read_res { - if buf.filled().len() == filled_before { - // A transport EOF before the peer's close_notify means the stream was - // truncated--possibly by an attacker, since a TCP FIN is not - // authenticated. Report it as an error. - return task::Poll::Ready(Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "peer closed connection without sending TLS close_notify", - ))); + ControlMessageOutcome::Eof } - } + TlsGetRecordType::Handshake => { + // https://www.rfc-editor.org/info/rfc9846/#appendix-B.3 + const MSG_NEW_SESSION_TICKET: u8 = 4; + const MSG_KEY_UPDATE: u8 = 24; + let message_type = r + .iovs() + .next() + .and_then(|iov| iov.first()); + match message_type { + Some(&MSG_KEY_UPDATE) => { + // KeyUpdate is fatal: This crate cannot switch traffic + // keys, so every read after the peer rekeys would fail + // to decrypt. Recent kernels (6.14+) support rekeying, + // but it's not implemented here. + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "peer sent a TLS 1.3 KeyUpdate, which is currently unsupported by the ktls crate", + )); + } + Some(&MSG_NEW_SESSION_TICKET) => { + // NewSessionTicket is safe to ignore: A ticket only + // matters if you want to resume later. Dropping it + // doesn't affect the current connection. + tracing::trace!("ignoring NewSessionTicket"); + ControlMessageOutcome::Continue + } + other => { + tracing::trace!(?other, "ignoring unexpected handshake message"); + ControlMessageOutcome::Continue + } + } + } + TlsGetRecordType::ApplicationData => { + unreachable!( + "received TLS application in recvmsg, this is supposed to happen in the poll_read codepath" + ) + } + TlsGetRecordType::Unknown(t) => { + // just ignore the record? + tracing::trace!("received record_type {t:#?}"); + ControlMessageOutcome::Continue + } + _ => { + tracing::trace!("received unsupported record type"); + ControlMessageOutcome::Continue + } + }; - read_res + Ok(outcome) } }