Jump to content

Help Converting Python to PHP


phillipmcsa

Recommended Posts

Hi There,

I run into trouble converting a code from Python into PHP
It said I need to have sha1 hash, but I have no clue what will the code on PHP to replace this

Big thanks in advance

secret = 'se:cr:et:co:de'
success = '1'
sess_timeout = '60'
idle_timeout = '30'
m = hashlib.sha1()
m.update(success+sess_timeout+idle_timeout+secret)
sig = m.hexdigest()

 

 

I did try with this but its not working or maybe its wrong anyway

 

$string1 = $success+$sess_timeout+$idle_timeout+$secret;

$string2 = $success.$sess_timeout.$idle_timeout.$secret;

 

$sig = sha1($string1);

 

or

 

$sig = sha1($string2);

 

or

 

$sig = mhash('sha1',$string1);

 

or

 

$sig = mhash('sha1',$string2);

Link to comment
Share on other sites

The Python code is fairly awful and shows a misunderstanding of security basics, so instead of trying to translate it, I'd rather solve the underlying problem. That is, unless you're somehow obliged to implement this wrong technique.

 

What is it you're trying to do? First off, mixing a secret into a plain SHA-1 hash is a bad idea. There are specialized constructs for this purpose like HMACs (hash-based authentication codes), and there are better hash algorithms like SHA-256. SHA-1 is pretty much obsolete by now.

 

You also need to decide exactly which data you store and how to store them in an unambiguous manner. Hashing timeout durations doesn't make much sense (you'd hash absolute times), and plain concatenation leads to ambiguities. For example, both data pairs (12, 6) and (1, 26) yield the exact same string when concatenated, but they're completely different.

 

A more sane approach:

<?php

const HMAC_ALGO = 'sha256';
const HMAC_KEY = 'f57a1c9756f056b74839ecfd036f273f99578babc704463043856fe1466b383a';

const SESSION_TIMEOUT_MINUTES = 60;
const SESSION_IDLE_TIMEOUT_MINUTES = 30;



// note absolute times
$sessionTimeoutTime = strtotime('+'.SESSION_TIMEOUT_MINUTES.' minutes');
$sessionIdleTimeoutTime = strtotime('+'.SESSION_IDLE_TIMEOUT_MINUTES.' minutes');

$sessionData = $sessionTimeoutTime.':'.$sessionIdleTimeoutTime;    // note the use of a colon as a separator
$hmac = hash_hmac(HMAC_ALGO, $sessionData, HMAC_KEY);

var_dump($hmac);

Note that I'm speculating here, because I don't know the exact requirements.

Edited by Jacques1
Link to comment
Share on other sites

Hi Jacques1,

 

Thanks for your reply

I understood what are you trying to help, but, I have to stuck with its rule this time

The magic clue I had is this
 
"A hex encoded string in lower case. It is a SHA1 checksum"
 
and the sample of that Python script
This is a supposedly a script to pass information back and forth into another system, so I have to follow exact requirement there...
 
Appreciate your help and will be glad if you can guide me a bit more
 
Cheers
Link to comment
Share on other sites

Hi Jacques1,


 


Mmmm.... you maybe right here...

The code is not working for me, I get error telling me that the signature is incorrect ($nonsense_hash)

 

And I directly under assumption that the PHP coding is incorrect

So do you think this code

 

$nonsense_hash = sha1($session_data);

 

should do or replicated correctly with that Python script?

 

I am also awaiting answer from the other end to confirm, but it will takes another 4 days before I get an answer.... :(

Link to comment
Share on other sites

Your Python code yields this hash:

220937f1bc13e2d44609c2126186291e39e92d31

My PHP code above yields this hash:

220937f1bc13e2d44609c2126186291e39e92d31

Looks identical to me.

 

So, yes, the PHP implementation should be functionally equivalent to the Python implementation. Of course there may still be problems with the input (e. g. you got the wrong secret or session parameters), or maybe you're not transmitting or checking the result correctly. But that's something I cannot do much about.

Link to comment
Share on other sites

Hi Jacques1,

 

The story is, there is a firewall device that enable hotspot authentication using external web

Watchguard only provide example with python language without any support for PHP because this is 'additional' feature, not really related to firewalling thing

As I read the script, it supposedly pass simple string back to Watchguard and off they go to browse the net

 

If I can trouble anyone here whom expert in Python, explaining what and why the PHP did not work, will be greatly appreciated

 

I will paste both Python and PHP separately to make it easier to read

Link to comment
Share on other sites


#!/Python27/python
import sys
import os
import hashlib
import cgi
import cgitb
cgitb.enable()
 
# The page #1, that receives the Access-Request-URL, for example
# http://<ip>:<port>/welcome.py?xtm=[url=http://172.26.0.1:4106/wgcgi.cgi&action=hotspot_auth&ts=1344238620 ]http://172.26.0.1:4106/wgcgi.cgi&action=hotspot_auth&ts=1344238620 [/url]
#   &sn=70AB02716F745&mac=9C:4E:36:30:2D:28&redirect=[url=http://www.bing.com/]http://www.bing.com/[/url]
def welcome(): 
  # parse the parameters
  xtm = ""
  if "xtm" in form:
    xtm = form["xtm"].value
  action = ""
  if "action" in form:
    action = form["action"].value
  timestamp = ""
  if "ts" in form:
    timestamp = form["ts"].value
  serial_no = ""
  if "sn" in form:
    serial_no = form["sn"].value
  mac = ""
  if "mac" in form:
    mac = form["mac"].value
  redirect = ""
  if "redirect" in form:
    redirect = form["redirect"].value
 
  print "Content-type: text/html\n"
  print '<html>'
  print '<head>'
  print style
  print '</head>'
  print '<body>'
  print '<div class="background">'
  print '<div class="transbox">'
  print "<h1>Joe's Cafe</h1>"
  print "<h2>Welcome to free Wi-Fi</h2>"
  print "<p>This location provides free wireless services. Our customers may surf the Internet at no charge after registering with our service. Please enter your email address and the order number from your receipt below.</p>"
 
  print '<div id="register">'
 
  if xtm == "" or action == "" or timestamp == "" or serial_no == "" or mac == "" or redirect == "":
    print "<b> Invalid Request, missing some parameters </b>"
  else:
    # show the form
    print '<form name="register" id="register" method="POST" action="welcome.py">'
    print '<ul>'
    print '<li><label>Email:</label><input type="text" name="email_address"></li>'
    print '<li><label>Receipt:</label><input type="text" name="order_number"></li>'
    print '<li><label> </label><input type="submit" value="Register" class="submit"></li>'
    print '<input type="hidden" name="mac" value="'+mac+'">'
    print '<input type="hidden" name="ts" value="'+timestamp+'">'
    print '</ul>'
    print '</form>'
 
  print "</div>"
  print "</div>"
  print "</div>"
 
  # show the annotation
  print "<hr>"
  print '<div style="color:gray">'
  print "This page is envoked by the Access-Request-URL redirected from XTM. <br>"
  print "The interesting parameters from the URL are <br>"
  print "<b>xtm</b>="+xtm+"<br>"
  print "<b>action</b>="+action+"<br>"
  print "<b>timestamp</b>=" + timestamp+ "<br>"
  print "<b>serial_no</b>="+ serial_no+ "<br>"
  print "<b>mac</b>="+ mac+ "<br>"
  print "<b>redirect</b>="+ redirect+ "<br>"
 
  # save request information per mac address and timestamp
  if mac != "":
    x = mac.split(':')
    fn = '_'.join(x)
    f = open('C:/Apache24/1hotspot/'+timestamp+'_'+fn, 'w')
    f.write(xtm+' '+action+' '+serial_no+' '+redirect)
    f.close()
 
  print "We save xtm, action, serial_no, and redirect in a local file", 'C:/Apache24/1hotspot/'+timestamp+'_'+fn
 
  print "</div>"
  print '</body>'
  print '</html>'
 
 
# The page #2, that can send out the Access-Decision-URL
def register(): 
  print "Content-type: text/html\n"
  print '<html>'
  print '<head>'
  print style
  print '</head>'
  print '<body>'
  print '<div class="background">'
  print '<div class="transbox">'
 
  if "order_number" not in form or "email_address" not in form:
    # user did not enter necessary info
    print "<h2>Please return to previous page, and enter order number and email address.</h2>" 
 
  else: 
    # get the request information saved in the file
    timestamp = form["ts"].value
    mac = form["mac"].value
    x = mac.split(':')
    fn = '_'.join(x)
    f = open('C:/Apache24/1hotspot/'+timestamp+'_'+fn)
    lines = f.readlines()
    f.close()
    w = lines[0].split()
    xtm = w[0]
    action = w[1]
    serial_no = w[2]
    redirect = w[3]
 
    # calculate hash
    #f = open('c:/www/hotspotdocs/secret')
    #lines = f.readlines()
    #f.close()
    #secret = lines[0]
    secret = 'thatsthekey'
    success = '1'
    sess_timeout = '60'
    idle_timeout = '30'
    m = hashlib.sha1()
    m.update(timestamp+serial_no+mac+success+sess_timeout+idle_timeout+secret)
    sig = m.hexdigest()
 
    # The main text
    print "<p>Value: ",timestamp+serial_no+mac+success+sess_timeout+idle_timeout+secret,"</p>"
    print "<h1>Joe's Cafe</h1>"
    print "<h2>Hello", form["email_address"].value, "</h2>" 
    print "<h2>Your order number is", form["order_number"].value, "</h2>" 
 
    # Create a link with the URL
    url = xtm+"?action="+action+"&ts="+timestamp+"&success=1&sess_timeout=60&idle_timeout=30&sig="+sig+"&redirect="+redirect
 
    print "<p>Thank you for visiting Joe's Cafe, press this "'<a href="', url, '">Connect</a>'" link or the button below to get access to the Internet.</p>" 
 
    # Create a form with the URL
    print '<form name="register" id="register" action="'+ xtm +'" method="post">'
    print '<ul>'
    print '<li><label> </label><input type="submit" name="Connect" value="Connect" class="submit"></li>'
    print '<input type="hidden" name="action" value="'+action+'">'
    print '<input type="hidden" name="ts" value="'+timestamp+'">'
    print '<input type="hidden" name="success" value="1">'
    print '<input type="hidden" name="sess_timeout" value="60">'
    print '<input type="hidden" name="idle_timeout" value="30">'
    print '<input type="hidden" name="sig" value="'+sig+'">'
    print '<input type="hidden" name="redirect" value="'+redirect+'">'
    print '</ul>'
    print '</form>'
 
    print '</div>'
    print '</div>'
 
    # show the annotation
    print "<hr>"
    print '<div style="color:gray">'
    print "<b>URL</b> of the link is "+url
    print "<p>Note the URL is point to XTM. XTM will process it. It is constructed from data saved in ", 'C:/Apache24/1hotspot/'+timestamp+'_'+fn
    print "</div>"
  print '</body>'
  print '</html>'
 
 
# The page #3, triggered by error in Access-Decision-URL. For example,
# http://<ip>:<port>/welcome.py?error=510&sn=70AB02716F745&mac=9C:4E:36:30:2D:28
def error():
  serial_no = ""
  if "sn" in form:
    serial_no = form["sn"].value
  mac = ""
  if "mac" in form:
    mac = form["mac"].value
 
  print '<html>'
  print '<head>'
  print style
  print '</head>'
  print '<body>'
  print '<div class="background">'
  print '<div class="transbox">'
  print "<h1>Joe's Cafe</h1>"
 
  print "<h2>We encountered a difficulty to grant you access to Internet.</h2>" 
  print "<h2>Error code="+form["error"].value+"</h2>"
 
  print '</div>'
  print '</div>'
 
  # show the annotation
  print "<hr>"
  print '<div style="color:gray">'
  print "This indicates XTM (", serial_no, ") did not successfully grant access to the mac address", mac
  print "</div>"
  print '</body>'
  print '</html>'
 
 
# read the css file
css = open('C:/Apache24/1hotspot/style.css')
style = css.read()
 
# determine whether this is for page #1 or page #2
form = cgi.FieldStorage() # parse query
 
if "order_number" in form:
  register()
elif "error" in form:
  error()
else:
  welcome()
 
# close the css file
css.close()
Link to comment
Share on other sites

This is the PHP just to create a simple link without any decision making or real authentication

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
 
 
<body>
 
<br />
<?
$action = $_GET['action'];
$ts = $_GET['ts'];
$sn = $_GET['sn'];
$mac = $_GET['mac'];
$redirect = $_GET['redirect'];
 
// create hash sh1 (timestamp + serial_no + mac + success + sess_timeout + idle_timeout + secret)
$secret = 'thatsthekey';
$success = '1';
$sess_timeout = '60';
$idle_timeout = '30';
$hash_string = $ts . $sn . $mac . $sucess . $sess_timeout . $idle_timeout . $secret;
$sig = sha1($hash_string);
 
?>
<a href="http://10.0.7.1:4106/wgcgi.cgi?action=hotspot_auth&ts=<? echo $ts; ?>&success=1&sess_timeout=60&idle_timeout=30&sig=<? echo $sig; ?>&redirect=http://www.google.com/">click</a>
<br /> <br />
 
<br /> <br /> <br />
 
</body>
</html>
Link to comment
Share on other sites

<?
$xtm = 'http://x.x.x.x:4106/wgcgi.cgi' ;
$action = $_GET['action'];
$ts = $_GET['ts'];
$sn = $_GET['sn'];
$mac = $_GET['mac'];
$redirect = $_GET['redirect'];

// create hash sh1 (timestamp + serial_no + mac + success + sess_timeout + idle_timeout + secret)
$secret = 'thatsthekey';
$success = '1';
$sess_timeout = '60';
$idle_timeout = '30';
$hash_string = $ts . $sn . $mac . $sucess . $sess_timeout . $idle_timeout . $secret;
$sig = sha1($hash_string);

?>
<a href="http://x.x.x.x:4106/wgcgi.cgi?action=hotspot_auth&ts=<? echo $ts; ?>&success=1&sess_timeout=60&idle_timeout=30&sig=<? echo $sig; ?>&redirect=http://www.google.com/">click</a>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.