Skip to content

VM: make reference to interface instead of vhost#2013

Merged
limetech merged 7 commits into
unraid:masterfrom
bergware:master
Feb 12, 2025
Merged

VM: make reference to interface instead of vhost#2013
limetech merged 7 commits into
unraid:masterfrom
bergware:master

Conversation

@bergware

@bergware bergware commented Feb 11, 2025

Copy link
Copy Markdown
Contributor

This requires users to update their VM settings and use the interface name instead of the vhost name as network source.

This brings VMs inline with Docker which also shows the interface name for custom networks

Summary by CodeRabbit

  • New Features

    • Enhanced network detection now supports additional connection types, including bonded and Ethernet interfaces.
    • Improved filtering eliminates redundant network entries, ensuring a more accurate and streamlined overview for users.
    • WiFi service now clears the IP address associated with the specified interface upon stopping, enhancing cleanup processes.
    • New external script introduced for SSL encryption and decryption, improving security for user credentials.
    • Form updates prevent modification of MAC addresses for wireless interfaces, enhancing user experience.
  • Bug Fixes

    • Updated handling of user credentials to ensure they are encrypted when stored, enhancing security.

This requires users to update their VM settings and use the interface name instead of the vhost name as network source.

This brings VMs inline with Docker which also shows the interface name for custom networks
@coderabbitai

coderabbitai Bot commented Feb 11, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes enhance the detection and handling of network interfaces within the VM manager plugin. In libvirt.php, the get_nic_info function's regex is updated to include bond and eth interfaces. Similarly, in libvirt_helpers.php, the getValidNetworks function is modified to recognize these interfaces and includes logic to filter out redundant references. Additionally, the handling of user credentials and IP address flushing in the rc.wireless script is improved, along with a new external script for SSL encryption.

Changes

File(s) Change Summary
emhttp/.../libvirt.php Updated get_nic_info function: Changed the grep regex to include bond and eth interfaces along with the previous interfaces.
emhttp/.../libvirt_helpers.php Updated getValidNetworks function: Modified regex to include bond and eth interfaces; added logic to remove redundant references for bond and bridge interfaces; updated array structure accordingly.
etc/rc.d/rc.wireless Updated wifi_stop function: Added command to flush IP address associated with the specified interface when stopping the WiFi service; enhanced credential handling using OpenSSL.
emhttp/plugins/dynamix/include/update.wireless.php Changed SSL handling: Updated to utilize an external script for encryption instead of inline PHP functions; removed previous SSL configuration file handling.
emhttp/plugins/dynamix/scripts/open_ssl New script added: Created to handle encryption and decryption operations using OpenSSL, supporting command-line arguments for 'encrypt' and 'decrypt'.
emhttp/plugins/dynamix.vm.manager/templates/Custom.form.php Updated network interface form: Added logic to disable MAC address input for wlan0 and introduced a new function for managing MAC address input based on selected network type.

Possibly related PRs

  • Wireless support - fine tuning #2001: The changes in the main PR and this one both involve modifications to network interface handling, specifically updating regex patterns to include additional network types in their respective functions.
  • Wireless support - fine tuning #2002: The changes in the main PR modify the get_nic_info function to include additional network interface types, which is related to the retrieved PR's updates to network interface handling.
  • Wireless and VM improvements #2007: The main PR's updates to the get_nic_info function are related to modifications in the getValidNetworks function from the retrieved PR, as both involve changes to network interface patterns.

Poem

I'm a hopper with whiskers all aglow,
Leaping through changes in code below,
Regex now sings of bond and eth in tune,
Filtering duplicates under the digital moon,
With carrots and bytes, I celebrate each line,
A bunny's code hop—simply divine!
🥕🐰


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 76f0d68 and fd6a70e.

📒 Files selected for processing (1)
  • emhttp/plugins/dynamix.vm.manager/templates/Custom.form.php (4 hunks)
🔇 Additional comments (4)
emhttp/plugins/dynamix.vm.manager/templates/Custom.form.php (4)

1477-1478: Network interface handling enhancement for wireless adapters.

The code now disables MAC address input and generation when 'wlan0' is selected as the network source. This is a good security practice as wireless adapters typically require specific MAC addresses.

Also applies to: 1483-1484


1492-1493: Network source change event handler added.

Added onchange event handler to update MAC address field state based on the selected network interface. This provides better user experience by dynamically enabling/disabling MAC address input.


1558-1559: Network interface template updated for consistency.

The template code for new network interfaces follows the same pattern as the main form, ensuring consistent behavior for MAC address handling across both existing and new network interfaces.

Also applies to: 1564-1565


2008-2012: New updateMAC function implementation.

The function properly handles MAC address field state based on network interface selection:

  • Disables MAC input and generation for wlan0
  • Re-enables and regenerates MAC for other interfaces

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
emhttp/plugins/dynamix.vm.manager/include/libvirt_helpers.php (1)

1247-1258: Consider removing commented out code.

This section is commented out to prevent breaking VMSettings.page when libvirt is not running. If this code is no longer needed, consider removing it entirely rather than leaving it commented out.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d46686c and 234d380.

📒 Files selected for processing (2)
  • emhttp/plugins/dynamix.vm.manager/include/libvirt.php (1 hunks)
  • emhttp/plugins/dynamix.vm.manager/include/libvirt_helpers.php (1 hunks)
🔇 Additional comments (2)
emhttp/plugins/dynamix.vm.manager/include/libvirt.php (1)

634-634: LGTM! The regex pattern update aligns with the PR objectives.

The change extends network interface detection to include bond and eth interfaces, which aligns with the goal of using interface names instead of vhost names for VM network configuration.

Let's verify the impact of this change by checking for any network interface references in the codebase:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check for network interface references in the codebase.

# Search for network interface patterns in the codebase
echo "Searching for network interface patterns..."
rg -A 5 "((vir)?br|bond|eth|wlan)[0-9]+(\.[0-9]+)?"

Length of output: 126650


Regex Update Verified: The pattern now correctly includes bond and eth interfaces.

The search results confirm that in the file emhttp/plugins/dynamix.vm.manager/include/libvirt.php the new regex:

'^((vir)?br|bond|eth|wlan)[0-9]+(\.[0-9]+)?'

is in place to correctly detect interfaces named with the prefixes bond and eth (in addition to virbr and wlan). Other parts of the codebase (like Docker and network configuration files) also consistently reference interfaces such as bond0, eth0, etc., aligning with the PR objectives.

  • The change extends detection to include bond and eth interfaces for virtual machine network configuration.
  • It aligns with the project's goal of using interface names rather than vhost names.
  • No inconsistencies were found in related files where this regex might impact behavior.
emhttp/plugins/dynamix.vm.manager/include/libvirt_helpers.php (1)

1230-1246: Improved network interface detection and filtering logic.

The changes enhance the network interface detection by:

  1. Including bond and eth interfaces in addition to bridges
  2. Filtering out redundant interfaces that are part of bonds or bridges
  3. Providing a cleaner, more accurate list of available network interfaces

This aligns well with the PR objective of using interface names instead of vhost names.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 234d380 and f9097ed.

📒 Files selected for processing (1)
  • etc/rc.d/rc.wireless (1 hunks)

Comment thread etc/rc.d/rc.wireless Outdated
When user name and password are stored in plain text, these will be encrypted at start up.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🔭 Outside diff range comments (1)
emhttp/plugins/dynamix/scripts/open_ssl (1)

1-29: 🛠️ Refactor suggestion

Consider adding input validation and rate limiting.

To prevent potential abuse, consider adding:

  1. Input length limits
  2. Rate limiting
  3. Input character validation

Apply this diff to add these security measures:

+// Add at the beginning of the file
+define('MAX_INPUT_LENGTH', 1024);
+define('RATE_LIMIT_FILE', '/tmp/ssl_operations');
+define('RATE_LIMIT_SECONDS', 60);
+define('RATE_LIMIT_OPERATIONS', 100);
+
+function checkRateLimit() {
+    $operations = @file_get_contents(RATE_LIMIT_FILE) ?: '{}';
+    $operations = json_decode($operations, true) ?: [];
+    $now = time();
+    
+    // Clean old entries
+    $operations = array_filter($operations, fn($time) => $time > $now - RATE_LIMIT_SECONDS);
+    
+    // Check limit
+    if (count($operations) >= RATE_LIMIT_OPERATIONS) {
+        error_log("Rate limit exceeded");
+        exit(1);
+    }
+    
+    // Add new operation
+    $operations[] = $now;
+    file_put_contents(RATE_LIMIT_FILE, json_encode($operations));
+}
+
+function validateInput($input) {
+    if (strlen($input) > MAX_INPUT_LENGTH) {
+        error_log("Input exceeds maximum length");
+        return false;
+    }
+    if (!preg_match('/^[\w\s@.-]+$/', $input)) {
+        error_log("Input contains invalid characters");
+        return false;
+    }
+    return true;
+}
+
+// Add before the switch statement
+checkRateLimit();
+if (!empty($argv[2]) && !validateInput($argv[2])) {
+    exit(1);
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d7aa0f and 300bd2d.

📒 Files selected for processing (3)
  • emhttp/plugins/dynamix/include/update.wireless.php (1 hunks)
  • emhttp/plugins/dynamix/scripts/open_ssl (1 hunks)
  • etc/rc.d/rc.wireless (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • etc/rc.d/rc.wireless

Comment on lines +17 to +18
if (!empty($_POST['USERNAME'])) $_POST['USERNAME'] = exec("$open_ssl encrypt \"{$_POST['USERNAME']}\"");
if (!empty($_POST['PASSWORD'])) $_POST['PASSWORD'] = exec("$open_ssl encrypt \"{$_POST['PASSWORD']}\"");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add input validation and error handling for encryption.

The current implementation has several security and reliability concerns:

  1. Using exec with user input without proper validation is potentially dangerous.
  2. No error handling for failed encryption attempts.
  3. No validation of the encryption results.

Apply this diff to improve security and reliability:

-if (!empty($_POST['USERNAME'])) $_POST['USERNAME'] = exec("$open_ssl encrypt \"{$_POST['USERNAME']}\"");
-if (!empty($_POST['PASSWORD'])) $_POST['PASSWORD'] = exec("$open_ssl encrypt \"{$_POST['PASSWORD']}\"");
+function safeEncrypt($value) {
+    if (empty($value)) return '';
+    // Validate input contains only allowed characters
+    if (!preg_match('/^[\w\s@.-]+$/', $value)) {
+        error_log("Invalid characters in input");
+        return '';
+    }
+    // Escape shell arguments properly
+    $escaped = escapeshellarg($value);
+    // Execute with error checking
+    $result = exec("$GLOBALS[open_ssl] encrypt $escaped 2>&1", $output, $returnCode);
+    if ($returnCode !== 0) {
+        error_log("Encryption failed: " . implode("\n", $output));
+        return '';
+    }
+    return $result;
+}
+
+$_POST['USERNAME'] = safeEncrypt($_POST['USERNAME']);
+$_POST['PASSWORD'] = safeEncrypt($_POST['PASSWORD']);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!empty($_POST['USERNAME'])) $_POST['USERNAME'] = exec("$open_ssl encrypt \"{$_POST['USERNAME']}\"");
if (!empty($_POST['PASSWORD'])) $_POST['PASSWORD'] = exec("$open_ssl encrypt \"{$_POST['PASSWORD']}\"");
function safeEncrypt($value) {
if (empty($value)) return '';
// Validate input contains only allowed characters
if (!preg_match('/^[\w\s@.-]+$/', $value)) {
error_log("Invalid characters in input");
return '';
}
// Escape shell arguments properly
$escaped = escapeshellarg($value);
// Execute with error checking
$result = exec("$GLOBALS[open_ssl] encrypt $escaped 2>&1", $output, $returnCode);
if ($returnCode !== 0) {
error_log("Encryption failed: " . implode("\n", $output));
return '';
}
return $result;
}
$_POST['USERNAME'] = safeEncrypt($_POST['USERNAME']);
$_POST['PASSWORD'] = safeEncrypt($_POST['PASSWORD']);

Comment on lines +18 to +27
switch ($argv[1]) {
case 'encrypt':
if (!empty($argv[2]) && isset($cipher,$key,$iv)) $encrypt = openssl_encrypt($argv[2],$cipher,$key,0,$iv);
if (!empty($encrypt)) echo "$encrypt";
break;
case 'decrypt':
if (!empty($argv[2]) && isset($cipher,$key,$iv)) $decrypt = openssl_decrypt($argv[2],$cipher,$key,0,$iv);
if (!empty($decrypt)) echo "$decrypt";
break;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve error handling and add logging.

The current implementation silently fails and doesn't provide feedback for troubleshooting.

Apply this diff to add proper error handling:

 switch ($argv[1]) {
 case 'encrypt':
-  if (!empty($argv[2]) && isset($cipher,$key,$iv)) $encrypt = openssl_encrypt($argv[2],$cipher,$key,0,$iv);
-  if (!empty($encrypt)) echo "$encrypt";
+  if (empty($argv[2])) {
+    error_log("No input provided for encryption");
+    exit(1);
+  }
+  $encrypt = openssl_encrypt($argv[2], $cipher, $key, 0, $iv);
+  if ($encrypt === false) {
+    error_log("Encryption failed: " . openssl_error_string());
+    exit(1);
+  }
+  echo $encrypt;
   break;
 case 'decrypt':
-  if (!empty($argv[2]) && isset($cipher,$key,$iv)) $decrypt = openssl_decrypt($argv[2],$cipher,$key,0,$iv);
-  if (!empty($decrypt)) echo "$decrypt";
+  if (empty($argv[2])) {
+    error_log("No input provided for decryption");
+    exit(1);
+  }
+  $decrypt = openssl_decrypt($argv[2], $cipher, $key, 0, $iv);
+  if ($decrypt === false) {
+    error_log("Decryption failed: " . openssl_error_string());
+    exit(1);
+  }
+  echo $decrypt;
   break;
+default:
+  error_log("Invalid command. Use 'encrypt' or 'decrypt'");
+  exit(1);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
switch ($argv[1]) {
case 'encrypt':
if (!empty($argv[2]) && isset($cipher,$key,$iv)) $encrypt = openssl_encrypt($argv[2],$cipher,$key,0,$iv);
if (!empty($encrypt)) echo "$encrypt";
break;
case 'decrypt':
if (!empty($argv[2]) && isset($cipher,$key,$iv)) $decrypt = openssl_decrypt($argv[2],$cipher,$key,0,$iv);
if (!empty($decrypt)) echo "$decrypt";
break;
}
switch ($argv[1]) {
case 'encrypt':
if (empty($argv[2])) {
error_log("No input provided for encryption");
exit(1);
}
$encrypt = openssl_encrypt($argv[2], $cipher, $key, 0, $iv);
if ($encrypt === false) {
error_log("Encryption failed: " . openssl_error_string());
exit(1);
}
echo $encrypt;
break;
case 'decrypt':
if (empty($argv[2])) {
error_log("No input provided for decryption");
exit(1);
}
$decrypt = openssl_decrypt($argv[2], $cipher, $key, 0, $iv);
if ($decrypt === false) {
error_log("Decryption failed: " . openssl_error_string());
exit(1);
}
echo $decrypt;
break;
default:
error_log("Invalid command. Use 'encrypt' or 'decrypt'");
exit(1);
}

Comment on lines +15 to +16
$ssl_input = '/etc/rc.d/rc.ssl.input';
if (is_readable($ssl_input)) extract(parse_ini_file($ssl_input));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Validate SSL configuration file contents.

The current implementation doesn't validate the INI file contents, which could lead to security issues if the file is corrupted or tampered with.

Apply this diff to add validation:

-if (is_readable($ssl_input)) extract(parse_ini_file($ssl_input));
+function validateSSLConfig($config) {
+    $required = ['cipher', 'key', 'iv'];
+    foreach ($required as $param) {
+        if (empty($config[$param])) {
+            error_log("Missing required SSL parameter: $param");
+            return false;
+        }
+    }
+    // Validate cipher is supported
+    if (!in_array($config['cipher'], openssl_get_cipher_methods())) {
+        error_log("Unsupported cipher method: {$config['cipher']}");
+        return false;
+    }
+    return true;
+}
+
+$config = [];
+if (is_readable($ssl_input)) {
+    $config = parse_ini_file($ssl_input);
+    if (!$config || !validateSSLConfig($config)) {
+        error_log("Invalid SSL configuration");
+        exit(1);
+    }
+    extract($config);
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$ssl_input = '/etc/rc.d/rc.ssl.input';
if (is_readable($ssl_input)) extract(parse_ini_file($ssl_input));
$ssl_input = '/etc/rc.d/rc.ssl.input';
function validateSSLConfig($config) {
$required = ['cipher', 'key', 'iv'];
foreach ($required as $param) {
if (empty($config[$param])) {
error_log("Missing required SSL parameter: $param");
return false;
}
}
// Validate cipher is supported
if (!in_array($config['cipher'], openssl_get_cipher_methods())) {
error_log("Unsupported cipher method: {$config['cipher']}");
return false;
}
return true;
}
$config = [];
if (is_readable($ssl_input)) {
$config = parse_ini_file($ssl_input);
if (!$config || !validateSSLConfig($config)) {
error_log("Invalid SSL configuration");
exit(1);
}
extract($config);
}

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
emhttp/plugins/dynamix/scripts/open_ssl (2)

15-16: ⚠️ Potential issue

Improve SSL configuration handling.

The current implementation doesn't validate the INI file contents, which could lead to security issues if the file is corrupted or tampered with.

Apply this diff to add validation:

-if (is_readable($ssl_input)) extract(parse_ini_file($ssl_input));
+function validateSSLConfig($config) {
+    $required = ['cipher', 'key', 'iv'];
+    foreach ($required as $param) {
+        if (empty($config[$param])) {
+            error_log("Missing required SSL parameter: $param");
+            return false;
+        }
+    }
+    // Validate cipher is supported
+    if (!in_array($config['cipher'], openssl_get_cipher_methods())) {
+        error_log("Unsupported cipher method: {$config['cipher']}");
+        return false;
+    }
+    return true;
+}
+
+$config = [];
+if (is_readable($ssl_input)) {
+    $config = parse_ini_file($ssl_input);
+    if (!$config || !validateSSLConfig($config)) {
+        error_log("Invalid SSL configuration");
+        exit(1);
+    }
+    extract($config);
+}

27-33: ⚠️ Potential issue

Improve error handling in encryption/decryption operations.

The current implementation silently fails and doesn't provide feedback for troubleshooting.

Apply this diff to add proper error handling:

 case 'encrypt':
-  if (!empty($argv[2]) && isset($cipher,$key,$iv)) $encrypt = openssl_encrypt($argv[2],$cipher,$key,0,$iv);
-  if (!empty($encrypt)) echo "$encrypt";
+  if (empty($argv[2])) {
+    error_log("No input provided for encryption");
+    exit(1);
+  }
+  $encrypt = openssl_encrypt($argv[2], $cipher, $key, 0, $iv);
+  if ($encrypt === false) {
+    error_log("Encryption failed: " . openssl_error_string());
+    exit(1);
+  }
+  echo $encrypt;
   break;
 case 'decrypt':
-  if (!empty($argv[2]) && isset($cipher,$key,$iv)) $decrypt = openssl_decrypt($argv[2],$cipher,$key,0,$iv);
-  if (!empty($decrypt)) echo "$decrypt";
+  if (empty($argv[2])) {
+    error_log("No input provided for decryption");
+    exit(1);
+  }
+  $decrypt = openssl_decrypt($argv[2], $cipher, $key, 0, $iv);
+  if ($decrypt === false) {
+    error_log("Decryption failed: " . openssl_error_string());
+    exit(1);
+  }
+  echo $decrypt;
🧹 Nitpick comments (1)
etc/rc.d/rc.wireless (1)

13-13: Use a configurable path for the OpenSSL script.

The path to the OpenSSL script is hardcoded, which could cause issues if the installation directory changes.

Apply this diff to make the path configurable:

-OPENSSL="/usr/local/emhttp/webGui/scripts/open_ssl"
+: ${OPENSSL:="/usr/local/emhttp/webGui/scripts/open_ssl"}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 300bd2d and 76f0d68.

📒 Files selected for processing (2)
  • emhttp/plugins/dynamix/scripts/open_ssl (1 hunks)
  • etc/rc.d/rc.wireless (4 hunks)
🔇 Additional comments (2)
etc/rc.d/rc.wireless (2)

210-210: Remove redundant IP address flush.

The IP address flush is redundant since ipaddr_down is already called earlier to handle IP address cleanup for both IPv4 and IPv6.

Remove the redundant line:

-    run ip addr flush dev $PORT

226-240: LGTM! Improved credential handling.

The changes improve security by:

  1. Encrypting plain credentials before storing
  2. Using the OpenSSL script for encryption/decryption
  3. Properly handling both encrypted and plain credentials

Comment on lines +22 to +24
$key = exec("dmidecode -qt1 | grep -Pom1 'Manufacturer: \K.+' | sed 's/ /_/g'")."ABCDEFGH";
$iv = "12".exec("cat /sys/class/net/wlan0/address | sed 's/://g'")."34";
file_put_contents($ssl_input, "cipher=aes-256-cbc\nkey=".substr($key,0,63)."\niv=$iv\n");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve key generation security.

The current key generation has several security concerns:

  1. Uses predictable system information for key generation
  2. Hardcoded values in the key and IV
  3. Fixed interface name 'wlan0' which may not exist

Apply this diff to improve security:

-  $key = exec("dmidecode -qt1 | grep -Pom1 'Manufacturer: \K.+' | sed 's/ /_/g'")."ABCDEFGH";
-  $iv  = "12".exec("cat /sys/class/net/wlan0/address | sed 's/://g'")."34";
-  file_put_contents($ssl_input, "cipher=aes-256-cbc\nkey=".substr($key,0,63)."\niv=$iv\n");
+  $key = bin2hex(random_bytes(32)); // Generate a secure random key
+  $iv = bin2hex(random_bytes(16));  // Generate a secure random IV
+  file_put_contents($ssl_input, "cipher=aes-256-gcm\nkey=$key\niv=$iv\n", LOCK_EX);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$key = exec("dmidecode -qt1 | grep -Pom1 'Manufacturer: \K.+' | sed 's/ /_/g'")."ABCDEFGH";
$iv = "12".exec("cat /sys/class/net/wlan0/address | sed 's/://g'")."34";
file_put_contents($ssl_input, "cipher=aes-256-cbc\nkey=".substr($key,0,63)."\niv=$iv\n");
$key = bin2hex(random_bytes(32)); // Generate a secure random key
$iv = bin2hex(random_bytes(16)); // Generate a secure random IV
file_put_contents($ssl_input, "cipher=aes-256-gcm\nkey=$key\niv=$iv\n", LOCK_EX);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants