Hacking Lua - Inject new functions into built Lua - lua

I am trying to hack a game (not for cheating though) by introducing new built-in methods and functions in order to communicate with the game using sockets. Here is a small "pseudo code" example of what I want to accomplish:
Inside the Lua code I am calling my_hack() and pass the current game state:
GameState = {}
-- Game state object to be passed on
function GameState:new()
-- Data
end
local gameState = GameState:new()
-- Collect game state data and pass it to 'my_hack' ..
my_hack(gameState)
and inside my_hack the object is getting sent away:
int my_hack(lua_State * l)
{
void* gameState= lua_topointer(l, 1);
// Send the game state:
socket->send_data(gameState);
return 0;
}
Now, the big question is how to introduce my_hack() to the game?
I assume, that all built in functions must be kept in some sort of lookup table. Since all Lua code is getting interpreted, functions like import etc. will have to be statically available, right? If that is correct, then it should be "enough" to find out where this code is residing in order to smuggle my code into the game that would allow me to call my_hack() in a Lua script.
There should be two options: The first is that the Lua built is embedded inside the executable and is completely static and the second is that all Lua code gets loaded dynamically from a DLL.
This question goes out to anybody who has a slightest clue about where and how I should keep looking for the built in functions. I've tried a few things with Cheat Engine but I wasn't too successful. I was able to cheat a bit ^^ but that's not what I'm looking out for.

Sorry for not providing a full answer, but if you can provide a custom Lua VM and change the standard libraries, you should be able to to change the luaL_openlibs method in the Lua source to provide a table with my_hack() inside of it.

Since the Lua interpreter is usually statically compiled into the host executable, modifying the interpreter in some way will probably not be possible.
I think your best bet is to find some piece of Lua code which gets called by the host, and from that file use dofile to run your own code.

Related

Call into Lua from TI-BASIC

I have an nspire calculator and after writing a hash table implementation, found the BASIC environment to be a pretty offensive programming environment. Unfortunately, as far as I'm aware, it's impossible to use Lua to write libraries.
I did see that somewhere in the Lua interface you can detect variable changes so it might be possible within a file to use Lua functions, but I fear it will go out of scope if used externally.
Is there a better way to do this?
It's not impossible to write Lua libraries for a TI-Nspire. You can put the libraries code into a string, store it as a variable in TI-Basic and put the file in the MyLibs folder. Then, when you want to load your library, do loadstring(var.recall("libfilename/programstring"))(). This will load the library's code as a string from that files, compile it (using loadstring), and execute it (practicaly the same as require).
Also, about getting from controlling a Lua script using TI-Basic, depending on what you want to do, you could use math.eval("<some TI-Basic code>"). This will execute the code in TI-Basic, and return the result as a Lua value (or string). This way, you can call a TI-Basic function every once in a while, and act according to its output.

Running script for a group to access functions within group parts

I was just wondering in roblox if anyone has ever come upon a situation where they needed to run scripts from another script. My situation is that I am making a control point system for a game. I need to be able to know if the other points are captured in order to capture the next ones so I am attempting to write a controller on top of it but i am not sure exactly how to access the functions from within the control point script.
Yes! ROBLOX provides a very useful feature called ModuleScripts for the very purpose of calling scripts from other scripts. The icon for ModuleScripts looks the same as the icon for regular Scripts except with a little brick in the bottom-right.
The way it works is that regular Scripts can call ModuleScripts in the game using the special require() function. The easiest way to explain this is with an example.
To begin, let's imagine that we have a Script and a ModuleScript. The Script will be located at game.Workspace.normalScript, and the ModuleScript will be located inside a brick called part at game.Workspace.part.moduleScript.
moduleScript will contain the following code:
script.Parent.Transparency = .5 --"Parent" is the part since this ModuleScript is located inside the part
Now, normalScript will contain the following code:
require(game.Workspace.part.moduleScript)
When you run the game, normalScript will execute moduleScript, changing the transparency of part to .5. When one calls require() on a ModuleScript, it will act as though it were a normal function being called. moduleScript acted as though it were a function, and ModuleScripts in general act the same way as functions for the most part.
This also means that ModuleScripts can return values like functions. For example, if we have the following code in moduleScript:
return 3+3
Now, our script will contain the following code:
local number = require(game.Workspace.moduleScript)
print(number) --> 6
This code will print "6" to the console since moduleScript returned 6. As you might guess, this means that ModuleScripts have many more uses than simply remotely executing code.
Here are two more examples of uses of ModuleScripts:
1) Returning functions:
moduleScript:
return function()
print("hey")
end
normalScript:
local func = require(game.Workspace.moduleScript)
func() --> hey
2) Returning modules such as apple below:
moduleScript:
local apple = {}
apple.flavor = "sweet"
return apple
normalScript:
local fruit = require(game.Workspace.moduleScript)
print(fruit.flavor) --> sweet
These are rather silly examples of ModuleScript uses, but ModuleScripts can actually be very powerful tools. For some cool examples, visit the ROBLOX Wiki page on ModuleScripts and scroll about halfway down.

How can I load a local file from embedded Rhino?

I'm using Rhino's context.evaluateString() to run some simple JavaScript from inside of Java. It's textbook right out of the Embedding Javascript guide:
String script = // simple logic
Context c = new ContextFactory().enterContext();
ScriptableObject scope = context.initStandardObjects();
Object o = context.evaluateString(scope, script, "myScript", 1, null);
ScriptableObject result = Context.jsToJava(o, ScriptableObject.class);
I'm not sure this is the current best-practice, because the main Rhino docs appear to be down, but it's working so far.
I'd like to be able to refer to a library in the working directory -- I see that Rhino shell supports load but I don't think this works in the embedding engine.
Is this possible? Is it documented anywhere? Ideally, I'd like to be able to just call something like load('other.js') and have it search directories I specify as a global property.
I have a sort-of answer that I don't really like, not least because it exposes what I'm pretty sure is a Rhino bug that drove me crazy for the last half hour:
eval("" + Packages.org.apache.commons.io.FileUtils.readFileToString(
new java.io.File("/the/local/root", "script.js");
));
{ That "" + ... is how I work around the bug -- if you eval() a Java String (such as is returned from the readFileToString call) without manually coercing it to a JavaScript native string, nothing appears to happen. The call just silently fails. }
This blindly reads an arbitrary file and evals it -- of course, this is what you do when you eval() from the Java side, so I don't worry about it too much.
Anyway, it's not elegant for a number of reasons, but it works. I'd love to hear a better answer!

Storing scripts

I'm implementing Lua scripting engine in my c++ game engine and I was wondering what is the best way to store and execute Lua scripts. I have many scene nodes where each of them could have it's own script assigned. Is calling lauL_dofile(...) every frame for that specific script a viable option, or is there a better way? For example, is there a way to store already parsed scripts? I was looking at luaL_loadfile and lua_pcall. I thought I would load scripts with first one, and call them with second one when I need, but lua_pcall doesn't seem to have an unique id as a parameter, so how should I know which script to execute?
If you're going to use the Lua API, you need to become comfortable with the Lua stack. And one of the most important things you can learn to do is understanding how to read the Lua API docs. For every function, there is a notation on the right about exactly how it affects the stack (if it modifies the stack at all).
luaL_loadfile loads a file and pushes that file as a Lua function onto the stack. lua_pcall executes a function on the stack. But it has a number of caveats about how it does stuff.
The way calling functions through Lua works in terms of the stack is simple. You push the function you want to call. Then you push all of the arguments, in order, from first to last. Then you issue your call of that function. lua_pcall works in this way. This means that the location of the function to execute is always nargs + 1, relative to the top of the stack, where nargs is the number of arguments you're passing to the function.
Note that lua_pcall will pop the function from the stack (along with all of the arguments). If you just loaded the file, this will be the only reference to that function in Lua. Thus, you will not be able to execute the file again. You should duplicate the function before pushing its arguments onto the stack, using lua_pushvalue to copy it. You should probably stick it in the LUA_REGISTRYINDEX table or something, so that it's value is preserved.
As I commented, you usually call luaL_loadfile at initialization time. The loaded files usually define some [global] names (or fill some slots in some global table) as Lua functions. The lua 5.2 documentation gives an example (ยง4 lua_call) of how to call one of them. You'll do such calls (perhaps using lua_pcall or lua_call) at appropriate places of your application, by pushing appropriate things on the Lua stack.

hot swap code in lua

I've heard mumblings around the internets about being able to hot-swap code in Lua similar to how it's done in Java, Erlang, Lisp, etc. However, 30 minutes of googling for it has turned up nothing. Has anyone read anything substantial about this? Anyone have any experience doing it? Does it work in LuaJIT or only in the reference VM?
I'm more interested in the technique as a shortcut in development/debugging than an upgrade path in a live environment.
Lua, and most scripting languages for that matter, do not support the most generalized form of "hot swapping" as you define it. That is, you cannot guaranteeably change a file on disk and have any changes in it propagate itself into an executing program.
However, Lua, and most scripting languages for that matter, are perfectly capable of controlled forms of hot swapping. Global functions are global functions. Modules simply load global functions (if you use them that way). So if a module loads global functions, you can reload the module again if it is changed, and those global function references will change to the newly loaded functions.
However, Lua, and most scripting languages for that matter, makes no guarantees about this. All that's happening is the changing of global state data. If someone copied an old function into a local variable, they can still access it. If your module uses local state data, the new version of the module cannot access the old module's state. If a module creates some kind of object that has member functions, unless those members are fetched from globals, these objects will always refer to the old functions, not the new ones. And so forth.
Also, Lua is not thread safe; you can't just interrupt a lua_State at some point and try to load a module again. So you would have to set up some specific point in time for it to check stuff out and reload changed files.
So you can do it, but it isn't "supported" in the sense that it can just happen. You have to work for it, and you have to be careful about how you write things and what you put in local vs. global functions.
As Nicol said, the language itself doesn't do it for you.
If you want to implement something like this yourself though, it's not that hard, the only thing "preventing" you is any "leftover" references (which will still point to the old code) and the fact require caches its return value in package.loaded.
The way I'd do it is by dividing your code into 3 modules:
the reloading logic at entry point (main.lua)
any data you want to preserve across reloads (data.lua)
the actual code to reload (payload.lua), making sure you don't keep any references to that (which is sometimes not possible when you e.g. have to give callbacks to some library; see below).
-- main.lua:
local PL = require("payload")
local D = require("data")
function reload(module)
package.loaded[module]=nil -- this makes `require` forget about its cache
return require(module)
end
PL.setX(5)
PL.setY(10)
PL.printX()
PL.printY()
-- .... somehow detect you want to reload:
print "reloading"
PL = reload("payload") -- make sure you don't keep references to PL elsewhere, e.g. as a function upvalue!
PL.printX()
PL.printY()
-- data.lua:
return {} -- this is a pretty dumb module, it's literally just a table stored in `package.loaded.data` to make sure everyone gets the same instance when requiring it.
-- payload.lua:
local D = require("data")
local y = 0
return {
setX = function(nx) D.x = nx end, -- using the data module is preserved
setY = function(ny) y = ny end, -- using a local is reset upon reload
printX = function() print("x:",D.x) end,
printY = function() print("y:", y) end
}
output:
x: 5
y: 10
reloading
x: 5
y: 0
you could flesh out that logic a bit better by having a "registry module" that keeps track of all the requiring/reloading for you and abstracts away any access into modules (thus allowing you to replace the references), and, using the __index metatable on that registry you could make it pretty much transparent without having to call ugly getters all over the place. this also means you can supply "one liner" callbacks that then actually just tail-call through the registry, if any 3rd party library needs that.

Resources