Merge pull request #1002 from itflow-org/api-logins

Allow decrypting logins/credentials via the API
This commit is contained in:
Johnny 2024-08-25 15:18:34 -04:00 committed by GitHub
commit 21a31a1fe1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 386 additions and 61 deletions

View File

@ -1,5 +1,6 @@
<?php
$key = randomString(156);
$decryptPW = randomString(160);
?>
<div class="modal" id="addApiKeyModal" tabindex="-1">
<div class="modal-dialog">
@ -13,64 +14,103 @@ $key = randomString(156);
<form action="post.php" method="post" autocomplete="off">
<div class="modal-body bg-white">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?>">
<input type="hidden" name="key" value="<?php echo $key ?>">
<div class="form-group">
<label>API Key <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
</div>
<input type="text" class="form-control" value="<?php echo $key ?>" required disabled>
<div class="input-group-append">
<button class="btn btn-default clipboardjs" type="button" data-clipboard-text="<?php echo $key; ?>"><i class="fa fa-fw fa-copy"></i></button>
</div>
</div>
</div>
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-toggle="pill" href="#pills-api-details">Details</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="pill" href="#pills-api-keys">Keys</a>
</li>
</ul>
<hr>
<div class="form-group">
<label>Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-sticky-note"></i></span>
<div class="tab-content">
<div class="tab-pane fade show active" id="pills-api-details">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?>">
<input type="hidden" name="key" value="<?php echo $key ?>">
<input type="hidden" name="password" value="<?php echo $decryptPW ?>">
<div class="form-group">
<label>Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-sticky-note"></i></span>
</div>
<input type="text" class="form-control" name="name" placeholder="Key Name" required autofocus>
</div>
</div>
<div class="form-group">
<label>Expiration Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
</div>
<input type="date" class="form-control" name="expire" min="<?php echo date('Y-m-d')?>" max="2999-12-31" required>
</div>
</div>
<div class="form-group">
<label>Client Access <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
</div>
<select class="form-control select2" name="client" required>
<option value="0"> ALL CLIENTS </option>
<?php
$sql = mysqli_query($mysqli, "SELECT * FROM clients ORDER BY client_name ASC");
while ($row = mysqli_fetch_array($sql)) {
$client_id = intval($row['client_id']);
$client_name = nullable_htmlentities($row['client_name']); ?>
<option value="<?php echo $client_id; ?>"><?php echo "$client_name (Client ID: $client_id)"; ?></option>
<?php } ?>
</select>
</div>
</div>
<input type="text" class="form-control" name="name" placeholder="Key Name" required autofocus>
</div>
<div class="tab-pane fade" id="pills-api-keys">
<div class="form-group">
<label>API Key <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
</div>
<input type="text" class="form-control" value="<?php echo $key ?>" required disabled>
<div class="input-group-append">
<button class="btn btn-default clipboardjs" type="button" data-clipboard-text="<?php echo $key; ?>"><i class="fa fa-fw fa-copy"></i></button>
</div>
</div>
</div>
<div class="form-group">
<label>Login credential decryption password <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-unlock-alt"></i></span>
</div>
<input type="text" class="form-control" value="<?php echo $decryptPW ?>" required disabled>
<div class="input-group-append">
<button class="btn btn-default clipboardjs" type="button" data-clipboard-text="<?php echo $decryptPW; ?>"><i class="fa fa-fw fa-copy"></i></button>
</div>
</div>
</div>
<br>
<div class="form-group">
<label>I have made a copy of the key(s)<strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<input type="checkbox" name="ack" value="1" required>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label>Expiration Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
</div>
<input type="date" class="form-control" name="expire" min="<?php echo date('Y-m-d')?>" max="2999-12-31" required>
</div>
</div>
<div class="form-group">
<label>Client Access <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
</div>
<select class="form-control select2" name="client" required>
<option value="0"> ALL CLIENTS </option>
<?php
$sql = mysqli_query($mysqli, "SELECT * FROM clients ORDER BY client_name ASC");
while ($row = mysqli_fetch_array($sql)) {
$client_id = intval($row['client_id']);
$client_name = nullable_htmlentities($row['client_name']); ?>
<option value="<?php echo $client_id; ?>"><?php echo "$client_name (Client ID: $client_id)"; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="modal-footer bg-white">
<button type="submit" name="add_api_key" class="btn btn-primary text-bold"><i class="fa fa-check mr-2"></i>Create</button>
<button type="button" class="btn btn-light" data-dismiss="modal"><i class="fas fa-times mr-2"></i>Cancel</button>

View File

@ -0,0 +1,30 @@
<?php
require_once '../validate_api_key.php';
require_once '../require_post_method.php';
// Parse info
require_once 'credential_model.php';
// Default
$insert_id = false;
if (!empty($api_key_decrypt_password) && !empty($name) && !(empty($password))) {
// Add credential
$insert_sql = mysqli_query($mysqli,"INSERT INTO logins SET login_name = '$name', login_description = '$description', login_uri = '$uri', login_uri_2 = '$uri_2', login_username = '$username', login_password = '$password', login_otp_secret = '$otp_secret', login_note = '$note', login_important = $important, login_contact_id = $contact_id, login_vendor_id = $vendor_id, login_asset_id = $asset_id, login_software_id = $software_id, login_client_id = $client_id");
// Check insert & get insert ID
if ($insert_sql) {
$insert_id = mysqli_insert_id($mysqli);
//Logging
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Credential', log_action = 'Create', log_description = '$name via API ($api_key_name)', log_ip = '$ip', log_user_agent = '$user_agent', log_client_id = $client_id");
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'API', log_action = 'Success', log_description = 'Created credential $name via API ($api_key_name)', log_ip = '$ip', log_user_agent = '$user_agent', log_client_id = $client_id");
}
}
// Output
require_once '../create_output.php';

View File

@ -0,0 +1,120 @@
<?php
// Variable assignment from POST (or: blank/from DB is updating)
$api_key_decrypt_password = '';
if (isset($_POST['api_key_decrypt_password'])) {
$api_key_decrypt_password = $_POST['api_key_decrypt_password']; // No sanitization
}
if (isset($_POST['login_name'])) {
$name = sanitizeInput($_POST['login_name']);
} elseif (isset($credential_row) && isset($credential_row['login_name'])) {
$name = $credential_row['login_name'];
} else {
$name = '';
}
if (isset($_POST['login_description'])) {
$description = sanitizeInput($_POST['login_description']);
} elseif (isset($credential_row) && isset($credential_row['login_description'])) {
$description = $credential_row['login_description'];
} else {
$description = '';
}
if (isset($_POST['login_uri'])) {
$uri = sanitizeInput($_POST['login_uri']);
} elseif (isset($credential_row) && isset($credential_row['login_uri'])) {
$uri = $credential_row['login_uri'];
} else {
$uri = '';
}
if (isset($_POST['login_uri_2'])) {
$uri_2 = sanitizeInput($_POST['login_uri_2']);
} elseif (isset($credential_row) && isset($credential_row['login_uri_2'])) {
$uri_2 = $credential_row['login_uri_2'];
} else {
$uri_2 = '';
}
if (isset($_POST['login_username'])) {
$username = $_POST['login_username'];
$username = apiEncryptLoginEntry($username, $api_key_decrypt_hash, $api_key_decrypt_password);
} elseif (isset($credential_row) && isset($credential_row['login_username'])) {
$username = $credential_row['login_username'];
} else {
$username = '';
}
if (isset($_POST['login_password'])) {
$password = $_POST['login_password'];
$password = apiEncryptLoginEntry($password, $api_key_decrypt_hash, $api_key_decrypt_password);
$password_changed = true;
} elseif (isset($credential_row) && isset($credential_row['login_password'])) {
$password = $credential_row['login_password'];
$password_changed = false;
} else {
$password = '';
$password_changed = false;
}
if (isset($_POST['login_otp_secret'])) {
$otp_secret = sanitizeInput($_POST['login_otp_secret']);
} elseif (isset($credential_row) && isset($credential_row['login_otp_secret'])) {
$otp_secret = $credential_row['login_otp_secret'];
} else {
$otp_secret = '';
}
if (isset($_POST['login_note'])) {
$note = sanitizeInput($_POST['login_note']);
} elseif (isset($credential_row) && isset($credential_row['login_note'])) {
$note = $credential_row['login_note'];
} else {
$note = '';
}
if (isset($_POST['login_important'])) {
$important = intval($_POST['login_important']);
} elseif (isset($credential_row) && isset($credential_row['login_important'])) {
$important = $credential_row['login_important'];
} else {
$important = '';
}
if (isset($_POST['login_contact_id'])) {
$contact_id = intval($_POST['login_contact_id']);
} elseif (isset($credential_row) && isset($credential_row['login_contact_id'])) {
$contact_id = $credential_row['login_contact_id'];
} else {
$contact_id = '';
}
if (isset($_POST['login_vendor_id'])) {
$vendor_id = intval($_POST['login_vendor_id']);
} elseif (isset($credential_row) && isset($credential_row['login_vendor_id'])) {
$vendor_id = $credential_row['login_vendor_id'];
} else {
$vendor_id = '';
}
if (isset($_POST['login_asset_id'])) {
$asset_id = intval($_POST['login_asset_id']);
} elseif (isset($credential_row) && isset($credential_row['login_asset_id'])) {
$asset_id = $credential_row['login_asset_id'];
} else {
$asset_id = '';
}
if (isset($_POST['login_software_id'])) {
$software_id = intval($_POST['login_software_id']);
} elseif (isset($credential_row) && isset($credential_row['login_software_id'])) {
$software_id = $credential_row['login_software_id'];
} else {
$software_id = '';
}

View File

@ -0,0 +1,60 @@
<?php
require_once '../validate_api_key.php';
require_once '../require_get_method.php';
// Defaults
$sql = false;
$api_key_decrypt_password = '';
if (isset($_GET['api_key_decrypt_password'])) {
$api_key_decrypt_password = $_GET['api_key_decrypt_password']; // No sanitization
}
// Specific credential/login via ID (single)
if (isset($_GET['login_id']) && !empty($api_key_decrypt_password)) {
$id = intval($_GET['login_id']);
$sql = mysqli_query($mysqli, "SELECT * FROM logins WHERE login_id = '$id' AND login_client_id LIKE '$client_id' LIMIT 1");
} elseif (!empty($api_key_decrypt_password)) {
// All credentials ("logins")
$api_key_decrypt_password = $_GET['api_key_decrypt_password']; // No sanitization
$sql = mysqli_query($mysqli, "SELECT * FROM logins WHERE login_client_id LIKE '$client_id' ORDER BY login_id LIMIT $limit OFFSET $offset");
}
// Output - Not using the standard API read_output.php
// Usually we just output what is in the database, but credentials need to be decrypted first.
if ($sql && mysqli_num_rows($sql) > 0) {
$return_arr['success'] = "True";
$return_arr['count'] = mysqli_num_rows($sql);
$row = array();
while ($row = mysqli_fetch_array($sql)) {
$row['login_username'] = apiDecryptLoginEntry($row['login_username'], $api_key_decrypt_hash, $api_key_decrypt_password);
$row['login_password'] = apiDecryptLoginEntry($row['login_password'], $api_key_decrypt_hash, $api_key_decrypt_password);
$return_arr['data'][] = $row;
}
echo json_encode($return_arr);
exit();
}
else {
$return_arr['success'] = "False";
$return_arr['message'] = "No resource (for this client and company) with the specified parameter(s).";
// Log any database/schema related errors to the PHP Error log
if (mysqli_error($mysqli)) {
error_log("API Database Error: " . mysqli_error($mysqli));
}
echo json_encode($return_arr);
exit();
}

View File

@ -0,0 +1,38 @@
<?php
require_once '../validate_api_key.php';
require_once '../require_post_method.php';
// Parse ID
$login_id = intval($_POST['login_id']);
// Default
$update_count = false;
if (!empty($_POST['api_key_decrypt_password']) && !empty($login_id)) {
$credential_row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM logins WHERE login_id = '$login_id' AND login_client_id = $client_id LIMIT 1"));
// Variable assignment from POST - assigning the current database value if a value is not provided
require_once 'credential_model.php';
$update_sql = mysqli_query($mysqli,"UPDATE logins SET login_name = '$name', login_description = '$description', login_uri = '$uri', login_uri_2 = '$uri_2', login_username = '$username', login_password = '$password', login_otp_secret = '$otp_secret', login_note = '$note', login_important = $important, login_contact_id = $contact_id, login_vendor_id = $vendor_id, login_asset_id = $asset_id, login_software_id = $software_id, login_client_id = $client_id WHERE login_id = '$login_id' AND login_client_id = $client_id LIMIT 1");
// Check insert & get insert ID
if ($update_sql) {
$update_count = mysqli_affected_rows($mysqli);
if ($password_changed) {
mysqli_query($mysqli, "UPDATE logins SET login_password_changed_at = NOW() WHERE login_id = $login_id LIMIT 1");
}
//Logging
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Credential', log_action = 'Update', log_description = '$name via API ($api_key_name)', log_ip = '$ip', log_user_agent = '$user_agent', log_client_id = $client_id");
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'API', log_action = 'Success', log_description = 'Updated credential $name via API ($api_key_name)', log_ip = '$ip', log_user_agent = '$user_agent', log_client_id = $client_id");
}
}
// Output
require_once '../update_output.php';

View File

@ -88,6 +88,7 @@ if (isset($api_key)) {
// Set client ID, company ID & key name
$row = mysqli_fetch_array($sql);
$api_key_name = htmlentities($row['api_key_name']);
$api_key_decrypt_hash = $row['api_key_decrypt_hash']; // No sanitization
$client_id = intval($row['api_key_client_id']);
// Set limit & offset for queries

View File

@ -2123,13 +2123,18 @@ if (LATEST_DATABASE_VERSION > CURRENT_DATABASE_VERSION) {
// DB Version
mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '1.4.4'");
}
// if (CURRENT_DATABASE_VERSION == '1.4.4') {
// // Insert queries here required to update to DB version 1.4.5
if (CURRENT_DATABASE_VERSION == '1.4.4') {
mysqli_query($mysqli, "ALTER TABLE `api_keys` ADD `api_key_decrypt_hash` VARCHAR(200) NOT NULL AFTER `api_key_secret`");
mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '1.4.5'");
}
// if (CURRENT_DATABASE_VERSION == '1.4.5') {
// // Insert queries here required to update to DB version 1.4.6
// // Then, update the database to the next sequential version
// mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '1.4.5'");
// mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '1.4.6'");
// }
} else {

View File

@ -5,4 +5,4 @@
* It is used in conjunction with database_updates.php
*/
DEFINE("LATEST_DATABASE_VERSION", "1.4.4");
DEFINE("LATEST_DATABASE_VERSION", "1.4.5");

1
db.sql
View File

@ -66,6 +66,7 @@ CREATE TABLE `api_keys` (
`api_key_id` int(11) NOT NULL AUTO_INCREMENT,
`api_key_name` varchar(255) NOT NULL,
`api_key_secret` varchar(255) NOT NULL,
`api_key_decrypt_hash` varchar(255) NULL,
`api_key_created_at` datetime NOT NULL DEFAULT current_timestamp(),
`api_key_expire` date NOT NULL,
`api_key_client_id` int(11) NOT NULL DEFAULT 0,

View File

@ -271,7 +271,7 @@ function setupFirstUserSpecificKey($user_password, $site_encryption_master_key)
}
/*
* For additional users / password changes
* For additional users / password changes (and now the API)
* New Users: Requires the admin setting up their account have a Specific/Session key configured
* Password Changes: Will use the current info in the session.
*/
@ -282,7 +282,7 @@ function encryptUserSpecificKey($user_password)
// Get the session info.
$user_encryption_session_ciphertext = $_SESSION['user_encryption_session_ciphertext'];
$user_encryption_session_iv = $_SESSION['user_encryption_session_iv'];
$user_encryption_session_iv = $_SESSION['user_encryption_session_iv'];
$user_encryption_session_key = $_COOKIE['user_encryption_session_key'];
// Decrypt the session key to get the master key
@ -297,7 +297,7 @@ function encryptUserSpecificKey($user_password)
return $salt . $iv . $ciphertext;
}
// Given a ciphertext (incl. IV) and the user's password, returns the site master key
// Given a ciphertext (incl. IV) and the user's (or API key) password, returns the site master key
// Ran at login, to facilitate generateUserSessionKey
function decryptUserSpecificKey($user_encryption_ciphertext, $user_password)
{
@ -380,6 +380,32 @@ function encryptLoginEntry($login_password_cleartext)
return $iv . $ciphertext;
}
function apiDecryptLoginEntry($login_ciphertext, $api_key_decrypt_hash, #[\SensitiveParameter]$api_key_decrypt_password)
{
// Split the login entry (username/password) into IV and Ciphertext
$login_iv = substr($login_ciphertext, 0, 16);
$login_ciphertext = $salt = substr($login_ciphertext, 16);
// Decrypt the api hash to get the master key
$site_encryption_master_key = decryptUserSpecificKey($api_key_decrypt_hash, $api_key_decrypt_password);
// Decrypt the login password using the master key
return openssl_decrypt($login_ciphertext, 'aes-128-cbc', $site_encryption_master_key, 0, $login_iv);
}
function apiEncryptLoginEntry(#[\SensitiveParameter]$credential_cleartext, $api_key_decrypt_hash, #[\SensitiveParameter]$api_key_decrypt_password)
{
$iv = randomString();
// Decrypt the api hash to get the master key
$site_encryption_master_key = decryptUserSpecificKey($api_key_decrypt_hash, $api_key_decrypt_password);
// Encrypt the credential using the master key
$ciphertext = openssl_encrypt($credential_cleartext, 'aes-128-cbc', $site_encryption_master_key, 0, $iv);
return $iv . $ciphertext;
}
// Get domain general info (whois + NS/A/MX records)
function getDomainRecords($name)
{

View File

@ -11,12 +11,16 @@ if (isset($_POST['add_api_key'])) {
// CSRF Check
validateCSRFToken($_POST['csrf_token']);
$secret = sanitizeInput($_POST['key']);
$name = sanitizeInput($_POST['name']);
$expire = sanitizeInput($_POST['expire']);
$client = intval($_POST['client']);
$secret = sanitizeInput($_POST['key']); // API Key
mysqli_query($mysqli,"INSERT INTO api_keys SET api_key_name = '$name', api_key_secret = '$secret', api_key_expire = '$expire', api_key_client_id = $client");
// Credential decryption password
$password = password_hash(trim($_POST['password']), PASSWORD_DEFAULT);
$apikey_specific_encryption_ciphertext = encryptUserSpecificKey(trim($_POST['password']));
mysqli_query($mysqli,"INSERT INTO api_keys SET api_key_name = '$name', api_key_secret = '$secret', api_key_decrypt_hash = '$apikey_specific_encryption_ciphertext', api_key_expire = '$expire', api_key_client_id = $client");
$api_key_id = mysqli_insert_id($mysqli);