So we're going to talk today about some Pyretic, which is a framework that I wrote for reverse engineering in Python at the Python layer. It's normally like about an hour-long talk and apparently I've got to do it in 45, so we're going to fly through some stuff. Probably not spend so much time on the understanding of the Python language. I assume if you're here you've at least got some understanding of that. So why reverse Python, which is probably a good question to begin with. Most people reverse at C or the assembly layer. I needed to assess the security posture of some closed source Python and the people who wrote that application had gone to some length to try and stop me assessing that security posture. So obviously it was a personal challenge of I would defeat them. All the available toolkits really didn't work with anything other than standard compiled Python byte code. Even the smallest obfuscation would kind of trip them up. So that was why I decided obviously I had to write some tools to do what I needed to do. Most of the kits, you know, will assume that all the decompilers and disassemblers just assume that the code that you're dealing with is standard byte code. You know, people won't have gone to any lengths to try and stop you reversing it. So none of the toolkits apart from this one now has kind of any understanding or attempt to get around any obfuscations which might have happened. So that's why I decided to write some tools to do what I think might be in place. Also obviously there's a huge amount of Python code out there. And a lot of these, you know, a lot of it is used in web applications and remote applications. So there's a big attack surface area to be working with. But there isn't a huge amount of work in actually doing Python-specific techniques. So it was a good area to carry on some research in. And maybe like in the past there actually hasn't needed to be much work in this space. Because people hadn't been distributing obfuscated Python, they'd just been throwing the PYs out. So you know, you could read the source code anyway. But this is changing. There's some general kind of bigger picture trends. Obviously people are moving away from developing in C and C++ for all the reasons that, you know, people have failed at it for the last 20, 30 years, found out that it's hard. Obviously high-level languages, Python, Ruby, Lua, et cetera, et cetera, much more rapid to develop in. The people that are able to develop in it are kind of straight out of university and are able to do Python much better than they are to be able to do C. So there's more developers. It's cheaper to develop. It's cross-platform, et cetera, et cetera. There's also a changing in the distribution. You know, five or six years ago, you always download an application. Now it's all Web 2.0, the cloud. You know, everything's got something to do with the cloud, but nobody knows exactly what the cloud is. It's got something to do with the network, the Internet. So everything now is, you know, software as a service. What this means for reverse engineering obviously is maybe you don't actually have access to the files in which you're trying to reverse because you're dealing with them on a remote server. Also, overflows aren't the only bugs. You know, everyone's obsessed with obviously stack overflows. It went to heap and people got more and more complicated and all the protections were put in place. To work up, you know, a good memory corruption bug now will take some talented guys, you know, a good six months of solid research. There's definitely a need for that, but the return on investment for those kind of bugs, you know, it's a significant investment. Some of the research is obviously immunity. Where I work, we've got the resources that we can invest six months in a bug, but obviously then the sale, the price of that bug has to reflect the amount of work that goes in. A lot of people aren't prepared to pay for bugs. Python will have lots of good bugs in it, and higher level languages can have lots of good bugs. And they're often very much cheaper to find because they just haven't had as much effort put into the techniques to find those kind of bugs. So it's easy. There's a lot more low-hanging fruit. Reverse engineering, a lot of the toolkits are often kind of done in a C-centric manner. With newer reflective languages, maybe there are some better ways. People are kind of stuck in this decompilation mindset. Maybe there are some better ways to go around it. And obviously lots of the toolkits, certainly anything to do with Python reversing, relied the fact that you had access to the file on disk, that you could do kind of a static reverse on the serialized object on disk. If you're working in a service-orientated method, that might not be the case. You might not actually have access to the disk, the file on disk, but you do have runtime access to the objects on a remote server. If you can get actually source code back out of that remote object, then obviously that's highly desirable, but you're never going to have access to the disk. So we're going to talk a little bit more about that. And bug snobbery. I certainly have fallen into this category. I get loud and vocal about why am I having to do a week's worth of assessment on XSS and CSRF. But to be quite honest, just because you're not working on some hardcore overflow, you can get some pretty good bugs. If it gets you in, it gets you in. You shouldn't be too proud to work on an XSS, even though it's in JavaScript and that's what all the kiddies are doing. And there are lots of areas with low-hanging fruit that haven't really had too much research put into them yet. And not everybody is an eco-weissman. Not everybody can do crazy heap reversing. So I came to the conclusion that I'd never become as good as an eco, so I had to start looking in other areas to make myself feel good. So other side effects of the new development model. Obviously, everything is always in beta. The less experienced developers are developing code that actually is used in products. And time to market and new features are key. So there'll be a lot of new code that's out there that hasn't necessarily been tested as thoroughly as you'd like. And obviously, the flip side of all those points is that there's going to be tons of bugs. And that's what we like. There's often new large populations of users for whatever the in-app of that week is. And they can often get a little bit of a bug. And that's what we like. There's often new large populations of users for whatever the in-app of that week is. And they can often be rapidly seeded. So a huge population of users running some very vulnerable code will burst up. And obviously, that's the best thing that you can have. And a lot of these bugs, because it's in the higher level languages, are actually cross-platform and cross-architecture. Now, that's awesome. You write one bug and it will execute across whatever architecture system they're running on and whatever operating system they're running on. So you could hack an iPhone right the way up to a mainframe. If it's running Python and there's a Python-level bug, you'll be good, which is huge. And there's obviously all these conferences, and certainly with Black Hat, you'll get a lot of vendors peddling huge amounts of snake oil. We're more secure than we've ever been. But I really think it depends on what metrics you're measuring on. There's more lines of code than there's ever been. There's more people who think they can code. I'm sure there's everyone sitting in here knows people at their place of work who should never be let near a keyboard, yet they're doing code which is going out in production systems or in internal systems. Obviously, everything's now about connectivity. Everything's network-aware. And the pervasiveness of technology is increasing. So I'm not sure, really, that we are more secure than ever. And the higher-level languages are being used increasingly to seed all this crap everywhere. So if we can find some good techniques to exploit them, then we will. What's not going to be discussed? There's not going to be any dropping of commercial application source code that I've reversed out from anything or any bugs that I found within, mainly because the lawyers don't seem to agree that what happens is going to happen. It happens in Vegas, stays in Vegas, and I can't afford to be taken to court. So why reversing a high layer? Most people assume that going in to the lowest layer is the best thing. But if an application has been written in a high-level language and reversing it at the layer it's been written means that you're closer to the developer. You're closer to the information. Further from the data, well, but closer to the information. So you can get a much better sense of bugs that might be around. We're not assessing the security posture of the Python runtime. That does have a ton of bugs, but we're looking for bugs in the Python code itself. So reversing out the layer that the code was implemented in is the best thing to do. I'm not sure how clear this will come out, but you should be able to see here this is reversing like in a normal debugger. And you'll see a lot of call-outs to kind of the Python DLLs. Even to do something simple, like print a hello world, there's actually a lot of layers in between you and the code. So it gets very complicated. Even to do simple things can actually take quite a lot of effort. And obviously, Python is a fairly complex language. It's got quirks and flaws and bugs just like every other language. But like I say, a lot of the people that develop in it are maybe less experienced developers. They don't really understand so much about how computars work. So there's kind of mistakes that everybody makes. I'm going to just highlight a couple. Anybody out there that's good at Python that can see the problem with this code? Shout. All right, I won't wait long. There's only one var. Well, yeah, the var is a class rather than an instance attribute. So you can see if you, on foo and var, which are the instantiations of the test class, if you actually print out the var variable, both of those instances of the class share the same variable because the variable is at the... at the class layer. People make this mistake all the time. If they make a new instance of an object on a shared system, you can actually get access, depending how they use the class, obviously, you can get access to other people's objects, which, depending on the situation, can be a good thing. Anybody can see the problem in this? Okay. It's a mutable default argument here. So when it was called here with an argument going in, we're all good. It acts as, you know... foo is appended to the end of the list that was supplied. That's as expected. If it's called without an argument, the default argument is used, but the default argument is made in instantiation time. So, again, it is shared. So you call it twice, and the list is growing. I've seen a lot of people make this mistake. Certainly in remote applications, they'll have socket objects here. It means you can access somebody else's socket object, and then you've got a route back to a different client. So, obviously, like every language, there's a ton of these bugs that maybe inexperienced developers, don't really understand because they don't understand really how Python's doing things. It's just a fairly easy language to write in. So lots of people make some pretty simple mistakes. So what were my initial aims for doing this? I wanted to be able to have a toolkit that would rapidly assess and find bugs within applications, even if they were obfuscated, and I didn't have access to the .py's themselves. Obviously, I wanted to get back to a source code representation from, you know, a live memory object. And I'd prefer to have a general approach against all the ways that people are obfuscating bytecode rather than a specific approach for each different thing because, obviously, that's a cat and mouse game and it's going to take a lot of time to carry on. So if there was a general way of defeating what people were doing, then I wanted to take that. Obviously, there was because I'm giving this talk. So we're going to blast through this because we haven't got much time. Like 101 of Python language. So, obviously, there's a fair amount of different file types with Python. The py is the one that everyone will be familiar with. It's where the source code lives. It's human-readable. Obviously, you can take that py. It will run on any Python platform. Then there's kind of the compiled and serialized versions of the Python languages, pyc being the, you know, the kind of most ubiquitous one. It's a standard serialized form. We'll have a look at the format very quickly. Anytime py is compiled or imported, import obviously implicitly compiles, a pyc will pop out of the... A pyc will pop out, which is the bytecode equivalent of the py. Contrary to popular belief, it doesn't actually speed up execution. It purely speeds up instantiation because you miss out that compile step. So you don't need to recompile every time you run the application. It is cross-platform. A pyc will run on, you know, Linux and Windows, but it's not cross-Python version. So a 2.4 pyc won't run with a 2.5 runtime. And it is purposely undocumented by the Python developers to allow them the flexibility to change the bytecode format without breaking the code. And a bunch of stuff where people have relied on it. PYOs, same structure as PYCs, but they're optimized at some point. You can optimize at the first level, which will remove all the asserts. Optimize at the second level, it will remove all the asserts and all the inline documentation. Nothing to do with speed, purely file size. This shouldn't break most things, but in some kind of corner cases it will. Python lex and yak is one of those that if you remove the doc strings then everything fails because the actual lex grammars are kept in the doc strings. But most of the time a PYO, just smaller file size, so that's all good. PYD, the most complex format that Python will produce by itself. It comes as standard with CPython. I've seen a lot on Windows. It will compile into a shared compiled C object. We're not really going to talk about these. There's been some good work done by Aaron Portnoy and Ali. And they can access the PYDs and they did a toolkit called anti-freeze where you can unpack the PYDs, modify the bytecode, repack them, and they did some good stuff with games on Windows making that character jump like 20 times higher. So the Python PYC format, there's a four byte magic number. This is for the version of Python. Like I say, to make sure, so the runtime can do a check of what version the Python was compiled with and bail out if it's not the version that it is. There's a four byte timestamp. So why this is important later, basically it's to decide whether a new PYC should be generated from a PY. And there's a Marshall code object which is the actual serialized code object where the Python code resides. You want to say something? Well, we made it to 2 o'clock this afternoon until I had to come and yell at you. So, several someones are stiffing Katie's who have been very nice to us for $100 plus bills. As in seven people eat, get up, walk out, leave the bill. Very, very uncool. Let's apply that whole new social media thing or whatever you guys are calling it. If you know who they are, pressure them to go pay their bill. If you know who you are, go pay your bill. If you're thinking about doing it, don't. The numbers isn't enough now that I'm coming over here to make an announcement about it. So it's not just one group. If it keeps happening, you will be, they will review the video tapes. They will catch you. You will be in trouble. And more importantly, we will be in trouble. We have a good relationship here at the hotel. Much as we love the Alexis Park, I would rather not go back to the Alexis Park. It is not a lot of fun doing CPR on somebody in 110 degree weather. Please don't send us back to the Alexis Park. Or I promise you, you and I will sit down and have a little talk. Okay, guys. Be responsible. Be adult. Get your friends to go pay their bills. Thank you. Okay. So it sounds like someone's fucked up. Yeah, let's please not go back to the Alexis Park. Right. So that was the bytecode format for PYCs. All those formats come out standard as Python. And then optionally, a lot of people are using packaging. Packaging allows you to distribute a runtime along with your Python code. It means that people don't have to have the version of Python which you need to be installed on their system to run your code. So Py2Xy, Py2App, they're all examples of packages. So they'll take your code, runtime code, bundle it up, and allow it much easier to run just with a double click. This is important because it means that developers can distribute a modified Python runtime along with their code. And a lot of the anti-reversing techniques that we'll talk about rely on the fact that they can distribute that modified Python runtime. We're going to speed up. So this is the object hierarchy. We're going to blast through this. Obviously, modules, the only thing to note is that a module doesn't have a code level object. It doesn't have a code object once you've imported it. This is for speed reasons. Once it's imported, it's not needed. It's a language design issue. But from reversing, it's a real pain in the ass. Obviously, then there's the class level objects. All the superclasses to a class are in underscore bases. Classes have methods. Methods are literally just a wrapper for functions. The functions held in the IAM func object. Functions have a func code object. The code object, which is actually what we care about, has various attributes. It's a very verbose code object. You can tell a lot about how the code will run. The biggest one is the CO code object. That's actually a string representation of the byte code. You can access that and start reversing things out. Then there's all these attributes here. Constants and variable names. The line numbers that the function was instantiated at. All really useful information as we get into some of the techniques. All you need to know is that from all the Python objects, the code is the one that we're really going for. Everything else just stacks into that. We've blasted through this pretty quick. Python has byte code language, obviously. It's a pretty simple language. And every opcode, just as an 8 byte opcode, so there's only 256 available. Currently in Python 2.6, there's 113 already defined. Optionally, one Python opcode can take arguments. All arguments are 2 bytes. So, if this is a Python source, just print bugs. When it goes into its byte code instructions, you can see there, these are the different instructions. Names. Each of those will map to a single integer. Just a mapping between a number and the instruction. And some of them take arguments. And this is the byte stream. So you can see that 64 would relate to load const. And it took two arguments, both of which in this case were null. Well, one argument is always 2 bytes. Fail. Okay. We're going to run through this now, and get on to the new techniques. The existing stuff that's available. Disassemblers. There's Dis that comes standard with Py. The representation that you saw from source code to instructions, that was just done using Dis. It will just dump out the bytecode for you. The important thing is it relies on opcode.py, which is the Python-level module which gives you those number-to-instruction mappings. Oh, fail again. So there's debuggers. The Python debugger comes, again, with normal Python. But it's very much a developer's debugger. It assumes that you're going to have access to the py. It is for finding bugs as you're developing as opposed to finding bugs in other people's code. So that was what I based a lot of my stuff on, but extended it up to be more useful when you haven't got access to a py file, only the py sees. Decompilers. There are a bunch of decompilers, some of which are an application that you download, some of which are an online service. Some are free, some are commercial. They do definitely vary in quality and depending on what version of Python you're running. The best free one that I found that I based a lot of the stuff that we talk about in Pyreticon is unpyc, from a Russian developer. It's not perfect, but it's good enough in most situations. For the online services, depython is certainly the best. The quality of their decompilation is really good, but it's not free, and you're giving them your source code, and you're giving them your code. Bytecode assemblers and modifiers. Byteplay and bytecode assembler are certainly good ones. Antifreeze is an example that we've already spoke about for PYDs. These allow you to work at the Python bytecode layer rather than at the Python source layer. If you're interested at this level of Python, they're certainly good to play with, and you'll learn a lot more about how the Python runtime actually operates by playing with them. So that's what exists so far. What are the anti-reversing techniques that I was seeing in a lot of these commercial apps? Like I say, increasingly, commercial and closed-source apps are putting obfuscation techniques in to stop you getting at their PY, because obviously they've put their effort into capitalizing on that, and there will be a bunch of bugs in there. The more effort that they go to to keep the source away from you, the more you know there's going to be bugs in there. I've worked with Python a lot, and there was a bunch of different techniques that I've seen, so we're going to blast through these techniques. They mainly focus on when the bytecode is on disk, when there's those PYC files on disk, all the techniques focus on obfuscating that PYC file so you can't... making it so it's not in its standard form. So all the basic tools that we've just talked about break. And that's pretty much the approach that everybody's taking. So, the simplest one that you see a fair amount is just hiding in the packages. You know, the Py2X, the Py2App. People believe that if they wrap their code in that, then you can't get access to it. It's easy just to reverse out. Often you'll find a packager and maybe even the PYs will be present in that. So that's super easy to get by. You often see this on Windows 32 applications. People will package it up into a PYD and assume that you can't get access to it. But it's a standard documented format, so it's very easy to just reverse out. Source code obfuscation. I've never actually seen this used in a real application. There's a commercial application that is sold to do the obfuscation, but I've never seen anyone actually use it. It's a similar kind of thing that you see in JavaScript malware, where they'll try and make the source code look complicated. The functionality will be the same. So for example, there's this kind of easy code on the left, and it goes to this kind of weird obfuscator code on the right. I'm sure it's very easy to actually undo what they've done. I haven't looked into doing it, because like I said, I've never seen it in a commercial application, so I haven't tried. When I was looking at the guy who sold this Python obfuscator though, I found a gem. And he also sells poor sense. Poor sense is a way to cat-proof your computer. And it will tell you when cat-like typing has been detected. So if people have cat-computer problems, this is your man. It's only $19.99, so it's a snip. Some of the more effective modifications that you use all rely on modifying the Python runtime. As we said, you can distribute the Python runtime in a package. This means the authors can modify the C Python at the C layer, compile their own version of the Python runtime, and then that can switch things around, make the bytecode that's produced different, etc. And this is what people are doing. So one of the simplest things is to just change that bytecode magic number. Remember from the PYC, the first four bytes are a magic number that say what version of Python it is. If the Python that you're running isn't the same version, it will bail with a bad magic number error. You probably can't see too well. So these are all the defined magic numbers for the different versions of Python. This is in the comments for the import.c. Basically all they do is they change the version of the Python number so any standard Python, apart from their modified runtime, won't run their code. It's kind of, if you fall at this barrier, you're failing pretty hard because you just need to replace the first four bytes with a four bytes standard Python magic number, and you're good. It does make all the standard tools fail because, like I say, they're expecting standard formatted bytecode. So it's a very easy change for developers to make, but it's very easy to get around as well. Changes to the marshalling format. As we said, there was the four byte magic number, there's a four byte timestamp, and then there's this marshalled code. Obviously the marshalling happens in a standard format. If they go in and go to marshall.c in the CPython runtime and change how it's marshalling things, then obviously all the standard tools won't understand how to unpack it. They can get arbitrarily fancy here. I've seen stuff that looks like it's pretty much doing some kind of encryption. I'm sure it's pretty crappy encryption, but still, to work out what they're doing, because it's happening in the CPython layer, you're going to have to trace it in a debugger, and you're going to have to do that for every different type of marshalling modification. Which is a bit of a pain, so I wanted to avoid that, and I managed to avoid it by working at the Python layer. We'll talk about that in a bit. And then opcode remapping. This is one of the more complex things that they do. Basically that table that I spoke of, of those integers to instruction pins, they juggle all that around, so it's not the standard format that you'd expect. They change the opcode.h in the runtime, and remove opcode.py from the distributed runtime, and that means that you can get access to the CO code object, but the byte stream makes no sense, and it makes no sense to any of the decompilers, because they're running off the standard opcode map, and this has got a juggled up opcode map. When I found this, it was a real pain, but I've got a pretty simple attack to get around it, which we'll talk about. So the general approach with what we're taking with Pyretic, I want to remove the reliance on having access to the file on disk. I want to work in memory only. I want any of the protections, like the marshalling and everything, the application to undo it, because however complex that they've got with marshalling up something, they're going to undo the marshalling, and then when it's in memory, it's just a standard Python object, and obviously it's easier to understand a standard Python object than piss about at the C layer trying to work out what they were doing with their marshalling. I'm going to get in process at the Python layer, and then obviously I have access to the full Python namespace and I can start to query the objects and then from querying the objects in the live memory, get back to a source code representation. So, the fact that you can, with a reflective language like Python, query an object, this is obviously really useful in the cloud paradigm, because you will never have access to their files. However, they may be, Python's a popular choice for using as a sandboxing environment, or as an environment to allow you to access their API. They think that maybe if you only have access to their objects, that's all good, but with these techniques you can actually get the source code back from their objects, so even though you're interacting with a remote computer, you can still get access back to the source code even though you haven't got their PYCs on disk, which is pretty cool. Moving forward, I think this is an area that more people are going to have to, for all types of languages, not just Python, put more effort into, purely because the paradigms of distributing applications are changing, so I'd expect it to be an area that you'll see a lot more activity in the future. How do we get in process? I said we need to be in process so we can query the Python objects. Obviously, Python, if people are trying to obfuscate their code, they won't distribute the pies, they'll only distribute the PYCs, and if they've modified their runtime, you need to use their interpreter to run their PYCs, because they've pissed about with the marshaling or the bytecode number or whatever. But the import rules for Python still apply. So in import C, you'll see there's this equality test here, where it talks about the timestamp, and they're saying if the, this is just saying, if the timestamp in the Python bytecode is not equal to the timestamp on the PY file that's on disk, then recompile that bytecode. So you're using the PY in preference to the PYC, because something may have changed in your PY, and then you'll recompile the bytecode. Obviously this test means that you can just, if their module was named foo-module-pyc, take it to another name, foo-original, and then you take your module, the code that you want to run, and just call it foo-module.py, your code will be run in preference. So that's this really easy way to get in process. All the distributors would need to do is take out is take out this equality test, and then stop people doing it. But I've never seen, people have put huge amounts of effort into their remarshalling and things, but they haven't taken out this like four line if statement. I don't know why, probably they fail. So obviously our PY takes precedence, and then because we're running arbitrary Python bytecode, now we can start to query those objects. There's some code that I haven't got on disk, but it's in the paper for blindly mirroring the object that you've replaced. And so you're acting as a proxy between the object that you've renamed and the object which is the code which is calling you. And you're literally passing the calls on into the object. So the code's in the paper. It's pretty useful. That means that the application won't crash. So as I said, non-standard marshalling can be a real pain in the ass. I didn't put much effort into trying to come up with a technique to undo their marshalling because as soon as you're in the Python runtime they've already undone it. So it was a real pain. So we just completely sidestepped the problem and accessed it at the Python layer. This is more complicated, however. We've got to re-remap their opcode. So we've got to work out how they juggled up their opcode mappings, their integer to instruction maps. Obviously we need to do this at runtime. We don't have access to the opcode.py, so we need to reproduce that opcode.py so all our other techniques can work at the Python runtime. Obviously we need an understanding of the opcode mapping to be able to get anything from the byte stream. It's this understanding which the vendors are assuming that they've broken. If you don't understand the opcode mapping, you can't get any sense out of a bytecode because it's just a stream of bytes. You don't really understand what it means. But there was a pretty easy way to get at this new opcode mapping. Essentially using a plain text attack against the compiler. So as I said, all instructions are just one byte and there's an optional two byte argument to it. So if we go and look at some normal Python bytecode on the left that we've already seen instruction arguments, if they've remapped their stack to 0x64 has been remapped to 0x44, 0x47 has been remapped to 0x11, et cetera, et cetera. If we can take a known set of .pys and compile them into bytecode for standard Python and then compile them into bytecode for the obfuscated Python using the obfuscated runtime, then we'll get a list of this bytecode and then we can just diff these two bytecode streams and we can say, oh cool, right, 0x64's gone to 0x44, 0x47's gone to 0x11. We do this for enough Python source code and then we'll hit all the bytecode instructions and then we've got the new mapping and we can rewrite the opcode.py and then we're good. Even though they've juggled it up, we can still work out what the instructions are. So for this example, obviously we've got these mappings here and you just keep doing it for a shit ton of Python and eventually you'll get all the opcode mappings out. As I said, everybody distributes the runtime in these package files the runtime contains all the normal Python modules, you know, os.py and sys.py. We've got access to those as well because they're standard library Python modules. So if you compare the obfuscated PYCs that they're distributing and then a normal PYC which you've compiled, you get this opcode mapping back out which is pretty useful. To do this in the tool, I created a new file format which is probably a bit of a grand term PYB file format which just means that we're dumping out raw Python bytecode to disk which allows me to sidestep the fact that I probably don't know how they're marshalling things up. So it's just a new format that we can produce two streams that are much easier to diff. I don't have to go through that stage of unmarshalling their PYCs. I'll show you a so this is like step by step. First we've got to find a version of Python that the obfuscated runtime is running. We need to compile the bytecode with the exact same version. So if they're running 2.5.4, we need to compile our PYBs with 2.5.4 otherwise we won't get streams that are perfectly in sync and we'll get less collisions for the plain text attack. So find out the version. We use standard library Python to compile up all the PYBs from in process we compile up the PYBs from in process of the obfuscated runtime, compile up all the PYBs and now we've got two systems that we can diff. We diff them. We get our new bytecode mappings and then we rewrite opcode.py and for unpyc we need to write opcodes.py which is the equivalent of it and then we're good to go. So even though they've gone to all this effort now we've remapped their opcodes, we understand what their byte streams mean and we can start to decompile. Again we're only getting this because we're working in memory at the Python layer so it's quite useful. And this is where I'm going to demo and things will fail. So I've got a little test application it's really lame but it shows the point. RePDB is my reverse engineering version of PDB so we'll start that up and we'll have a look at the... So we'll just set a project You can see all our source code is going to be dumped out to a particular directory and you can see the project was created here. All our PYBs are going to be going out into here. So I'll just get my cheat sheet so I don't fail at the path. So first we're going to generate the reference PYBs so just gen ref 26 and a path to all the standard library modules it's just the standard module set the PYs so we compile all those up so we're compiling them into PYCs so we know we've got a good compile and then we're taking them to PYBs so we've done all that, that's good and now we do the same for the obfuscated Python bytecode so we can get out our sets so gen 026 gen 026 and this time we give it the path to all the PYCs which are distributed, the modified PYCs. I've created my own you'll see Python 262 is a standard compiled runtime this one here is one that I've modified that will do opcode remapping so we compile up everything here got a bunch of warnings but that's because I haven't cleaned up my code properly and now we just tell it to remap and it will take those two byte streams and diff them together and so you can see further up here where it's finding bytecodes and remapping so you can see binary write shift, it wasn't 63 it's moved to 64 so we found all the shifts and now we're going to rewrite the opcode.py so we say yes, we want to rewrite the opcode.py and now if we look at here you can see there's all the PYBs that we've produced for the obfuscated all the PYBs that we've produced for the reference and then in the libs we've got a new opcode.py remapped by Pyretic and then these are all the new opcode listings and equivalent equivalent for the opcodes.py it's just the equivalent file for the unpyc so we've remapped the bytecode so now we're in a position that we can understand what the byte streams mean and we've probably really got to hurry up so in memory decompilation versus static obviously all the decompilers at the moment take files on disk and decompile them by accessing those serialized objects that we spoke about in the marshaled PYC in memory obviously we're going to access the bytecode from the function object co.code object because then everything will be automatically unmarshalled and we can get access to that at runtime, we're going to have to hurry up so as I said a top level Python object doesn't have a code object which is a real pain so at runtime there's no code object for us to decompile this means that we have to use I've termed it source code reconstruction I'm not sure if that's a proper term or not but rather than decompiling the stream of bytecode we're prodding and poking at a lot of the objects and asking questions at them in the runtime and then from the answers to all those questions we've got have a good guess at what they actually look like in source code so when we're working in memory decompiling if we can get access to a function we can get access to the code object and decompile that. 5 minutes, awesome if we're doing reconstruction at runtime we need to query a lot of the objects so we'll talk about so if this is the source code these objects are obviously top level so we need to use reconstruction on those so we have to query a lot of the objects this function actually has it's got a CO code object so we can just use standard decompilation there there's some stuff that we can and can't get out of reconstruction so obviously you can see here that bar is calling test function 3 from reconstruction we can never tell that it's called test function 3 we only get the return from that similarly with foo that was initially set to 9 and then was set to 10 we'll never know that it was initially set to 9 we only get it when it's at 10 because that's the state from which we're asking the question of it so we have no pre-state history so it's not perfect but remember we're looking for bugs we're not looking to completely re-get the python source code so it's good enough for finding bugs in realistic applications most of the functionality is actually in the classes and the functions not at the top level so if we can get roughly right it's good enough for finding bugs so it's not perfect but it's good enough and that's just saying what I've said so the Pyretic toolkit this is what I wrote to kind of mean that I didn't have to do all this manually obviously it came from my real need to actually find some bugs it's kind of in three sections there's the decompilation section and source code reconstruction that we've just spoke about it will do three types of decompilation depending on the kind of obfuscations which are in place and the access that you have so there's file system traversal module object decompile which means that you're walking the file system you've got access to the file system you've got access to their PYCs and you will take those PYCs and they also give you access to their un-marshalling so they haven't restricted access to their un-marshalling you can take the files off disk un-marshall them, throw them in memory into the decompiler and get the source code back out oh file system traversal so you've got access to the code on disk but you don't have access to the un-marshalling so this means you have to do the source code reconstruction and the actual decompile on the objects that you can access with the CO code object again you get pretty good decompilation out of this but not perfect, not as good as the first case and then this case is when you don't have access to anything on disk you've only got access to the objects in memory so you've got to do you're not traversing the file system so that means you can only decompile anything instantiated at the point that you're in state so a lot less code gets decompiled you can only get access to something that's actually been instantiated in memory at the time but you don't have access to anything on disk so you'll get less code decompiled but at least you'll get something this is the opcode remapping which you saw demoed earlier so it's all packaged up in a nice easy to use way so you don't have to do it all by hand and then there's the re-pdb which is kind of my version of pdb it builds on it superclasses out pdb but it allows you to access lots of extra functionality which is useful for assessing the code at runtime and things like it calls through to third party modules like pycallgraph so you can just get a nice callgraph out and actually understand what that code's doing at a very high level so yeah some future directions there's lots of potential to actually take this more usable by other people rather than just me I'll just show you the decompilation of the three types and then I'll be kicked off I think so we've already done all the remapping so we've got the opcode so now we're going to do the three decompilations so you can see how the source code kind of differs and degrades when you're doing the pure in memory stuff so first we'll do the file system traversal so file system traversal file system traversal unmarched and decompile and this is the you know the silly test application which I pulled up at the time which I compiled so it's pretty quick because it was a simple application so we'll go to our source code and then this ridiculously long path yeah we're there so this is the PYC that's been decompiled through the first method you can see it's pretty good you get some strange things where things are specified as longs but it's a pretty good decompilation you'll see things change when we're doing the pure memory stuff so we'll do this again with file system mem decompile to the same path again pretty quick and so it's in a different and you've guessed it all the way back out and we're there you'll see here things like this was a function call but we only get the return value from that function call for the reasons that I said earlier and you'll see that some of the classes kind of have an elongated name because that's where we got the in memory when we were asking a question of that class object this is the answer that we got so again not perfect but good enough for finding bugs definitely and then the pure memory decompile we need to obviously import the object so if we import the test app and then we do a I'll show you it's in so you can see that it's actually in the name space of the debugger so if you do a pure mem decompile on this object so obviously we're not passing it a path anymore we're passing it an object because we're assuming that we don't have access to the path it'll do the same thing and if we go to the mem object now we don't have a long path and you'll see that it's come out again we only get the return values but it's pretty much similar to the previous one so the decompilation is pretty good and we had no access to anything on disk this was source code coming out of an instantiated object in memory which obviously is a simple test app but it's pretty powerful what you can do with that moving forward so I think I've completely run out of time fail so completely run out of time are there any questions awesome that means nobody followed even better the other thing I'm going to announce is there was a hack cup for a lot of teams a lot of hacking teams playing in a football competition yesterday so these are the results of that team ZA won and they won a load of tickets to echo party down in our gym in Argentina so that's pretty cool and Nico who put this cup on is going to be throwing it again next year so if people are hackers that like football which I know is a strange mix because that means athleticism and getting out from the basement but it will be on next year so if you want to enter a team get in touch with Nico Weissman and he'll give you all the details other than that thank you