flooder.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. collections::{HashMap, HashSet},
  20. sync::Arc,
  21. };
  22. use darkfi::{
  23. net::{channel::ChannelPtr, P2pPtr},
  24. rpc::jsonrpc::JsonSubscriber,
  25. system::{ExecutorPtr, StoppableTask, StoppableTaskPtr},
  26. Error, Result,
  27. };
  28. use log::{debug, error, info};
  29. use smol::lock::Mutex;
  30. use tinyjson::JsonValue;
  31. use crate::proto::{
  32. protocol_bar::Bar,
  33. protocol_foo::{FooRequest, FooResponse},
  34. };
  35. /// Atomic pointer to the Denial-of-service Analysis Multitool flooder.
  36. pub type DamFlooderPtr = Arc<DamFlooder>;
  37. /// Denial-of-service Analysis Multitool flooder.
  38. pub struct DamFlooder {
  39. /// P2P network pointer
  40. p2p: P2pPtr,
  41. /// Executor to spawn flooding tasks
  42. executor: ExecutorPtr,
  43. /// Set to keep track of all the spawned tasks
  44. tasks: Arc<Mutex<HashSet<StoppableTaskPtr>>>,
  45. }
  46. impl DamFlooder {
  47. /// Initialize a Denial-of-service Analysis Multitool flooder.
  48. pub fn init(p2p: &P2pPtr, ex: &ExecutorPtr) -> DamFlooderPtr {
  49. Arc::new(Self {
  50. p2p: p2p.clone(),
  51. executor: ex.clone(),
  52. tasks: Arc::new(Mutex::new(HashSet::new())),
  53. })
  54. }
  55. /// Start the Denial-of-service Analysis Multitool flooder.
  56. pub async fn start(&self, subscribers: &HashMap<&'static str, JsonSubscriber>, limit: u32) {
  57. info!(
  58. target: "damd::flooder::DamFlooder::start",
  59. "Starting the Denial-of-service Analysis Multitool flooder..."
  60. );
  61. // Check if tasks already exist
  62. let mut lock = self.tasks.lock().await;
  63. if !lock.is_empty() {
  64. info!(
  65. target: "damd::flooder::DamFlooder::start",
  66. "Denial-of-service Analysis Multitool flooder already started!"
  67. );
  68. return
  69. }
  70. // Spawn a task for each connected peer for `Foo` messages, since we expect responses
  71. for peer in self.p2p.hosts().channels() {
  72. let task = StoppableTask::new();
  73. task.clone().start(
  74. flood_foo(self.p2p.settings().read().await.outbound_connect_timeout, peer, subscribers.get("attack_foo").unwrap().clone(), limit),
  75. |res| async move {
  76. match res {
  77. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  78. Err(e) => error!(target: "damd::Damd::start", "Failed starting flood foo task: {e}")
  79. }
  80. },
  81. Error::DetachedTaskStopped,
  82. self.executor.clone(),
  83. );
  84. lock.insert(task);
  85. }
  86. // Spawn a task for `Bar` messages to broadcast to everyone
  87. let task = StoppableTask::new();
  88. task.clone().start(
  89. flood_bar(self.p2p.clone(), subscribers.get("attack_bar").unwrap().clone(), limit),
  90. |res| async move {
  91. match res {
  92. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  93. Err(e) => {
  94. error!(target: "damd::Damd::start", "Failed starting flood bar task: {e}")
  95. }
  96. }
  97. },
  98. Error::DetachedTaskStopped,
  99. self.executor.clone(),
  100. );
  101. lock.insert(task);
  102. info!(
  103. target: "damd::flooder::DamFlooder::start",
  104. "Denial-of-service Analysis Multitool flooder started successfully!"
  105. );
  106. }
  107. /// Stop the Denial-of-service Analysis flooder.
  108. pub async fn stop(&self) {
  109. info!(target: "damd::flooder::DamFlooder::stop", "Terminating Denial-of-service Analysis Multitool flooder...");
  110. // Check if tasks already terminated
  111. let mut lock = self.tasks.lock().await;
  112. if lock.is_empty() {
  113. info!(
  114. target: "damd::flooder::DamFlooder::start",
  115. "Denial-of-service Analysis Multitool flooder already terminated!"
  116. );
  117. return
  118. }
  119. // Terminate the tasks
  120. for task in lock.iter() {
  121. task.stop().await;
  122. }
  123. // Clean the set
  124. *lock = HashSet::new();
  125. info!(target: "damd::flooder::DamFlooder::stop", "Denial-of-service Analysis Multitool flooder terminated successfully!");
  126. }
  127. }
  128. /// Background flooder function for `ProtocolFoo`.
  129. async fn flood_foo(
  130. comms_timeout: u64,
  131. peer: ChannelPtr,
  132. subscriber: JsonSubscriber,
  133. limit: u32,
  134. ) -> Result<()> {
  135. debug!(target: "damd::flooder::flood_foo", "START");
  136. // Communication setup
  137. let Ok(response_sub) = peer.subscribe_msg::<FooResponse>().await else {
  138. let notification =
  139. format!("Failure during `FooResponse` communication setup with peer: {peer:?}");
  140. error!(target: "damd::flooder::flood_foo", "{notification}");
  141. subscriber.notify(vec![JsonValue::String(notification)].into()).await;
  142. return Ok(())
  143. };
  144. // Flood the peer
  145. let mut message_index = 0;
  146. loop {
  147. // Node creates a `FooRequest` and sends it
  148. let message = format!("Flood message {message_index}");
  149. let notification = format!("Sending foo request to {peer:?}: {message}");
  150. info!(target: "damd::flooder::flood_foo", "{notification}");
  151. subscriber.notify(vec![JsonValue::String(notification)].into()).await;
  152. if let Err(e) = peer.send(&FooRequest { message }).await {
  153. let notification = format!("Failure during `FooRequest` send to peer {peer:?}: {e}");
  154. error!(target: "damd::flooder::flood_foo", "{notification}");
  155. subscriber.notify(vec![JsonValue::String(notification)].into()).await;
  156. return Ok(())
  157. };
  158. // Node waits for response
  159. let Ok(response) = response_sub.receive_with_timeout(comms_timeout).await else {
  160. let notification =
  161. format!("Timeout while waiting for `FooResponse` from peer: {peer:?}");
  162. error!(target: "damd::flooder::flood_foo", "{notification}");
  163. subscriber.notify(vec![JsonValue::String(notification)].into()).await;
  164. return Ok(())
  165. };
  166. // Notify subscriber
  167. let notification = format!("Retrieved foo response from {peer:?}: {}", response.code);
  168. info!(target: "damd::flooder::flood_foo", "{notification}");
  169. subscriber.notify(vec![JsonValue::String(notification)].into()).await;
  170. message_index += 1;
  171. // Check limit
  172. if limit != 0 && message_index > limit {
  173. debug!(target: "damd::flooder::flood_foo", "STOP");
  174. info!(target: "damd::flooder::flood_foo", "Flood limit reached!");
  175. return Ok(())
  176. }
  177. }
  178. }
  179. /// Background flooder function for `ProtocolBar`.
  180. async fn flood_bar(p2p: P2pPtr, subscriber: JsonSubscriber, limit: u32) -> Result<()> {
  181. debug!(target: "damd::flooder::flood_bar", "START");
  182. // Flood the network, if we are connected to peers
  183. let mut message_index = 0;
  184. while p2p.is_connected() {
  185. // Node creates a `Bar` message and broadcasts it
  186. let message = format!("Flood message {message_index}");
  187. let notification = format!("Broadcasting bar message: {message}");
  188. info!(target: "damd::flooder::flood_bar", "{notification}");
  189. subscriber.notify(vec![JsonValue::String(notification)].into()).await;
  190. p2p.broadcast(&Bar { message }).await;
  191. message_index += 1;
  192. // Check limit
  193. if limit != 0 && message_index > limit {
  194. debug!(target: "damd::flooder::flood_bar", "STOP");
  195. info!(target: "damd::flooder::flood_foo", "Flood limit reached!");
  196. return Ok(())
  197. }
  198. }
  199. debug!(target: "damd::flooder::flood_bar", "STOP");
  200. subscriber
  201. .notify(vec![JsonValue::String(String::from("We are not connected to any peers"))].into())
  202. .await;
  203. Ok(())
  204. }