diff --git a/ajax.php b/ajax.php index 856e4402..52c5d5c6 100644 --- a/ajax.php +++ b/ajax.php @@ -6,161 +6,159 @@ * Always returns data in JSON format, unless otherwise specified */ -include("config.php"); -include("functions.php"); -include("check_login.php"); +require_once("config.php"); +require_once("functions.php"); +require_once("check_login.php"); require_once("rfc6238.php"); /* * Fetches SSL certificates from remote hosts & returns the relevant info (issuer, expiry, public key) */ -if(isset($_GET['certificate_fetch_parse_json_details'])){ - // PHP doesn't appreciate attempting SSL sockets to non-existent domains - if(empty($_GET['domain'])){ - exit(); - } - $domain = $_GET['domain']; +if (isset($_GET['certificate_fetch_parse_json_details'])) { + // PHP doesn't appreciate attempting SSL sockets to non-existent domains + if (empty($_GET['domain'])) { + exit(); + } + $domain = $_GET['domain']; - // FQDNs in database shouldn't have a URL scheme, adding one - $domain = "https://".$domain; + // FQDNs in database shouldn't have a URL scheme, adding one + $domain = "https://".$domain; - // Parse host and port - $url = parse_url($domain, PHP_URL_HOST); - $port = parse_url($domain, PHP_URL_PORT); - // Default port - if(!$port){ - $port = "443"; - } + // Parse host and port + $url = parse_url($domain, PHP_URL_HOST); + $port = parse_url($domain, PHP_URL_PORT); + // Default port + if (!$port) { + $port = "443"; + } - // Get certificate (using verify peer false to allow for self-signed certs) - $socket = "ssl://$url:$port"; - $get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE, "verify_peer" => FALSE,))); - $read = stream_socket_client($socket, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get); - $cert = stream_context_get_params($read); - $cert_public_key_obj = openssl_x509_parse($cert['options']['ssl']['peer_certificate']); - openssl_x509_export($cert['options']['ssl']['peer_certificate'], $export); + // Get certificate (using verify peer false to allow for self-signed certs) + $socket = "ssl://$url:$port"; + $get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE, "verify_peer" => FALSE,))); + $read = stream_socket_client($socket, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get); + $cert = stream_context_get_params($read); + $cert_public_key_obj = openssl_x509_parse($cert['options']['ssl']['peer_certificate']); + openssl_x509_export($cert['options']['ssl']['peer_certificate'], $export); - // Process data - if($cert_public_key_obj){ - $response['success'] = "TRUE"; - $response['expire'] = date('Y-m-d', $cert_public_key_obj['validTo_time_t']); - $response['issued_by'] = strip_tags($cert_public_key_obj['issuer']['O']); - $response['public_key'] = $export; //nl2br - } - else{ - $response['success'] = "FALSE"; - } + // Process data + if ($cert_public_key_obj) { + $response['success'] = "TRUE"; + $response['expire'] = date('Y-m-d', $cert_public_key_obj['validTo_time_t']); + $response['issued_by'] = strip_tags($cert_public_key_obj['issuer']['O']); + $response['public_key'] = $export; //nl2br + } else { + $response['success'] = "FALSE"; + } - echo json_encode($response); + echo json_encode($response); } /* * Looks up info for a given certificate ID from the database, used to dynamically populate modal fields */ -if(isset($_GET['certificate_get_json_details'])){ - validateTechRole(); +if (isset($_GET['certificate_get_json_details'])) { + validateTechRole(); - $certificate_id = intval($_GET['certificate_id']); - $client_id = intval($_GET['client_id']); + $certificate_id = intval($_GET['certificate_id']); + $client_id = intval($_GET['client_id']); - // Individual certificate lookup - $cert_sql = mysqli_query($mysqli,"SELECT * FROM certificates WHERE certificate_id = $certificate_id AND certificate_client_id = $client_id"); - while($row = mysqli_fetch_array($cert_sql)){ - $response['certificate'][] = $row; - } + // Individual certificate lookup + $cert_sql = mysqli_query($mysqli, "SELECT * FROM certificates WHERE certificate_id = $certificate_id AND certificate_client_id = $client_id"); + while ($row = mysqli_fetch_array($cert_sql)) { + $response['certificate'][] = $row; + } - // Get all domains for this client that could be linked to this certificate - $domains_sql = mysqli_query($mysqli, "SELECT domain_id, domain_name FROM domains WHERE domain_client_id = '$client_id' AND company_id = '$session_company_id'"); - while($row = mysqli_fetch_array($domains_sql)){ - $response['domains'][] = $row; - } + // Get all domains for this client that could be linked to this certificate + $domains_sql = mysqli_query($mysqli, "SELECT domain_id, domain_name FROM domains WHERE domain_client_id = '$client_id' AND company_id = '$session_company_id'"); + while ($row = mysqli_fetch_array($domains_sql)) { + $response['domains'][] = $row; + } - echo json_encode($response); + echo json_encode($response); } /* * Looks up info for a given domain ID from the database, used to dynamically populate modal fields */ -if(isset($_GET['domain_get_json_details'])){ - validateTechRole(); +if (isset($_GET['domain_get_json_details'])) { + validateTechRole(); - $domain_id = intval($_GET['domain_id']); - $client_id = intval($_GET['client_id']); + $domain_id = intval($_GET['domain_id']); + $client_id = intval($_GET['client_id']); - // Individual domain lookup - $cert_sql = mysqli_query($mysqli,"SELECT * FROM domains WHERE domain_id = $domain_id AND domain_client_id = $client_id"); - while($row = mysqli_fetch_array($cert_sql)){ - $response['domain'][] = $row; - } + // Individual domain lookup + $cert_sql = mysqli_query($mysqli, "SELECT * FROM domains WHERE domain_id = $domain_id AND domain_client_id = $client_id"); + while ($row = mysqli_fetch_array($cert_sql)) { + $response['domain'][] = $row; + } - // Get all registrars/webhosts (vendors) for this client that could be linked to this domain - $vendor_sql = mysqli_query($mysqli, "SELECT vendor_id, vendor_name FROM vendors WHERE vendor_client_id = $client_id"); - while($row = mysqli_fetch_array($vendor_sql)){ - $response['vendors'][] = $row; - } + // Get all registrars/webhosts (vendors) for this client that could be linked to this domain + $vendor_sql = mysqli_query($mysqli, "SELECT vendor_id, vendor_name FROM vendors WHERE vendor_client_id = $client_id"); + while ($row = mysqli_fetch_array($vendor_sql)) { + $response['vendors'][] = $row; + } - echo json_encode($response); + echo json_encode($response); } /* * Looks up info on the ticket number provided, used to populate the ticket merge modal */ -if(isset($_GET['merge_ticket_get_json_details'])){ - validateTechRole(); +if (isset($_GET['merge_ticket_get_json_details'])) { + validateTechRole(); - $merge_into_ticket_number = intval($_GET['merge_into_ticket_number']); + $merge_into_ticket_number = intval($_GET['merge_into_ticket_number']); - $sql = mysqli_query($mysqli,"SELECT * FROM tickets + $sql = mysqli_query($mysqli, "SELECT * FROM tickets LEFT JOIN clients ON ticket_client_id = client_id LEFT JOIN contacts ON ticket_contact_id = contact_id WHERE ticket_number = '$merge_into_ticket_number' AND tickets.company_id = '$session_company_id'"); - if(mysqli_num_rows($sql) == 0){ - //Do nothing. - } - else { - //Return ticket, client and contact details for the given ticket number - $response = mysqli_fetch_array($sql); - echo json_encode($response); - } + if (mysqli_num_rows($sql) == 0) { + //Do nothing. + } else { + //Return ticket, client and contact details for the given ticket number + $response = mysqli_fetch_array($sql); + echo json_encode($response); + } } /* * Looks up info for a given network ID from the database, used to dynamically populate modal fields */ -if(isset($_GET['network_get_json_details'])){ - validateTechRole(); +if (isset($_GET['network_get_json_details'])) { + validateTechRole(); - $network_id = intval($_GET['network_id']); - $client_id = intval($_GET['client_id']); + $network_id = intval($_GET['network_id']); + $client_id = intval($_GET['client_id']); - // Individual network lookup - $network_sql = mysqli_query($mysqli,"SELECT * FROM networks WHERE network_id = $network_id AND network_client_id = $client_id"); - while($row = mysqli_fetch_array($network_sql)){ - $response['network'][] = $row; - } + // Individual network lookup + $network_sql = mysqli_query($mysqli, "SELECT * FROM networks WHERE network_id = $network_id AND network_client_id = $client_id"); + while ($row = mysqli_fetch_array($network_sql)) { + $response['network'][] = $row; + } - // Lookup all client locations, as networks can be associated with any client location - $locations_sql = mysqli_query($mysqli, "SELECT location_id, location_name FROM locations + // Lookup all client locations, as networks can be associated with any client location + $locations_sql = mysqli_query($mysqli, "SELECT location_id, location_name FROM locations WHERE location_client_id = '$client_id' AND company_id = '$session_company_id'" - ); - while($row = mysqli_fetch_array($locations_sql)){ - $response['locations'][] = $row; - } + ); + while ($row = mysqli_fetch_array($locations_sql)) { + $response['locations'][] = $row; + } - echo json_encode($response); + echo json_encode($response); } -if(isset($_POST['client_set_notes'])){ - $client_id = intval($_POST['client_id']); - $notes = trim(strip_tags(mysqli_real_escape_string($mysqli, $_POST['notes']))); +if (isset($_POST['client_set_notes'])) { + $client_id = intval($_POST['client_id']); + $notes = trim(strip_tags(mysqli_real_escape_string($mysqli, $_POST['notes']))); - // Update notes - mysqli_query($mysqli, "UPDATE clients SET client_notes = '$notes' WHERE client_id = '$client_id'"); + // Update notes + mysqli_query($mysqli, "UPDATE clients SET client_notes = '$notes' WHERE client_id = '$client_id'"); - // Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Client', log_action = 'Modify', log_description = '$session_name modified client notes', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_created_at = NOW(), log_client_id = $client_id, log_user_id = $session_user_id, company_id = $session_company_id"); + // Logging + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Client', log_action = 'Modify', log_description = '$session_name modified client notes', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_created_at = NOW(), log_client_id = $client_id, log_user_id = $session_user_id, company_id = $session_company_id"); } @@ -169,10 +167,10 @@ if(isset($_POST['client_set_notes'])){ * Called upon loading a ticket, and every 2 mins thereafter * Is used in conjunction with ticket_query_views to show who is currently viewing a ticket */ -if(isset($_GET['ticket_add_view'])){ - $ticket_id = intval($_GET['ticket_id']); +if (isset($_GET['ticket_add_view'])) { + $ticket_id = intval($_GET['ticket_id']); - mysqli_query($mysqli, "INSERT INTO ticket_views SET view_ticket_id = '$ticket_id', view_user_id = '$session_user_id', view_timestamp = NOW()"); + mysqli_query($mysqli, "INSERT INTO ticket_views SET view_ticket_id = '$ticket_id', view_user_id = '$session_user_id', view_timestamp = NOW()"); } /* @@ -180,112 +178,112 @@ if(isset($_GET['ticket_add_view'])){ * Returns formatted text of the agents currently viewing a ticket * Called upon loading a ticket, and every 2 mins thereafter */ -if(isset($_GET['ticket_query_views'])){ - $ticket_id = intval($_GET['ticket_id']); +if (isset($_GET['ticket_query_views'])) { + $ticket_id = intval($_GET['ticket_id']); - $query = mysqli_query($mysqli, "SELECT user_name FROM ticket_views LEFT JOIN users ON view_user_id = user_id WHERE view_ticket_id = '$ticket_id' AND view_user_id != '$session_user_id' AND view_timestamp > DATE_SUB(NOW(), INTERVAL 2 MINUTE)"); - while($row = mysqli_fetch_array($query)){ - $users[] = $row['user_name']; - } - if(!empty($users)){ - $users = array_unique($users); - if(count($users) > 1){ - // Multiple viewers - $response['message'] = implode(", ", $users) . " are viewing this ticket."; + $query = mysqli_query($mysqli, "SELECT user_name FROM ticket_views LEFT JOIN users ON view_user_id = user_id WHERE view_ticket_id = '$ticket_id' AND view_user_id != '$session_user_id' AND view_timestamp > DATE_SUB(NOW(), INTERVAL 2 MINUTE)"); + while ($row = mysqli_fetch_array($query)) { + $users[] = $row['user_name']; } - else{ - // Single viewer - $response['message'] = implode("", $users) . " is viewing this ticket."; + + if (!empty($users)) { + $users = array_unique($users); + if (count($users) > 1) { + // Multiple viewers + $response['message'] = implode(", ", $users) . " are viewing this ticket."; + } else { + // Single viewer + $response['message'] = implode("", $users) . " is viewing this ticket."; + } + } else { + // No viewers + $response['message'] = ""; } - } - else{ - // No viewers - $response['message'] = ""; - } - echo json_encode($response); + + echo json_encode($response); } /* * Generates public/guest links for sharing logins/docs */ -if(isset($_GET['share_generate_link'])){ - validateTechRole(); +if (isset($_GET['share_generate_link'])) { + validateTechRole(); - $item_encrypted_credential = ''; // Default empty + $item_encrypted_credential = ''; // Default empty - $client_id = intval($_GET['client_id']); - $item_type = trim(strip_tags(mysqli_real_escape_string($mysqli,$_GET['type']))); - $item_id = intval($_GET['id']); - $item_note = trim(strip_tags(mysqli_real_escape_string($mysqli,$_GET['note']))); - $item_view_limit = intval($_GET['views']); - $item_expires = trim(strip_tags(mysqli_real_escape_string($mysqli,$_GET['expires']))); - $item_key = bin2hex(random_bytes(78)); + $client_id = intval($_GET['client_id']); + $item_type = trim(strip_tags(mysqli_real_escape_string($mysqli,$_GET['type']))); + $item_id = intval($_GET['id']); + $item_note = trim(strip_tags(mysqli_real_escape_string($mysqli,$_GET['note']))); + $item_view_limit = intval($_GET['views']); + $item_expires = trim(strip_tags(mysqli_real_escape_string($mysqli,$_GET['expires']))); + $item_key = bin2hex(random_bytes(78)); - if($item_type == "Document"){ - $row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT document_name FROM documents WHERE document_id = '$item_id' AND document_client_id = '$client_id' LIMIT 1")); - $item_name = $row['document_name']; - } + if ($item_type == "Document") { + $row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT document_name FROM documents WHERE document_id = '$item_id' AND document_client_id = '$client_id' LIMIT 1")); + $item_name = $row['document_name']; + } - if($item_type == "File"){ - $row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT file_name FROM files WHERE file_id = '$item_id' AND file_client_id = '$client_id' LIMIT 1")); - $item_name = $row['file_name']; - } + if ($item_type == "File") { + $row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT file_name FROM files WHERE file_id = '$item_id' AND file_client_id = '$client_id' LIMIT 1")); + $item_name = $row['file_name']; + } - if($item_type == "Login"){ - $login = mysqli_query($mysqli, "SELECT login_name, login_password FROM logins WHERE login_id = '$item_id' AND login_client_id = '$client_id' LIMIT 1"); - $row = mysqli_fetch_array($login); + if ($item_type == "Login") { + $login = mysqli_query($mysqli, "SELECT login_name, login_password FROM logins WHERE login_id = '$item_id' AND login_client_id = '$client_id' LIMIT 1"); + $row = mysqli_fetch_array($login); - $item_name = $row['login_name']; + $item_name = $row['login_name']; - // Decrypt & re-encrypt password for sharing - $login_password_cleartext = decryptLoginEntry($row['login_password']); - $login_encryption_key = bin2hex(random_bytes(8)); - $iv = bin2hex(random_bytes(8)); - $ciphertext = openssl_encrypt($login_password_cleartext, 'aes-128-cbc', $login_encryption_key, 0, $iv); + // Decrypt & re-encrypt password for sharing + $login_password_cleartext = decryptLoginEntry($row['login_password']); + $login_encryption_key = bin2hex(random_bytes(8)); + $iv = bin2hex(random_bytes(8)); + $ciphertext = openssl_encrypt($login_password_cleartext, 'aes-128-cbc', $login_encryption_key, 0, $iv); - $item_encrypted_credential = $iv . $ciphertext; - } + $item_encrypted_credential = $iv . $ciphertext; + } - // Insert entry into DB - $sql = mysqli_query($mysqli, "INSERT INTO shared_items SET item_active = '1', item_key = '$item_key', item_type = '$item_type', item_related_id = '$item_id', item_encrypted_credential = '$item_encrypted_credential', item_note = '$item_note', item_views = 0, item_view_limit = '$item_view_limit', item_created_at = NOW(), item_expire_at = '$item_expires', item_client_id = '$client_id'"); - $share_id = $mysqli->insert_id; + // Insert entry into DB + $sql = mysqli_query($mysqli, "INSERT INTO shared_items SET item_active = '1', item_key = '$item_key', item_type = '$item_type', item_related_id = '$item_id', item_encrypted_credential = '$item_encrypted_credential', item_note = '$item_note', item_views = 0, item_view_limit = '$item_view_limit', item_created_at = NOW(), item_expire_at = '$item_expires', item_client_id = '$client_id'"); + $share_id = $mysqli->insert_id; - // Return URL - if($item_type == "Login"){ - $url = "$config_base_url/guest_view_item.php?id=$share_id&key=$item_key&ek=$login_encryption_key"; - } - else{ - $url = "$config_base_url/guest_view_item.php?id=$share_id&key=$item_key"; - } - echo json_encode($url); + // Return URL + if ($item_type == "Login") { + $url = "$config_base_url/guest_view_item.php?id=$share_id&key=$item_key&ek=$login_encryption_key"; + } + else { + $url = "$config_base_url/guest_view_item.php?id=$share_id&key=$item_key"; + } + echo json_encode($url); - // Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Sharing', log_action = 'Create', log_description = '$session_name created shared link for $item_type - $item_name', log_client_id = '$client_id', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_user_id = $session_user_id, company_id = $session_company_id"); + // Logging + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Sharing', log_action = 'Create', log_description = '$session_name created shared link for $item_type - $item_name', log_client_id = '$client_id', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_user_id = $session_user_id, company_id = $session_company_id"); } /* * Looks up info for a given scheduled ticket ID from the database, used to dynamically populate modal edit fields */ -if(isset($_GET['scheduled_ticket_get_json_details'])){ - validateTechRole(); +if (isset($_GET['scheduled_ticket_get_json_details'])) { + validateTechRole(); - $client_id = intval($_GET['client_id']); - $ticket_id = intval($_GET['ticket_id']); + $client_id = intval($_GET['client_id']); + $ticket_id = intval($_GET['ticket_id']); - $ticket_sql = mysqli_query($mysqli, "SELECT * FROM scheduled_tickets + $ticket_sql = mysqli_query($mysqli, "SELECT * FROM scheduled_tickets WHERE scheduled_ticket_id = $ticket_id AND scheduled_ticket_client_id = $client_id LIMIT 1"); - while($row = mysqli_fetch_array($ticket_sql)){ - $response['ticket'][] = $row; - } + while ($row = mysqli_fetch_array($ticket_sql)) { + $response['ticket'][] = $row; + } - $asset_sql = mysqli_query($mysqli, "SELECT asset_id, asset_name FROM assets WHERE asset_client_id = $client_id AND asset_archived_at IS NULL"); - while($row = mysqli_fetch_array($asset_sql)){ - $response['assets'][] = $row; - } + $asset_sql = mysqli_query($mysqli, "SELECT asset_id, asset_name FROM assets WHERE asset_client_id = $client_id AND asset_archived_at IS NULL"); + while ($row = mysqli_fetch_array($asset_sql)) { + $response['assets'][] = $row; + } - echo json_encode($response); + echo json_encode($response); } @@ -293,8 +291,8 @@ if(isset($_GET['scheduled_ticket_get_json_details'])){ * Dynamic TOTP for client login page * When provided with a TOTP secret, returns a 6-digit code */ -if(isset($_GET['get_totp_token'])){ - $otp = TokenAuth6238::getTokenCode($_GET['totp_secret']); +if (isset($_GET['get_totp_token'])) { + $otp = TokenAuth6238::getTokenCode($_GET['totp_secret']); - echo json_encode($otp); + echo json_encode($otp); } \ No newline at end of file diff --git a/get_credential.php b/get_credential.php index b928197a..39f41fda 100644 --- a/get_credential.php +++ b/get_credential.php @@ -18,17 +18,16 @@ // Headers to allow extensions access (CORS) $chrome_id = "chrome-extension://afgpakhonllnmnomchjhidealcpmnegc"; -//$firefox_id = "moz-extension://857479e9-3992-4e99-9a5e-b514d2ad0a82"; // Firefox rejected the extension. They are still using manifest v2 so will just focus on Chrome/Edge with v3 for now until Mozilla catches up if (isset($_SERVER['HTTP_ORIGIN'])) { - if($_SERVER['HTTP_ORIGIN'] == $chrome_id){ + if ($_SERVER['HTTP_ORIGIN'] == $chrome_id) { header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); } } -include("config.php"); -include("functions.php"); +include_once("config.php"); +include_once("functions.php"); // IP & User Agent for logging $ip = strip_tags(mysqli_real_escape_string($mysqli,get_ip())); @@ -41,13 +40,13 @@ DEFINE("WORDING_BAD_EXT_COOKIE_KEY", "ITFlow - You are not logged into ITFlow, d // Check user is logged in & has extension access // We're not using the PHP session as we don't want to potentially expose the session cookie with SameSite None -if(!isset($_COOKIE['user_extension_key'])){ +if (!isset($_COOKIE['user_extension_key'])) { $data['found'] = "FALSE"; $data['message'] = WORDING_BAD_EXT_COOKIE_KEY; - echo(json_encode($data)); + echo json_encode($data); - //Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = 'Failed login attempt using extension (get_credential.php)', log_ip = '$ip', log_user_agent = '$user_agent'"); + // Logging + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = 'Failed login attempt using extension (get_credential.php)', log_ip = '$ip', log_user_agent = '$user_agent'"); exit(); } @@ -56,13 +55,13 @@ if(!isset($_COOKIE['user_extension_key'])){ $user_extension_key = $_COOKIE['user_extension_key']; // Check the key isn't empty, less than 17 characters or the word "disabled". -if(empty($user_extension_key) || strlen($user_extension_key) < 16 || strtolower($user_extension_key) == "disabled"){ +if (empty($user_extension_key) || strlen($user_extension_key) < 16 || strtolower($user_extension_key) == "disabled") { $data['found'] = "FALSE"; $data['message'] = WORDING_BAD_EXT_COOKIE_KEY; - echo(json_encode($data)); + echo json_encode($data); - //Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = 'Failed login attempt using extension (get_credential.php)', log_ip = '$ip', log_user_agent = '$user_agent'"); + // Logging + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = 'Failed login attempt using extension (get_credential.php)', log_ip = '$ip', log_user_agent = '$user_agent'"); exit(); } @@ -74,25 +73,25 @@ $auth_user = mysqli_query($mysqli, "SELECT * FROM users LEFT JOIN user_settings $row = mysqli_fetch_array($auth_user); // Check SQL query state -if(mysqli_num_rows($auth_user) < 1 || !$auth_user){ +if (mysqli_num_rows($auth_user) < 1 || !$auth_user) { $data['found'] = "FALSE"; $data['message'] = WORDING_BAD_EXT_COOKIE_KEY; - echo(json_encode($data)); + echo json_encode($data); //Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = 'Failed login attempt using extension (get_credential.php)', log_ip = '$ip', log_user_agent = '$user_agent'"); + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = 'Failed login attempt using extension (get_credential.php)', log_ip = '$ip', log_user_agent = '$user_agent'"); exit(); } // Sanity check -if(hash('sha256', $row['user_extension_key']) !== hash('sha256', $_COOKIE['user_extension_key'])){ +if (hash('sha256', $row['user_extension_key']) !== hash('sha256', $_COOKIE['user_extension_key'])) { $data['found'] = "FALSE"; $data['message'] = WORDING_BAD_EXT_COOKIE_KEY; - echo(json_encode($data)); + echo json_encode($data); //Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = 'Failed login attempt using extension (get_credential.php)', log_ip = '$ip', log_user_agent = '$user_agent'"); + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = 'Failed login attempt using extension (get_credential.php)', log_ip = '$ip', log_user_agent = '$user_agent'"); exit(); } @@ -110,28 +109,28 @@ $session_company_id = $row['user_default_company']; $session_user_role = $row['user_role']; // Check user access level is correct (not an accountant) -if($session_user_role < 1){ +if ($session_user_role < 1) { $data['found'] = "FALSE"; $data['message'] = WORDING_ROLECHECK_FAILED; - echo(json_encode($data)); + echo json_encode($data); //Logging $user_name = mysqli_real_escape_string($mysqli, $session_name); - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = '$user_name not authorised to use extension', log_ip = '$ip', log_user_agent = '$user_agent', log_user_id = $session_user_id"); + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Extension Failed', log_description = '$user_name not authorised to use extension', log_ip = '$ip', log_user_agent = '$user_agent', log_user_id = $session_user_id"); exit(); } // Lets go! -if(isset($_GET['host'])){ +if (isset($_GET['host'])) { - if(!empty($_GET['host'])){ - $url = trim(strip_tags(mysqli_real_escape_string($mysqli,$_GET['host']))); + if (!empty($_GET['host'])) { + $url = trim(strip_tags(mysqli_real_escape_string($mysqli, $_GET['host']))); $sql_logins = mysqli_query($mysqli, "SELECT * FROM logins WHERE (login_uri = '$url' AND company_id = '$session_company_id') LIMIT 1"); - if(mysqli_num_rows($sql_logins) > 0){ + if (mysqli_num_rows($sql_logins) > 0) { $row = mysqli_fetch_array($sql_logins); $data['found'] = "TRUE"; $data['username'] = htmlentities($row['login_username']); diff --git a/portal/login_microsoft.php b/portal/login_microsoft.php index 3de64f77..e6ff7286 100644 --- a/portal/login_microsoft.php +++ b/portal/login_microsoft.php @@ -4,20 +4,20 @@ * OAuth Login via Microsoft IDP */ -include('../config.php'); -include('../functions.php'); +require_once('../config.php'); +require_once('../functions.php'); -if(!isset($_SESSION)){ - // HTTP Only cookies - ini_set("session.cookie_httponly", True); - if($config_https_only){ - // Tell client to only send cookie(s) over HTTPS - ini_set("session.cookie_secure", True); - } - session_start(); +if (!isset($_SESSION)) { + // HTTP Only cookies + ini_set("session.cookie_httponly", true); + if ($config_https_only) { + // Tell client to only send cookie(s) over HTTPS + ini_set("session.cookie_secure", true); + } + session_start(); } -$sql_settings = mysqli_query($mysqli,"SELECT config_azure_client_id, config_azure_client_secret FROM settings WHERE company_id = '1'"); +$sql_settings = mysqli_query($mysqli, "SELECT config_azure_client_id, config_azure_client_secret FROM settings WHERE company_id = '1'"); $settings = mysqli_fetch_array($sql_settings); $client_id = $settings['config_azure_client_id']; @@ -33,15 +33,15 @@ $token_grant_url = "https://login.microsoftonline.com/organizations/oauth2/v2.0/ // Returns a authorization code if login was successful if ($_SERVER['REQUEST_METHOD'] == "GET"){ - $params = array ( - 'client_id' => $client_id, - 'redirect_uri' => $redirect_uri, - 'response_type' => 'code', - 'response_mode' =>'form_post', - 'scope' => 'https://graph.microsoft.com/User.Read', - 'state' => session_id()); + $params = array ( + 'client_id' => $client_id, + 'redirect_uri' => $redirect_uri, + 'response_type' => 'code', + 'response_mode' =>'form_post', + 'scope' => 'https://graph.microsoft.com/User.Read', + 'state' => session_id()); - header ('Location: '.$auth_code_url.'?'.http_build_query ($params)); + header('Location: '.$auth_code_url.'?'.http_build_query($params)); } @@ -49,78 +49,75 @@ if ($_SERVER['REQUEST_METHOD'] == "GET"){ // Request an access token using authorization code (& client secret) (server side) if (isset($_POST['code']) && $_POST['state'] == session_id()){ - $params = array ( - 'client_id' =>$client_id, - 'code' => $_POST['code'], - 'redirect_uri' => $redirect_uri, - 'grant_type' => 'authorization_code', - 'client_secret' => $client_secret - ); - - // Send request via CURL (server side) so user cannot see the client secret - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL,$token_grant_url); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, - http_build_query($params)); - curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); - #curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // DEBUG ONLY - WAMP - - $access_token_response = json_decode(curl_exec($ch),1); - - // Check if we have an access token - // If we do, send a request to Microsoft Graph API to get user info - if (isset($access_token_response['access_token'])){ + $params = array ( + 'client_id' =>$client_id, + 'code' => $_POST['code'], + 'redirect_uri' => $redirect_uri, + 'grant_type' => 'authorization_code', + 'client_secret' => $client_secret + ); + // Send request via CURL (server side) so user cannot see the client secret $ch = curl_init(); - curl_setopt ($ch, CURLOPT_HTTPHEADER, array ('Authorization: Bearer '.$access_token_response['access_token'], - 'Content-type: application/json')); - curl_setopt ($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/me/"); - curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_URL, $token_grant_url); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, + http_build_query($params)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); #curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // DEBUG ONLY - WAMP - $msgraph_response = json_decode (curl_exec ($ch), 1); + $access_token_response = json_decode(curl_exec($ch), 1); - if (isset($msgraph_response['error'])){ - // Something went wrong verifying the token/using the Graph API - quit - echo "Error with MS Graph API. Details:"; - var_dump ($msgraph_response['error']); - exit(); + // Check if we have an access token + // If we do, send a request to Microsoft Graph API to get user info + if (isset($access_token_response['access_token'])){ + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Authorization: Bearer '.$access_token_response['access_token'], + 'Content-type: application/json')); + curl_setopt($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/me/"); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + #curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // DEBUG ONLY - WAMP + + $msgraph_response = json_decode(curl_exec($ch), 1); + + if (isset($msgraph_response['error'])){ + // Something went wrong verifying the token/using the Graph API - quit + echo "Error with MS Graph API. Details:"; + var_dump($msgraph_response['error']); + exit(); + + } elseif (isset($msgraph_response['id'])) { + + $upn = mysqli_real_escape_string($mysqli, $msgraph_response["userPrincipalName"]); + + $sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$upn' LIMIT 1"); + $row = mysqli_fetch_array($sql); + if ($row['contact_auth_method'] == 'azure') { + + $_SESSION['client_logged_in'] = TRUE; + $_SESSION['client_id'] = $row['contact_client_id']; + $_SESSION['contact_id'] = $row['contact_id']; + $_SESSION['company_id'] = $row['company_id']; + $_SESSION['login_method'] = "azure"; + + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Client Login', log_action = 'Success', log_description = 'Client contact $upn successfully logged in via Azure', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW(), log_client_id = $row[contact_client_id]"); + + header("Location: index.php"); + + } else { + $_SESSION['login_message'] = 'Something went wrong with login. Ensure you are setup for SSO.'; + header("Location: index.php"); + } + } + header('Location: index.php'); + } else { + echo "Error getting access_token"; } - elseif(isset($msgraph_response['id'])){ - - $upn = mysqli_real_escape_string($mysqli, $msgraph_response["userPrincipalName"]); - - $sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$upn' LIMIT 1"); - $row = mysqli_fetch_array($sql); - if($row['contact_auth_method'] == 'azure'){ - - $_SESSION['client_logged_in'] = TRUE; - $_SESSION['client_id'] = $row['contact_client_id']; - $_SESSION['contact_id'] = $row['contact_id']; - $_SESSION['company_id'] = $row['company_id']; - $_SESSION['login_method'] = "azure"; - - mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Client Login', log_action = 'Success', log_description = 'Client contact $upn successfully logged in via Azure', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW(), log_client_id = $row[contact_client_id]"); - - header("Location: index.php"); - - } - else{ - $_SESSION['login_message'] = 'Something went wrong with login. Ensure you are setup for SSO.'; - header("Location: index.php"); - } - } - header ('Location: index.php'); - } - else{ - echo "Error getting access_token"; - } - } // If the user is just sat on the page, redirect them to login to try again -if(empty($_GET)){ - echo ""; +if (empty($_GET)) { + echo ""; } \ No newline at end of file diff --git a/portal/login_reset.php b/portal/login_reset.php index 6351f6e6..6b9716fd 100644 --- a/portal/login_reset.php +++ b/portal/login_reset.php @@ -7,19 +7,19 @@ $session_company_id = 1; require_once('../config.php'); require_once('../functions.php'); -require_once ('../get_settings.php'); +require_once('../get_settings.php'); if (empty($config_smtp_host)) { header("Location: login.php"); exit(); } -if(!isset($_SESSION)){ +if (!isset($_SESSION)) { // HTTP Only cookies - ini_set("session.cookie_httponly", True); - if($config_https_only){ + ini_set("session.cookie_httponly", true); + if ($config_https_only) { // Tell client to only send cookie(s) over HTTPS - ini_set("session.cookie_secure", True); + ini_set("session.cookie_secure", true); } session_start(); } @@ -38,7 +38,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") { /* * Send password reset email */ - if(isset($_POST['password_reset_email_request'])){ + if (isset($_POST['password_reset_email_request'])) { $email = strip_tags(mysqli_real_escape_string($mysqli, $_POST['email'])); @@ -54,7 +54,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") { $token = key32gen(); $url = "https://$config_base_url/portal/login_reset.php?email=$email&token=$token&client=$client"; mysqli_query($mysqli, "UPDATE contacts SET contact_password_reset_token = '$token' WHERE contact_id = $id LIMIT 1"); - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Contact', log_action = 'Modify', log_description = 'Sent a portal password reset e-mail for $email.', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW(), log_client_id = $client, company_id = $company"); + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Contact', log_action = 'Modify', log_description = 'Sent a portal password reset e-mail for $email.', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW(), log_client_id = $client, company_id = $company"); // Send reset email @@ -82,10 +82,9 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") { /* * Do password reset */ - } - elseif(isset($_POST['password_reset_set_password'])){ + } elseif (isset($_POST['password_reset_set_password'])) { - if(!isset($_POST['new_password']) || !isset($_POST['email']) || !isset($_POST['token']) || !isset($_POST['client'])) { + if (!isset($_POST['new_password']) || !isset($_POST['email']) || !isset($_POST['token']) || !isset($_POST['client'])) { $_SESSION['login_message'] = WORDING_ERROR; } @@ -106,7 +105,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") { // Set password, invalidate token, logging $password = mysqli_real_escape_string($mysqli, password_hash($_POST['new_password'], PASSWORD_DEFAULT)); mysqli_query($mysqli, "UPDATE contacts SET contact_password_hash = '$password', contact_password_reset_token = NULL WHERE contact_id = $contact_id LIMIT 1"); - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Contact', log_action = 'Modify', log_description = 'Reset portal password for $email.', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW(), log_client_id = $client, company_id = $company"); + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Contact', log_action = 'Modify', log_description = 'Reset portal password for $email.', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW(), log_client_id = $client, company_id = $company"); // Send confirmation email $subject = "Password reset confirmation for $company_name ITFlow Portal"; @@ -232,7 +231,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") {