bash rest-api call authentication problem, I propaly use wrong syntax in my rest-api call but can't find the error - bash

I wrote a powershell script for setting downtimes in our monitoring software "checkmk" and now I have to convert that so a bash script because we are switching from windows server to linux.
user will be "XXX" password will be "YYY" and the hostname will be "ZZZ"
For that I used the documentation from CheckMK:
documentation for show sheduled downtimes
documentation for setting a downtime
and in the end it looks like that:
<#
.Synopsis
Downtime per Rest API bei Check MK Setzen
.DESCRIPTION
Doku https://apt-omd-vip.ads.vhv.de/umbrella/check_mk/openapi/#operation/cmk.gui.plugins.openapi.endpoints.downtime.create_host_related_downtime
30 min Downtime Setzen = 1800 sekunden
.EXAMPLE
Example of how to use this cmdlet
.EXAMPLE
Another example of how to use this cmdlet
#>
function set-Downtime
{
[CmdletBinding()]
[OutputType([int])]
Param
(
$USERNAME="XXX",
$PASSWORD="XXX",
[Parameter(Mandatory=$true)]
$HOSTNAME,
#Zeit soll die Downtime in Minuten angeben, wird dieseer Parameter leer gelassen wird Standdardmäßig 30min verwendet.
[Parameter(Mandatory=$false)]
[Int]$TIME=30
)
Begin
{
}
Process
{
#=============
# Abfrage der DownTimes, sonst kein Connect möglich
#=============
$headers = #{
‘Accept’ = ‘application/json’
‘Authorization’ = “Bearer $USERNAME $PASSWORD”
}
$body = #{
'host_name' = $HOSTNAME
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
$result = Invoke-RestMethod -uri “here was a URL” -Headers $headers -Body $body
#write-host($rest_uri)
#=============
# DownTime
#=============
$headers = #{
'Content-Type' = 'application/json'
‘Accept’ = ‘application/json’
‘Authorization’ = “Bearer $USERNAME $PASSWORD”
}
$datum_start = (get-date).AddHours(-2).ToString("u")
$datum_ende = (get-date).AddHours(-2).addminutes($TIME).ToString("u") ;
$comment = "$TIME min Restart Downtime, $EXTRAINFO"
$body =#{
start_time = $datum_start;
end_time = $datum_ende;
comment = $comment;
host_name = $HOSTNAME;
downtime_type = 'host';
} | ConvertTo-Json -Compress
$result = Invoke-RestMethod -Method Post -uri "here was a URL" -Headers $headers -Body $body
}
End
{
}
}
I apologize for the english-german mix in the script but in theory you shouldn't need my comments.
I reconstructed the command from this bash to powershell help blog
Here is one time my bash script hole and after that I will only post the part I changed:
#!/bin/bash
##Variables
base_url='here was a URL'
request_url="$base_url/all"
post_url="$base_url/host"
user="XXX"
passwd="YYY"
hostname="ZZZ"
user_pass="$user:$passwd"
#header=["Accep"t = "application/json"
#"Authorisation" = "Bearer $user $passwd"]
#body1=["host_name" = "ZZZ"]
curl -u $user_pass -X GET --header 'Accept: application/json' -d {'host_name: ZZZ'} 'here was an URL'
as I am still unexperienced in bash I tried my decleration of variables with the '' and "" quotes because I am still not sure when to use what (but thats not the question here)
Answer is following:
{"title": "You need to be authenticated to use the REST API.", "status": 401}
Next thing I tried was a header construct similar to my ps script:
header=( ["Accept"]="application/json" ["Authorization"]="Bearer XXX YYY")
curl --anyauth -X GET --header $header -d {'host_name: ZZZ'} 'here was an URL'
the answer this times was way longer but in the end I got the same error message:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "censored doc url">
<html>
<!-- FileName: index.html
Language: [en]
-->
<!--Head-->
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<title>McAfee Web Gateway - Notification</title>
<script src="censored" type="text/vascript" ></script>
<link rel="stylesheet" href="censored" />
</head>
<!--/Head-->
<!--Body-->
<body onload="swOnLoad();">
<table class='bodyTable'>
<tr>
<td class='bodyData' background='censored'>
<!--Logo-->
<table class='logoTable'>
<tr>
<td class='logoData'>
<a href='http://www.mcafee.com'>
<img src='censored'>a>
</td>
</tr>
</table>
<!--/Logo-->
<!--Contents-->
<!-- FileName: authenticationrequired.html
Language: [en]
-->
<!--Title-->
<table class='titleTable' background='censored.jpg'>
<tr>
<td class='titleData'>
Authentication Required
</td>
</tr>
</table>
<!--/Title-->
<!--Content-->
<table class="contentTable">
<tr>
<td class="contentData">
You must be authenticated to access this URL.
</td>
</tr>
</table>
<script language="javascript" type="text/javascript">
urlprotocol = "http";
statuscode=407;
if(statuscode==401 && urlprotocol == "ftp"){
document.write("<form name=\"ftpform\" method=\"get\" action=\"\">");
document.write("<table class=\"contentData\">");
document.write("<tr><td class=\"contentData\" colspan=2>Please enter youcredentials in the form below and click \"Access FTP\" button if your browser esn't present authentication prompt for FTP sites.</td></tr>");
document.write("<tr><td class=\"contentData\">Username:</td><td><input te=\"text\" id=\"ftpUsername\" name=\"ftpUsername\" size=40 /></td></tr>");
document.write("<tr><td class=\"contentData\">Password:</td><td><input te=\"password\" id=\"ftpPassword\" name=\"ftpPassword\" size=40 /></td></tr>");
document.write("<tr><td class=\"contentData\" colspan=2 align=center><int type=\"button\" onclick=\"redirectToFTP();\" value=\"Access FTP\" /></td></t");
document.write("</table>");
document.write("</form>");
}
function redirectToFTP(){
var username=escape(document.getElementById("ftpUsername").value);
var password=escape(document.getElementById("ftpPassword").value);
location.href = "ftp://"+username+":"+password+"#XXX:80/"
}
</script>
<!--/Content-->
<!--Info-->
<table class="infoTable">
<tr>
<td class="infoData">
<b>URL: </b><script type="censored");</script><br />
</td>
</tr>
</table>
<!--/Info-->
<!--/Contents-->
<!--Policy-->
<table class='policyTable'>
<tr>
<td class='policyHeading'>
<hr>
Company Acceptable Use Policy
</td>
</tr>
<tr>
<td class='policyData'>
This is an optional acceptable use disclaimer that appears on every pageYou may change the wording or remove this section entirely in index.html.
</td>
</tr>
</table>
<!--/Policy-->
<!--Foot-->
<table class='footTable'>
<tr>
<td class='helpDeskData' background='censored'>
For assistance, please contact your system administrator.
</td>
</tr>
<tr>
<td class='footData'>
generated <span id="time">2022-08-09 14:58:22</span> by McAfee Web Gatew
<br />
curl/7.60.0<br />
Node: censored<br />
Client IP: censored<br />
User: <br />
User-Groups: <br />
Authentication Method: <br />
Rule Set: Authentication with Kerberos and NTLM Fallback<br />
Rule: Perform Authentication<br />
</td>
</tr>
</table>
<!--/Foot-->
</td>
</tr>
</table>
</body>
<!--/Body-->
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "censored">
<html>
<!-- FileName: index.html
Language: [en]
-->
<!--Head-->
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<title>McAfee Web Gateway - Notification</title>
<script src="censored" type="text/vascript" ></script>
<link rel="stylesheet" href="/mwg-internal/de5fs23hu73ds/files/default/styleeet.css" />
</head>
<!--/Head-->
<!--Body-->
<body onload="swOnLoad();">
<table class='bodyTable'>
<tr>
<td class='bodyData' background='censored'>
<!--Logo-->
<table class='logoTable'>
<tr>
<td class='logoData'>
<a href='http://www.mcafee.com'>
<img src='censored'>a>
</td>
</tr>
</table>
<!--/Logo-->
<!--Contents-->
<!-- FileName: authenticationrequired.html
Language: [en]
-->
<!--Title-->
<table class='titleTable' background='/mwg-internal/de5fs23hu73ds/files/defaulimg/bg_navbar.jpg'>
<tr>
<td class='titleData'>
Authentication Required
</td>
</tr>
</table>
<!--/Title-->
<!--Content-->
<table class="contentTable">
<tr>
<td class="contentData">
You must be authenticated to access this URL.
</td>
</tr>
</table>
<script language="javascript" type="text/javascript">
urlprotocol = "http";
statuscode=407;
if(statuscode==401 && urlprotocol == "ftp"){
document.write("<form name=\"ftpform\" method=\"get\" action=\"\">");
document.write("<table class=\"contentData\">");
document.write("<tr><td class=\"contentData\" colspan=2>Please enter youcredentials in the form below and click \"Access FTP\" button if your browser esn't present authentication prompt for FTP sites.</td></tr>");
document.write("<tr><td class=\"contentData\">Username:</td><td><input te=\"text\" id=\"ftpUsername\" name=\"ftpUsername\" size=40 /></td></tr>");
document.write("<tr><td class=\"contentData\">Password:</td><td><input te=\"password\" id=\"ftpPassword\" name=\"ftpPassword\" size=40 /></td></tr>");
document.write("<tr><td class=\"contentData\" colspan=2 align=center><int type=\"button\" onclick=\"redirectToFTP();\" value=\"Access FTP\" /></td></t");
document.write("</table>");
document.write("</form>");
}
function redirectToFTP(){
var username=escape(document.getElementById("ftpUsername").value);
var password=escape(document.getElementById("ftpPassword").value);
location.href = "ftp://"+username+":"+password+"#YYY:80/"
}
</script>
<!--/Content-->
<!--Info-->
<table class="infoTable">
<tr>
<td class="infoData">
<b>URL: </b><script type="text/javascript">break_line("http://setDownTim");</script><br />
</td>
</tr>
</table>
<!--/Info-->
<!--/Contents-->
<!--Policy-->
<table class='policyTable'>
<tr>
<td class='policyHeading'>
<hr>
Company Acceptable Use Policy
</td>
</tr>
<tr>
<td class='policyData'>
This is an optional acceptable use disclaimer that appears on every pageYou may change the wording or remove this section entirely in index.html.
</td>
</tr>
</table>
<!--/Policy-->
<!--Foot-->
<table class='footTable'>
<tr>
<td class='helpDeskData' background='/mwg-internal/de5fs23hu73ds/files/deflt/img/bg_navbar.jpg'>
For assistance, please contact your system administrator.
</td>
</tr>
<tr>
<td class='footData'>
generated <span id="time">2022-08-09 14:58:22</span> by McAfee Web Gatew
<br />
curl/7.60.0<br />
Node:censored<br />
Client IP: censored<br />
User: <br />
User-Groups: <br />
Authentication Method: <br />
Rule Set: Authentication with Kerberos and NTLM Fallback<br />
Rule: Perform Authentication<br />
</td>
</tr>
</table>
<!--/Foot-->
</td>
</tr>
</table>
</body>
<!--/Body-->
</html>
{"title": "You need to be authenticated to use the REST API.", "status": 401}
I needed to cut that part because I was over the characterlimit for the post...
I think that my error is not that hard to solve but I dont know enough about bash to search for the right things so please get easy on me. I used bash the first time in june this year so try to keep the answers a bit simpler than to an usual bash user please, thank you in advance for your help and consideration.

Like I guessed my problem was a minor one... only thing wrong was the ":" in my headers, just had to exchange them for "=".
Well got a new problem but I doubt that you guys can help me when I am not allowed to share more information about our server and applications.
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
</body></html>
afer that message I did the same thing in the body like in my header but that didnt do the thing.

Here's a rewrite of your script in bash using curl, because it'll be easier to discuss against an example rather than an abstract in comments.
This, at least to my eyes, does exactly what your Powershell script is doing.
#!/bin/bash
url="https://YOUR-URL"
username="XXX"
password="YYY"
hostname="ZZZ"
# first Invoke-RestMethod, which is a GET with JSON...
# -1 means "use TLS1 or newer"
# -XGET is required here to force it to be a request
# that uses GET with a body, since curl would default to POST
# if '-d' is specified
# -w "%{http_code}\n" means output the http code
# if you want to suppress all other output and only
# get the http code output, specify these additional options:
# -o /dev/null -s
curl $url -1 -XGET \
-H "Accept: application/json" \
-H "Authorization: Bearer $username $password" \
-w "%{http_code}\n" \
-d "{ \"host_name\": \"$hostname\" }"
# Downtime Invoke-RestMethod
minutes_diff=30
start_diff=120
# because in your original, you do (now - 2 hours) + $minutes_diff
# so it's just now -(120 - $minutes_diff) minutes
end_diff=$(( 120 - $minutes_diff ))
# This was based on you using the .NET -u specifier which is
# intended for use with UTC DateTime objects
# I don't know if you actually want your timestamps derived
# from UTC time, which is what "-u" does for the date command
start_time=$(date -u -d "$start_diff minutes ago" +"%Y-%m-%d %H:%M:%SZ")
end_time=$(date -u -d "$end_diff minutes ago" +"%Y-%m-%d %H:%M:%SZ")
# you didn't have an EXTRAINFO in your original script
# so I left it out
comment="$minutes_diff min Restart Downtime"
# The -d #- <<-JSON uses a heredoc so I can
# more nicely express the JSON you send
curl $url -1 \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "Authorization: Bearer $username $password" \
-w "%{http_code}\n" \
-d #- <<-JSON
{
"start_time": "$start_time",
"end_time": "$end_time",
"comment": "$comment",
"host_name": "$hostname",
"downtime_type": "host"
}
JSON

Related

How to Load Data From a Json Using Thymeleaf Template

I have a rest api returns a Json value as a Output of the service call.
eg:- https://localhost:8080/getEmployees/loadAll
this returns following json values
eg:-
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
I need to load the following json values to my thymeleaf table.
In normal way returning values in controller using modal in spring can retun values as list like following.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Employee List</title>
</head>
<body>
<h1>Welcome</h1>
<br>
<h3>Employee List</h3>
<br />
<table border="1">
<tr>
<td>Employee First Name</td>
<td>Employee Last Name</td>
</tr>
<tr th:each="emp : ${empList}">
<td th:text="${emp.firstName}">First Name</td>
<td th:text="${emp.name}">Last Name</td>
</tr>
</table>
</body>
</html>
is there a way to accomplish this using above json using thymeleaf?
You can do something like that using the following structure.
When you call the service
https://localhost:8080/getEmployees/loadAll
you will need to pass the employees data using model.addAttribute.
For instance, let's say you have the following method:
#RequestMapping(value="/getEmployees/loadAll")
String getAllEmployees(Model model) {
model.addAttribute("empList", <your service here that generates the data>);
return "pagenamehere";
}
The above method, will only be executed when you make a call using the following url: https://localhost:8080/getEmployees/loadAll
and it will add your empList data as an attribute. Then, the return string indicates the name of the page that will load. You will need to use your own page with the thymeleaf code.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Employee List</title>
</head>
<body>
<h1>Welcome</h1>
<br>
<h3>Employee List</h3>
<br />
<table border="1">
<tr>
<td>Employee First Name</td>
<td>Employee Last Name</td>
</tr>
<tr th:each="emp : ${empList}">
<td th:text="${emp.firstName}">First Name</td>
<td th:text="${emp.lastNname}">Last Name</td>
</tr>
</table>
</body>
</html>
Now, thymeleaf will be able to display the given data.
I think that you are a little confused. Thymeleaf templates are compiled on server side generating html code. Then, no thymeleaf code found on client side.
The json data got of the api response is generated on client side.
One way is use javascript to load the api response data into a html table.
Another way can you take is modify the controller that calls to the thymeleaf template to get the JSon value. If you store this response (on an object List named empList on your example) yo can add the object into the Controller response (Model or ModelAndView objects) as a template attribute.

Adding a Logon message to pages

I'm looking to create a log in feature every time users go to various members only pages, which returns them to the original page after logging in. I've seen various answers to this question but none of them seem to include a check feature followed by a return to the original page. At the moment the code I have created doesn't seem to recognize that I have logged in and keeps returning me to the log in form. Any answers will be greatly appreciated. I realize I am using deprecated code but that is the only version my host provider's servers recognize.
Here's the code I am putting at the top of each members page
<?php
session_start();
if($_SESSION['login'] != "yes" )
{
header("Location: main_login.php");
exit();
}
?>
This then opens the main_login.php page
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
On clicking the login button the following code in checklogin.php checks the entries
<?php
$host='.....'; // Host name
$username='.....'; // Mysql username
$password='........'; // Mysql password
$db_name='....'; // Database name
$tbl_name='......'; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_start();
$_SESSION['myusername'];
$_SESSION['mypassword'];
header("location:entry_form_european_languages.php");
}
else {
echo "Wrong Username or Password";
}
?>
The last header location refers to the page I would like to return to, which seems to the repeat the process of opening up the login and check in files- as if to indicate that the return page doesn't recognize that the log in was successful.
I would need to add something that was relative to each page, but since I don't know where I am going wrong with the fixed page return, I can't move on to that stage of coding.
I did have an alternative header address which took it to the following page login_success.php which gave the impression that username entries had been accepted, but this doesn't allow me to return to the original page
<?php
session_start();
if(isset($_SESSION[$myusername])){
header("Location:entry_form_european_languages.php");
}
?>
<?php
include '........';//Formatting for the page
?>
<html>
<body>
Login Successful
</body>
</html>
Thanks in advance.
There are a few extra things I needed to add to make the session details work, as follows. This code needs to go ahead of any other code on the page including any html code that relates to character formatting. Although I have coded it out the error reporting line is handy for indicating which line is not being read by the php server, should you have continued problems.
<?php
//error_reporting(E_ALL); ini_set('display_errors', 'On');
session_start();
ob_start();
if(!isset($_SESSION['myusername'])){
header('Location:main_login.php');
}
else if (isset($_SESSION['myusername'])){
}
$myusername=$_SESSION['myusername'];
$Page_Title ='Members Profile';
?>

Password failing using Bcrypt

So far bcrypt has had no problems until now. For some reason the following password won't work. UIO78349%^&(]\\';= This is the first time I've had a password not work and I hope somebody has an explanation. I hunted the net and read about the character limit but this is well below that. Not sure if it makes any difference but the user input for password is going through mysqli_real_escape_string.
First batch of code where the login form is located:
<?php
session_start();
?>
<html>
<body>
<form method="post" action="sidebar-signin-block.php">
<table width="90%" border="0" align="center" bgcolor="white">
<tr>
<td bgcolor="ffffff" colspan="2" align="center"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="login" value="Login"></td>
</tr>
<tr>
<td colspan="2" align="center"><h3 style="margin-top:7px;">Forgot Password?</h3></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2" align="center"><div style="padding-top:5px;"><span style="font-size:20px;">Don't have an account?<br />Sign Up is <em>quick</em> and <em>easy</em>!</span></div></td>
</table>
</form>
<?php
// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");
// Gathering and sanitizing user login input
if(isset($_POST['login'])){
$email = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['email']) :((trigger_error ("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
$pass = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['password']) : ((trigger_error ("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
// Checking the database records for the user login input
$hash_query = "select nonadmin_user_pass from nonadmin_user_login where email='$email'";{
$run_query = mysqli_query($conn, $hash_query);}
while ($row = mysqli_fetch_assoc($run_query)) {
$fetch_pass = $row['nonadmin_user_pass'];
}
// If the user email and password matches we start a session
if ((password_verify($pass, $fetch_pass)) == 1){
// Verifying user login success with splash page then sending user back to the home page
$_SESSION['email']=$email;
echo "<script>window.open('login-success.php','_self')</script>";}
// When the user login fails an alert is given to inform them
else {
echo "<script>alert('Email or password is incorrect please try again')</script>";
echo "<script>window.open('index.php','_self')</script>";}
}
?>
</body>
</html>
Here the js.
<script>$(document).ready(function(){
$("#login").click(function(){
var email = $("#email").val();
var password = $("#password").val();
// Checking for blank fields.
if( email =='' || password ==''){
$('input[type="text"],input[type="password"]');
$('input[type="text"],input[type="password"]');
alert("Please fill all fields.");
}else {
$.post("log-me-in.php",{ email1: email, password1:password},
function(data) {
if(data=='Invalid Email.......') {
$('input[type="text"]');
$('input[type="password"]');
alert(data);
}else if(data=='Email or Password is wrong please try again.'){
$('input[type="text"],input[type="password"]');
alert(data);
} else if(data=='Successfully Logged in.'){
window.location.reload();
$("form")[0].reset();
$('input[type="text"],input[type="password"]');
alert(data);
} else{
alert(data);
}
});
}
});
});</script>
Here's the php being called:
<?php
session_start();
// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");
$email=$_POST['email1']; // Fetching Values from URL.
$password= ($_POST['password1']);
// check if e-mail address syntax is valid or not
//$email = filter_var($email, FILTER_SANITIZE_EMAIL); // sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
//if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
//echo "Invalid Email.......";
//}else{
// Matching user input email and password with stored email and password in database.
$result = mysqli_query($conn, "SELECT * FROM nonadmin_user_login WHERE email='$email'");
$data = mysqli_fetch_array($result);
$bcrypt_pass = $data['nonadmin_user_pass'];
$email_match = $data['email'];
if (password_verify ($password, $bcrypt_pass) == 1 AND $email == $email_match) {
$_SESSION['email']=$email;
echo "Successfully Logged in.";
}
else{
echo "Email or Password is wrong please try again";
}
//}
?>
Here is the user registration code where the password initially gets entered before mail verification:
<html>
<head>
<title>Register at Recycling Kansas City</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/styles/register-user.css" media="all">
<!-- ie compatibility -->
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->
<!--[if lt IE 9]>
<script src="Site/javascript/bootstrap/html5shiv.js"></script>
<![endif]-->
<meta content="recycling kansas city, recycling centers, recycling locations" name="keywords">
<meta content="Recycling Kansas City is an efficient resource to help you quickly find a recycle center that is nearby. Use our map to find locations and accepted items." name="description">
</head>
<h1 class="center">Why register at Recycling Kansas City?</h1>
<p>By registering here you will gain access to additional features. Once registered you can create your own custom profile, submit and comment on blog articles, advertise your products or services and have the choice to opt in for email announcements.</p>
<p>All of your information will be securely stored in our database and you can delete your account at any time. Also, rest assured that we will never share any of your submitted details with anyone ever.</p>
<form method="post" action="register-user.php">
<table width="520" border="10" align="center" bgcolor="white">
<tr>
<td bgcolor="ffffff" colspan="2" align="center"><h1>Registration</h1></td>
</tr>
<tr>
<td align="right">Email</td>
<td><input type="text" name="email" size="53"></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="pwd" size="53"></td>
</tr>
<tr>
<td align="right">User Name:</td>
<td><input type="text" name="name" size="53"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="register" value="Register"></td>
</tr>
</table>
</form>
</html>
<?php
include ("../admin/includes/connect.php");
include ("../lib/password.php");
$con = new mysqli("localhost", "$username", "$password", "$database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST['register'])){
$email = trim(mysql_escape_string($_POST['email']));
$nonadmin_user_pass = trim(mysql_escape_string($_POST['pwd']));
$password = password_hash($nonadmin_user_pass, PASSWORD_BCRYPT);
$nonadmin_user_name = trim(mysql_escape_string($_POST['name']));
$query_verify_email = "SELECT * FROM nonadmin_user_login WHERE email ='$email' and verified = 1";
$verified_email = mysqli_query($con,$query_verify_email);
if (!$verified_email) {
echo ' System Error';
}
if (mysqli_num_rows($verified_email) == 0) {
// Generate a unique code:
$hash = md5(uniqid(rand(), true));
$query_create_user = "INSERT INTO `nonadmin_user_login` (`email`, `nonadmin_user_pass`, `nonadmin_user_name`, `hash`) VALUES ('$email', '$password', '$nonadmin_user_name', '$hash')";
$created_user = mysqli_query($con,$query_create_user);
if (!$created_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($con) == 1) { //If the Insert Query was successfull.
$subject = 'Activate Your Email';
$headers = "From: admin#recyclingkansascity.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$url= 'http://recyclingkansascity.com/includes/register-verify.php?email=' . urlencode($email) . "&key=$hash";
$message ='<p>To activate your account please click on Activate buttton</p>';
$message.='<table cellspacing="0" cellpadding="0"> <tr>';
$message .= '<td align="center" width="300" height="40" bgcolor="#000091" style="-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;
color: #ffffff; display: block;">';
$message .= '<a href="'.$url.'" style="color: #ffffff; font-size:16px; font-weight: bold; font-family: Helvetica, Arial, sans-serif; text-decoration: none;
line-height:40px; width:100%; display:inline-block">Click to Activate</a>';
$message .= '</td> </tr> </table>';
mail($email, $subject, $message, $headers);
echo '<p class="center">A confirmation email
has been sent to <b>'. $email.' </b></p><p class="center">Please <strong>click</strong> on the <strong><em>Activate</em> Button</strong> to Activate your account.</p> ';
} else { // If it did not run OK.
echo '<div>You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
}
}
else{
echo '<div>Email already registered</div>';}
}
?>
So far never a hiccup on any password until the password at the top of the post? Weird if you ask me.
Remove all calls to mysqli_real_escape_string() for password input, the functions password_hash() and password_verify() accept even binary input and are not prone to SQL-injection. I assume this already solves your problem. Escaping should be done as late as possible and only for the given target system, so the function mysqli_real_escape_string() should only be called to build an SQL query.
Then the function password_verify() already returns a boolean, no need to compare it with == 1.
if (password_verify($pass, $fetch_pass))
{
...
}
If this doesn't solve your problem, i would make sure that every page uses UTF-8 as file format and defined it in the header.

I'm not able to excute perl script inside ajax

I have set of AJAX code, that code call a Perl Script and script have some functionality.Whenever i click on Dial button Perl script should be run but i'm not able to run script.When i click on dial button my complete Perl program is showing on Web.On other had when i execute my program forcefully it executed properly.
HTML Code
<!CTYPE html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<title>Outbound Calling Demo Site</title>
<script language="Javascript">
function doDial(phone)
{
var phone_no = document.getElementById('phone').value;
// alert(phone_no);
var ajaxRequest; // The variable that makes Ajax possible!
if (window.XMLHttpRequest)
{ //Opera 8.0+, Firefox, Safari
ajaxRequest= new window.XMLHttpRequest();
}
else
{
try {
ajaxRequest= new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch (e) {}
try { ajaxRequest= new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { ajaxRequest= new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
function handler()
{
if (ajaxRequest.readyState==4 && ajaxRequest.status==200)
{
document.getElementById("ajaxDiv").innerHTML=ajaxRequest.responseText;
}
}
var queryString = "?phone=" + phone_no ;
get_selected_data(document.getElementById('agent'));
if(ajaxRequest != null)
{
ajaxRequest.open("POST", "dial_call2.pl" + queryString , true);
ajaxRequest.onreadystatechange = handler;
//console.log(queryObj.fund);
ajaxRequest.send(null);
}
else
{
window.console.log("AJAX (XMLHTTP) not supported.");
}
}
</script>
<table >
Number to dial: <input class="text_box" name="phone" type="text" id="phone" size="14" value="" />
<input type="button" value="Dial" onClick="javascript:doDial();"/>
<div id='ajaxDiv'></div>
<tr>
<td><input type="button" name="dtmf1" value='1' id="dtmf1" onClick="sendDTMF(1);"/></td>
<td><input type="button" name="dtmf2" value='2' id="dtmf2" onClick="sendDTMF(2);"/></td>
<td><input type="button" name="dtmf3" value='3' id="dtmf3" onClick="sendDTMF(3);"/></td>
</tr>
<tr>
<td><input type="button" name="dtmf4" value='4' id="dtmf4" onClick="sendDTMF(4);"/></td>
<td><input type="button" name="dtmf5" value='5' id="dtmf5" onClick="sendDTMF(5);"/></td>
<td><input type="button" name="dtmf6" value='6' id="dtmf6" onClick="sendDTMF(6);"/></td>
</tr>
<tr>
<td><input type="button" name="dtmf7" value='7' id="dtmf7" onClick="sendDTMF(7);"/></td>
<td><input type="button" name="dtmf8" value='8' id="dtmf8" onClick="sendDTMF(8);"/></td>
<td><input type="button" name="dtmf9" value='9' id="dtmf9" onClick="sendDTMF(9);"/></td>
</tr>
<tr>
<td><input type="button" name="dtmf*" value='*' id="dtmf*" onClick="sendDTMF(this.value);"/></td>
<td><input type="button" name="dtmf0" value='0' id="dtmf0" onClick="sendDTMF(0);"/></td>
<td><input type="button" name="dtmf#" value='#' id="dtmf#" onClick="sendDTMF(this.value);"/></td>
</tr>
<tr>
<td><input type="button" name="dtmfClr" value="Clr" onClick="number_clear(this.value);"/></td>
<td><input type="button" name="dtmfC" value="C" onClick="number_c(this.value);"/></td>
</tr>
</table>
<tr>
<th>
<td><input type="button" id="hangup" value="Hangup" onClick="javascript:doHangup();"/></td>
<td><input type="button" id="unregister" value="Unregister" onClick="javascript:doUnregister();"/></td>
<td><input type="button" id="answer" value="Answer Call" onClick="javascript:doAnswer();" style="visibility:hidden;"/><br/></td>
</th>
</tr>
</form>
</body>
</html>
Perl Code :-
#!/usr/bin/perl
use strict;
use CGI;
my $cgi = new CGI;
use CGI::Carp qw(fatalsToBrowser);
use IO::Socket;
print $cgi->header();
print $cgi->start_html('Asterisk Caller');
print '<center><p>call</p>';
my ($request,#phone_no,$phone_no);
if ($ENV{'REQUEST_METHOD'} eq "GET")
{
$request = $ENV{'QUERY_STRING'};
}
elsif ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $request,$ENV{'CONTENT_LENGTH'}) || die "Could not get query\n";
}
my #phone_no=split(/=/,$request);
my $phone_no;
my $phone_number = $phone_no[1];
chomp($phone_number);
my $host = '127.0.0.1';
my $login = "Action: login\r\nUsername: lite\r\nSecret: 4003\r\n\r\n";
$/ = "\r\n"; # <> reads a single line for signon banner
# Code for making connection with Telnet
my $s = IO::Socket::INET->new("$host:5038") or die "can't connect to $host: $!\n";
my $banner = <$s>; # read the banner
my $line = ('-' x 78)."\n";
print $banner,$line;
print $s $login;
my $resp = <$s>;
print $resp,$line;
print $s "Action: Originate\r\nChannel: DAHDI/42/$phone_number\r\nContext: oreilly\r\nExten: s\r\nCallerID: 7702009896\r\nPriority: 1\r\nWaitTime: 10\r\nRetryTime: 20\r\nMaxRetries: 2\r\n\r\n";
$resp = <$s>;
print $resp,$line;
print $s "Action: Logoff\r\n\r\n";
$resp = <$s>;
print $resp,$line;
close $s;
If you are using Apache and running on a Linux server, then the following may help.
You may need the following .htaccess file alongside your Perl code:
<FilesMatch "\.pl$">
Options +ExecCGI
SetHandler cgi-script
</FilesMatch>
For this to work you'd also need to ensure that the Perl script is executable:
chmod 755 myscript.pl
.. and that the first line of the script is something like:
#!/usr/bin/perl

Cannot Disable Certificate Revocation on Internet Explorer (Expired Cert)

Apparently there is an expired certificate on a site that I use for automated testing with Selenium Webdriver. I've tried disabling the certificate revocation in Internet Settings, and restarting IE (as well as Windows, just to be safe), but to no avail.
I also tried using Webdriver to navigate past the warning page, but no success there either. For some reason it can't detect the "Continue" button on the page, either using xpath, or the built in "By.id" locating mechanism. I'm open to a WebDriver solution to this problem, but I would prefer a solution that allows me to disable certificate revocation. I don't use IE for anything else than automated testing on a VM, so I'm not concerned about security problems.
Just in case WebDriver is the only option, here is the source code of the page
<HTML dir=ltr><HEAD><TITLE>Certificate Error: Navigation Blocked</TITLE><LINK rel=stylesheet type=text/css href="ErrorPageTemplate.css">
<META name=MS.LOCALE content=EN-US>
<META content="text/html; charset=utf-8" http-equiv=Content-Type>
<META content=Yes http-equiv=MSThemeCompatible>
<SCRIPT language=javascript type=text/javascript src="errorPageStrings.js">
</SCRIPT>
<SCRIPT language=javascript type=text/javascript src="httpErrorPagesScripts.js">
</SCRIPT>
<SCRIPT language=javascript type=text/javascript src="invalidcert.js">
</SCRIPT>
</HEAD>
<BODY class=securityError onload="BodyLoad(); initMoreInfo('infoBlockID');">
<TABLE border=0 cellSpacing=0 cellPadding=0 width=730><!-- Main title -->
<TBODY>
<TR>
<TD id=shieldIconAlign vAlign=top rowSpan=3 width=60 align=left><IMG id=shieldIcon alt="Shield icon" src="red_shield_48.png"> </TD>
<TD id=mainTitleAlign vAlign=center width=* align=left>
<H1 id=mainTitle>There is a problem with this website's security certificate.</H1></TD></TR>
<TR>
<TD>
<H3>
<DIV id=linkdiv name="linkdiv"></DIV></H3></TD></TR>
<TR><!-- This row is for the the divider-->
<TD id=errorCodeAlign class=errorCodeAndDivider align=right>
<DIV class=divider></DIV></TD></TR><!-- Error Body -->
<TR>
<TD></TD>
<TD>
<H3>
<DIV style="DISPLAY: none" id=CertUnknownCA name="CertUnknownCA"></DIV>
<DIV style="DISPLAY: block" id=CertExpired name="CertExpired">The security certificate presented by this website has expired or is not yet valid.</DIV>
<DIV style="DISPLAY: block" id=CertCNMismatch name="CertCNMismatch">The security certificate presented by this website was issued for a different website's address.</DIV>
<DIV style="DISPLAY: none" id=CertRevoked name="CertRevoked"></DIV><NOSCRIPT id=securityCert1></NOSCRIPT><BR><ID id=securityCert2>Security certificate problems may indicate an attempt to fool you or intercept any data you send to the server.</ID> </H3></TD></TR><!-- Recommendation-->
<TR>
<TD> </TD>
<TD>
<H2 id=recommendation><B>We recommend that you close this webpage and do not continue to this website. </B></H2></TD></TR><!-- close webpage-->
<TR>
<TD> </TD>
<TD id=closeWebpageAlign vAlign=center align=left>
<H4 id=closeWebpage><IMG class=actionIcon border=0 alt="Recommended icon" src="green_shield.png">Click here to close this webpage. </H4></TD></TR><!-- continue to site-->
<TR>
<TD> </TD>
<TD id=continueToSiteAlign vAlign=center align=left>
<H4 id=continueToSite><IMG id=ImgOverride class=actionIcon border=0 alt="Not recommended icon" src="red_shield.png"><A id=overridelink href="<href>" name=overridelink>Continue to this website (not recommended).</A> </H4></TD></TR><!-- InfoBlock -->
<TR>
<TD id=infoBlockAlign vAlign=top align=right> </TD>
<TD id=moreInformationAlign vAlign=center align=left>
<H4>
<TABLE>
<TBODY>
<TR>
<TD vAlign=top><A onclick="javascript:expandCollapse('infoBlockID', true); return false;" href="#"><IMG id=infoBlockIDImage class=actionIcon border=0 alt="More information" src="down.png"></A> </TD>
<TD vAlign=top><SPAN id=moreInfoContainer>More information</SPAN><NOSCRIPT></NOSCRIPT></TD></TR></TBODY></TABLE></H4>
<DIV style="DISPLAY: none" id=infoBlockID class=infoBlock>
<P>
<LI id=errorExpl1>If you arrived at this page by clicking a link, check the website address in the address bar to be sure that it is the address you were expecting.
<LI id=errorExpl2>When going to a website with an address such as https://example.com, try adding the 'www' to the address, https://www.example.com.
<LI id=errorExpl3>If you choose to ignore this error and continue, do not enter private information into the website.
<P></P>
<P id=moreInfoSeeHelpPF>For more information, see "Certificate Errors" in Internet Explorer Help.</P></LI></DIV></TD></TR></TBODY></TABLE></BODY></HTML>
And here is what I tried (in Java):
ieDriver.findElement(By.id("overridelink")).click();
ieDriver.findElement(By.xpath("//a[#id='overridelink']")).click();
ieDriver.findElement(By.xpath("//A[#id='overridelink']")).click();
Which I'm guessing doesn't work because the attribute value is not specified in quotes, so it's incorrect html.
I also tried this:
ieDriver.findElement(By.xpath("//a[#href='<href>']")).click();
ieDriver.findElement(By.xpath("//A[#id='<href>']")).click();
Where
<href>
Symbolizes the actual URL.
I also was unable to locate surrounding tags using the same method.
Note: This also did not work for me: Webdriver not finding elements in remote IE
I suspect because it doesn't alleviate security concerns to trust an expired certificate.
If this is an alert box that IE is creating you can try the .SwitchTo() I use it for alert boxes.
WebDriver.SwitchTo().Alert().Accept();
Hope that helps
Well, one solution that works is just to create a new certificate with an acceptable end date. This works only if you have access to the server, permission from the administrator to do so, and don't mind signing your own certificate (at least temporarily). I don't really like this solution, but because it seems like a valid answer to my question, I'll just go with it. I'll create a new question related to WebDriver functionality specifically.

Resources