Freeradius - Receive data from external script - php

I am using Freeradius v3 for my project, and I am executing an external php script to do some checks in the authorization section. What I am trying to achieve is to get multiple attribute-value pairs from the script like:
Auth-Type (control) : value Reply-Message (reply) : value ...
So, for example, i would like to receive and Auth-Type = Accept plus a Reply-Message from the script.
I used this post: FreeRadius Reading attributes while executing external script as reference, and I tried to do as suggested but it isn't working.
Here is some code to explain what I'm doing:
1 - Authorize section
authorize{
update{
control: += `/usr/bin/php -f /path/to/script/test.php '%{User-Name}'`
}
....
2 - Php script (echo section)
echo "Auth-Type = Accept,\n";
echo "reply:WISPr-Redirection-URL = http://google.com,\n";
echo "reply:Reply-Message = 'hello world'\n";
3 - Php output (as suggested from the linked post)
Auth-Type = Accept
reply:WISPr-Redirection-URL = http://google.com
reply:Reply-Message = 'hello world'
4 - Freeradius output
Proxying to virtual server test-server
(0) # Executing section authorize from file /etc/freeradius/sites-enabled/test-server
(0) authorize {
(0) update {
(0) Executing: /usr/bin/php -f /path/to/script/test.php '%{User-Name}':
(0) EXPAND %{User-Name}
(0) --> alice
(0) ERROR: Failed parsing output from: /usr/bin/php -f /home/saiv/radius_script/test.php '%{User-Name}': Expecting operator
(0) ERROR: Program returned code (0) and output 'Auth-Type = Accept, reply:WISPr-Redirection-URL = http://google.com, reply:Reply-Message = 'hello world''
(0) } # update = fail
(0) } # authorize = fail
If I remove the "reply:Reply-Message ..." and put only "Reply-Message:..." the output is accepted by freeradius but the Reply-Message avp goes under "control" and this is not correct.
(0) Program returned code (0) and output 'Auth-Type = Accept, WISPr-Redirection-URL = http://google.com, Reply-Message = 'hello world''
(0) control::Auth-Type = Accept
(0) control::WISPr-Redirection-URL = http://google.com
(0) control::Reply-Message = hello world
Can someone tell me what I am missing?
Any help would be appreciated.

Related

shell_exec command in php not working properly

I am trying to execute a C program using the shell_exec command, which needs arguments to be passed. It is working for one input, but not working for others. I tried to run the C program through terminal, it is working for all the inputs.
This is my execprog.php file. I have to give 2 inputs as command line arguments to file. /var/www/project is the path.
$query = "/var/www/project/./a.out /var/www/project/constraints.txt /var/www/project/constraints_keyword.txt /var/www/project/FIB.txt /var/www/project/ANS.txt";
echo $query;
$var = shell_exec($query);
echo $var;
<?php
$query = "/var/www/project/./a.out";
$arguments = array
(
'/var/www/project/constraints.txt',
'/var/www/project/constraints_keyword.txt',
'/var/www/project/FIB.txt',
'/var/www/project/ANS.txt'
);
$string = '';
for($i=0;$i<count($arguments);$i++)
$string.= ' %s';
$command = vsprintf("{$query}{$string}", $arguments);
$var = shell_exec($command);
echo $var;
As you it works on the terminal and not on apache then apache's php.ini file may be disabling the use of shell_exec().
See http://www.php.net/manual/en/ini.core.php#ini.disable-functions
Your apache's php.ini file may look something like
disable_functions=exec,passthru,shell_exec,system,proc_open,popen
Remove shell_exec from this list and restart the web server, although this is a security risk and I don't recommend it.
In general functions such as exec,shell_exec and system are always used to execute the external programs. Even a shell command can also be executed. If these two functions are enabled then a user can enter any command as input and execute into your server. So usually people disable in apache config as disable_functions to secure their site.
It works for me - Here is test run
Sample test c code
[akshay#gold tmp]$ cat test.c
#include<stdio.h>
int main(int args, char *argv[]) {
int i = 0;
for (i = 0; i < args; i++)
printf("Arg[%d] = %s\n",i, argv[i]);
return 0;
}
Compile
[akshay#gold tmp]$ gcc test.c
Sample php script
[akshay#gold tmp]$ cat test.php
<?php
$query = "/tmp/./a.out /var/www/project/constraints.txt /var/www/project/constraints_keyword.txt /var/www/project/FIB.txt /var/www/project/ANS.txt";
$var = shell_exec($query);
echo $var;
?>
Execution and output
[akshay#gold tmp]$ php test.php
Arg[0] = /tmp/./a.out
Arg[1] = /var/www/project/constraints.txt
Arg[2] = /var/www/project/constraints_keyword.txt
Arg[3] = /var/www/project/FIB.txt
Arg[4] = /var/www/project/ANS.txt

Losing JSON value from Python to PHP?

I am struggling with a weird issue. I have a Python script that is accessed from a page via PHP and returns a JSON object with about 20 variables. All of them work all of the time except one that always returns an empty value. Directly running the Python script on the server returns a value every time, but php never sees it. I have tried output as a string, as an int, and even a string combined with a preset value. The posted code has only two shown, most of the functional values are omitted for length. ("cpul" is the one not working.)
PythonScript.py:
#!/usr/bin/python2.7
import os, json
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
tmp = (1.8 * float(res.replace("temp=","").replace("'C\n",""))) + 32
return(tmp)
# Return % of CPU used by user as a character string
def getCPUuse():
val = str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\
)[2:4])
return(val)
result = {'cput': CPU_temp, 'cpul': CPU_usage}
print json.dumps(result)
OUTPUT FROM SSH TERMINAL: {"cpul": "9", "cput": 106.16000000000001}
phpScript.php just passes the result on to the browser:
<?php
session_start();
try {
$result = exec('/usr/bin/python /scripts/PyhtonScript.py');
echo $result;
} catch (Exception $e) {
echo '{"res" : "ERROR", "msg" : "Caught exception: ' . $e->getMessage() . '"}';
}
?>
OUTPUT FROM BROWSER: {"cpul": "", "cput": 106.16000000000001}
If I change PythonScript.py 'result' to say:
result = {'cput': CPU_temp, 'cpul': 'foo'}
OUTPUT FROM BROWSER: {"cpul": "foo", "cput": 106.16000000000001}
and if I change PythonScript.py 'result' to say:
result = {'cput': CPU_temp, 'cpul': 'foo' + CPU_usage}
OUTPUT FROM BROWSER: {"cpul": "foo", "cput": 106.16000000000001}
If I modify the function to output an int rather than a string I get the same results without the quotes:
OUTPUT FROM SSH TERMINAL: {"cpul": 9, "cput": 106.16000000000001}
OUTPUT FROM BROWSER: {"cpul": "", "cput": 106.16000000000001}
The value is a percentage, so I would love to multiply it by 100 before sending, but if I modify the function as:
def getCPUuse():
val = str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\
))
mod = int(val) * 100
return(mod)
OUTPUT FROM SSH TERMINAL: {"cpul": 90, "cput": 106.16000000000001}
OUTPUT FROM BROWSER: Nothing, blank screen
APACHE2/error.log:
Traceback (most recent call last):
File "/var/www/html/assets/scripts/info_lkp.py", line 49, in <module>
CPU_usage = getCPUuse()
File "/var/www/html/assets/scripts/info_lkp.py", line 29, in getCPUuse
mod2 = int(mod)*10
ValueError: invalid literal for int() with base 10: ''
'unknown': I need something more specific.
Any idea what I am missing before I run out of hair to pull out? As stated, posted code is truncated to remove unrelated working similar functions and their associated outputs.
This is a Python error
When you multiply it by 100 before sending it, in your python script, error happens there.
And value is being lost, well, not because of the PHP.
It's because your python script does not return valid JSON.
Read about this error here ValueError: invalid literal for int() with base 10: ''

Passing variables from php to python and python to php

I am breaking my head to make this work but I am in a dead end. I have no idea what I am doing wrong.
I play with php and python; trying to execute a python script through php exec(), return an output and pass it to another python script.
This is my workflow:
1) Through jquery and an ajax request I pass some data to a php file (exec1.php) which looks like this:
$number = $_POST['numberOfClusters'];
$shape = $_POST['shapeFilePath'];
// EXECUTE THE PYTHON SCRIPT
$command = "python ./python/Module1.py $number $shape";
exec($command,$out,$ret);
print_r($out);
print_r($r); //return nicely 1.
2) The python file which I run Module1.py looks like this:
# this is a list of list of tuples
cls000 = [[(365325.342877, 4385460.998374), (365193.884409, 4385307.899807), (365433.717878, 4385148.9983749995)]]
# RETURN DATA TO PHP
print cls000
3) Then I have a nested AJAX request inside the success function of my previous AJAX request in which I pass the response (in this case the cls000 list) into a php script called (exec2.php) like this:
# PASS VARIABLES FROM FORM
$number = $_POST['numberOfClusters'];
$shape = $_POST['shapeFilePath'];
$clusterCoords = $_POST['response']; # response from previous Ajax request
// EXECUTE THE PYTHON SCRIPT
$command = "python ./python/Module2.py $number $shape $clusterCoords";
exec($command,$out,$ret);
print_r($out); ## THIS GIVES ME AN EMPTY ARRAY!!
print_r($ret); ## THIS GIVES ME A RETURN STATUS: 2
4) My Module2.py script looks like this:
number = int(sys.argv[1])
shape = sys.argv[2]
cls000 = json.loads(sys.argv[3])
# RETURN DATA TO PHP
print cls000
What am I doing wrong? If I remove this line 'cls000 = json.loads(sys.argv[9])' and return for example 'shape' everything works fine. But when I try to return cls000 I get a status code 2.
What am I missing here?

Passing GET/POST parameteres to php via commandline

I'll excuse myself behorehand because i'm quite sure there'll be some obvious solution or an answer already out there, but after quite some extensive search I just cant find it.
I'm developing a simplified web server as a project in .net. What i want to do is calling the php.exe for each HTML request to execute any php code within the file, and then return the result to my server where it will be served to the client.
This was quite simple without passing GET/POST parameters, but I can't find the way to make this work.
Right now i have this as my function to write the call the php via command line
Public Shared Function phpparse(ByVal requesttype As String, ByVal argnames() As String, ByVal argvals() As String)
Dim proc As Process = New Process
proc.StartInfo.FileName = "php\php.exe"
Dim B As New System.Text.StringBuilder
B.Append("-B ""$_")
B.Append(requesttype & " = array(")
For i As Integer = 0 To argnames.Length - 1
B.Append("'" & argnames(i) & "' => '" & argvals(i) & "', ")
Next
B.Remove(B.Length - 2, 2)
B.Append(");"" -F script.php")
InputBox("", "", B.ToString)
proc.StartInfo.Arguments = B.ToString
proc.StartInfo.UseShellExecute = False
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.CreateNoWindow = True
proc.Start()
Return proc.StandardOutput.ReadToEnd
End Function
which returns something like this:
-B "$_GET = array('name' => 'John', 'email' => 'john.doe#no.com');" -F script.php
and should be calling this test php script:
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
but it gets stuck trying to read the answer
With php you could read the args like this:
<?php
if (isset($argv)) {
echo $argv[1]." ".$argv[2];
}
?>
this will return
John john.doe#no.com
I don't really get it how do you send the command line params.
You should just run the php like
php.exe John john.doe#no.com
I've found a work around the issue. I'm still looking for a proper solution but I can work with this for now
The parameters of the call to the PHP CLI should be
-r "$arrayname = array('arraypar1' => 'arrayval1', 'arraypar2' => 'arrayval2', ); require_once('C:\fullroutetofile\script.php');"
It seems that you can't call -B and -f at the same time, but require_once lets you bypass that.

what is the correct syntax of BLPOP on Predis?

I do it like this:
$r = new Predis\Client($single_server, $options);
$retval = $r->blpop('queue:query');
But I get this error:
ERR wrong number of arguments for 'blpop' command
Whenever I do this
$r = new Predis\Client($single_server, $options);
$retval = $r->blpop('queue:query',0);
I get the error:
Error while reading line from the server
Doing it from redis-cli
redis 127.0.0.1:6379> BLPOP queue:query
(error) ERR wrong number of arguments for 'blpop' command
redis 127.0.0.1:6379> BLPOP queue:query 0
1) "queue:query"
2) "hello world"
Seems like a bug. The latest version doesn't have this issue, also it apparently dropped namespaces:
<?
include_once "Predis.php";
$r = new Predis_Client();
$retval = $r->blpop('queue:query',0);
var_dump($retval);
?>
It blocked when I accessed the page. Then, I issued LPUSH queue:query 0, went back to the page, and got this:
array(2) { [0]=> string(11) "queue:query" [1]=> string(1) "0" }
Nevertheless, I would recommend the use of phpredis, it is faster than this library, because it is compiled as a php extension. If you have the rights in your server, that's a good pick.

Categories