« Posts under ActionScript

ListenerProxy v3.0.0 is now OpenSource!

I’m happy to announce that my ListenerProxy is updated to version 3.0.0. I also made it OpenSource. See the ListenerProxy page for more information: ListenerProxy v3.0.0

How we managed to get Alchemy1 working with FlashPlayer 11.2 Incubator and the secrets of SWF Tag 92

NOTE: The technique described in the following text is no longer used in public builds. It was limited to the Incubator release of FlashPlayer 11.2.

A few weeks ago, EPIC published it’s Citadel Demo, driven by Alchemy2 with Stage3D. I assume, if you read this post, you’ll know it wasn’t possible to run Alchemy1 in FP 11.2. There was a lot of discussion about this on the internet and also at Adobe’s prerelease forums. If you wanted to run your Stage3D application along with some Alchemy1 code, e.g. a physics library, the SWF won’t run.
The mysterious thing was that EPIC’s Citadel Demo also uses Stage3D along with Alchemy2. We thought the Player must be told by something inside the SWF that it’s allowed to run Alchemy2 with Stage3D, so we started looking inside the UDKGamePreloader.swf. It’s compiled with SWF Verison 13, while the UDKGame.swf is also compiled with SWF Version 13, but won’t run if started directly.
What is this magic behind the scenes?
Adobe recently announced a nice little tool, called SWFInvestigator. With this tool you can inspect SWF files. We used this on the UDKGamePreloader.swf file and discovered a new unknown SWF Tag 92. I extracted the Tag by opening the file in a Hex Editor and jumping to the beginning of the Tag. SWFInvesitagor is so helpful that it tells you the position of the ‘(invalid)’ Tag:

Name: (invalid)

Type: 92

Position: 8816

Length: 2722

RecordHeader: long

To extract the Tag, jump to this position and copy ‘Length’ Bytes from that position into a new file.
If you look through these Bytes, you’ll discover some human readable Strings like ‘Flash Runtime MOP’ or ‘Adobe Flash Runtime Premium Feature Certificate Authority1′. This might tell you the SWF is signed with some kind of code signing certificate. @ASVGuy found out it’s ASN1 and shared his ASN1 Dump.
I found this nice program to inspect the certificate: ASN.1 Editor that provides a more comfortable viewing of the contents. But there’s another way of inspecting the certificate. Just rename the file with the extracted Tag 92 to the suffix ‘p7b’, so you’ll end up with a file ‘Tag92.p7b’. Double click it and the Windows certmgr will open (I don’t know if there’re similar tools on Mac/Linux). Now you can easily view the contents. Unfortunately I don’t know much about certificates, but I know that for code signing you need a public and a private certificate.
The big question is, how does FlashPlayer certify that the loaded SWF is well signed? Either they do an online-lookup, but Wireshark didn’t capture any connection to be like that. So the private certificate has to be somewhere inside the FlashPlayer Plugin.
Please note that the License Agreement prohibits to reverse engineer, decompile or disassemble the plugin. However, in my interpretation, it does not cover extracting private certificates. You can also get the private certificate with a hex editor by opening the plugin DLL and search for ‘Premium’. I won’t describe it any further and leave this up to you.

Fine. Found out the SWF is signed and if so, changing any Byte will cause the SWF to fail, but that’s not entirely true. You may change the Bytes prior to the FrameRect Tag. But this is not really interesting.
Ok, let’s get to the part how we got Alchemy1 running in FP 11.2.

EPIC’s Loader is really fantastic! They’ve got a background picture as well as a soundloop playing while the SWF loads. We simply tried to load one of our demos by renaming our SWF file to ‘UDKGame.swf’. SUCCESS! It loaded :)
It really was that simple to work around this code sigining thing. With EPIC’s epic preloader SWF, you’ve got the ultimate weapon. A preloader loading the content you want, a background screen, music – anything else you need? ;)
We immediately contacted Adobe to inform them about this major security hole. This might be why they changed how this will work in future. I’m unsure, but I think the details are covered by the prerelease NDA, so I won’t talk about this. What I can say is that Premium Features won’t be signature based. Adobe will use a solution that is as straightforward as possible, so that devs can easily distribute their SWFs without having to resign them constantly.

Some last words on the future of Alchemy and Stage3D.
The following information about Alchemy2 is my very own interpretation.

Alchemy2 is not really a new version of Alchemy, since the produced ByteCode uses the same ‘MOPs’ as Alchemy1, e.g. li16. What’s new about Alchemy2 is that it will be more easy to reuse existing C++ code with less modification. Alchemy2 will for example have it’s own VFS(Virtual File System), it will also wrap a lot of libraries (we found an OpenGL ES2 wrapper in the UDKGame.swf). If you liked Alchemy1, you might want to continue using it. It will continue to work without needing to sign a SWF, buy licenses or anything else.

But if you want to use Stage3D along with Alchemy, you’ll need a license and share revenue with Adobe. You won’t have to share anything unless you made $50K. More details at Adobe.

Quote Tom Nguyen

- Anyone can use Alchemy (domain memory) with any SWF version now, no special signing or cert needed, in the final release of FP11.2 that we just released.

– The approach used in the FP11.2 prereleases was temporary behavior, and is not related to how premium features will be enabled in the future.

Keep the CheateEngine out of your Flash Online Games

Recently, my colleague sent me a few YouTube links, showing how easy popular Flash Games (I won’t tell you any names) can be manipulated. If you don’t know what the CheatEngine is and/or how it works,
you should probably read this post: http://forum.cheatengine.org/viewtopic.php?t=18163. The core functionality of what is does is simple and very effective: It’s an extended memory modify/search tool.

Let’s say you display the user’s experience(XP) in your HUD as an uint. The potential attacker might note this number and put it into the CheatEngine to search the application’s memory for this value. He might get a huge number of
memory addresses returned, might be 100 just as an example, so he needs to filter the particular address. To filter the wanted address, the attacker just needs to get that number changed by the game itself – let’s say by shooting an enemy, so the XP will increase.

He’ll notice one or more addresses have changed. Only the changed values may belong to our XP, so he’ll have a good chance to select the right memory address that stores the XP.

To cheat more XP, all he needs to do, is to change the value at that memory address – that’s it! With the next update of the HUD (shooting another enemy), the new value will be displayed in the HUD, because most of the time developers will use objPlayer.xp += value;. The += first gets the value from the memory, puts it onto the stack, then adds the value behind the operator and stores the result back at that same memory address.

As long as you don’t re-check this value on a server-side, this is a large security hole. But even if you do, it’s not nice to have your HUD displaying 100 mio XP, where 1 mio is the overall maximum value. It’s not good for your game’s image.

Now you might ask yourself “I use uints and Numbers, how can I prevent manipulation?” The answer is “Don’t store the original values”.

  1. The first step should be to use some kind of cryptography, like multiplying the values when writing and dividing them when reading.
  2. The second step could be to use different memory addresses on each write phase.
  3. The third step might be to change the cryptography mechanism on each write phase.
  4. A fourth step could be storing the values twice, once for backup reasons with different crypto to the original values.
  5. Finally, if you want to track which values the attacker tried to change, you can add a sort of silent report to your server.

How does this work? Well, I’d like to provide some basic classes for this.
In the code below, you’ll see some errors, caused by the code parser of my blog (should always read “Vector.<uint>”).

First we’ve got our example Player class:

package my.game
{
	import my.game.cryptovars.CryptoUInt;
 
	public class Player
	{
		private var uintXP	:CryptoUInt;
 
		public function Player():void
		{
			this.uintXP = new CryptoUInt;
		}
 
		public function increaseXP(uintValue:uint):void
		{
			this.uintXP.value += uintValue;
		}
 
		public function traceXP():void
		{
			trace('XP: '+ this.uintXP.value);
		}
	}
}

Second, we need a basic cryptographic class that can be extended by the different types.

package my.game.cryptovars
{
	public class CryptoVar 
	{
		protected	var	uintCryptShiftBackup		:uint,
					uintCryptShiftProperty		:uint,
					uintPointerBackup		:uint,
					uintPointerProperty		:uint,
					uintVectorLengthBackup		:uint,
					uintVectorLengthProperty	:uint;
 
		public function CryptoVar():void
		{
			this.uintCryptShiftBackup	= Math.max(1, Math.random() * 8);
			this.uintCryptShiftProperty	= Math.max(1, Math.random() * 8);
 
			this.uintVectorLengthBackup	= Math.max(4, Math.random() * 32);
			this.uintVectorLengthProperty	= Math.max(4, Math.random() * 32);
		}
	}
}

Third, we extend the CryptoVar class and implement the algorithm for uints.

package my.game.cryptoVars
{
	public class CryptoUInt extends CryptoVar
	{
		private	var	vecSlotsBackup		:Vector.<uint>	,
				vecSlotsProperty	:Vector.</uint><uint>	;
 
		public function CryptoUInt(uintValue:uint = 0):void
		{
			super();
 
			this.vecSlotsBackup	= new Vector.</uint><uint>(super.uintVectorLengthBackup	, true);
			this.vecSlotsProperty	= new Vector.</uint><uint>(super.uintVectorLengthProperty	, true);
 
			this.value		= uintValue;
		}
 
// -- PUBLIC METHODS -- //
		public function destruct():void
		{
			var	i	:int,
				intLen	:int;
 
			i	= -1;
			intLen	= this.vecSlotsBackup.length;
			while(++i !== intLen)
			{
				this.vecSlotsBackup[i] = 0;
			}
 
			i	= -1;
			intLen	= this.vecSlotsProperty.length;
			while(++i !== intLen)
			{
				this.vecSlotsProperty[i] = 0;
			}
 
			super.uintCryptShiftBackup	= 0;
			super.uintCryptShiftProperty	= 0;
			super.uintPointerBackup		= 0;
			super.uintPointerProperty	= 0;
			super.uintVectorLengthBackup	= 0;
			super.uintVectorLengthProperty	= 0;
 
			this.vecSlotsBackup		= null;
			this.vecSlotsProperty		= null;
		}
 
		public function reportIntrusion(uintType:uint):void
		{
			trace('I N T R U S I O N   D E T E C T E D  | Backup ['+ this.vecSlotsBackup[super.uintPointerBackup] +']{Shift: '+ super.uintCryptShiftBackup +'} => '+ (this.vecSlotsBackup[super.uintPointerBackup] >>> super.uintCryptShiftBackup) +' |  Value ['+ this.vecSlotsProperty[super.uintPointerProperty] +']{Shift: '+ super.uintCryptShiftProperty +'} => '+ (this.vecSlotsProperty[super.uintPointerProperty] >>> super.uintCryptShiftProperty));
		}
 
// -- GETTERS AND SETTERS -- //
		public function get value():uint
		{
			var	uintBackup	:uint = this.vecSlotsBackup[super.uintPointerBackup]		>>> super.uintCryptShiftBackup		,
				uintValue	:uint = this.vecSlotsProperty[super.uintPointerProperty]	>>> super.uintCryptShiftProperty	;
 
			trace
			(
				'CryptoUInt::value[get]'			 		+
				' deciphered: '							+
				this.vecSlotsProperty[super.uintPointerProperty].toString()	+
				' deciphered(Backup): '						+
				this.vecSlotsBackup[super.uintPointerBackup].toString()
			);
 
			if(uintValue !== uintBackup)
			{
				this.reportIntrusion(super.uintType);
 
				//restore value from backup and write both with new positions
				super.uintPointerBackup					= Math.random() * super.uintVectorLengthBackup;
				this.vecSlotsBackup[super.uintPointerBackup]		= uintBackup < < super.uintCryptShiftBackup;
 
				super.uintPointerProperty				= Math.random() * super.uintVectorLengthProperty;
				this.vecSlotsProperty[super.uintPointerProperty]	= uintBackup << super.uintCryptShiftProperty;
 
				uintValue = uintBackup;
			}
 
			return uintValue;
		}
 
		public function set value(uintValue:uint):void
		{
			super.uintCryptShiftBackup				= Math.max(1, Math.random() * 8);
			super.uintCryptShiftProperty				= Math.max(1, Math.random() * 8);
 
			super.uintPointerBackup					= Math.random() * super.uintVectorLengthBackup;
			this.vecSlotsBackup[super.uintPointerBackup]		= uintValue << super.uintCryptShiftBackup;
 
			super.uintPointerProperty				= Math.random() * super.uintVectorLengthProperty;
			this.vecSlotsProperty[super.uintPointerProperty]	= uintValue << super.uintCryptShiftProperty;
 
			trace
			(
				'CryptoUInt::value[set] original: ' 				+
				uintValue.toString()						+
				' enciphered: '							+
				this.vecSlotsProperty[super.uintPointerProperty].toString()	+
				' enciphered(Backup): ' +
				this.vecSlotsBackup[super.uintPointerBackup].toString()
			);
		}
	}
}

You can apply this technique to all native types, including int, uint, Number, String and Boolean.
Please note that the limits of the native types change when using this technique, because values are shifted around, so this can cause some unexpected and strange behaviour. You could, for example, limit the shifting value.

Embed Bitmaps, Fonts, BinaryData, etc. without using the Flex framework at all

As a matter of fact, I don’t like the Flex framework very much. To be honest, I don’t like it at all. IMO it’s totally overloaded, slow and grows your SWF’s filesize a lot.
Why I’m writing this post, is because I spend approximately 3-4 hours on searching for a solution and now that I’ve got this solution, I want to share this with you.

At the moment I build an application that loads our noob3D-Library dynamically. While developing I need syntax completion, to do fast coding without having to read the docs again and again ;)
For a normal project it would just be fine to include the lib into your SWF, but I want to load it seperately. To get mxmlc to “exclude” the noob3D-Library from my SWF, I can use the “external-library-path” compiler argument (in my case it’s a custom-flex-config.xml).
This works just fine and the noob3D-Library isn’t linked to my SWF. But this is where my journey begun on yesterday evening: If I use the “external-library-path” argument with mxmlc, also the Flex framework isn’t linked to the SWF anymore. I don’t know if this is a bug or if someone at Adobe smoked too much of whatever kind of plants grow in California ;-)

You might probably also got the nice Error message “VerifyError: Error #1014: Class IFlexAsset could not be found” or something similar in your language. This is what I got. I tried lots of things to “re-include” these Flex files, but nothing worked for me.
Somewhere during my research, I found out that you can also use the Embed tag on classes, rather than variables or consts. I read this concerning Font embedding, but it was mentioned that you can only embed one Font in one class with this. Since this was not what I wanted, I closed the page and continued searching.

However, I finally tried the solution to use Embed in another way ;)
You may know how to use the Embed tag with consts and vars, like this

public final class GeneralCursor
{
    [Embed(source=''D:/Morpheus/src/assets/AwesayCursorArrow.png')]
    private static const AWESAY_CURSOR_ARROW_DATA:Class;
[...]

This includes the specified file as a Symbol into the SWF and works just fine for most of us. But this way uses the Flex framework. If you explore your SWF with your favorite tool of choice, you might see that classes like IFlexAsset, BitmapAsset, ByteArrayAsset, NameUtil, etc. are included in your SWF. But this is not the case if you use “external-library-path”, as I already mentioned above. So, now you may know why I was talking about smoking ;)

OK, what we can do instead is embedding our Symbols, Fonts, Bitmaps, XMLs, or any other data without using the Flex framework at all. It’s pretty simple!
For every file you want to include, you’ll have to create an own class. This class must inherit from the type of file you want to embed. For embedding Pictures, the class should inherit from Bitmap, if you want to include binary data, it should inherit from ByteArray.
Please NOTE: You can’t include XMLs as a subclass of XML, because the compiler isn’t able to transcode this. See the example code below.

Embedding XML files:

package com.badnoob.awesay.morpheus.embeds 
{
    import flash.utils.ByteArray;
 
    [Embed(source='D:/Morpheus/src/assets/xml/i18n/de-DE.xml', mimeType='application/octet-stream')]
    public final class FailSafeLanguageData extends ByteArray 
    {
        public function FailSafeLanguageData():void {}	
    }
}

Embedding Pictures:

package com.badnoob.awesay.morpheus.embeds
{
    import flash.display.Bitmap;
 
    [Embed(source='D:/Morpheus/src/assets/AwesayCursorArrow.png')]
    public final class AwesayGeneralCursorData extends Bitmap 
    {
        public function AwesayGeneralCursorData():void {}	
    }
}

Using XML data:

package foo
{
    import com.badnoob.awesay.morpheus.embeds.FailSafeLanguageData;
 
    import flash.utils.ByteArray
 
    public class EmdeddedXMLLoader
    {
        public static function loadEmbeddedXMLData():XML
        {
            var baFileData  :ByteArray = new FailSafeLanguageData,
                strFileData :String    = objFileData.readUTFBytes(objFileData.length);
 
            return XML(strFileData);
        }
    }
}

Using Pictures:

package foo
{
    import com.badnoob.awesay.morpheus.embeds.AwesayGeneralCursorData;
 
    public class EmbeddedPictureLoader
    {
        public static function loadEmbeddedPicture():Bitmap
        {
            return new AwesayGeneralCursorData;
        }
    }
}

I hope this helps!

noob3D – high quality 3D-Engine for Flash released

I’m proud to announce that badnoob.com’s 3D-Engine, called noob3D, is finally released.
Check it out: http://www.noob3D.com

XMLParser :: save XML.hasOwnProperty as local variable

hi there,
at the moment, I’m writing a XML parser to parse a config file. I always try to keep the calls of “findproperty” low, because it’s very time-consuming. “findproperty” is called everytime you access a method or a property, like “objMyClass.myFunction()”. the AVM searches for the given property every time you use this syntax. if I need a property or method more than once, I always save it to a local variable.

I also tried this with XML.hasOwnProperty, what didn’t work for me. I got runtime errors, but no compilation errors. the used variable was always null.
this is the code I used:

[...]
var funcHasOwnProperty:Function = xmlFileData.hasOwnProperty;
[...]

as one would expect, this should be working without any problems. but you’re wrong, because funcHasOwnProperty will always be null. don’t ask me why and what adobe thought when designing this. maybe I should report a bug…

I still didn’t want to call the “findproperty” OP-Code for every XMLNode and every XMLAttribute, so I tried different things like coerce via

[...]
var funcHasOwnProperty:Function = (xmlFileData.hasOwnProperty as Function);
[...]

but that also didn’t work.
please note: if you call “xmlFileData.hasOwnProperty(‘foo’)” directly, everything is fine, but it seems that you can’t save it to a local variable.

finally, after different approaches, I found the solution by first coercing xmlFileData to Object

[...]
var funcHasOwnProperty:Function = (xmlFileData as Object).hasOwnProperty;
[...]

this is crazy, isn’t it?
this workaround may also work for other fields of application, but I didn’t test it yet.

Receiving Event.COPY, Event.PASTE and Event.SELECT_ALL events on Sprites

According to my work on http://www.awesay.com, I needed to create my own TextField. One could argument to use the TextLayoutFramework (TLF) created by Adobe, but for our uses it’s overloaded. We don’t want our users to need to download ~ 0.5 MB to just be able to read one line of text. In addition to this, we may need other parts of the FlexSDK to be downloaded, so we easily end up with a download of 1 MB or more. The Spark SWC has a size of 1.3 MB, what’s just too much.
So I started to create my own TextInputField with not more than 650 lines of code. I also want the user to be able to copy and paste text from and to his Clipboard, so I’ve had a look at the Event.PASTE, etc. events that I needed to listen for.

My first problem with this was that my TextInputField didn’t receive any of these events, so I double checked the listeners, but everything was fine. After some research I found out that I need to set stage.focus to the current TextInputField. I thought it should be easy by just doing

this.stage.focus = this;

The TextInputField still didn’t receive any events though…
So I traced the actual value of stage.focus after setting and I got “null” in my trace. Just wonderful…
After some more research, I actually found a solution at stackoverflow.com.
What you need to do to keep stage.focus on your InteractiveObject is to listen for the FocusEvent.FOCUS_OUT event and reset the stage.focus property.
Finally I got the copy and paste functionality to work as expected by first setting stage.focus to this and then listen for the focusOut event to reset it once:

[ ... ]
private function setStageFocus():void
{
  this.addEventListener(FocusEvent.FOCUS_OUT, this.focusOutHandler);
  this.stage.focus = this;
}
 
 
private function focusOutHandler(evt:FocusEvent):void
{
  this.removeEventListener(FocusEvent.FOCUS_OUT, this.focusOutHandler);
  this.stage.focus = this;
}
 
[ ... ]

noobFuscator released

Our Flash / ActionScript 3.0 obfuscator is being shipped right now.
It’s available on the Adobe Marketplace:

noobFuscator Download

You need an AdobeID (free Adobe Account).
It’s a 14 day Try and Buy offer.

Find a Roadmap and Feature overview on our blog.badnoob.com

Reviews, opinions and feature request are welcome!

Getter/Setter best practices

In the german flashforum.de, there was a recent discussion about getters and setters. Some of the developers always use getter and setter-methods instead of just using public variables. They believe it’s good OOP-practice.
In my opinion, everybody can do what he/she wants to do, but should always keep something in mind: speed.

Since the moste ActionScripting is done for the Flash Player rather than other applications, we need to keep track of speed. The AVM itself can be very very fast. What’s slowing down there is the FP (my very own experience).

So, OK you want to use get/set because of good OOP or the advanced ASDoc functionality for it – that’s fine! But don’t tell me your code is slow! NAARP… :)

I really wanted to know, if there are any losings in performance when using getters and setters instead of public variables, or the other way around.
Yes, there are losings! In my tests, reading public variables was almost 3 times faster than doing the same with getter-methods. But writing a public variable was more than 4 times faster than writing via setter. I didn’t think that it would be that huge difference…

So my best practices for using getters/setters:
Use getters only if
1. Your getter returns more than only the requested value, e. g. you have a getter to read the full name and it will give you a String of firstName +’ ‘+ lastName.
2. You want a property to be read-only (only makes sense, if you’re creating an API for other developers, because you should know your own code ;)).

Use setters only if
1. You want to validate the given value.
2. When a property is changed, something else needs to be changed too, e. g. you change the labelString of a button, so the TextField’s text of that button should change accordingly.

You may want to download my test-case and share your results: BenchmarkTests

Molehill news

I’m happy to inform you about some news concerning molehill. However it’s not the news I wanted to provide. We are in the prerelease team of molehill for a few weeks now. When joining the team, we had to sign a contract that does not allow me to talk about molehill in details.
But don’t be frustrated – there’s not much more detail than Sebastian Marketsmueller provided in his talk at Adobe MAX. If you really want to code an engine with molehill, you may want to drop an email to Thibault Imbert and tell him about what you’re doing right now and why you should get access to the API.
You also won’t benefit from the news I might be able to give you, because Molehill is still in alpha and a lot of methods may change til the final release.
For using molehill I didn’t took our Alchemy-based engine “noob3D with BlackCat core”, but I rebuild it from scratch. Building the main part of the engine took me about two or three days and it does handle 3k objects with ease. But at this state of development, I haven’t implemented features like Frustum- and Octree-Culling yet, so this number will change.
You may want to study the Assembler-Codes, presented in Marketsmueller’s video on AdobeTV.
I’m sorry, but I’m not able to provide any further details on this.