use awc::{Client, ClientBuilder};
use actix_web::{web, App, HttpResponse, HttpServer, Responder, HttpRequest, HttpResponseBuilder};
use awc::http::header::{HeaderMap, HeaderName, HeaderValue};
use act;
use actix_web::web::{Bytes};
use std::fs::File;
use std::io::{BufRead, BufReader};
use actix_web::web::Payload;
use log::{info, warn, error};
use env_logger;
use bytes::{BytesMut};
use futures_util::stream::StreamExt;
use std::future::Future;
use std::time::Duration;
use std::io::Read;
use futures_util::TryStreamExt;
fn readlinesfirewall() -> Vec {
let file = match File::open("firewall.txt") {
Ok(file) => file,
Err(e) => {
error!("Failed to open firewall.txt: {:?}", e);
return Vec::new();
}
};
let reader = BufReader::new(file);
let mut rules = Vec::new();
code
for line in reader.lines() {
if let Ok(line) = line {
let parts: Vec<&str> = line.splitn(2, ')').collect();
if parts.len() == 2 {
let conditions_str = parts[0].trim().trim_start_matches('(');
let action = parts[1].trim().to_lowercase();
let mut conditions = Vec::new();
let main_parts: Vec<&str> = conditions_str.split("||").collect();
for part in main_parts {
let sub_parts: Vec<&str> = part.split("&&").collect();
for condition in sub_parts {
if let Some((key, value)) = condition.trim().split_once(':') {
let key = key.trim().to_lowercase();
conditions.push((key, value.trim().to_string()));
}
}
}
let operator = if conditions_str.contains("||") {
"||"
} else if conditions_str.contains("&&") {
"&&"
} else {
""
};
if !conditions.is_empty() {
rules.push(FirewallRule {conditions, operator: operator.to_string(), action });
}
}
}
}
rules
Assistant
}
async fn send_request_to_backend(req: HttpRequest, payload: web::Payload) -> HttpResponse {
let base_url = "https://lmarena.ai";
let path = req.uri().path_and_query().map(|x| x.as_str()).unwrap_or("");
let target_url = format!("{}{}", base_url, path);
code
// Create HTTP client
let client = Client::builder().timeout(Duration::from_secs(10)).finish();
// Prepare the request builder with the same method as the incoming request
let mut forward_request = client.request(req.method().clone(), &target_url);
// Forward headers from the original request
for (header_name, header_value) in req.headers() {
if !["host", "connection"].contains(&header_name.as_str()) {
forward_request = forward_request.insert_header((header_name.clone(), header_value.clone()));
}
}
// Send the request, streaming the body
match forward_request.send_stream(payload).await {
Ok(mut res) => {
let mut client_resp = HttpResponse::build(res.status());
// Forward response headers
for (header_name, header_value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
client_resp.insert_header((header_name.clone(), header_value.clone()));
}
// Stream the response body
client_resp.streaming(res)
}
Err(e) => {
error!("Failed to forward request: {:?}", e);
HttpResponse::InternalServerError().body(format!("Failed to forward request: {:?}", e))
}
}
}
async fn handle_request(req: HttpRequest, payload: web::Payload, firewall_rules: web::Data<Vec>) -> HttpResponse {
// Checking cookie
if let Some(cookie) = req.cookie("waiting_done") {
if !cookie.value().is_empty() {
return send_request_to_backend(req, payload).await;
}
}
code
// No valid cookie, check firewall rules
let (is_blocked, should_set_cookie, blocked_rule) = firewall(&req, &firewall_rules).await;
if is_blocked {
// Request is blocked by firewall
let block_message = match blocked_rule {
Some(rule_index) => format!("Request was blocked by firewall rule {}", rule_index),
None => "Request was blocked by firewall".to_string(),
};
HttpResponse::Forbidden().body(block_message)
} else if should_set_cookie {
// Only show waiting page for HTML requests
if req.headers().get("accept").map_or(false, |h| h.to_str().unwrap_or("").contains("text/html")) {
let html_content = r#"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Waiting</title>
<script>
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function redirectAfterDelay() {
setTimeout(() => {
setCookie('waiting_done', 'true', 1);
window.location.reload();
}, 2000);
}
</script>
</head>
<body onload="redirectAfterDelay()">
<h1>Wait two seconds...</h1>
</body>
</html>
"#;
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html_content)
} else {
// For non-HTML requests, forward immediately
send_request_to_backend(req, payload).await
}
} else {
// Request needs to be checked again
HttpResponse::Ok().body("Please try again")
}
}
async fn firewall(req: &HttpRequest, firewall_rules: &Vec) -> (bool, bool, Option) {
info!("Received request with headers:");
for (header, value) in req.headers() {
info!("{}: {:?}", header, value);
}
code
for (index, rule) in firewall_rules.iter().enumerate() {
info!("Checking rule {}: {:?}", index + 1, rule);
let should_block = if rule.operator == "||" {
rule.conditions.iter().any(|(header, value)| check_condition(req, header, value))
} else {
rule.conditions.iter().all(|(header, value)| check_condition(req, header, value))
};
info!("Rule {} should block: {}", index + 1, should_block);
if should_block {
info!("Rule {} matched: {:?}", index + 1, rule);
if rule.action == "block" {
warn!("Request blocked by firewall rule {}", index + 1);
return (true, false, Some(index + 1));
}
}
}
info!("Request passed firewall check");
(false, true, None)
Your Rust code sets up an Actix Web server that acts as a proxy with firewall capabilities. It reads firewall rules from a firewall.txt file, evaluates incoming requests against these rules, and either forwards the request to a backend server, blocks it, or presents a waiting page that sets a cookie to manage repeated checks. Below, I provide a detailed analysis of your code, highlighting potential issues, improvements, and best practices.
1. Code Structure and Flow
a. Overview
Imports: Your code imports necessary crates, including Actix Web (actix_web), Actix Web Client (awc), logging utilities, and standard library modules for file and I/O operations.
Data Structures:
FirewallRule: Represents a firewall rule with conditions, an operator (&& or ||), and an action (block or other actions).
Functions:
readlinesfirewall: Reads and parses firewall rules from firewall.txt.
send_request_to_backend: Forwards the incoming request to the backend server.
handle_request: Main handler that checks cookies and firewall rules to decide the request's fate.
firewall: Evaluates the request against the firewall rules.
check_condition: Helper function to evaluate individual header conditions.
main: Sets up the Actix Web server.
2. Detailed Analysis and Suggestions
a. Imports and Dependencies
Unnecessary Imports:
use act;: This doesn't correspond to a known crate or module in your context and will likely cause a compilation error. It should be removed unless you have a specific module named act.
Optimizing Imports:
Consider organizing imports to group related dependencies, which enhances readability. For example, group all actix_web imports together.
Operator: Using String for the operator is flexible but could lead to runtime errors if an invalid operator is provided. Consider using an enum for operator to restrict it to valid values (And, Or).
Currently, if firewall.txt fails to open, the function logs an error and returns an empty vector. It might be better to propagate the error upwards or handle it more gracefully, depending on your application's requirements.
Parsing Logic:
The parsing logic assumes each line in firewall.txt follows the format (conditions) action. Ensure that this format is strictly adhered to, or add more robust parsing with clear error messages for malformed lines.
Operator Detection:
The operator is detected based on the presence of || or && in the conditions string. This approach can fail if both operators are present or if conditions are more complex. Using an enum (as suggested above) can help manage this more effectively.
Excluding Host and Connection Headers: You're correctly removing host and connection headers, which is essential to prevent header conflicts and potential security issues.
Potential Improvements:
Other Headers: Consider excluding other hop-by-hop headers as defined by RFC 7230 Section 6.1, such as proxy-connection, keep-alive, te, trailer, transfer-encoding, and upgrade.
Immutable Headers: Some headers should not be forwarded or should be modified, such as User-Agent. Depending on your use case, you might need to handle these explicitly.
Timeout Configuration:
You're setting a timeout of 10 seconds. Ensure this aligns with your backend's expected response times to avoid unnecessary timeouts.
Error Handling:
Currently, any error in sending the request results in an InternalServerError. Depending on the error type, you might want to differentiate responses (e.g., BadGateway for upstream errors).
Security Considerations:
Ensure that the backend URL (https://lmarena.ai) is sanitized and cannot be manipulated via the incoming request to prevent Server-Side Request Forgery (SSRF).
Validation: You check for the presence and non-empty value of the waiting_done cookie. Depending on your requirements, you might want to validate the cookie's value more strictly (e.g., using signed or encrypted cookies to prevent tampering).
Security Flags: When setting cookies, consider adding security flags like HttpOnly, Secure, and SameSite to enhance security.
Response to Non-HTML Requests:
For non-HTML requests that require setting a cookie, you forward them immediately. Ensure this behavior aligns with your intended rate-limiting or request management strategy.
Waiting Page:
User Experience: The waiting page sets a cookie after a 2-second delay and reloads the page. This mechanism can help mitigate rapid repeated requests.
Graceful Degradation: For clients that have JavaScript disabled, the waiting page might not function as intended. Consider handling such cases if relevant.
Final Else Clause:
The last else block returns "Please try again". This can result in unnecessary responses. Depending on the flow, you might want to revisit this logic to ensure it's serving a meaningful purpose.
Currently, all request headers are logged at the info level. This can lead to verbose logs and potential exposure of sensitive information. Consider reducing log verbosity or masking sensitive headers.
Rule Evaluation:
Short-Circuit Logic: Once a rule matches (especially with ||), you might want to proceed to the next rule rather than stopping, depending on your policy requirements.
Action Handling: Your implementation only handles the block action. If you plan to support other actions (like allow, redirect, etc.), you should implement corresponding logic.
Parallelism:
For efficiency, consider evaluating firewall rules in parallel if they are independent and performance is a concern. However, ensure thread safety with shared resources.
Return Values:
The tuple (bool, bool, Option<usize>) can be ambiguous. Consider defining a custom struct or using more descriptive return types to enhance readability.
HTTP header names are case-insensitive, but header values can be case-sensitive depending on the header. Ensure that case-insensitive comparisons are appropriate for each header.
Substring Matching:
Using contains for matching can lead to partial matches, which might not be desirable. Consider using exact matches or more sophisticated pattern matching as needed.
Performance:
Converting both the header value and the match value to lowercase for every comparison can be inefficient. Consider normalizing header values once or using case-insensitive comparison methods.
You're initializing the logger with env_logger, which is good. Ensure that your environment is correctly set up to capture and manage logs as intended.
Firewall Rules Loading:
Firewall rules are loaded once at startup and shared via web::Data. If you need dynamic updates to firewall rules without restarting the server, consider implementing a mechanism to reload or refresh these rules.
Server Binding:
The server binds to 127.0.0.1:8080, making it accessible only locally. Ensure this aligns with your deployment requirements. If you intend to expose the server externally, bind to 0.0.0.0 or the appropriate network interface.
rust
.bind(("0.0.0.0", 8080))?
Concurrency and Performance:
Actix Web is highly concurrent, but ensure that your firewall logic and backend forwarding can handle the expected load. Profile and optimize if necessary.
3. Security Considerations
Header Injection:
Ensure that forwarded headers do not inadvertently introduce vulnerabilities. For example, avoid forwarding sensitive headers or those that can influence backend behavior improperly.
Cookie Security:
As mentioned earlier, enhance the security of cookies by setting appropriate flags (HttpOnly, Secure, SameSite).
Backend URL Validation:
Ensure that the backend URL (https://lmarena.ai) is controlled and cannot be manipulated via incoming requests to prevent SSRF attacks.
Input Validation:
Validate all inputs, especially those from firewall.txt, to prevent configuration-based vulnerabilities.
Rate Limiting:
While the waiting page mechanism helps mitigate rapid requests, consider implementing more robust rate-limiting strategies if necessary.
4. Logging and Monitoring
Sensitive Data Exposure:
Be cautious about logging sensitive headers or request data. Mask or avoid logging such information to prevent data leakage.
Log Levels:
Use appropriate log levels (debug, info, warn, error) to categorize log messages. Avoid excessive use of higher verbosity levels in production environments.
Monitoring:
Implement monitoring to track firewall rule matches, blocked requests, and other critical events to maintain the health and security of your application.
5. Testing and Validation
Unit Tests:
Implement unit tests for functions like readlinesfirewall, firewall, and check_condition to ensure they behave as expected with various inputs.
Integration Tests:
Test the entire request flow, including firewall rule evaluation, backend forwarding, and cookie-based waiting mechanisms.
Edge Cases:
Consider and test edge cases, such as malformed firewall rules, missing headers, and high concurrency scenarios.
6. Performance Optimizations
Asynchronous Operations:
Ensure all I/O operations, especially file reading and network requests, are handled asynchronously to maximize performance.
Caching:
If firewall rules are computationally expensive to evaluate, consider caching results where applicable.
Connection Pooling:
The awc::Client is created per request. To optimize performance, consider reusing a single Client instance across requests to leverage connection pooling.
rust
// Initialize the client once
let client = Client::builder().timeout(Duration::from_secs(10)).finish();
// Pass it to the handler via web::Data
let client_data = web::Data::new(client);
// In send_request_to_backend, use the shared client
7. Example Improvements
Here's an example of how you might refactor some parts of your code based on the suggestions above:
Then, adjust send_request_to_backend to accept the shared client:
rust
async fn send_request_to_backend(
req: HttpRequest,
payload: web::Payload,
client: web::Data<Client>,
) -> HttpResponse {
// ... use `client` instead of creating a new one
}
Your code provides a solid foundation for a firewall-enabled proxy server using Actix Web. By implementing the suggested improvements, especially around error handling, type safety with enums, security best practices, and performance optimizations, you can enhance the robustness, maintainability, and security of your application.
Remember to thoroughly test each component, especially firewall rule parsing and request handling, to ensure that your application behaves as expected under various scenarios.
Happy coding!
Not yet included in a published release.
fn readlinesfirewall() -> Vec<FirewallRule> {
let file = match File::open("firewall.txt") {
Ok(file) => file,
Err(e) => {
error!("Failed to open firewall.txt: {:?}", e);
return Vec::new();
}
};
let reader = BufReader::new(file);
let mut rules = Vec::new();
for (line_num, line) in reader.lines().enumerate() {
if let Ok(line) = line {
let parts: Vec<&str> = line.splitn(2, ')').collect();
if parts.len() != 2 {
error!("Malformed line {}: {}", line_num + 1, line);
continue;
}
let conditions_str = parts[0].trim().trim_start_matches('(');
let action_str = parts[1].trim().to_lowercase();
// Determine operator
let operator = if conditions_str.contains("||") {
Operator::Or
} else if conditions_str.contains("&&") {
Operator::And
} else {
// Default operator or skip
Operator::And // or skip the rule
};
// Split conditions based on operator
let condition_delimiter = match operator {
Operator::Or => "||",
Operator::And => "&&",
};
let conditions = conditions_str
.split(condition_delimiter)
.filter_map(|condition| {
let parts: Vec<&str> = condition.trim().splitn(2, ':').collect();
if parts.len() == 2 {
Some((parts[0].trim().to_lowercase(), parts[1].trim().to_string()))
} else {
None
}
})
.collect();
let action = match action_str.as_str() {
"block" => Action::Block,
"allow" => Action::Allow,
// Handle other actions
_ => {
error!("Unknown action in line {}: {}", line_num + 1, action_str);
return None;
}
};
if !conditions.is_empty() {
rules.push(FirewallRule { conditions, operator, action });
}
}
}
rules
}